xref: /sqlite-3.40.0/src/select.c (revision e6f85e71)
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*e6f85e71Sdrh ** $Id: select.c,v 1.219 2004/12/25 01:03:14 drh Exp $
16cce7d176Sdrh */
17cce7d176Sdrh #include "sqliteInt.h"
18cce7d176Sdrh 
19315555caSdrh 
20cce7d176Sdrh /*
219bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
229bb61fe7Sdrh ** structure.
23cce7d176Sdrh */
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;
845719628aSdrh   static const struct {
8501f3f253Sdrh     const char *zKeyword;
86290c1948Sdrh     u8 nChar;
87290c1948Sdrh     u8 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   ){
119ae29ffbeSdrh     const char *zSp1 = " ";
120ae29ffbeSdrh     const char *zSp2 = " ";
121ae29ffbeSdrh     if( pB==0 ){ zSp1++; }
122ae29ffbeSdrh     if( pC==0 ){ zSp2++; }
123ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
124ae29ffbeSdrh        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
12501f3f253Sdrh     jointype = JT_INNER;
126195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1274adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
128da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
129195e6967Sdrh     jointype = JT_INNER;
13001f3f253Sdrh   }
13101f3f253Sdrh   return jointype;
13201f3f253Sdrh }
13301f3f253Sdrh 
13401f3f253Sdrh /*
135ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
136ad2d8307Sdrh ** is not contained in the table.
137ad2d8307Sdrh */
138ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
139ad2d8307Sdrh   int i;
140ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1414adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
142ad2d8307Sdrh   }
143ad2d8307Sdrh   return -1;
144ad2d8307Sdrh }
145ad2d8307Sdrh 
146ad2d8307Sdrh /*
14791bb0eedSdrh ** Set the value of a token to a '\000'-terminated string.
14891bb0eedSdrh */
14991bb0eedSdrh static void setToken(Token *p, const char *z){
15091bb0eedSdrh   p->z = z;
15191bb0eedSdrh   p->n = strlen(z);
15291bb0eedSdrh   p->dyn = 0;
15391bb0eedSdrh }
15491bb0eedSdrh 
15591bb0eedSdrh 
15691bb0eedSdrh /*
157ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
158ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
159ad2d8307Sdrh */
160ad2d8307Sdrh static void addWhereTerm(
161ad2d8307Sdrh   const char *zCol,        /* Name of the column */
162ad2d8307Sdrh   const Table *pTab1,      /* First table */
163ad2d8307Sdrh   const Table *pTab2,      /* Second table */
164ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
165ad2d8307Sdrh ){
166ad2d8307Sdrh   Token dummy;
167ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
168ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
169ad2d8307Sdrh   Expr *pE;
170ad2d8307Sdrh 
17191bb0eedSdrh   setToken(&dummy, zCol);
1724adee20fSdanielk1977   pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
1734adee20fSdanielk1977   pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
17491bb0eedSdrh   setToken(&dummy, pTab1->zName);
1754adee20fSdanielk1977   pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
17691bb0eedSdrh   setToken(&dummy, pTab2->zName);
1774adee20fSdanielk1977   pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
1784adee20fSdanielk1977   pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
1794adee20fSdanielk1977   pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
1804adee20fSdanielk1977   pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
1811f16230bSdrh   ExprSetProperty(pE, EP_FromJoin);
18291bb0eedSdrh   *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
183ad2d8307Sdrh }
184ad2d8307Sdrh 
185ad2d8307Sdrh /*
1861f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
1871cc093c2Sdrh **
188e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
1891cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
1901f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
1911f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
1921f16230bSdrh ** WHERE clause during join processing but we need to remember that they
1931f16230bSdrh ** originated in the ON or USING clause.
1941cc093c2Sdrh */
1951cc093c2Sdrh static void setJoinExpr(Expr *p){
1961cc093c2Sdrh   while( p ){
1971f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
1981cc093c2Sdrh     setJoinExpr(p->pLeft);
1991cc093c2Sdrh     p = p->pRight;
2001cc093c2Sdrh   }
2011cc093c2Sdrh }
2021cc093c2Sdrh 
2031cc093c2Sdrh /*
204ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
205ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
206ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
207ad2d8307Sdrh **
20891bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
20991bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
21091bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
21191bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
21291bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
21391bb0eedSdrh ** also attached to the left entry.
21491bb0eedSdrh **
215ad2d8307Sdrh ** This routine returns the number of errors encountered.
216ad2d8307Sdrh */
217ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
21891bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
21991bb0eedSdrh   int i, j;                       /* Loop counters */
22091bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
22191bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
222ad2d8307Sdrh 
22391bb0eedSdrh   pSrc = p->pSrc;
22491bb0eedSdrh   pLeft = &pSrc->a[0];
22591bb0eedSdrh   pRight = &pLeft[1];
22691bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
22791bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
22891bb0eedSdrh     Table *pRightTab = pRight->pTab;
22991bb0eedSdrh 
23091bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
231ad2d8307Sdrh 
232ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
233ad2d8307Sdrh     ** every column that the two tables have in common.
234ad2d8307Sdrh     */
23591bb0eedSdrh     if( pLeft->jointype & JT_NATURAL ){
23691bb0eedSdrh       if( pLeft->pOn || pLeft->pUsing ){
2374adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
238ad2d8307Sdrh            "an ON or USING clause", 0);
239ad2d8307Sdrh         return 1;
240ad2d8307Sdrh       }
24191bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
24291bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
24391bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
24491bb0eedSdrh           addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
245ad2d8307Sdrh         }
246ad2d8307Sdrh       }
247ad2d8307Sdrh     }
248ad2d8307Sdrh 
249ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
250ad2d8307Sdrh     */
25191bb0eedSdrh     if( pLeft->pOn && pLeft->pUsing ){
2524adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
253da93d238Sdrh         "clauses in the same join");
254ad2d8307Sdrh       return 1;
255ad2d8307Sdrh     }
256ad2d8307Sdrh 
257ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
25891bb0eedSdrh     ** an AND operator.
259ad2d8307Sdrh     */
26091bb0eedSdrh     if( pLeft->pOn ){
26191bb0eedSdrh       setJoinExpr(pLeft->pOn);
26291bb0eedSdrh       p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
26391bb0eedSdrh       pLeft->pOn = 0;
264ad2d8307Sdrh     }
265ad2d8307Sdrh 
266ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
267ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
268ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
269ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
270ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
271ad2d8307Sdrh     ** not contained in both tables to be joined.
272ad2d8307Sdrh     */
27391bb0eedSdrh     if( pLeft->pUsing ){
27491bb0eedSdrh       IdList *pList = pLeft->pUsing;
275ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
27691bb0eedSdrh         char *zName = pList->a[j].zName;
27791bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
2784adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
27991bb0eedSdrh             "not present in both tables", zName);
280ad2d8307Sdrh           return 1;
281ad2d8307Sdrh         }
28291bb0eedSdrh         addWhereTerm(zName, pLeftTab, pRightTab, &p->pWhere);
283ad2d8307Sdrh       }
284ad2d8307Sdrh     }
285ad2d8307Sdrh   }
286ad2d8307Sdrh   return 0;
287ad2d8307Sdrh }
288ad2d8307Sdrh 
289ad2d8307Sdrh /*
2909bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
2919bb61fe7Sdrh */
2924adee20fSdanielk1977 void sqlite3SelectDelete(Select *p){
29382c3d636Sdrh   if( p==0 ) return;
2944adee20fSdanielk1977   sqlite3ExprListDelete(p->pEList);
2954adee20fSdanielk1977   sqlite3SrcListDelete(p->pSrc);
2964adee20fSdanielk1977   sqlite3ExprDelete(p->pWhere);
2974adee20fSdanielk1977   sqlite3ExprListDelete(p->pGroupBy);
2984adee20fSdanielk1977   sqlite3ExprDelete(p->pHaving);
2994adee20fSdanielk1977   sqlite3ExprListDelete(p->pOrderBy);
3004adee20fSdanielk1977   sqlite3SelectDelete(p->pPrior);
3019bb61fe7Sdrh   sqliteFree(p);
3029bb61fe7Sdrh }
3039bb61fe7Sdrh 
3049bb61fe7Sdrh /*
3052282792aSdrh ** Delete the aggregate information from the parse structure.
3062282792aSdrh */
3071d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){
3082282792aSdrh   sqliteFree(pParse->aAgg);
3092282792aSdrh   pParse->aAgg = 0;
3102282792aSdrh   pParse->nAgg = 0;
3112282792aSdrh   pParse->useAgg = 0;
3122282792aSdrh }
3132282792aSdrh 
3142282792aSdrh /*
315c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
316c926afbcSdrh ** stack into the sorter.
317c926afbcSdrh */
318c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
319c926afbcSdrh   int i;
320c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
3214adee20fSdanielk1977     sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
322c926afbcSdrh   }
323ededfd5eSdanielk1977   sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
3244adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
325c926afbcSdrh }
326c926afbcSdrh 
327c926afbcSdrh /*
328ea48eb2eSdrh ** Add code to implement the OFFSET and LIMIT
329ea48eb2eSdrh */
330ea48eb2eSdrh static void codeLimiter(
331bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
332ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
333ea48eb2eSdrh   int iContinue,    /* Jump here to skip the current record */
334ea48eb2eSdrh   int iBreak,       /* Jump here to end the loop */
335ea48eb2eSdrh   int nPop          /* Number of times to pop stack when jumping */
336ea48eb2eSdrh ){
337ea48eb2eSdrh   if( p->iOffset>=0 ){
338ea48eb2eSdrh     int addr = sqlite3VdbeCurrentAddr(v) + 2;
339ea48eb2eSdrh     if( nPop>0 ) addr++;
340ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr);
341ea48eb2eSdrh     if( nPop>0 ){
342ea48eb2eSdrh       sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
343ea48eb2eSdrh     }
344ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
345ad6d9460Sdrh     VdbeComment((v, "# skip OFFSET records"));
346ea48eb2eSdrh   }
347ea48eb2eSdrh   if( p->iLimit>=0 ){
348ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
349ad6d9460Sdrh     VdbeComment((v, "# exit when LIMIT reached"));
350ea48eb2eSdrh   }
351ea48eb2eSdrh }
352ea48eb2eSdrh 
353ea48eb2eSdrh /*
3542282792aSdrh ** This routine generates the code for the inside of the inner loop
3552282792aSdrh ** of a SELECT.
35682c3d636Sdrh **
35738640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
35838640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
35938640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
36038640e15Sdrh ** datatypes for each column.
3612282792aSdrh */
3622282792aSdrh static int selectInnerLoop(
3632282792aSdrh   Parse *pParse,          /* The parser context */
364df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3652282792aSdrh   ExprList *pEList,       /* List of values being extracted */
36682c3d636Sdrh   int srcTab,             /* Pull data from this table */
367967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3682282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3692282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3702282792aSdrh   int eDest,              /* How to dispose of the results */
3712282792aSdrh   int iParm,              /* An argument to the disposal method */
3722282792aSdrh   int iContinue,          /* Jump here to continue with next row */
37384ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
37484ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
3752282792aSdrh ){
3762282792aSdrh   Vdbe *v = pParse->pVdbe;
3772282792aSdrh   int i;
378ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
37938640e15Sdrh 
380daffd0e5Sdrh   if( v==0 ) return 0;
38138640e15Sdrh   assert( pEList!=0 );
3822282792aSdrh 
383df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
384df199a25Sdrh   ** to see if this row should be output.
385df199a25Sdrh   */
386ea48eb2eSdrh   hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
387ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
388bab39e13Sdrh     codeLimiter(v, p, iContinue, iBreak, 0);
389df199a25Sdrh   }
390df199a25Sdrh 
391967e8b73Sdrh   /* Pull the requested columns.
3922282792aSdrh   */
39338640e15Sdrh   if( nColumn>0 ){
394967e8b73Sdrh     for(i=0; i<nColumn; i++){
3954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
39682c3d636Sdrh     }
39738640e15Sdrh   }else{
39838640e15Sdrh     nColumn = pEList->nExpr;
39938640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
4004adee20fSdanielk1977       sqlite3ExprCode(pParse, pEList->a[i].pExpr);
40138640e15Sdrh     }
40282c3d636Sdrh   }
4032282792aSdrh 
404daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
405daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
406daffd0e5Sdrh   ** part of the result.
4072282792aSdrh   */
408ea48eb2eSdrh   if( hasDistinct ){
4090bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4104adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
4110bd1f4eaSdrh #endif
412ededfd5eSdanielk1977     /* Deliberately leave the affinity string off of the following
413ededfd5eSdanielk1977     ** OP_MakeRecord */
414ededfd5eSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
4154adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
4164adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
4174adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
418ad6d9460Sdrh     VdbeComment((v, "# skip indistinct records"));
4190f69c1e3Sdanielk1977     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
4204adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
421ea48eb2eSdrh     if( pOrderBy==0 ){
422bab39e13Sdrh       codeLimiter(v, p, iContinue, iBreak, nColumn);
423ea48eb2eSdrh     }
4242282792aSdrh   }
42582c3d636Sdrh 
426c926afbcSdrh   switch( eDest ){
42782c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
42882c3d636Sdrh     ** table iParm.
4292282792aSdrh     */
430c926afbcSdrh     case SRT_Union: {
4314adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
43284ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
4330f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
4344adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
435c926afbcSdrh       break;
436c926afbcSdrh     }
43782c3d636Sdrh 
4385974a30fSdrh     /* Store the result as data using a unique key.
4395974a30fSdrh     */
440c926afbcSdrh     case SRT_Table:
441c926afbcSdrh     case SRT_TempTable: {
4424adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
443c926afbcSdrh       if( pOrderBy ){
444c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
445c926afbcSdrh       }else{
4464adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
4474adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
4484adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
449c926afbcSdrh       }
450c926afbcSdrh       break;
451c926afbcSdrh     }
4525974a30fSdrh 
45382c3d636Sdrh     /* Construct a record from the query result, but instead of
45482c3d636Sdrh     ** saving that record, use it as a key to delete elements from
45582c3d636Sdrh     ** the temporary table iParm.
45682c3d636Sdrh     */
457c926afbcSdrh     case SRT_Except: {
4580bd1f4eaSdrh       int addr;
4594adee20fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
46084ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
4614adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
4624adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
463c926afbcSdrh       break;
464c926afbcSdrh     }
4652282792aSdrh 
4662282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4672282792aSdrh     ** then there should be a single item on the stack.  Write this
4682282792aSdrh     ** item into the set table with bogus data.
4692282792aSdrh     */
470c926afbcSdrh     case SRT_Set: {
4714adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
47252b36cabSdrh       int addr2;
473e014a838Sdanielk1977 
474967e8b73Sdrh       assert( nColumn==1 );
4754adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
4764adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
4774adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
478c926afbcSdrh       if( pOrderBy ){
479c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
480c926afbcSdrh       }else{
481e014a838Sdanielk1977         char aff = (iParm>>16)&0xFF;
482e014a838Sdanielk1977         aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
48394a11211Sdrh         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
4840f69c1e3Sdanielk1977         sqlite3VdbeAddOp(v, OP_String8, 0, 0);
485e014a838Sdanielk1977         sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
486c926afbcSdrh       }
4874adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
488c926afbcSdrh       break;
489c926afbcSdrh     }
49082c3d636Sdrh 
4912282792aSdrh     /* If this is a scalar select that is part of an expression, then
4922282792aSdrh     ** store the results in the appropriate memory cell and break out
4932282792aSdrh     ** of the scan loop.
4942282792aSdrh     */
495c926afbcSdrh     case SRT_Mem: {
496967e8b73Sdrh       assert( nColumn==1 );
497c926afbcSdrh       if( pOrderBy ){
498c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
499c926afbcSdrh       }else{
5004adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
5014adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
502c926afbcSdrh       }
503c926afbcSdrh       break;
504c926afbcSdrh     }
5052282792aSdrh 
506f46f905aSdrh     /* Send the data to the callback function.
507f46f905aSdrh     */
508f46f905aSdrh     case SRT_Callback:
509f46f905aSdrh     case SRT_Sorter: {
510f46f905aSdrh       if( pOrderBy ){
511ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
512f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
513f46f905aSdrh       }else{
514f46f905aSdrh         assert( eDest==SRT_Callback );
5154adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
516f46f905aSdrh       }
517f46f905aSdrh       break;
518f46f905aSdrh     }
519f46f905aSdrh 
520142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
521142e30dfSdrh     ** is responsible for popping the results off of the stack.
522142e30dfSdrh     */
523142e30dfSdrh     case SRT_Subroutine: {
524ac82fcf5Sdrh       if( pOrderBy ){
5254adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
526ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
527ac82fcf5Sdrh       }else{
5284adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
529ac82fcf5Sdrh       }
530142e30dfSdrh       break;
531142e30dfSdrh     }
532142e30dfSdrh 
533d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
534d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
535d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
536d7489c39Sdrh     ** about the actual results of the select.
537d7489c39Sdrh     */
538c926afbcSdrh     default: {
539f46f905aSdrh       assert( eDest==SRT_Discard );
5404adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
541c926afbcSdrh       break;
542c926afbcSdrh     }
543c926afbcSdrh   }
54482c3d636Sdrh   return 0;
54582c3d636Sdrh }
54682c3d636Sdrh 
54782c3d636Sdrh /*
548d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
549d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
550d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
551d8bc7086Sdrh ** routine generates the code needed to do that.
552d8bc7086Sdrh */
553c926afbcSdrh static void generateSortTail(
554ffbc3088Sdrh   Parse *pParse,   /* The parsing context */
555c926afbcSdrh   Select *p,       /* The SELECT statement */
556c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
557c926afbcSdrh   int nColumn,     /* Number of columns of data */
558c926afbcSdrh   int eDest,       /* Write the sorted results here */
559c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
560c926afbcSdrh ){
5614adee20fSdanielk1977   int end1 = sqlite3VdbeMakeLabel(v);
5624adee20fSdanielk1977   int end2 = sqlite3VdbeMakeLabel(v);
563d8bc7086Sdrh   int addr;
564ffbc3088Sdrh   KeyInfo *pInfo;
565ffbc3088Sdrh   ExprList *pOrderBy;
566ffbc3088Sdrh   int nCol, i;
5679bb575fdSdrh   sqlite3 *db = pParse->db;
568ffbc3088Sdrh 
569f46f905aSdrh   if( eDest==SRT_Sorter ) return;
570ffbc3088Sdrh   pOrderBy = p->pOrderBy;
571ffbc3088Sdrh   nCol = pOrderBy->nExpr;
572ffbc3088Sdrh   pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
573ffbc3088Sdrh   if( pInfo==0 ) return;
574ffbc3088Sdrh   pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
575ffbc3088Sdrh   pInfo->nField = nCol;
576ffbc3088Sdrh   for(i=0; i<nCol; i++){
5770202b29eSdanielk1977     /* If a collation sequence was specified explicity, then it
5780202b29eSdanielk1977     ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
5790202b29eSdanielk1977     ** collation type for the expression.
5800202b29eSdanielk1977     */
5817cedc8d4Sdanielk1977     pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
5820202b29eSdanielk1977     if( !pInfo->aColl[i] ){
583ffbc3088Sdrh       pInfo->aColl[i] = db->pDfltColl;
5840202b29eSdanielk1977     }
585ffbc3088Sdrh     pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
586ffbc3088Sdrh   }
587ffbc3088Sdrh   sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
5884adee20fSdanielk1977   addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
589bab39e13Sdrh   codeLimiter(v, p, addr, end2, 1);
590c926afbcSdrh   switch( eDest ){
591c926afbcSdrh     case SRT_Table:
592c926afbcSdrh     case SRT_TempTable: {
5934adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
5944adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
5954adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
596c926afbcSdrh       break;
597c926afbcSdrh     }
598c926afbcSdrh     case SRT_Set: {
599c926afbcSdrh       assert( nColumn==1 );
6004adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
6014adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6024adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
603ededfd5eSdanielk1977       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
6040f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
605e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
606c926afbcSdrh       break;
607c926afbcSdrh     }
608c926afbcSdrh     case SRT_Mem: {
609c926afbcSdrh       assert( nColumn==1 );
6104adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
6114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
612c926afbcSdrh       break;
613c926afbcSdrh     }
614ce665cf6Sdrh     case SRT_Callback:
615ac82fcf5Sdrh     case SRT_Subroutine: {
616ac82fcf5Sdrh       int i;
61784ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
61884ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
619ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
6204adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
621ac82fcf5Sdrh       }
622ce665cf6Sdrh       if( eDest==SRT_Callback ){
623ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
624ce665cf6Sdrh       }else{
6254adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
626ce665cf6Sdrh       }
62784ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
628ac82fcf5Sdrh       break;
629ac82fcf5Sdrh     }
630c926afbcSdrh     default: {
631f46f905aSdrh       /* Do nothing */
632c926afbcSdrh       break;
633c926afbcSdrh     }
634c926afbcSdrh   }
6354adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
6364adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end2);
6374adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6384adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end1);
6394adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
640d8bc7086Sdrh }
641d8bc7086Sdrh 
642d8bc7086Sdrh /*
643517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
644517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
645e78e8284Sdrh **
646517eb646Sdanielk1977 ** If the declaration type is the exact datatype definition extracted from
647517eb646Sdanielk1977 ** the original CREATE TABLE statement if the expression is a column.
648e78e8284Sdrh **
649517eb646Sdanielk1977 ** The declaration type for an expression is either TEXT, NUMERIC or ANY.
650517eb646Sdanielk1977 ** The declaration type for a ROWID field is INTEGER.
651fcb78a49Sdrh */
652517eb646Sdanielk1977 static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
65300e279d9Sdanielk1977   char const *zType;
654517eb646Sdanielk1977   int j;
65500e279d9Sdanielk1977   if( pExpr==0 || pTabList==0 ) return 0;
65600e279d9Sdanielk1977 
65700e279d9Sdanielk1977   switch( pExpr->op ){
65800e279d9Sdanielk1977     case TK_COLUMN: {
6596a3ea0e6Sdrh       Table *pTab;
660517eb646Sdanielk1977       int iCol = pExpr->iColumn;
661517eb646Sdanielk1977       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
6626a3ea0e6Sdrh       assert( j<pTabList->nSrc );
6636a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
664fcb78a49Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
665fcb78a49Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
666fcb78a49Sdrh       if( iCol<0 ){
667fcb78a49Sdrh         zType = "INTEGER";
668fcb78a49Sdrh       }else{
669fcb78a49Sdrh         zType = pTab->aCol[iCol].zType;
670fcb78a49Sdrh       }
67100e279d9Sdanielk1977       break;
672736c22b8Sdrh     }
67300e279d9Sdanielk1977     case TK_AS:
67400e279d9Sdanielk1977       zType = columnType(pParse, pTabList, pExpr->pLeft);
67500e279d9Sdanielk1977       break;
67600e279d9Sdanielk1977     case TK_SELECT: {
67700e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
67800e279d9Sdanielk1977       zType = columnType(pParse, pS->pSrc, pS->pEList->a[0].pExpr);
67900e279d9Sdanielk1977       break;
680fcb78a49Sdrh     }
68100e279d9Sdanielk1977     default:
68200e279d9Sdanielk1977       zType = 0;
68300e279d9Sdanielk1977   }
68400e279d9Sdanielk1977 
685517eb646Sdanielk1977   return zType;
686517eb646Sdanielk1977 }
687517eb646Sdanielk1977 
688517eb646Sdanielk1977 /*
689517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
690517eb646Sdanielk1977 ** in the result set.
691517eb646Sdanielk1977 */
692517eb646Sdanielk1977 static void generateColumnTypes(
693517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
694517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
695517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
696517eb646Sdanielk1977 ){
697517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
698517eb646Sdanielk1977   int i;
699517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
700517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
701517eb646Sdanielk1977     const char *zType = columnType(pParse, pTabList, p);
70200e279d9Sdanielk1977     if( zType==0 ) continue;
703fbcd585fSdanielk1977     /* The vdbe must make it's own copy of the column-type, in case the
704fbcd585fSdanielk1977     ** schema is reset before this virtual machine is deleted.
705fbcd585fSdanielk1977     */
706fbcd585fSdanielk1977     sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
707fcb78a49Sdrh   }
708fcb78a49Sdrh }
709fcb78a49Sdrh 
710fcb78a49Sdrh /*
711fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
712fcb78a49Sdrh ** in the result set.  This information is used to provide the
713fcabd464Sdrh ** azCol[] values in the callback.
71482c3d636Sdrh */
715832508b7Sdrh static void generateColumnNames(
716832508b7Sdrh   Parse *pParse,      /* Parser context */
717ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
718832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
719832508b7Sdrh ){
720d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
7216a3ea0e6Sdrh   int i, j;
7229bb575fdSdrh   sqlite3 *db = pParse->db;
723fcabd464Sdrh   int fullNames, shortNames;
724fcabd464Sdrh 
7253cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
7263cf86063Sdanielk1977   if( pParse->explain ){
72761de0d1bSdanielk1977     return;
7283cf86063Sdanielk1977   }
7293cf86063Sdanielk1977 
730d6502758Sdrh   assert( v!=0 );
7316f8a503dSdanielk1977   if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
732d8bc7086Sdrh   pParse->colNamesSet = 1;
733fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
734fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
73522322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
73682c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
73782c3d636Sdrh     Expr *p;
7385a38705eSdrh     p = pEList->a[i].pExpr;
7395a38705eSdrh     if( p==0 ) continue;
74082c3d636Sdrh     if( pEList->a[i].zName ){
74182c3d636Sdrh       char *zName = pEList->a[i].zName;
742d8123366Sdanielk1977       sqlite3VdbeSetColName(v, i, zName, strlen(zName));
74382c3d636Sdrh       continue;
74482c3d636Sdrh     }
745fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
7466a3ea0e6Sdrh       Table *pTab;
74797665873Sdrh       char *zCol;
7488aff1015Sdrh       int iCol = p->iColumn;
7496a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7506a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7516a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
7528aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
75397665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
754b1363206Sdrh       if( iCol<0 ){
755b1363206Sdrh         zCol = "_ROWID_";
756b1363206Sdrh       }else{
757b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
758b1363206Sdrh       }
759fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
7603cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
761fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
76282c3d636Sdrh         char *zName = 0;
76382c3d636Sdrh         char *zTab;
76482c3d636Sdrh 
7656a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
766fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
7674adee20fSdanielk1977         sqlite3SetString(&zName, zTab, ".", zCol, 0);
7683cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
76982c3d636Sdrh       }else{
7703cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, zCol, 0);
77182c3d636Sdrh       }
7726977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
7733cf86063Sdanielk1977       sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
7743cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
7751bee3d7bSdrh     }else{
7761bee3d7bSdrh       char zName[30];
7771bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
7781bee3d7bSdrh       sprintf(zName, "column%d", i+1);
7793cf86063Sdanielk1977       sqlite3VdbeSetColName(v, i, zName, 0);
78082c3d636Sdrh     }
78182c3d636Sdrh   }
78276d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
7835080aaa7Sdrh }
78482c3d636Sdrh 
78582c3d636Sdrh /*
786d8bc7086Sdrh ** Name of the connection operator, used for error messages.
787d8bc7086Sdrh */
788d8bc7086Sdrh static const char *selectOpName(int id){
789d8bc7086Sdrh   char *z;
790d8bc7086Sdrh   switch( id ){
791d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
792d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
793d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
794d8bc7086Sdrh     default:           z = "UNION";       break;
795d8bc7086Sdrh   }
796d8bc7086Sdrh   return z;
797d8bc7086Sdrh }
798d8bc7086Sdrh 
799d8bc7086Sdrh /*
800315555caSdrh ** Forward declaration
801315555caSdrh */
802315555caSdrh static int fillInColumnList(Parse*, Select*);
803315555caSdrh 
804315555caSdrh /*
80522f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
80622f70c32Sdrh ** the result set of that SELECT.
80722f70c32Sdrh */
8084adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
80922f70c32Sdrh   Table *pTab;
810b733d037Sdrh   int i, j;
81122f70c32Sdrh   ExprList *pEList;
812290c1948Sdrh   Column *aCol, *pCol;
81322f70c32Sdrh 
81422f70c32Sdrh   if( fillInColumnList(pParse, pSelect) ){
81522f70c32Sdrh     return 0;
81622f70c32Sdrh   }
81722f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
81822f70c32Sdrh   if( pTab==0 ){
81922f70c32Sdrh     return 0;
82022f70c32Sdrh   }
82122f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
82222f70c32Sdrh   pEList = pSelect->pEList;
82322f70c32Sdrh   pTab->nCol = pEList->nExpr;
824417be79cSdrh   assert( pTab->nCol>0 );
825b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
826290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
827517eb646Sdanielk1977     Expr *pR;
828517eb646Sdanielk1977     char *zType;
82991bb0eedSdrh     char *zName;
830517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
831290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
83291bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
83391bb0eedSdrh       zName = sqliteStrDup(zName);
834517eb646Sdanielk1977     }else if( p->op==TK_DOT
835b733d037Sdrh                && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
836b733d037Sdrh       int cnt;
83791bb0eedSdrh       zName = sqlite3MPrintf("%T", &pR->token);
838b733d037Sdrh       for(j=cnt=0; j<i; j++){
83991bb0eedSdrh         if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
84091bb0eedSdrh           sqliteFree(zName);
84191bb0eedSdrh           zName = sqlite3MPrintf("%T_%d", &pR->token, ++cnt);
842b733d037Sdrh           j = -1;
843b733d037Sdrh         }
844b733d037Sdrh       }
845b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
84691bb0eedSdrh       zName = sqlite3MPrintf("%T", &p->span);
84722f70c32Sdrh     }else{
84891bb0eedSdrh       zName = sqlite3MPrintf("column%d", i+1);
84922f70c32Sdrh     }
85091bb0eedSdrh     sqlite3Dequote(zName);
85191bb0eedSdrh     pCol->zName = zName;
852e014a838Sdanielk1977 
853517eb646Sdanielk1977     zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
854290c1948Sdrh     pCol->zType = zType;
855290c1948Sdrh     pCol->affinity = SQLITE_AFF_NUMERIC;
856517eb646Sdanielk1977     if( zType ){
857290c1948Sdrh       pCol->affinity = sqlite3AffinityType(zType, strlen(zType));
858517eb646Sdanielk1977     }
859290c1948Sdrh     pCol->pColl = sqlite3ExprCollSeq(pParse, p);
860290c1948Sdrh     if( !pCol->pColl ){
861290c1948Sdrh       pCol->pColl = pParse->db->pDfltColl;
8620202b29eSdanielk1977     }
86322f70c32Sdrh   }
86422f70c32Sdrh   pTab->iPKey = -1;
86522f70c32Sdrh   return pTab;
86622f70c32Sdrh }
86722f70c32Sdrh 
86822f70c32Sdrh /*
869ad2d8307Sdrh ** For the given SELECT statement, do three things.
870d8bc7086Sdrh **
871ad3cab52Sdrh **    (1)  Fill in the pTabList->a[].pTab fields in the SrcList that
87263eb5f29Sdrh **         defines the set of tables that should be scanned.  For views,
87363eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
87463eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
87563eb5f29Sdrh **         statement so that we can freely modify or delete that statement
87663eb5f29Sdrh **         without worrying about messing up the presistent representation
87763eb5f29Sdrh **         of the view.
878d8bc7086Sdrh **
879ad2d8307Sdrh **    (2)  Add terms to the WHERE clause to accomodate the NATURAL keyword
880ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
881ad2d8307Sdrh **
882ad2d8307Sdrh **    (3)  Scan the list of columns in the result set (pEList) looking
88354473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
88454473229Sdrh **         If found, expand each "*" to be every column in every table
88554473229Sdrh **         and TABLE.* to be every column in TABLE.
886d8bc7086Sdrh **
887d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
888d8bc7086Sdrh ** in pParse and return non-zero.
889d8bc7086Sdrh */
890d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){
89154473229Sdrh   int i, j, k, rc;
892ad3cab52Sdrh   SrcList *pTabList;
893daffd0e5Sdrh   ExprList *pEList;
894a76b5dfcSdrh   Table *pTab;
895290c1948Sdrh   struct SrcList_item *pFrom;
896daffd0e5Sdrh 
897daffd0e5Sdrh   if( p==0 || p->pSrc==0 ) return 1;
898daffd0e5Sdrh   pTabList = p->pSrc;
899daffd0e5Sdrh   pEList = p->pEList;
900d8bc7086Sdrh 
901d8bc7086Sdrh   /* Look up every table in the table list.
902d8bc7086Sdrh   */
903290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
904290c1948Sdrh     if( pFrom->pTab ){
905d8bc7086Sdrh       /* This routine has run before!  No need to continue */
906d8bc7086Sdrh       return 0;
907d8bc7086Sdrh     }
908290c1948Sdrh     if( pFrom->zName==0 ){
90922f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
910290c1948Sdrh       assert( pFrom->pSelect!=0 );
911290c1948Sdrh       if( pFrom->zAlias==0 ){
91291bb0eedSdrh         pFrom->zAlias =
91391bb0eedSdrh           sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
914ad2d8307Sdrh       }
915290c1948Sdrh       pFrom->pTab = pTab =
916290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
91722f70c32Sdrh       if( pTab==0 ){
918daffd0e5Sdrh         return 1;
919daffd0e5Sdrh       }
9205cf590c1Sdrh       /* The isTransient flag indicates that the Table structure has been
9215cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
9225cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
9235cf590c1Sdrh       ** part of the schema. */
92422f70c32Sdrh       pTab->isTransient = 1;
92522f70c32Sdrh     }else{
926a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
927290c1948Sdrh       pFrom->pTab = pTab =
928290c1948Sdrh         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
929a76b5dfcSdrh       if( pTab==0 ){
930d8bc7086Sdrh         return 1;
931d8bc7086Sdrh       }
932a76b5dfcSdrh       if( pTab->pSelect ){
93363eb5f29Sdrh         /* We reach here if the named table is a really a view */
9344adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
935417be79cSdrh           return 1;
936417be79cSdrh         }
937290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
93863eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
93963eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
94063eb5f29Sdrh         ** in the inner view.
94163eb5f29Sdrh         */
942290c1948Sdrh         if( pFrom->pSelect==0 ){
943290c1948Sdrh           pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
944a76b5dfcSdrh         }
945d8bc7086Sdrh       }
94622f70c32Sdrh     }
94763eb5f29Sdrh   }
948d8bc7086Sdrh 
949ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
950ad2d8307Sdrh   */
951ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
952ad2d8307Sdrh 
9537c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
95454473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
95554473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
9567c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
9577c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
9587c917d19Sdrh   ** each one to the list of all columns in all tables.
95954473229Sdrh   **
96054473229Sdrh   ** The first loop just checks to see if there are any "*" operators
96154473229Sdrh   ** that need expanding.
962d8bc7086Sdrh   */
9637c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
96454473229Sdrh     Expr *pE = pEList->a[k].pExpr;
96554473229Sdrh     if( pE->op==TK_ALL ) break;
96654473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
96754473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
9687c917d19Sdrh   }
96954473229Sdrh   rc = 0;
9707c917d19Sdrh   if( k<pEList->nExpr ){
97154473229Sdrh     /*
97254473229Sdrh     ** If we get here it means the result set contains one or more "*"
97354473229Sdrh     ** operators that need to be expanded.  Loop through each expression
97454473229Sdrh     ** in the result set and expand them one by one.
97554473229Sdrh     */
9767c917d19Sdrh     struct ExprList_item *a = pEList->a;
9777c917d19Sdrh     ExprList *pNew = 0;
9787c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
97954473229Sdrh       Expr *pE = a[k].pExpr;
98054473229Sdrh       if( pE->op!=TK_ALL &&
98154473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
98254473229Sdrh         /* This particular expression does not need to be expanded.
98354473229Sdrh         */
9844adee20fSdanielk1977         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
9857c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
9867c917d19Sdrh         a[k].pExpr = 0;
9877c917d19Sdrh         a[k].zName = 0;
9887c917d19Sdrh       }else{
98954473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
99054473229Sdrh         ** expanded. */
99154473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
992cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
99354473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
994cf55b7aeSdrh           zTName = sqlite3NameFromToken(&pE->pLeft->token);
99554473229Sdrh         }else{
996cf55b7aeSdrh           zTName = 0;
99754473229Sdrh         }
998290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
999290c1948Sdrh           Table *pTab = pFrom->pTab;
1000290c1948Sdrh           char *zTabName = pFrom->zAlias;
100154473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
100254473229Sdrh             zTabName = pTab->zName;
100354473229Sdrh           }
1004cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1005cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
100654473229Sdrh             continue;
100754473229Sdrh           }
100854473229Sdrh           tableSeen = 1;
1009d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
101022f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
1011ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1012ad2d8307Sdrh 
101391bb0eedSdrh             if( i>0 ){
101491bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
101591bb0eedSdrh               if( (pLeft->jointype & JT_NATURAL)!=0 &&
101691bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1017ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1018ad2d8307Sdrh                 ** table on the right */
1019ad2d8307Sdrh                 continue;
1020ad2d8307Sdrh               }
102191bb0eedSdrh               if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1022ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1023ad2d8307Sdrh                 ** using clause from the table on the right. */
1024ad2d8307Sdrh                 continue;
1025ad2d8307Sdrh               }
102691bb0eedSdrh             }
10274adee20fSdanielk1977             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
102822f70c32Sdrh             if( pRight==0 ) break;
102991bb0eedSdrh             setToken(&pRight->token, zName);
10304b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
10314adee20fSdanielk1977               pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
10324adee20fSdanielk1977               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
103322f70c32Sdrh               if( pExpr==0 ) break;
103491bb0eedSdrh               setToken(&pLeft->token, zTabName);
103591bb0eedSdrh               setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
10366977fea8Sdrh               pExpr->span.dyn = 1;
10376977fea8Sdrh               pExpr->token.z = 0;
10386977fea8Sdrh               pExpr->token.n = 0;
10396977fea8Sdrh               pExpr->token.dyn = 0;
104022f70c32Sdrh             }else{
104122f70c32Sdrh               pExpr = pRight;
10426977fea8Sdrh               pExpr->span = pExpr->token;
104322f70c32Sdrh             }
10444adee20fSdanielk1977             pNew = sqlite3ExprListAppend(pNew, pExpr, 0);
1045d8bc7086Sdrh           }
1046d8bc7086Sdrh         }
104754473229Sdrh         if( !tableSeen ){
1048cf55b7aeSdrh           if( zTName ){
1049cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1050f5db2d3eSdrh           }else{
10514adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1052f5db2d3eSdrh           }
105354473229Sdrh           rc = 1;
105454473229Sdrh         }
1055cf55b7aeSdrh         sqliteFree(zTName);
10567c917d19Sdrh       }
10577c917d19Sdrh     }
10584adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
10597c917d19Sdrh     p->pEList = pNew;
1060d8bc7086Sdrh   }
106154473229Sdrh   return rc;
1062d8bc7086Sdrh }
1063d8bc7086Sdrh 
1064d8bc7086Sdrh /*
1065ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1066ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1067ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1068ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1069ff78bd2fSdrh **
1070ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1071ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1072ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
10735cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
10745cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the
10755cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used.
1076ff78bd2fSdrh */
10774adee20fSdanielk1977 void sqlite3SelectUnbind(Select *p){
1078ff78bd2fSdrh   int i;
1079ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
108091bb0eedSdrh   struct SrcList_item *pItem;
1081ff78bd2fSdrh   Table *pTab;
1082ff78bd2fSdrh   if( p==0 ) return;
108391bb0eedSdrh   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
108491bb0eedSdrh     if( (pTab = pItem->pTab)!=0 ){
1085ff78bd2fSdrh       if( pTab->isTransient ){
10864adee20fSdanielk1977         sqlite3DeleteTable(0, pTab);
1087ff78bd2fSdrh       }
108891bb0eedSdrh       pItem->pTab = 0;
108991bb0eedSdrh       if( pItem->pSelect ){
109091bb0eedSdrh         sqlite3SelectUnbind(pItem->pSelect);
1091ff78bd2fSdrh       }
1092ff78bd2fSdrh     }
1093ff78bd2fSdrh   }
1094ff78bd2fSdrh }
1095ff78bd2fSdrh 
1096ff78bd2fSdrh /*
1097d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1098d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1099967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1100d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1101d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1102d8bc7086Sdrh **
1103d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1104d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1105d8bc7086Sdrh **
1106d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1107d8bc7086Sdrh ** of errors is returned.
1108d8bc7086Sdrh */
1109d8bc7086Sdrh static int matchOrderbyToColumn(
1110d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1111d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1112d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1113e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1114d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1115d8bc7086Sdrh ){
1116d8bc7086Sdrh   int nErr = 0;
1117d8bc7086Sdrh   int i, j;
1118d8bc7086Sdrh   ExprList *pEList;
1119d8bc7086Sdrh 
1120daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1121d8bc7086Sdrh   if( mustComplete ){
1122d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1123d8bc7086Sdrh   }
1124d8bc7086Sdrh   if( fillInColumnList(pParse, pSelect) ){
1125d8bc7086Sdrh     return 1;
1126d8bc7086Sdrh   }
1127d8bc7086Sdrh   if( pSelect->pPrior ){
112892cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
112992cd52f5Sdrh       return 1;
113092cd52f5Sdrh     }
1131d8bc7086Sdrh   }
1132d8bc7086Sdrh   pEList = pSelect->pEList;
1133d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1134d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1135e4de1febSdrh     int iCol = -1;
1136d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
11374adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1138e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
11394adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1140da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1141e4de1febSdrh           iCol, pEList->nExpr);
1142e4de1febSdrh         nErr++;
1143e4de1febSdrh         break;
1144e4de1febSdrh       }
1145fcb78a49Sdrh       if( !mustComplete ) continue;
1146e4de1febSdrh       iCol--;
1147e4de1febSdrh     }
1148e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
11494cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1150a76b5dfcSdrh         char *zName, *zLabel;
1151a76b5dfcSdrh         zName = pEList->a[j].zName;
1152a99db3b6Sdrh         zLabel = sqlite3NameFromToken(&pE->token);
1153a99db3b6Sdrh         assert( zLabel!=0 );
11544adee20fSdanielk1977         if( sqlite3StrICmp(zName, zLabel)==0 ){
1155e4de1febSdrh           iCol = j;
1156d8bc7086Sdrh         }
11576e142f54Sdrh         sqliteFree(zLabel);
1158d8bc7086Sdrh       }
11594adee20fSdanielk1977       if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
1160e4de1febSdrh         iCol = j;
1161d8bc7086Sdrh       }
1162e4de1febSdrh     }
1163e4de1febSdrh     if( iCol>=0 ){
1164967e8b73Sdrh       pE->op = TK_COLUMN;
1165e4de1febSdrh       pE->iColumn = iCol;
1166d8bc7086Sdrh       pE->iTable = iTable;
1167d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1168d8bc7086Sdrh     }
1169e4de1febSdrh     if( iCol<0 && mustComplete ){
11704adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1171da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1172d8bc7086Sdrh       nErr++;
1173d8bc7086Sdrh       break;
1174d8bc7086Sdrh     }
1175d8bc7086Sdrh   }
1176d8bc7086Sdrh   return nErr;
1177d8bc7086Sdrh }
1178d8bc7086Sdrh 
1179d8bc7086Sdrh /*
1180d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1181d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1182d8bc7086Sdrh */
11834adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1184d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1185d8bc7086Sdrh   if( v==0 ){
11864adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1187d8bc7086Sdrh   }
1188d8bc7086Sdrh   return v;
1189d8bc7086Sdrh }
1190d8bc7086Sdrh 
1191d8bc7086Sdrh /*
11927b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
11937b58daeaSdrh ** nLimit and nOffset fields.  nLimit and nOffset hold the integers
11947b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
11957b58daeaSdrh ** keywords.  Or that hold -1 and 0 if those keywords are omitted.
11967b58daeaSdrh ** iLimit and iOffset are the integer memory register numbers for
11977b58daeaSdrh ** counters used to compute the limit and offset.  If there is no
11987b58daeaSdrh ** limit and/or offset, then iLimit and iOffset are negative.
11997b58daeaSdrh **
12007b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if
12017b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset.  iLimit and
12027b58daeaSdrh ** iOffset should have been preset to appropriate default values
12037b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
12047b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get
12057b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
12067b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
12077b58daeaSdrh ** SELECT statements.
12087b58daeaSdrh */
12097b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){
12107b58daeaSdrh   /*
12117b58daeaSdrh   ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
12127b58daeaSdrh   ** all rows.  It is the same as no limit. If the comparision is
12137b58daeaSdrh   ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
12147b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
12157b58daeaSdrh   ** contraversy about what the correct behavior should be.
12167b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
12177b58daeaSdrh   ** no rows.
12187b58daeaSdrh   */
12197b58daeaSdrh   if( p->nLimit>=0 ){
12207b58daeaSdrh     int iMem = pParse->nMem++;
12214adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12227b58daeaSdrh     if( v==0 ) return;
12234adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0);
12244adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1225ad6d9460Sdrh     VdbeComment((v, "# LIMIT counter"));
12267b58daeaSdrh     p->iLimit = iMem;
12277b58daeaSdrh   }
12287b58daeaSdrh   if( p->nOffset>0 ){
12297b58daeaSdrh     int iMem = pParse->nMem++;
12304adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
12317b58daeaSdrh     if( v==0 ) return;
12324adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0);
12334adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1234ad6d9460Sdrh     VdbeComment((v, "# OFFSET counter"));
12357b58daeaSdrh     p->iOffset = iMem;
12367b58daeaSdrh   }
12377b58daeaSdrh }
12387b58daeaSdrh 
12397b58daeaSdrh /*
1240d3d39e93Sdrh ** Generate VDBE instructions that will open a transient table that
1241d3d39e93Sdrh ** will be used for an index or to store keyed results for a compound
1242d3d39e93Sdrh ** select.  In other words, open a transient table that needs a
1243d3d39e93Sdrh ** KeyInfo structure.  The number of columns in the KeyInfo is determined
1244d3d39e93Sdrh ** by the result set of the SELECT statement in the second argument.
1245d3d39e93Sdrh **
1246dc1bdc4fSdanielk1977 ** Specifically, this routine is called to open an index table for
1247dc1bdc4fSdanielk1977 ** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1248dc1bdc4fSdanielk1977 ** UNION ALL).
1249dc1bdc4fSdanielk1977 **
1250d3d39e93Sdrh ** Make the new table a KeyAsData table if keyAsData is true.
1251dc1bdc4fSdanielk1977 **
1252dc1bdc4fSdanielk1977 ** The value returned is the address of the OP_OpenTemp instruction.
1253d3d39e93Sdrh */
1254dc1bdc4fSdanielk1977 static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1255d3d39e93Sdrh   KeyInfo *pKeyInfo;
1256736c22b8Sdrh   int nColumn;
12579bb575fdSdrh   sqlite3 *db = pParse->db;
1258d3d39e93Sdrh   int i;
1259d3d39e93Sdrh   Vdbe *v = pParse->pVdbe;
1260dc1bdc4fSdanielk1977   int addr;
1261d3d39e93Sdrh 
1262736c22b8Sdrh   if( fillInColumnList(pParse, p) ){
1263dc1bdc4fSdanielk1977     return 0;
1264736c22b8Sdrh   }
1265736c22b8Sdrh   nColumn = p->pEList->nExpr;
1266d3d39e93Sdrh   pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1267dc1bdc4fSdanielk1977   if( pKeyInfo==0 ) return 0;
126891bb0eedSdrh   pKeyInfo->enc = db->enc;
1269d3d39e93Sdrh   pKeyInfo->nField = nColumn;
1270d3d39e93Sdrh   for(i=0; i<nColumn; i++){
1271dc1bdc4fSdanielk1977     pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1272dc1bdc4fSdanielk1977     if( !pKeyInfo->aColl[i] ){
1273d3d39e93Sdrh       pKeyInfo->aColl[i] = db->pDfltColl;
1274d3d39e93Sdrh     }
1275dc1bdc4fSdanielk1977   }
1276dc1bdc4fSdanielk1977   addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1277dc1bdc4fSdanielk1977       (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1278d3d39e93Sdrh   if( keyAsData ){
1279d3d39e93Sdrh     sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1280d3d39e93Sdrh   }
1281dc1bdc4fSdanielk1977   return addr;
1282dc1bdc4fSdanielk1977 }
1283dc1bdc4fSdanielk1977 
1284b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1285fbc4ee7bSdrh /*
12868cdbf836Sdrh ** Add the address "addr" to the set of all OpenTemp opcode addresses
12878cdbf836Sdrh ** that are being accumulated in p->ppOpenTemp.
1288fbc4ee7bSdrh */
12898cdbf836Sdrh static int multiSelectOpenTempAddr(Select *p, int addr){
12908cdbf836Sdrh   IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
1291fbc4ee7bSdrh   if( pList==0 ){
1292dc1bdc4fSdanielk1977     return SQLITE_NOMEM;
1293dc1bdc4fSdanielk1977   }
1294fbc4ee7bSdrh   pList->a[pList->nId-1].idx = addr;
1295dc1bdc4fSdanielk1977   return SQLITE_OK;
1296dc1bdc4fSdanielk1977 }
1297b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1298dc1bdc4fSdanielk1977 
1299b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1300fbc4ee7bSdrh /*
1301fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1302fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1303fbc4ee7bSdrh ** the column has no default collating sequence.
1304fbc4ee7bSdrh **
1305fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1306fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1307fbc4ee7bSdrh */
1308dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1309fbc4ee7bSdrh   CollSeq *pRet;
1310dc1bdc4fSdanielk1977   if( p->pPrior ){
1311dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1312fbc4ee7bSdrh   }else{
1313fbc4ee7bSdrh     pRet = 0;
1314dc1bdc4fSdanielk1977   }
1315fbc4ee7bSdrh   if( pRet==0 ){
1316dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1317dc1bdc4fSdanielk1977   }
1318dc1bdc4fSdanielk1977   return pRet;
1319d3d39e93Sdrh }
1320b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1321d3d39e93Sdrh 
1322b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1323d3d39e93Sdrh /*
132482c3d636Sdrh ** This routine is called to process a query that is really the union
132582c3d636Sdrh ** or intersection of two or more separate queries.
1326c926afbcSdrh **
1327e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1328e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1329e78e8284Sdrh ** in which case this routine will be called recursively.
1330e78e8284Sdrh **
1331e78e8284Sdrh ** The results of the total query are to be written into a destination
1332e78e8284Sdrh ** of type eDest with parameter iParm.
1333e78e8284Sdrh **
1334e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1335e78e8284Sdrh **
1336e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1337e78e8284Sdrh **
1338e78e8284Sdrh ** This statement is parsed up as follows:
1339e78e8284Sdrh **
1340e78e8284Sdrh **     SELECT c FROM t3
1341e78e8284Sdrh **      |
1342e78e8284Sdrh **      `----->  SELECT b FROM t2
1343e78e8284Sdrh **                |
13444b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1345e78e8284Sdrh **
1346e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1347e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1348e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1349e78e8284Sdrh **
1350e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1351e78e8284Sdrh ** individual selects always group from left to right.
135282c3d636Sdrh */
135384ac9d02Sdanielk1977 static int multiSelect(
1354fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1355fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1356fbc4ee7bSdrh   int eDest,            /* \___  Store query results as specified */
1357fbc4ee7bSdrh   int iParm,            /* /     by these two parameters.         */
135884ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
135984ac9d02Sdanielk1977 ){
136084ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
136110e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
136210e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
1363fbc4ee7bSdrh   IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
13648cdbf836Sdrh   int aAddr[5];         /* Addresses of SetNumColumns operators */
13658cdbf836Sdrh   int nAddr = 0;        /* Number used */
13668cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
136782c3d636Sdrh 
13687b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1369fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
137082c3d636Sdrh   */
137184ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
137284ac9d02Sdanielk1977     rc = 1;
137384ac9d02Sdanielk1977     goto multi_select_end;
137484ac9d02Sdanielk1977   }
1375d8bc7086Sdrh   pPrior = p->pPrior;
1376d8bc7086Sdrh   if( pPrior->pOrderBy ){
13774adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1378da93d238Sdrh       selectOpName(p->op));
137984ac9d02Sdanielk1977     rc = 1;
138084ac9d02Sdanielk1977     goto multi_select_end;
138182c3d636Sdrh   }
13827b58daeaSdrh   if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
13834adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
13847b58daeaSdrh       selectOpName(p->op));
138584ac9d02Sdanielk1977     rc = 1;
138684ac9d02Sdanielk1977     goto multi_select_end;
13877b58daeaSdrh   }
138882c3d636Sdrh 
1389d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1390d8bc7086Sdrh   */
13914adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
139284ac9d02Sdanielk1977   if( v==0 ){
139384ac9d02Sdanielk1977     rc = 1;
139484ac9d02Sdanielk1977     goto multi_select_end;
139584ac9d02Sdanielk1977   }
1396d8bc7086Sdrh 
13978cdbf836Sdrh   /* If *p this is the right-most select statement, then initialize
13988cdbf836Sdrh   ** p->ppOpenTemp to point to pOpenTemp.  If *p is not the right most
13998cdbf836Sdrh   ** statement then p->ppOpenTemp will have already been initialized
14008cdbf836Sdrh   ** by a prior call to this same procedure.  Pass along the pOpenTemp
14018cdbf836Sdrh   ** pointer to pPrior, the next statement to our left.
1402fbc4ee7bSdrh   */
1403fbc4ee7bSdrh   if( p->ppOpenTemp==0 ){
1404fbc4ee7bSdrh     p->ppOpenTemp = &pOpenTemp;
1405fbc4ee7bSdrh   }
1406fbc4ee7bSdrh   pPrior->ppOpenTemp = p->ppOpenTemp;
1407fbc4ee7bSdrh 
14081cc3d75fSdrh   /* Create the destination temporary table if necessary
14091cc3d75fSdrh   */
14101cc3d75fSdrh   if( eDest==SRT_TempTable ){
1411b4964b72Sdanielk1977     assert( p->pEList );
14124adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
14138cdbf836Sdrh     assert( nAddr==0 );
14148cdbf836Sdrh     aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
14151cc3d75fSdrh     eDest = SRT_Table;
14161cc3d75fSdrh   }
14171cc3d75fSdrh 
1418f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1419d8bc7086Sdrh   */
142082c3d636Sdrh   switch( p->op ){
1421f46f905aSdrh     case TK_ALL: {
1422f46f905aSdrh       if( p->pOrderBy==0 ){
14237b58daeaSdrh         pPrior->nLimit = p->nLimit;
14247b58daeaSdrh         pPrior->nOffset = p->nOffset;
142584ac9d02Sdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
142684ac9d02Sdanielk1977         if( rc ){
142784ac9d02Sdanielk1977           goto multi_select_end;
142884ac9d02Sdanielk1977         }
1429f46f905aSdrh         p->pPrior = 0;
14307b58daeaSdrh         p->iLimit = pPrior->iLimit;
14317b58daeaSdrh         p->iOffset = pPrior->iOffset;
14327b58daeaSdrh         p->nLimit = -1;
14337b58daeaSdrh         p->nOffset = 0;
143484ac9d02Sdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1435f46f905aSdrh         p->pPrior = pPrior;
143684ac9d02Sdanielk1977         if( rc ){
143784ac9d02Sdanielk1977           goto multi_select_end;
143884ac9d02Sdanielk1977         }
1439f46f905aSdrh         break;
1440f46f905aSdrh       }
1441f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1442f46f905aSdrh     }
144382c3d636Sdrh     case TK_EXCEPT:
144482c3d636Sdrh     case TK_UNION: {
1445d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1446742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1447d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
14487b58daeaSdrh       int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
1449c926afbcSdrh       ExprList *pOrderBy;  /* The ORDER BY clause for the right SELECT */
1450dc1bdc4fSdanielk1977       int addr;
145182c3d636Sdrh 
1452d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
14537b58daeaSdrh       if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
1454d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1455c926afbcSdrh         ** right.
1456d8bc7086Sdrh         */
145782c3d636Sdrh         unionTab = iParm;
145882c3d636Sdrh       }else{
1459d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1460d8bc7086Sdrh         ** intermediate results.
1461d8bc7086Sdrh         */
146282c3d636Sdrh         unionTab = pParse->nTab++;
1463d8bc7086Sdrh         if( p->pOrderBy
1464d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
146584ac9d02Sdanielk1977           rc = 1;
146684ac9d02Sdanielk1977           goto multi_select_end;
1467d8bc7086Sdrh         }
1468dc1bdc4fSdanielk1977         addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
1469d8bc7086Sdrh         if( p->op!=TK_ALL ){
14708cdbf836Sdrh           rc = multiSelectOpenTempAddr(p, addr);
1471dc1bdc4fSdanielk1977           if( rc!=SQLITE_OK ){
1472dc1bdc4fSdanielk1977             goto multi_select_end;
1473dc1bdc4fSdanielk1977           }
1474dc1bdc4fSdanielk1977           sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
147582c3d636Sdrh         }
14768cdbf836Sdrh 	assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
14778cdbf836Sdrh         aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
147884ac9d02Sdanielk1977         assert( p->pEList );
1479d8bc7086Sdrh       }
1480d8bc7086Sdrh 
1481d8bc7086Sdrh       /* Code the SELECT statements to our left
1482d8bc7086Sdrh       */
148384ac9d02Sdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
148484ac9d02Sdanielk1977       if( rc ){
148584ac9d02Sdanielk1977         goto multi_select_end;
148684ac9d02Sdanielk1977       }
1487d8bc7086Sdrh 
1488d8bc7086Sdrh       /* Code the current SELECT statement
1489d8bc7086Sdrh       */
1490d8bc7086Sdrh       switch( p->op ){
1491d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1492d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1493d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1494d8bc7086Sdrh       }
149582c3d636Sdrh       p->pPrior = 0;
1496c926afbcSdrh       pOrderBy = p->pOrderBy;
1497c926afbcSdrh       p->pOrderBy = 0;
14987b58daeaSdrh       nLimit = p->nLimit;
14997b58daeaSdrh       p->nLimit = -1;
15007b58daeaSdrh       nOffset = p->nOffset;
15017b58daeaSdrh       p->nOffset = 0;
150284ac9d02Sdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
150382c3d636Sdrh       p->pPrior = pPrior;
1504c926afbcSdrh       p->pOrderBy = pOrderBy;
15057b58daeaSdrh       p->nLimit = nLimit;
15067b58daeaSdrh       p->nOffset = nOffset;
1507be5fd490Sdrh       p->iLimit = -1;
1508be5fd490Sdrh       p->iOffset = -1;
150984ac9d02Sdanielk1977       if( rc ){
151084ac9d02Sdanielk1977         goto multi_select_end;
151184ac9d02Sdanielk1977       }
151284ac9d02Sdanielk1977 
1513d8bc7086Sdrh 
1514d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1515d8bc7086Sdrh       ** it is that we currently need.
1516d8bc7086Sdrh       */
1517c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
15186b56344dSdrh         int iCont, iBreak, iStart;
151982c3d636Sdrh         assert( p->pEList );
152041202ccaSdrh         if( eDest==SRT_Callback ){
15216a3ea0e6Sdrh           generateColumnNames(pParse, 0, p->pEList);
152241202ccaSdrh         }
15234adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
15244adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
15254adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
15267b58daeaSdrh         computeLimitRegisters(pParse, p);
15274adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
152838640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1529d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
153084ac9d02Sdanielk1977                              iCont, iBreak, 0);
153184ac9d02Sdanielk1977         if( rc ){
153284ac9d02Sdanielk1977           rc = 1;
153384ac9d02Sdanielk1977           goto multi_select_end;
153484ac9d02Sdanielk1977         }
15354adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
15364adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
15374adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
15384adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
153982c3d636Sdrh       }
154082c3d636Sdrh       break;
154182c3d636Sdrh     }
154282c3d636Sdrh     case TK_INTERSECT: {
154382c3d636Sdrh       int tab1, tab2;
15446b56344dSdrh       int iCont, iBreak, iStart;
15457b58daeaSdrh       int nLimit, nOffset;
1546dc1bdc4fSdanielk1977       int addr;
154782c3d636Sdrh 
1548d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
15496206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1550d8bc7086Sdrh       ** by allocating the tables we will need.
1551d8bc7086Sdrh       */
155282c3d636Sdrh       tab1 = pParse->nTab++;
155382c3d636Sdrh       tab2 = pParse->nTab++;
1554d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
155584ac9d02Sdanielk1977         rc = 1;
155684ac9d02Sdanielk1977         goto multi_select_end;
1557d8bc7086Sdrh       }
1558dc1bdc4fSdanielk1977 
1559dc1bdc4fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
15608cdbf836Sdrh       rc = multiSelectOpenTempAddr(p, addr);
1561dc1bdc4fSdanielk1977       if( rc!=SQLITE_OK ){
1562dc1bdc4fSdanielk1977         goto multi_select_end;
1563dc1bdc4fSdanielk1977       }
1564dc1bdc4fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
15658cdbf836Sdrh       assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
15668cdbf836Sdrh       aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
156784ac9d02Sdanielk1977       assert( p->pEList );
1568d8bc7086Sdrh 
1569d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1570d8bc7086Sdrh       */
157184ac9d02Sdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
157284ac9d02Sdanielk1977       if( rc ){
157384ac9d02Sdanielk1977         goto multi_select_end;
157484ac9d02Sdanielk1977       }
1575d8bc7086Sdrh 
1576d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1577d8bc7086Sdrh       */
1578dc1bdc4fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
15798cdbf836Sdrh       rc = multiSelectOpenTempAddr(p, addr);
1580dc1bdc4fSdanielk1977       if( rc!=SQLITE_OK ){
1581dc1bdc4fSdanielk1977         goto multi_select_end;
1582dc1bdc4fSdanielk1977       }
1583dc1bdc4fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
15848cdbf836Sdrh       assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
15858cdbf836Sdrh       aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
158682c3d636Sdrh       p->pPrior = 0;
15877b58daeaSdrh       nLimit = p->nLimit;
15887b58daeaSdrh       p->nLimit = -1;
15897b58daeaSdrh       nOffset = p->nOffset;
15907b58daeaSdrh       p->nOffset = 0;
159184ac9d02Sdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
159282c3d636Sdrh       p->pPrior = pPrior;
15937b58daeaSdrh       p->nLimit = nLimit;
15947b58daeaSdrh       p->nOffset = nOffset;
159584ac9d02Sdanielk1977       if( rc ){
159684ac9d02Sdanielk1977         goto multi_select_end;
159784ac9d02Sdanielk1977       }
1598d8bc7086Sdrh 
1599d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1600d8bc7086Sdrh       ** tables.
1601d8bc7086Sdrh       */
160282c3d636Sdrh       assert( p->pEList );
160341202ccaSdrh       if( eDest==SRT_Callback ){
16046a3ea0e6Sdrh         generateColumnNames(pParse, 0, p->pEList);
160541202ccaSdrh       }
16064adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
16074adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
16084adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
16097b58daeaSdrh       computeLimitRegisters(pParse, p);
16104adee20fSdanielk1977       iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
16114adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
161238640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1613d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
161484ac9d02Sdanielk1977                              iCont, iBreak, 0);
161584ac9d02Sdanielk1977       if( rc ){
161684ac9d02Sdanielk1977         rc = 1;
161784ac9d02Sdanielk1977         goto multi_select_end;
161884ac9d02Sdanielk1977       }
16194adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
16204adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
16214adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
16224adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
16234adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
162482c3d636Sdrh       break;
162582c3d636Sdrh     }
162682c3d636Sdrh   }
16278cdbf836Sdrh 
16288cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
16298cdbf836Sdrh   ** in their result sets.
16308cdbf836Sdrh   */
163182c3d636Sdrh   assert( p->pEList && pPrior->pEList );
163282c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
16334adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1634da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
163584ac9d02Sdanielk1977     rc = 1;
163684ac9d02Sdanielk1977     goto multi_select_end;
16372282792aSdrh   }
163884ac9d02Sdanielk1977 
16398cdbf836Sdrh   /* Set the number of columns in temporary tables
16408cdbf836Sdrh   */
16418cdbf836Sdrh   nCol = p->pEList->nExpr;
16428cdbf836Sdrh   while( nAddr>0 ){
16438cdbf836Sdrh     nAddr--;
16448cdbf836Sdrh     sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
16458cdbf836Sdrh   }
16468cdbf836Sdrh 
1647fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
1648fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
1649fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
1650fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
16518cdbf836Sdrh   **
16528cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
16538cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
16548cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
16558cdbf836Sdrh   ** no temp tables are required.
1656fbc4ee7bSdrh   */
1657dc1bdc4fSdanielk1977   if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
1658fbc4ee7bSdrh     int i;                        /* Loop counter */
1659fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
1660fbc4ee7bSdrh 
16618cdbf836Sdrh     assert( p->ppOpenTemp == &pOpenTemp );
1662fbc4ee7bSdrh     pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
1663dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1664dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1665dc1bdc4fSdanielk1977       goto multi_select_end;
1666dc1bdc4fSdanielk1977     }
1667dc1bdc4fSdanielk1977 
1668dc1bdc4fSdanielk1977     pKeyInfo->enc = pParse->db->enc;
1669dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
1670dc1bdc4fSdanielk1977 
1671dc1bdc4fSdanielk1977     for(i=0; i<nCol; i++){
1672dc1bdc4fSdanielk1977       pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1673dc1bdc4fSdanielk1977       if( !pKeyInfo->aColl[i] ){
1674dc1bdc4fSdanielk1977         pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1675dc1bdc4fSdanielk1977       }
1676dc1bdc4fSdanielk1977     }
1677dc1bdc4fSdanielk1977 
1678dc1bdc4fSdanielk1977     for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1679dc1bdc4fSdanielk1977       int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1680dc1bdc4fSdanielk1977       int addr = pOpenTemp->a[i].idx;
1681dc1bdc4fSdanielk1977       sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1682dc1bdc4fSdanielk1977     }
1683dc1bdc4fSdanielk1977 
1684dc1bdc4fSdanielk1977     if( p->pOrderBy ){
1685fbc4ee7bSdrh       struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1686fbc4ee7bSdrh       for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1687fbc4ee7bSdrh         Expr *pExpr = pOrderByTerm->pExpr;
1688fbc4ee7bSdrh         char *zName = pOrderByTerm->zName;
1689dc1bdc4fSdanielk1977         assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1690dc1bdc4fSdanielk1977         assert( !pExpr->pColl );
1691dc1bdc4fSdanielk1977         if( zName ){
1692dc1bdc4fSdanielk1977           pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
169384ac9d02Sdanielk1977         }else{
1694dc1bdc4fSdanielk1977           pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
169584ac9d02Sdanielk1977         }
169684ac9d02Sdanielk1977       }
1697dc1bdc4fSdanielk1977       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1698dc1bdc4fSdanielk1977     }
1699dc1bdc4fSdanielk1977 
1700dc1bdc4fSdanielk1977     if( !pOpenTemp ){
1701dc1bdc4fSdanielk1977       /* This happens for UNION ALL ... ORDER BY */
1702dc1bdc4fSdanielk1977       sqliteFree(pKeyInfo);
1703dc1bdc4fSdanielk1977     }
1704dc1bdc4fSdanielk1977   }
1705dc1bdc4fSdanielk1977 
1706dc1bdc4fSdanielk1977 multi_select_end:
1707dc1bdc4fSdanielk1977   if( pOpenTemp ){
1708dc1bdc4fSdanielk1977     sqlite3IdListDelete(pOpenTemp);
1709dc1bdc4fSdanielk1977   }
1710dc1bdc4fSdanielk1977   p->ppOpenTemp = 0;
171184ac9d02Sdanielk1977   return rc;
17122282792aSdrh }
1713b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
17142282792aSdrh 
1715b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
17162282792aSdrh /*
1717832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
17186a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
171984e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
17206a3ea0e6Sdrh ** unchanged.)
1721832508b7Sdrh **
1722832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1723832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1724832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1725832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1726832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1727832508b7Sdrh ** of the subquery rather the result set of the subquery.
1728832508b7Sdrh */
17296a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
17306a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1731832508b7Sdrh   if( pExpr==0 ) return;
173250350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
173350350a15Sdrh     if( pExpr->iColumn<0 ){
173450350a15Sdrh       pExpr->op = TK_NULL;
173550350a15Sdrh     }else{
1736832508b7Sdrh       Expr *pNew;
173784e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1738832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1739832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
1740832508b7Sdrh       assert( pNew!=0 );
1741832508b7Sdrh       pExpr->op = pNew->op;
1742d94a6698Sdrh       assert( pExpr->pLeft==0 );
17434adee20fSdanielk1977       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
1744d94a6698Sdrh       assert( pExpr->pRight==0 );
17454adee20fSdanielk1977       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
1746d94a6698Sdrh       assert( pExpr->pList==0 );
17474adee20fSdanielk1977       pExpr->pList = sqlite3ExprListDup(pNew->pList);
1748832508b7Sdrh       pExpr->iTable = pNew->iTable;
1749832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
1750832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
17514adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->token, &pNew->token);
17524adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->span, &pNew->span);
175350350a15Sdrh     }
1754832508b7Sdrh   }else{
17556a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
17566a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
17576a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
1758832508b7Sdrh   }
1759832508b7Sdrh }
1760832508b7Sdrh static void
17616a3ea0e6Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList){
1762832508b7Sdrh   int i;
1763832508b7Sdrh   if( pList==0 ) return;
1764832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
17656a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
1766832508b7Sdrh   }
1767832508b7Sdrh }
1768b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
1769832508b7Sdrh 
1770b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
1771832508b7Sdrh /*
17721350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
17731350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
17741350b030Sdrh ** occurs.
17751350b030Sdrh **
17761350b030Sdrh ** To understand the concept of flattening, consider the following
17771350b030Sdrh ** query:
17781350b030Sdrh **
17791350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
17801350b030Sdrh **
17811350b030Sdrh ** The default way of implementing this query is to execute the
17821350b030Sdrh ** subquery first and store the results in a temporary table, then
17831350b030Sdrh ** run the outer query on that temporary table.  This requires two
17841350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
17851350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1786832508b7Sdrh ** optimized.
17871350b030Sdrh **
1788832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
17891350b030Sdrh ** a single flat select, like this:
17901350b030Sdrh **
17911350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
17921350b030Sdrh **
17931350b030Sdrh ** The code generated for this simpification gives the same result
1794832508b7Sdrh ** but only has to scan the data once.  And because indices might
1795832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1796832508b7Sdrh ** avoided.
17971350b030Sdrh **
1798832508b7Sdrh ** Flattening is only attempted if all of the following are true:
17991350b030Sdrh **
1800832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
18011350b030Sdrh **
1802832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1803832508b7Sdrh **
18048af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
18058af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
1806832508b7Sdrh **
1807832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1808832508b7Sdrh **
1809832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1810832508b7Sdrh **        aggregates.
1811832508b7Sdrh **
1812832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1813832508b7Sdrh **        DISTINCT.
1814832508b7Sdrh **
181508192d5fSdrh **   (7)  The subquery has a FROM clause.
181608192d5fSdrh **
1817df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1818df199a25Sdrh **
1819df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1820df199a25Sdrh **        aggregates.
1821df199a25Sdrh **
1822df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1823df199a25Sdrh **        use LIMIT.
1824df199a25Sdrh **
1825174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1826174b6195Sdrh **
18273fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
18283fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
18293fc673e6Sdrh **
1830832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1831832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1832832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1833832508b7Sdrh **
1834665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
1835832508b7Sdrh ** If flattening is attempted this routine returns 1.
1836832508b7Sdrh **
1837832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1838832508b7Sdrh ** the subquery before this routine runs.
18391350b030Sdrh */
18408c74a8caSdrh static int flattenSubquery(
18418c74a8caSdrh   Parse *pParse,       /* The parsing context */
18428c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
18438c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
18448c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
18458c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
18468c74a8caSdrh ){
18470bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1848ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1849ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
18500bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
18516a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
185291bb0eedSdrh   int i;              /* Loop counter */
185391bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
185491bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
18551350b030Sdrh 
1856832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1857832508b7Sdrh   */
1858832508b7Sdrh   if( p==0 ) return 0;
1859832508b7Sdrh   pSrc = p->pSrc;
1860ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
186191bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
186291bb0eedSdrh   pSub = pSubitem->pSelect;
1863832508b7Sdrh   assert( pSub!=0 );
1864832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1865ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1866832508b7Sdrh   pSubSrc = pSub->pSrc;
1867832508b7Sdrh   assert( pSubSrc );
1868c31c2eb8Sdrh   if( pSubSrc->nSrc==0 ) return 0;
1869df199a25Sdrh   if( (pSub->isDistinct || pSub->nLimit>=0) &&  (pSrc->nSrc>1 || isAgg) ){
1870df199a25Sdrh      return 0;
1871df199a25Sdrh   }
1872d11d382cSdrh   if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
1873174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1874832508b7Sdrh 
18758af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
18768af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
18778af4d3acSdrh   ** is not allowed:
18788af4d3acSdrh   **
18798af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
18808af4d3acSdrh   **
18818af4d3acSdrh   ** If we flatten the above, we would get
18828af4d3acSdrh   **
18838af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
18848af4d3acSdrh   **
18858af4d3acSdrh   ** which is not at all the same thing.
18868af4d3acSdrh   */
18878af4d3acSdrh   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
18888af4d3acSdrh     return 0;
18898af4d3acSdrh   }
18908af4d3acSdrh 
18913fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
18923fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
18933fc673e6Sdrh   ** An examples of why this is not allowed:
18943fc673e6Sdrh   **
18953fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
18963fc673e6Sdrh   **
18973fc673e6Sdrh   ** If we flatten the above, we would get
18983fc673e6Sdrh   **
18993fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
19003fc673e6Sdrh   **
19013fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
19023fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
19033fc673e6Sdrh   */
19043fc673e6Sdrh   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
19053fc673e6Sdrh       && pSub->pWhere!=0 ){
19063fc673e6Sdrh     return 0;
19073fc673e6Sdrh   }
19083fc673e6Sdrh 
19090bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
191063eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
1911832508b7Sdrh   */
1912c31c2eb8Sdrh 
1913c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
1914c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
1915c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
1916c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
1917c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
1918c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
1919c31c2eb8Sdrh   ** elements we are now copying in.
1920c31c2eb8Sdrh   */
192191bb0eedSdrh   iParent = pSubitem->iCursor;
1922c31c2eb8Sdrh   {
1923c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
192491bb0eedSdrh     int jointype = pSubitem->jointype;
192591bb0eedSdrh     Table *pTab = pSubitem->pTab;
1926c31c2eb8Sdrh 
192791bb0eedSdrh     if( pTab && pTab->isTransient ){
192891bb0eedSdrh       sqlite3DeleteTable(0, pSubitem->pTab);
1929c31c2eb8Sdrh     }
193091bb0eedSdrh     sqliteFree(pSubitem->zDatabase);
193191bb0eedSdrh     sqliteFree(pSubitem->zName);
193291bb0eedSdrh     sqliteFree(pSubitem->zAlias);
1933c31c2eb8Sdrh     if( nSubSrc>1 ){
1934c31c2eb8Sdrh       int extra = nSubSrc - 1;
1935c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
19364adee20fSdanielk1977         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
1937c31c2eb8Sdrh       }
1938c31c2eb8Sdrh       p->pSrc = pSrc;
1939c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
1940c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
1941c31c2eb8Sdrh       }
1942c31c2eb8Sdrh     }
1943c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
1944c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
1945c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
1946c31c2eb8Sdrh     }
19478af4d3acSdrh     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
1948c31c2eb8Sdrh   }
1949c31c2eb8Sdrh 
1950c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
1951c31c2eb8Sdrh   ** references to the iParent in the outer query.
1952c31c2eb8Sdrh   **
1953c31c2eb8Sdrh   ** Example:
1954c31c2eb8Sdrh   **
1955c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
1956c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
1957c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
1958c31c2eb8Sdrh   **
1959c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
1960c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
1961c31c2eb8Sdrh   */
19626a3ea0e6Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
1963832508b7Sdrh   pList = p->pEList;
1964832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
19656977fea8Sdrh     Expr *pExpr;
19666977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
19676977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
1968832508b7Sdrh     }
1969832508b7Sdrh   }
19701b2e0329Sdrh   if( isAgg ){
19716a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
19726a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
19731b2e0329Sdrh   }
1974174b6195Sdrh   if( pSub->pOrderBy ){
1975174b6195Sdrh     assert( p->pOrderBy==0 );
1976174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
1977174b6195Sdrh     pSub->pOrderBy = 0;
1978174b6195Sdrh   }else if( p->pOrderBy ){
19796a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
1980174b6195Sdrh   }
1981832508b7Sdrh   if( pSub->pWhere ){
19824adee20fSdanielk1977     pWhere = sqlite3ExprDup(pSub->pWhere);
1983832508b7Sdrh   }else{
1984832508b7Sdrh     pWhere = 0;
1985832508b7Sdrh   }
1986832508b7Sdrh   if( subqueryIsAgg ){
1987832508b7Sdrh     assert( p->pHaving==0 );
19881b2e0329Sdrh     p->pHaving = p->pWhere;
19891b2e0329Sdrh     p->pWhere = pWhere;
19906a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
199191bb0eedSdrh     p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
19921b2e0329Sdrh     assert( p->pGroupBy==0 );
19934adee20fSdanielk1977     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
1994832508b7Sdrh   }else{
19956a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
199691bb0eedSdrh     p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
1997832508b7Sdrh   }
1998c31c2eb8Sdrh 
1999c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2000c31c2eb8Sdrh   ** outer query is distinct.
2001c31c2eb8Sdrh   */
2002832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
20038c74a8caSdrh 
2004c31c2eb8Sdrh   /* Transfer the limit expression from the subquery to the outer
2005c31c2eb8Sdrh   ** query.
2006c31c2eb8Sdrh   */
2007df199a25Sdrh   if( pSub->nLimit>=0 ){
2008df199a25Sdrh     if( p->nLimit<0 ){
2009df199a25Sdrh       p->nLimit = pSub->nLimit;
2010df199a25Sdrh     }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
2011df199a25Sdrh       p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
2012df199a25Sdrh     }
2013df199a25Sdrh   }
2014df199a25Sdrh   p->nOffset += pSub->nOffset;
20158c74a8caSdrh 
2016c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2017c31c2eb8Sdrh   ** success.
2018c31c2eb8Sdrh   */
20194adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2020832508b7Sdrh   return 1;
20211350b030Sdrh }
2022b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
20231350b030Sdrh 
20241350b030Sdrh /*
20259562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
20269562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
20279562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
2028e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
20299562b551Sdrh ** simple min() or max() query, then return 0;
20309562b551Sdrh **
20319562b551Sdrh ** A simply min() or max() query looks like this:
20329562b551Sdrh **
20339562b551Sdrh **    SELECT min(a) FROM table;
20349562b551Sdrh **    SELECT max(a) FROM table;
20359562b551Sdrh **
20369562b551Sdrh ** The query may have only a single table in its FROM argument.  There
20379562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
20389562b551Sdrh ** be the min() or max() of a single column of the table.  The column
20399562b551Sdrh ** in the min() or max() function must be indexed.
20409562b551Sdrh **
20414adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
20429562b551Sdrh ** See the header comment on that routine for additional information.
20439562b551Sdrh */
20449562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
20459562b551Sdrh   Expr *pExpr;
20469562b551Sdrh   int iCol;
20479562b551Sdrh   Table *pTab;
20489562b551Sdrh   Index *pIdx;
20499562b551Sdrh   int base;
20509562b551Sdrh   Vdbe *v;
20519562b551Sdrh   int seekOp;
20529562b551Sdrh   int cont;
20536e17529eSdrh   ExprList *pEList, *pList, eList;
20549562b551Sdrh   struct ExprList_item eListItem;
20556e17529eSdrh   SrcList *pSrc;
20566e17529eSdrh 
20579562b551Sdrh 
20589562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
20599562b551Sdrh   ** zero if it is  not.
20609562b551Sdrh   */
20619562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
20626e17529eSdrh   pSrc = p->pSrc;
20636e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
20646e17529eSdrh   pEList = p->pEList;
20656e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
20666e17529eSdrh   pExpr = pEList->a[0].pExpr;
20679562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
20686e17529eSdrh   pList = pExpr->pList;
20696e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
20706977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
20714adee20fSdanielk1977   if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
20720bce8354Sdrh     seekOp = OP_Rewind;
20734adee20fSdanielk1977   }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
20740bce8354Sdrh     seekOp = OP_Last;
20750bce8354Sdrh   }else{
20760bce8354Sdrh     return 0;
20770bce8354Sdrh   }
20786e17529eSdrh   pExpr = pList->a[0].pExpr;
20799562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
20809562b551Sdrh   iCol = pExpr->iColumn;
20816e17529eSdrh   pTab = pSrc->a[0].pTab;
20829562b551Sdrh 
20839562b551Sdrh   /* If we get to here, it means the query is of the correct form.
208417f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
208517f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
208617f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
208717f71934Sdrh   ** usable index is found, return 0.
20889562b551Sdrh   */
20899562b551Sdrh   if( iCol<0 ){
20909562b551Sdrh     pIdx = 0;
20919562b551Sdrh   }else{
2092dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
20939562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
20949562b551Sdrh       assert( pIdx->nColumn>=1 );
2095dc1bdc4fSdanielk1977       if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
20969562b551Sdrh     }
20979562b551Sdrh     if( pIdx==0 ) return 0;
20989562b551Sdrh   }
20999562b551Sdrh 
2100e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
21019562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2102e5f50722Sdrh   ** The column names have already been generated in the calling function.
21039562b551Sdrh   */
21044adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
21059562b551Sdrh   if( v==0 ) return 0;
21069562b551Sdrh 
21070c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
21080c37e630Sdrh   */
21090c37e630Sdrh   if( eDest==SRT_TempTable ){
21104adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2111b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
21120c37e630Sdrh   }
21130c37e630Sdrh 
211417f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
211517f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
211617f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
211717f71934Sdrh   ** or last entry in the main table.
21189562b551Sdrh   */
21194adee20fSdanielk1977   sqlite3CodeVerifySchema(pParse, pTab->iDb);
21206e17529eSdrh   base = pSrc->a[0].iCursor;
21217b58daeaSdrh   computeLimitRegisters(pParse, p);
21226e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
2123ad6d9460Sdrh     sqlite3OpenTableForReading(v, base, pTab);
21246e17529eSdrh   }
21254adee20fSdanielk1977   cont = sqlite3VdbeMakeLabel(v);
21269562b551Sdrh   if( pIdx==0 ){
21274adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
21289562b551Sdrh   }else{
21294adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
2130d3d39e93Sdrh     sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum,
2131d3d39e93Sdrh                    (char*)&pIdx->keyInfo, P3_KEYINFO);
21329eb516c0Sdrh     if( seekOp==OP_Rewind ){
21331af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_String, 0, 0);
21341af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
21351af3fdb4Sdrh       seekOp = OP_MoveGt;
21369eb516c0Sdrh     }
21371af3fdb4Sdrh     sqlite3VdbeAddOp(v, seekOp, base+1, 0);
21384adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0);
21394adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Close, base+1, 0);
21407cf6e4deSdrh     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
21419562b551Sdrh   }
21425cf8e8c7Sdrh   eList.nExpr = 1;
21435cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
21445cf8e8c7Sdrh   eList.a = &eListItem;
21455cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
214684ac9d02Sdanielk1977   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
21474adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, cont);
21484adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
21496e17529eSdrh 
21509562b551Sdrh   return 1;
21519562b551Sdrh }
21529562b551Sdrh 
21539562b551Sdrh /*
2154290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
2155290c1948Sdrh ** the number of errors seen.
2156290c1948Sdrh **
2157290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions.  If any expression
2158290c1948Sdrh ** is an integer constant, then that expression is replaced by the
2159290c1948Sdrh ** corresponding entry in the result set.
2160290c1948Sdrh */
2161290c1948Sdrh static int processOrderGroupBy(
2162290c1948Sdrh   Parse *pParse,        /* Parsing context */
2163290c1948Sdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
2164290c1948Sdrh   SrcList *pTabList,    /* The FROM clause */
2165290c1948Sdrh   ExprList *pEList,     /* The result set */
2166290c1948Sdrh   int isAgg,            /* True if aggregate functions are involved */
2167290c1948Sdrh   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
2168290c1948Sdrh ){
2169290c1948Sdrh   int i;
2170290c1948Sdrh   if( pOrderBy==0 ) return 0;
2171290c1948Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
2172290c1948Sdrh     int iCol;
2173290c1948Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
2174290c1948Sdrh     if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
2175290c1948Sdrh       sqlite3ExprDelete(pE);
2176290c1948Sdrh       pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2177290c1948Sdrh     }
2178290c1948Sdrh     if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList, pE, isAgg, 0) ){
2179290c1948Sdrh       return 1;
2180290c1948Sdrh     }
2181290c1948Sdrh     if( sqlite3ExprIsConstant(pE) ){
2182290c1948Sdrh       if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
2183290c1948Sdrh         sqlite3ErrorMsg(pParse,
2184290c1948Sdrh           "%s BY terms must not be non-integer constants", zType);
2185290c1948Sdrh         return 1;
2186290c1948Sdrh       }else if( iCol<=0 || iCol>pEList->nExpr ){
2187290c1948Sdrh         sqlite3ErrorMsg(pParse,
2188290c1948Sdrh            "%s BY column number %d out of range - should be "
2189290c1948Sdrh            "between 1 and %d", zType, iCol, pEList->nExpr);
2190290c1948Sdrh         return 1;
2191290c1948Sdrh       }
2192290c1948Sdrh     }
2193290c1948Sdrh   }
2194290c1948Sdrh   return 0;
2195290c1948Sdrh }
2196290c1948Sdrh 
2197290c1948Sdrh /*
21989bb61fe7Sdrh ** Generate code for the given SELECT statement.
21999bb61fe7Sdrh **
2200fef5208cSdrh ** The results are distributed in various ways depending on the
2201fef5208cSdrh ** value of eDest and iParm.
2202fef5208cSdrh **
2203fef5208cSdrh **     eDest Value       Result
2204fef5208cSdrh **     ------------    -------------------------------------------
2205fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2206fef5208cSdrh **
2207fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
2208fef5208cSdrh **
2209e014a838Sdanielk1977 **     SRT_Set         Store results as keys of table iParm.
2210fef5208cSdrh **
221182c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
221282c3d636Sdrh **
22134b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
2214c4a3c779Sdrh **
2215c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
22169bb61fe7Sdrh **
2217e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
2218e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
2219e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
2220e78e8284Sdrh **
22219bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
22229bb61fe7Sdrh ** encountered, then an appropriate error message is left in
22239bb61fe7Sdrh ** pParse->zErrMsg.
22249bb61fe7Sdrh **
22259bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
22269bb61fe7Sdrh ** calling function needs to do that.
22271b2e0329Sdrh **
22281b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
22291b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
22301b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
22311b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
22321b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
22331b2e0329Sdrh ** can be changed.
2234e78e8284Sdrh **
2235e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
2236e78e8284Sdrh **
2237e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2238e78e8284Sdrh **    \                      \_______ subquery _______/        /
2239e78e8284Sdrh **     \                                                      /
2240e78e8284Sdrh **      \____________________ outer query ___________________/
2241e78e8284Sdrh **
2242e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
2243e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
2244e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
2245e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
2246e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
2247e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
22489bb61fe7Sdrh */
22494adee20fSdanielk1977 int sqlite3Select(
2250cce7d176Sdrh   Parse *pParse,         /* The parser context */
22519bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
2252e78e8284Sdrh   int eDest,             /* How to dispose of the results */
2253e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
2254832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
2255832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
225684ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
225784ac9d02Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
2258cce7d176Sdrh ){
2259d8bc7086Sdrh   int i;
2260cce7d176Sdrh   WhereInfo *pWInfo;
2261cce7d176Sdrh   Vdbe *v;
2262cce7d176Sdrh   int isAgg = 0;         /* True for select lists like "count(*)" */
2263a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2264ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
22659bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
22669bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
22672282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
22682282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
226919a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
227019a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
22711d83f052Sdrh   int rc = 1;            /* Value to return from this function */
22729bb61fe7Sdrh 
22736f8a503dSdanielk1977   if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
22744adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2275daffd0e5Sdrh 
2276b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
227782c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
227882c3d636Sdrh   */
227982c3d636Sdrh   if( p->pPrior ){
2280b6c29897Sdrh #ifndef SQLITE_OMIT_CURSOR
2281b6c29897Sdrh     if( p->pFetch ){
2282b6c29897Sdrh       sqlite3ErrorMsg(pParse, "cursors cannot be used on compound queries");
2283b6c29897Sdrh       goto select_end;
2284b6c29897Sdrh     }
2285b6c29897Sdrh #endif
228684ac9d02Sdanielk1977     return multiSelect(pParse, p, eDest, iParm, aff);
228782c3d636Sdrh   }
2288b7f9164eSdrh #endif
228982c3d636Sdrh 
229082c3d636Sdrh   /* Make local copies of the parameters for this query.
229182c3d636Sdrh   */
22929bb61fe7Sdrh   pTabList = p->pSrc;
22939bb61fe7Sdrh   pWhere = p->pWhere;
22949bb61fe7Sdrh   pOrderBy = p->pOrderBy;
22952282792aSdrh   pGroupBy = p->pGroupBy;
22962282792aSdrh   pHaving = p->pHaving;
229719a775c2Sdrh   isDistinct = p->isDistinct;
22989bb61fe7Sdrh 
22996a3ea0e6Sdrh   /* Allocate VDBE cursors for each table in the FROM clause
230010e5e3cfSdrh   */
23014adee20fSdanielk1977   sqlite3SrcListAssignCursors(pParse, pTabList);
230210e5e3cfSdrh 
23039bb61fe7Sdrh   /*
23049bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
23059bb61fe7Sdrh   ** errors before this routine starts.
23069bb61fe7Sdrh   */
23071d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2308cce7d176Sdrh 
2309e78e8284Sdrh   /* Expand any "*" terms in the result set.  (For example the "*" in
2310e78e8284Sdrh   ** "SELECT * FROM t1")  The fillInColumnlist() routine also does some
2311e78e8284Sdrh   ** other housekeeping - see the header comment for details.
2312cce7d176Sdrh   */
2313d8bc7086Sdrh   if( fillInColumnList(pParse, p) ){
23141d83f052Sdrh     goto select_end;
2315cce7d176Sdrh   }
2316ad2d8307Sdrh   pWhere = p->pWhere;
2317d8bc7086Sdrh   pEList = p->pEList;
23181d83f052Sdrh   if( pEList==0 ) goto select_end;
2319cce7d176Sdrh 
23202282792aSdrh   /* If writing to memory or generating a set
23212282792aSdrh   ** only a single column may be output.
232219a775c2Sdrh   */
2323fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
23244adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "only a single result allowed for "
2325da93d238Sdrh        "a SELECT that is part of an expression");
23261d83f052Sdrh     goto select_end;
232719a775c2Sdrh   }
232819a775c2Sdrh 
2329c926afbcSdrh   /* ORDER BY is ignored for some destinations.
23302282792aSdrh   */
2331c926afbcSdrh   switch( eDest ){
2332c926afbcSdrh     case SRT_Union:
2333c926afbcSdrh     case SRT_Except:
2334c926afbcSdrh     case SRT_Discard:
2335acd4c695Sdrh       pOrderBy = 0;
2336c926afbcSdrh       break;
2337c926afbcSdrh     default:
2338c926afbcSdrh       break;
23392282792aSdrh   }
23402282792aSdrh 
234110e5e3cfSdrh   /* At this point, we should have allocated all the cursors that we
2342832508b7Sdrh   ** need to handle subquerys and temporary tables.
234310e5e3cfSdrh   **
2344967e8b73Sdrh   ** Resolve the column names and do a semantics check on all the expressions.
23452282792aSdrh   */
23464794b980Sdrh   for(i=0; i<pEList->nExpr; i++){
2347290c1948Sdrh     if( sqlite3ExprResolveAndCheck(pParse, pTabList, 0, pEList->a[i].pExpr,
2348290c1948Sdrh                                     1, &isAgg) ){
23491d83f052Sdrh       goto select_end;
2350cce7d176Sdrh     }
2351cce7d176Sdrh   }
2352290c1948Sdrh   if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList, pWhere, 0, 0) ){
23531d83f052Sdrh     goto select_end;
2354cce7d176Sdrh   }
2355c66c5a26Sdrh   if( pHaving ){
2356c66c5a26Sdrh     if( pGroupBy==0 ){
23574adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2358c66c5a26Sdrh       goto select_end;
2359c66c5a26Sdrh     }
2360290c1948Sdrh     if( sqlite3ExprResolveAndCheck(pParse, pTabList, pEList,pHaving,1,&isAgg) ){
2361c66c5a26Sdrh       goto select_end;
2362c66c5a26Sdrh     }
2363c66c5a26Sdrh   }
2364290c1948Sdrh   if( processOrderGroupBy(pParse, pOrderBy, pTabList, pEList, isAgg, "ORDER")
2365290c1948Sdrh    || processOrderGroupBy(pParse, pGroupBy, pTabList, pEList, isAgg, "GROUP")
2366290c1948Sdrh   ){
236788eee38aSdrh     goto select_end;
236888eee38aSdrh   }
2369cce7d176Sdrh 
2370b6c29897Sdrh   /* We cannot use a SQL cursor on a join or on a DISTINCT query
2371b6c29897Sdrh   */
2372b6c29897Sdrh #ifndef SQLITE_OMIT_CURSOR
2373b6c29897Sdrh   if( p->pFetch ){
2374b6c29897Sdrh     if( p->isDistinct ){
2375b6c29897Sdrh       sqlite3ErrorMsg(pParse, "cursors cannot be used on DISTINCT queries");
2376b6c29897Sdrh       goto select_end;
2377b6c29897Sdrh     }
2378b6c29897Sdrh     if( pTabList->nSrc>0 ){
2379b6c29897Sdrh       sqlite3ErrorMsg(pParse, "cursors cannot be used on joins");
2380b6c29897Sdrh       goto select_end;
2381b6c29897Sdrh     }
2382b6c29897Sdrh     if( pTabList->a[0].pSelect ){
2383b6c29897Sdrh       sqlite3ErrorMsg(pParse, "cursor cannot be used with nested queries "
2384b6c29897Sdrh           "or views");
2385b6c29897Sdrh       goto select_end;
2386b6c29897Sdrh     }
2387b6c29897Sdrh   }
2388b6c29897Sdrh #endif
2389b6c29897Sdrh 
2390d820cb1bSdrh   /* Begin generating code.
2391d820cb1bSdrh   */
23924adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2393d820cb1bSdrh   if( v==0 ) goto select_end;
2394d820cb1bSdrh 
2395e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2396e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
23970bb28106Sdrh   */
23980bb28106Sdrh   if( eDest==SRT_Callback ){
23996a3ea0e6Sdrh     generateColumnNames(pParse, pTabList, pEList);
24000bb28106Sdrh   }
24010bb28106Sdrh 
2402d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2403d820cb1bSdrh   */
2404ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
2405742f947bSdanielk1977     const char *zSavedAuthContext = 0;
2406c31c2eb8Sdrh     int needRestoreContext;
2407c31c2eb8Sdrh 
2408a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
24095cf590c1Sdrh     if( pTabList->a[i].zName!=0 ){
24105cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
24115cf590c1Sdrh       pParse->zAuthContext = pTabList->a[i].zName;
2412c31c2eb8Sdrh       needRestoreContext = 1;
2413c31c2eb8Sdrh     }else{
2414c31c2eb8Sdrh       needRestoreContext = 0;
24155cf590c1Sdrh     }
24164adee20fSdanielk1977     sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
241784ac9d02Sdanielk1977                  pTabList->a[i].iCursor, p, i, &isAgg, 0);
2418c31c2eb8Sdrh     if( needRestoreContext ){
24195cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
24205cf590c1Sdrh     }
2421832508b7Sdrh     pTabList = p->pSrc;
2422832508b7Sdrh     pWhere = p->pWhere;
2423c31c2eb8Sdrh     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2424832508b7Sdrh       pOrderBy = p->pOrderBy;
2425acd4c695Sdrh     }
2426832508b7Sdrh     pGroupBy = p->pGroupBy;
2427832508b7Sdrh     pHaving = p->pHaving;
2428832508b7Sdrh     isDistinct = p->isDistinct;
24291b2e0329Sdrh   }
24301b2e0329Sdrh 
24316e17529eSdrh   /* Check for the special case of a min() or max() function by itself
24326e17529eSdrh   ** in the result set.
24336e17529eSdrh   */
24346e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
24356e17529eSdrh     rc = 0;
24366e17529eSdrh     goto select_end;
24376e17529eSdrh   }
24386e17529eSdrh 
24391b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
24401b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
24411b2e0329Sdrh   */
2442b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
24431b2e0329Sdrh   if( pParent && pParentAgg &&
24448c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
24451b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
24461b2e0329Sdrh     return rc;
24471b2e0329Sdrh   }
2448b7f9164eSdrh #endif
2449832508b7Sdrh 
24507cedc8d4Sdanielk1977   /* If there is an ORDER BY clause, resolve any collation sequences
24517cedc8d4Sdanielk1977   ** names that have been explicitly specified.
24527cedc8d4Sdanielk1977   */
24537cedc8d4Sdanielk1977   if( pOrderBy ){
24547cedc8d4Sdanielk1977     for(i=0; i<pOrderBy->nExpr; i++){
24557cedc8d4Sdanielk1977       if( pOrderBy->a[i].zName ){
24567cedc8d4Sdanielk1977         pOrderBy->a[i].pExpr->pColl =
24577cedc8d4Sdanielk1977             sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
24587cedc8d4Sdanielk1977       }
24597cedc8d4Sdanielk1977     }
24607cedc8d4Sdanielk1977     if( pParse->nErr ){
24617cedc8d4Sdanielk1977       goto select_end;
24627cedc8d4Sdanielk1977     }
24637cedc8d4Sdanielk1977   }
24647cedc8d4Sdanielk1977 
24657b58daeaSdrh   /* Set the limiter.
24667b58daeaSdrh   */
24677b58daeaSdrh   computeLimitRegisters(pParse, p);
24687b58daeaSdrh 
24692d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
24702d0794e3Sdrh   */
24712d0794e3Sdrh   if( eDest==SRT_TempTable ){
24724adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2473b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
24742d0794e3Sdrh   }
24752d0794e3Sdrh 
24762282792aSdrh   /* Do an analysis of aggregate expressions.
2477efb7251dSdrh   */
2478d820cb1bSdrh   sqliteAggregateInfoReset(pParse);
2479bb999ef6Sdrh   if( isAgg || pGroupBy ){
24800bce8354Sdrh     assert( pParse->nAgg==0 );
2481bb999ef6Sdrh     isAgg = 1;
24822282792aSdrh     for(i=0; i<pEList->nExpr; i++){
24834adee20fSdanielk1977       if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
24841d83f052Sdrh         goto select_end;
24852282792aSdrh       }
24862282792aSdrh     }
24872282792aSdrh     if( pGroupBy ){
24882282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
24894adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
24901d83f052Sdrh           goto select_end;
24912282792aSdrh         }
24922282792aSdrh       }
24932282792aSdrh     }
24944adee20fSdanielk1977     if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){
24951d83f052Sdrh       goto select_end;
24962282792aSdrh     }
2497191b690eSdrh     if( pOrderBy ){
2498191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
24994adee20fSdanielk1977         if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
25001d83f052Sdrh           goto select_end;
2501191b690eSdrh         }
2502191b690eSdrh       }
2503191b690eSdrh     }
2504efb7251dSdrh   }
2505efb7251dSdrh 
25062282792aSdrh   /* Reset the aggregator
2507cce7d176Sdrh   */
2508cce7d176Sdrh   if( isAgg ){
2509e159fdf2Sdanielk1977     int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
2510e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
25110bce8354Sdrh       FuncDef *pFunc;
25120bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
2513f9b596ebSdrh         sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
2514e5095355Sdrh       }
2515e5095355Sdrh     }
2516e159fdf2Sdanielk1977     if( pGroupBy ){
2517ce2663ccSdanielk1977       int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2518ce2663ccSdanielk1977       KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2519ce2663ccSdanielk1977       if( 0==pKey ){
2520ce2663ccSdanielk1977         goto select_end;
2521ce2663ccSdanielk1977       }
2522ce2663ccSdanielk1977       pKey->enc = pParse->db->enc;
2523ce2663ccSdanielk1977       pKey->nField = pGroupBy->nExpr;
2524ce2663ccSdanielk1977       for(i=0; i<pGroupBy->nExpr; i++){
2525ce2663ccSdanielk1977         pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2526ce2663ccSdanielk1977         if( !pKey->aColl[i] ){
2527ce2663ccSdanielk1977           pKey->aColl[i] = pParse->db->pDfltColl;
2528ce2663ccSdanielk1977         }
2529ce2663ccSdanielk1977       }
2530ce2663ccSdanielk1977       sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
25311bee3d7bSdrh     }
2532cce7d176Sdrh   }
2533cce7d176Sdrh 
253419a775c2Sdrh   /* Initialize the memory cell to NULL
253519a775c2Sdrh   */
2536fef5208cSdrh   if( eDest==SRT_Mem ){
25370f69c1e3Sdanielk1977     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
25384adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
253919a775c2Sdrh   }
254019a775c2Sdrh 
2541832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2542cce7d176Sdrh   */
254319a775c2Sdrh   if( isDistinct ){
2544832508b7Sdrh     distinct = pParse->nTab++;
2545d3d39e93Sdrh     openTempIndex(pParse, p, distinct, 0);
2546832508b7Sdrh   }else{
2547832508b7Sdrh     distinct = -1;
2548efb7251dSdrh   }
2549832508b7Sdrh 
2550832508b7Sdrh   /* Begin the database scan
2551832508b7Sdrh   */
2552*e6f85e71Sdrh   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
2553e4e72072Sdrh                              pGroupBy ? 0 : &pOrderBy, p->pFetch);
25541d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2555cce7d176Sdrh 
25562282792aSdrh   /* Use the standard inner loop if we are not dealing with
25572282792aSdrh   ** aggregates
2558cce7d176Sdrh   */
2559da9d6c45Sdrh   if( !isAgg ){
2560df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
256184ac9d02Sdanielk1977                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
25621d83f052Sdrh        goto select_end;
2563cce7d176Sdrh     }
2564da9d6c45Sdrh   }
2565cce7d176Sdrh 
2566e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
25672282792aSdrh   ** processing.
2568efb7251dSdrh   */
25692282792aSdrh   else{
2570268380caSdrh     AggExpr *pAgg;
25712282792aSdrh     if( pGroupBy ){
25721bee3d7bSdrh       int lbl1;
25732282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
25744adee20fSdanielk1977         sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
2575efb7251dSdrh       }
2576ededfd5eSdanielk1977       /* No affinity string is attached to the following OP_MakeRecord
2577d3d39e93Sdrh       ** because we do not need to do any coercion of datatypes. */
2578ededfd5eSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
25794adee20fSdanielk1977       lbl1 = sqlite3VdbeMakeLabel(v);
25804adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
2581268380caSdrh       for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2582268380caSdrh         if( pAgg->isAgg ) continue;
25834adee20fSdanielk1977         sqlite3ExprCode(pParse, pAgg->pExpr);
25844adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
25852282792aSdrh       }
25864adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, lbl1);
25872282792aSdrh     }
2588268380caSdrh     for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
25892282792aSdrh       Expr *pE;
2590268380caSdrh       int nExpr;
2591268380caSdrh       FuncDef *pDef;
2592268380caSdrh       if( !pAgg->isAgg ) continue;
2593268380caSdrh       assert( pAgg->pFunc!=0 );
2594268380caSdrh       assert( pAgg->pFunc->xStep!=0 );
2595268380caSdrh       pDef = pAgg->pFunc;
2596268380caSdrh       pE = pAgg->pExpr;
2597268380caSdrh       assert( pE!=0 );
25982282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
2599f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
26004adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2601dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
2602dc1bdc4fSdanielk1977         CollSeq *pColl = 0;
2603dc1bdc4fSdanielk1977         int j;
2604dc1bdc4fSdanielk1977         for(j=0; !pColl && j<nExpr; j++){
2605dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2606dc1bdc4fSdanielk1977         }
2607dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
2608dc1bdc4fSdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2609dc1bdc4fSdanielk1977       }
26104adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
26112282792aSdrh     }
26122282792aSdrh   }
26132282792aSdrh 
2614cce7d176Sdrh   /* End the database scan loop.
2615cce7d176Sdrh   */
26164adee20fSdanielk1977   sqlite3WhereEnd(pWInfo);
2617cce7d176Sdrh 
26182282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
26192282792aSdrh   ** over all of the aggregate values and process them.
26202282792aSdrh   */
26212282792aSdrh   if( isAgg ){
26224adee20fSdanielk1977     int endagg = sqlite3VdbeMakeLabel(v);
26232282792aSdrh     int startagg;
26244adee20fSdanielk1977     startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
26252282792aSdrh     pParse->useAgg = 1;
26262282792aSdrh     if( pHaving ){
26274adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
26282282792aSdrh     }
2629df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
263084ac9d02Sdanielk1977                     iParm, startagg, endagg, aff) ){
26311d83f052Sdrh       goto select_end;
26322282792aSdrh     }
26334adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
26344adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, endagg);
26354adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
26362282792aSdrh     pParse->useAgg = 0;
26372282792aSdrh   }
26382282792aSdrh 
2639cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2640cce7d176Sdrh   ** and send them to the callback one by one.
2641cce7d176Sdrh   */
2642cce7d176Sdrh   if( pOrderBy ){
2643ffbc3088Sdrh     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
2644cce7d176Sdrh   }
26456a535340Sdrh 
2646f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
2647f620b4e2Sdrh   ** temporary table.  So delete the subquery structure from the parent
2648f620b4e2Sdrh   ** to prevent this subquery from being evaluated again and to force the
2649f620b4e2Sdrh   ** the use of the temporary table.
2650f620b4e2Sdrh   */
2651f620b4e2Sdrh   if( pParent ){
2652f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
2653f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
26544adee20fSdanielk1977     sqlite3SelectDelete(p);
2655f620b4e2Sdrh     pParent->pSrc->a[parentTab].pSelect = 0;
2656f620b4e2Sdrh   }
2657f620b4e2Sdrh 
26581d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
26591d83f052Sdrh   ** to indicate no errors.
26601d83f052Sdrh   */
26611d83f052Sdrh   rc = 0;
26621d83f052Sdrh 
26631d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
26641d83f052Sdrh   ** successful coding of the SELECT.
26651d83f052Sdrh   */
26661d83f052Sdrh select_end:
26671d83f052Sdrh   sqliteAggregateInfoReset(pParse);
26681d83f052Sdrh   return rc;
2669cce7d176Sdrh }
2670