xref: /sqlite-3.40.0/src/select.c (revision dd5b2fa5)
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*dd5b2fa5Sdrh ** $Id: select.c,v 1.243 2005/03/28 03:39:56 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 */
32a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
33a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
349bb61fe7Sdrh ){
359bb61fe7Sdrh   Select *pNew;
369bb61fe7Sdrh   pNew = sqliteMalloc( sizeof(*pNew) );
37a2dc3b1aSdanielk1977   assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
38daffd0e5Sdrh   if( pNew==0 ){
394adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
404adee20fSdanielk1977     sqlite3SrcListDelete(pSrc);
414adee20fSdanielk1977     sqlite3ExprDelete(pWhere);
424adee20fSdanielk1977     sqlite3ExprListDelete(pGroupBy);
434adee20fSdanielk1977     sqlite3ExprDelete(pHaving);
444adee20fSdanielk1977     sqlite3ExprListDelete(pOrderBy);
45a2dc3b1aSdanielk1977     sqlite3ExprDelete(pLimit);
46a2dc3b1aSdanielk1977     sqlite3ExprDelete(pOffset);
47daffd0e5Sdrh   }else{
48b733d037Sdrh     if( pEList==0 ){
494adee20fSdanielk1977       pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0);
50b733d037Sdrh     }
519bb61fe7Sdrh     pNew->pEList = pEList;
529bb61fe7Sdrh     pNew->pSrc = pSrc;
539bb61fe7Sdrh     pNew->pWhere = pWhere;
549bb61fe7Sdrh     pNew->pGroupBy = pGroupBy;
559bb61fe7Sdrh     pNew->pHaving = pHaving;
569bb61fe7Sdrh     pNew->pOrderBy = pOrderBy;
579bb61fe7Sdrh     pNew->isDistinct = isDistinct;
5882c3d636Sdrh     pNew->op = TK_SELECT;
59a2dc3b1aSdanielk1977     pNew->pLimit = pLimit;
60a2dc3b1aSdanielk1977     pNew->pOffset = pOffset;
617b58daeaSdrh     pNew->iLimit = -1;
627b58daeaSdrh     pNew->iOffset = -1;
63daffd0e5Sdrh   }
649bb61fe7Sdrh   return pNew;
659bb61fe7Sdrh }
669bb61fe7Sdrh 
679bb61fe7Sdrh /*
6801f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
6901f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
7001f3f253Sdrh ** in terms of the following bit values:
7101f3f253Sdrh **
7201f3f253Sdrh **     JT_INNER
7301f3f253Sdrh **     JT_OUTER
7401f3f253Sdrh **     JT_NATURAL
7501f3f253Sdrh **     JT_LEFT
7601f3f253Sdrh **     JT_RIGHT
7701f3f253Sdrh **
7801f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
7901f3f253Sdrh **
8001f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
8101f3f253Sdrh ** a join type, but put an error in the pParse structure.
8201f3f253Sdrh */
834adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
8401f3f253Sdrh   int jointype = 0;
8501f3f253Sdrh   Token *apAll[3];
8601f3f253Sdrh   Token *p;
875719628aSdrh   static const struct {
8801f3f253Sdrh     const char *zKeyword;
89290c1948Sdrh     u8 nChar;
90290c1948Sdrh     u8 code;
9101f3f253Sdrh   } keywords[] = {
9201f3f253Sdrh     { "natural", 7, JT_NATURAL },
93195e6967Sdrh     { "left",    4, JT_LEFT|JT_OUTER },
94195e6967Sdrh     { "right",   5, JT_RIGHT|JT_OUTER },
95195e6967Sdrh     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
9601f3f253Sdrh     { "outer",   5, JT_OUTER },
9701f3f253Sdrh     { "inner",   5, JT_INNER },
9801f3f253Sdrh     { "cross",   5, JT_INNER },
9901f3f253Sdrh   };
10001f3f253Sdrh   int i, j;
10101f3f253Sdrh   apAll[0] = pA;
10201f3f253Sdrh   apAll[1] = pB;
10301f3f253Sdrh   apAll[2] = pC;
104195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
10501f3f253Sdrh     p = apAll[i];
10601f3f253Sdrh     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
10701f3f253Sdrh       if( p->n==keywords[j].nChar
1084adee20fSdanielk1977           && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
10901f3f253Sdrh         jointype |= keywords[j].code;
11001f3f253Sdrh         break;
11101f3f253Sdrh       }
11201f3f253Sdrh     }
11301f3f253Sdrh     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
11401f3f253Sdrh       jointype |= JT_ERROR;
11501f3f253Sdrh       break;
11601f3f253Sdrh     }
11701f3f253Sdrh   }
118ad2d8307Sdrh   if(
119ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
120195e6967Sdrh      (jointype & JT_ERROR)!=0
121ad2d8307Sdrh   ){
122ae29ffbeSdrh     const char *zSp1 = " ";
123ae29ffbeSdrh     const char *zSp2 = " ";
124ae29ffbeSdrh     if( pB==0 ){ zSp1++; }
125ae29ffbeSdrh     if( pC==0 ){ zSp2++; }
126ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
127ae29ffbeSdrh        "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
12801f3f253Sdrh     jointype = JT_INNER;
129195e6967Sdrh   }else if( jointype & JT_RIGHT ){
1304adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
131da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
132195e6967Sdrh     jointype = JT_INNER;
13301f3f253Sdrh   }
13401f3f253Sdrh   return jointype;
13501f3f253Sdrh }
13601f3f253Sdrh 
13701f3f253Sdrh /*
138ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
139ad2d8307Sdrh ** is not contained in the table.
140ad2d8307Sdrh */
141ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
142ad2d8307Sdrh   int i;
143ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1444adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
145ad2d8307Sdrh   }
146ad2d8307Sdrh   return -1;
147ad2d8307Sdrh }
148ad2d8307Sdrh 
149ad2d8307Sdrh /*
15091bb0eedSdrh ** Set the value of a token to a '\000'-terminated string.
15191bb0eedSdrh */
15291bb0eedSdrh static void setToken(Token *p, const char *z){
15391bb0eedSdrh   p->z = z;
15491bb0eedSdrh   p->n = strlen(z);
15591bb0eedSdrh   p->dyn = 0;
15691bb0eedSdrh }
15791bb0eedSdrh 
15891bb0eedSdrh 
15991bb0eedSdrh /*
160ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the
161ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2.
162ad2d8307Sdrh */
163ad2d8307Sdrh static void addWhereTerm(
164ad2d8307Sdrh   const char *zCol,        /* Name of the column */
165ad2d8307Sdrh   const Table *pTab1,      /* First table */
166030530deSdrh   const char *zAlias1,     /* Alias for first table.  May be NULL */
167ad2d8307Sdrh   const Table *pTab2,      /* Second table */
168030530deSdrh   const char *zAlias2,     /* Alias for second table.  May be NULL */
169ad2d8307Sdrh   Expr **ppExpr            /* Add the equality term to this expression */
170ad2d8307Sdrh ){
171ad2d8307Sdrh   Token dummy;
172ad2d8307Sdrh   Expr *pE1a, *pE1b, *pE1c;
173ad2d8307Sdrh   Expr *pE2a, *pE2b, *pE2c;
174ad2d8307Sdrh   Expr *pE;
175ad2d8307Sdrh 
17691bb0eedSdrh   setToken(&dummy, zCol);
1774adee20fSdanielk1977   pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy);
1784adee20fSdanielk1977   pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy);
179030530deSdrh   if( zAlias1==0 ){
180030530deSdrh     zAlias1 = pTab1->zName;
181030530deSdrh   }
182030530deSdrh   setToken(&dummy, zAlias1);
1834adee20fSdanielk1977   pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy);
184030530deSdrh   if( zAlias2==0 ){
185030530deSdrh     zAlias2 = pTab2->zName;
186030530deSdrh   }
187030530deSdrh   setToken(&dummy, zAlias2);
1884adee20fSdanielk1977   pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy);
1894adee20fSdanielk1977   pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0);
1904adee20fSdanielk1977   pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0);
1914adee20fSdanielk1977   pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0);
1921f16230bSdrh   ExprSetProperty(pE, EP_FromJoin);
19391bb0eedSdrh   *ppExpr = sqlite3ExprAnd(*ppExpr, pE);
194ad2d8307Sdrh }
195ad2d8307Sdrh 
196ad2d8307Sdrh /*
1971f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
1981cc093c2Sdrh **
199e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2001cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2011f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2021f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2031f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2041f16230bSdrh ** originated in the ON or USING clause.
2051cc093c2Sdrh */
2061cc093c2Sdrh static void setJoinExpr(Expr *p){
2071cc093c2Sdrh   while( p ){
2081f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
2091cc093c2Sdrh     setJoinExpr(p->pLeft);
2101cc093c2Sdrh     p = p->pRight;
2111cc093c2Sdrh   }
2121cc093c2Sdrh }
2131cc093c2Sdrh 
2141cc093c2Sdrh /*
215ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
216ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
217ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
218ad2d8307Sdrh **
21991bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
22091bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
22191bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
22291bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
22391bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
22491bb0eedSdrh ** also attached to the left entry.
22591bb0eedSdrh **
226ad2d8307Sdrh ** This routine returns the number of errors encountered.
227ad2d8307Sdrh */
228ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
22991bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
23091bb0eedSdrh   int i, j;                       /* Loop counters */
23191bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
23291bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
233ad2d8307Sdrh 
23491bb0eedSdrh   pSrc = p->pSrc;
23591bb0eedSdrh   pLeft = &pSrc->a[0];
23691bb0eedSdrh   pRight = &pLeft[1];
23791bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
23891bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
23991bb0eedSdrh     Table *pRightTab = pRight->pTab;
24091bb0eedSdrh 
24191bb0eedSdrh     if( pLeftTab==0 || pRightTab==0 ) continue;
242ad2d8307Sdrh 
243ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
244ad2d8307Sdrh     ** every column that the two tables have in common.
245ad2d8307Sdrh     */
24691bb0eedSdrh     if( pLeft->jointype & JT_NATURAL ){
24791bb0eedSdrh       if( pLeft->pOn || pLeft->pUsing ){
2484adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
249ad2d8307Sdrh            "an ON or USING clause", 0);
250ad2d8307Sdrh         return 1;
251ad2d8307Sdrh       }
25291bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
25391bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
25491bb0eedSdrh         if( columnIndex(pRightTab, zName)>=0 ){
255030530deSdrh           addWhereTerm(zName, pLeftTab, pLeft->zAlias,
256030530deSdrh                               pRightTab, pRight->zAlias, &p->pWhere);
257ad2d8307Sdrh         }
258ad2d8307Sdrh       }
259ad2d8307Sdrh     }
260ad2d8307Sdrh 
261ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
262ad2d8307Sdrh     */
26391bb0eedSdrh     if( pLeft->pOn && pLeft->pUsing ){
2644adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
265da93d238Sdrh         "clauses in the same join");
266ad2d8307Sdrh       return 1;
267ad2d8307Sdrh     }
268ad2d8307Sdrh 
269ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
27091bb0eedSdrh     ** an AND operator.
271ad2d8307Sdrh     */
27291bb0eedSdrh     if( pLeft->pOn ){
27391bb0eedSdrh       setJoinExpr(pLeft->pOn);
27491bb0eedSdrh       p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn);
27591bb0eedSdrh       pLeft->pOn = 0;
276ad2d8307Sdrh     }
277ad2d8307Sdrh 
278ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
279ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
280ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
281ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
282ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
283ad2d8307Sdrh     ** not contained in both tables to be joined.
284ad2d8307Sdrh     */
28591bb0eedSdrh     if( pLeft->pUsing ){
28691bb0eedSdrh       IdList *pList = pLeft->pUsing;
287ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
28891bb0eedSdrh         char *zName = pList->a[j].zName;
28991bb0eedSdrh         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
2904adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
29191bb0eedSdrh             "not present in both tables", zName);
292ad2d8307Sdrh           return 1;
293ad2d8307Sdrh         }
294030530deSdrh         addWhereTerm(zName, pLeftTab, pLeft->zAlias,
295030530deSdrh                             pRightTab, pRight->zAlias, &p->pWhere);
296ad2d8307Sdrh       }
297ad2d8307Sdrh     }
298ad2d8307Sdrh   }
299ad2d8307Sdrh   return 0;
300ad2d8307Sdrh }
301ad2d8307Sdrh 
302ad2d8307Sdrh /*
3039bb61fe7Sdrh ** Delete the given Select structure and all of its substructures.
3049bb61fe7Sdrh */
3054adee20fSdanielk1977 void sqlite3SelectDelete(Select *p){
30682c3d636Sdrh   if( p==0 ) return;
3074adee20fSdanielk1977   sqlite3ExprListDelete(p->pEList);
3084adee20fSdanielk1977   sqlite3SrcListDelete(p->pSrc);
3094adee20fSdanielk1977   sqlite3ExprDelete(p->pWhere);
3104adee20fSdanielk1977   sqlite3ExprListDelete(p->pGroupBy);
3114adee20fSdanielk1977   sqlite3ExprDelete(p->pHaving);
3124adee20fSdanielk1977   sqlite3ExprListDelete(p->pOrderBy);
3134adee20fSdanielk1977   sqlite3SelectDelete(p->pPrior);
314a2dc3b1aSdanielk1977   sqlite3ExprDelete(p->pLimit);
315a2dc3b1aSdanielk1977   sqlite3ExprDelete(p->pOffset);
3169bb61fe7Sdrh   sqliteFree(p);
3179bb61fe7Sdrh }
3189bb61fe7Sdrh 
3199bb61fe7Sdrh /*
320c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
321c926afbcSdrh ** stack into the sorter.
322c926afbcSdrh */
323c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
324c926afbcSdrh   int i;
325c926afbcSdrh   for(i=0; i<pOrderBy->nExpr; i++){
3264adee20fSdanielk1977     sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr);
327c926afbcSdrh   }
328ededfd5eSdanielk1977   sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0);
3294adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortPut, 0, 0);
330c926afbcSdrh }
331c926afbcSdrh 
332c926afbcSdrh /*
333ea48eb2eSdrh ** Add code to implement the OFFSET and LIMIT
334ea48eb2eSdrh */
335ea48eb2eSdrh static void codeLimiter(
336bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
337ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
338ea48eb2eSdrh   int iContinue,    /* Jump here to skip the current record */
339ea48eb2eSdrh   int iBreak,       /* Jump here to end the loop */
340ea48eb2eSdrh   int nPop          /* Number of times to pop stack when jumping */
341ea48eb2eSdrh ){
342ea48eb2eSdrh   if( p->iOffset>=0 ){
343a2dc3b1aSdanielk1977     int addr = sqlite3VdbeCurrentAddr(v) + 3;
344ea48eb2eSdrh     if( nPop>0 ) addr++;
345a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, 0);
346a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_IfMemPos, p->iOffset, addr);
347ea48eb2eSdrh     if( nPop>0 ){
348ea48eb2eSdrh       sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
349ea48eb2eSdrh     }
350ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
351ad6d9460Sdrh     VdbeComment((v, "# skip OFFSET records"));
352ea48eb2eSdrh   }
353ea48eb2eSdrh   if( p->iLimit>=0 ){
354ea48eb2eSdrh     sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
355ad6d9460Sdrh     VdbeComment((v, "# exit when LIMIT reached"));
356ea48eb2eSdrh   }
357ea48eb2eSdrh }
358ea48eb2eSdrh 
359ea48eb2eSdrh /*
3602282792aSdrh ** This routine generates the code for the inside of the inner loop
3612282792aSdrh ** of a SELECT.
36282c3d636Sdrh **
36338640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
36438640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
36538640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
36638640e15Sdrh ** datatypes for each column.
3672282792aSdrh */
3682282792aSdrh static int selectInnerLoop(
3692282792aSdrh   Parse *pParse,          /* The parser context */
370df199a25Sdrh   Select *p,              /* The complete select statement being coded */
3712282792aSdrh   ExprList *pEList,       /* List of values being extracted */
37282c3d636Sdrh   int srcTab,             /* Pull data from this table */
373967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
3742282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
3752282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
3762282792aSdrh   int eDest,              /* How to dispose of the results */
3772282792aSdrh   int iParm,              /* An argument to the disposal method */
3782282792aSdrh   int iContinue,          /* Jump here to continue with next row */
37984ac9d02Sdanielk1977   int iBreak,             /* Jump here to break out of the inner loop */
38084ac9d02Sdanielk1977   char *aff               /* affinity string if eDest is SRT_Union */
3812282792aSdrh ){
3822282792aSdrh   Vdbe *v = pParse->pVdbe;
3832282792aSdrh   int i;
384ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
38538640e15Sdrh 
386daffd0e5Sdrh   if( v==0 ) return 0;
38738640e15Sdrh   assert( pEList!=0 );
3882282792aSdrh 
389df199a25Sdrh   /* If there was a LIMIT clause on the SELECT statement, then do the check
390df199a25Sdrh   ** to see if this row should be output.
391df199a25Sdrh   */
392ea48eb2eSdrh   hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
393ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
394bab39e13Sdrh     codeLimiter(v, p, iContinue, iBreak, 0);
395df199a25Sdrh   }
396df199a25Sdrh 
397967e8b73Sdrh   /* Pull the requested columns.
3982282792aSdrh   */
39938640e15Sdrh   if( nColumn>0 ){
400967e8b73Sdrh     for(i=0; i<nColumn; i++){
4014adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
40282c3d636Sdrh     }
40338640e15Sdrh   }else{
40438640e15Sdrh     nColumn = pEList->nExpr;
40538640e15Sdrh     for(i=0; i<pEList->nExpr; i++){
4064adee20fSdanielk1977       sqlite3ExprCode(pParse, pEList->a[i].pExpr);
40738640e15Sdrh     }
40882c3d636Sdrh   }
4092282792aSdrh 
410daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
411daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
412daffd0e5Sdrh   ** part of the result.
4132282792aSdrh   */
414ea48eb2eSdrh   if( hasDistinct ){
4150bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT
4164adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7);
4170bd1f4eaSdrh #endif
418ededfd5eSdanielk1977     /* Deliberately leave the affinity string off of the following
419ededfd5eSdanielk1977     ** OP_MakeRecord */
420ededfd5eSdanielk1977     sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0);
4214adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3);
4224adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
4234adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
424ad6d9460Sdrh     VdbeComment((v, "# skip indistinct records"));
4250f69c1e3Sdanielk1977     sqlite3VdbeAddOp(v, OP_String8, 0, 0);
4264adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0);
427ea48eb2eSdrh     if( pOrderBy==0 ){
428bab39e13Sdrh       codeLimiter(v, p, iContinue, iBreak, nColumn);
429ea48eb2eSdrh     }
4302282792aSdrh   }
43182c3d636Sdrh 
432c926afbcSdrh   switch( eDest ){
4335338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
43482c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
43582c3d636Sdrh     ** table iParm.
4362282792aSdrh     */
437c926afbcSdrh     case SRT_Union: {
4384adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
43984ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
4400f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
4414adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0);
442c926afbcSdrh       break;
443c926afbcSdrh     }
44482c3d636Sdrh 
44582c3d636Sdrh     /* Construct a record from the query result, but instead of
44682c3d636Sdrh     ** saving that record, use it as a key to delete elements from
44782c3d636Sdrh     ** the temporary table iParm.
44882c3d636Sdrh     */
449c926afbcSdrh     case SRT_Except: {
4500bd1f4eaSdrh       int addr;
4514adee20fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
45284ac9d02Sdanielk1977       sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
4534adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
4544adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
455c926afbcSdrh       break;
456c926afbcSdrh     }
4575338a5f7Sdanielk1977 #endif
4585338a5f7Sdanielk1977 
4595338a5f7Sdanielk1977     /* Store the result as data using a unique key.
4605338a5f7Sdanielk1977     */
4615338a5f7Sdanielk1977     case SRT_Table:
4625338a5f7Sdanielk1977     case SRT_TempTable: {
4635338a5f7Sdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
4645338a5f7Sdanielk1977       if( pOrderBy ){
4655338a5f7Sdanielk1977         pushOntoSorter(pParse, v, pOrderBy);
4665338a5f7Sdanielk1977       }else{
4675338a5f7Sdanielk1977         sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
4685338a5f7Sdanielk1977         sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
4695338a5f7Sdanielk1977         sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
4705338a5f7Sdanielk1977       }
4715338a5f7Sdanielk1977       break;
4725338a5f7Sdanielk1977     }
4732282792aSdrh 
47493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
4752282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
4762282792aSdrh     ** then there should be a single item on the stack.  Write this
4772282792aSdrh     ** item into the set table with bogus data.
4782282792aSdrh     */
479c926afbcSdrh     case SRT_Set: {
4804adee20fSdanielk1977       int addr1 = sqlite3VdbeCurrentAddr(v);
48152b36cabSdrh       int addr2;
482e014a838Sdanielk1977 
483967e8b73Sdrh       assert( nColumn==1 );
4844adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
4854adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
4864adee20fSdanielk1977       addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
487c926afbcSdrh       if( pOrderBy ){
488c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
489c926afbcSdrh       }else{
490e014a838Sdanielk1977         char aff = (iParm>>16)&0xFF;
491e014a838Sdanielk1977         aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff);
49294a11211Sdrh         sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1);
4930f69c1e3Sdanielk1977         sqlite3VdbeAddOp(v, OP_String8, 0, 0);
494e014a838Sdanielk1977         sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
495c926afbcSdrh       }
4964adee20fSdanielk1977       sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v));
497c926afbcSdrh       break;
498c926afbcSdrh     }
49982c3d636Sdrh 
5002282792aSdrh     /* If this is a scalar select that is part of an expression, then
5012282792aSdrh     ** store the results in the appropriate memory cell and break out
5022282792aSdrh     ** of the scan loop.
5032282792aSdrh     */
50451522cd3Sdrh     case SRT_Exists:
505c926afbcSdrh     case SRT_Mem: {
506967e8b73Sdrh       assert( nColumn==1 );
507c926afbcSdrh       if( pOrderBy ){
508c926afbcSdrh         pushOntoSorter(pParse, v, pOrderBy);
509c926afbcSdrh       }else{
5104adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
5114adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak);
512c926afbcSdrh       }
513c926afbcSdrh       break;
514c926afbcSdrh     }
51593758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
5162282792aSdrh 
517f46f905aSdrh     /* Send the data to the callback function.
518f46f905aSdrh     */
519f46f905aSdrh     case SRT_Callback:
520f46f905aSdrh     case SRT_Sorter: {
521f46f905aSdrh       if( pOrderBy ){
522ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
523f46f905aSdrh         pushOntoSorter(pParse, v, pOrderBy);
524f46f905aSdrh       }else{
525f46f905aSdrh         assert( eDest==SRT_Callback );
5264adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
527f46f905aSdrh       }
528f46f905aSdrh       break;
529f46f905aSdrh     }
530f46f905aSdrh 
531142e30dfSdrh     /* Invoke a subroutine to handle the results.  The subroutine itself
532142e30dfSdrh     ** is responsible for popping the results off of the stack.
533142e30dfSdrh     */
534142e30dfSdrh     case SRT_Subroutine: {
535ac82fcf5Sdrh       if( pOrderBy ){
5364adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
537ac82fcf5Sdrh         pushOntoSorter(pParse, v, pOrderBy);
538ac82fcf5Sdrh       }else{
5394adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
540ac82fcf5Sdrh       }
541142e30dfSdrh       break;
542142e30dfSdrh     }
543142e30dfSdrh 
5446a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
545d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
546d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
547d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
548d7489c39Sdrh     ** about the actual results of the select.
549d7489c39Sdrh     */
550c926afbcSdrh     default: {
551f46f905aSdrh       assert( eDest==SRT_Discard );
5524adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
553c926afbcSdrh       break;
554c926afbcSdrh     }
55593758c8dSdanielk1977 #endif
556c926afbcSdrh   }
55782c3d636Sdrh   return 0;
55882c3d636Sdrh }
55982c3d636Sdrh 
56082c3d636Sdrh /*
561d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
562d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
563d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
564d8bc7086Sdrh ** routine generates the code needed to do that.
565d8bc7086Sdrh */
566c926afbcSdrh static void generateSortTail(
567ffbc3088Sdrh   Parse *pParse,   /* The parsing context */
568c926afbcSdrh   Select *p,       /* The SELECT statement */
569c926afbcSdrh   Vdbe *v,         /* Generate code into this VDBE */
570c926afbcSdrh   int nColumn,     /* Number of columns of data */
571c926afbcSdrh   int eDest,       /* Write the sorted results here */
572c926afbcSdrh   int iParm        /* Optional parameter associated with eDest */
573c926afbcSdrh ){
5744adee20fSdanielk1977   int end1 = sqlite3VdbeMakeLabel(v);
5754adee20fSdanielk1977   int end2 = sqlite3VdbeMakeLabel(v);
576d8bc7086Sdrh   int addr;
577ffbc3088Sdrh   KeyInfo *pInfo;
578ffbc3088Sdrh   ExprList *pOrderBy;
579ffbc3088Sdrh   int nCol, i;
5809bb575fdSdrh   sqlite3 *db = pParse->db;
581ffbc3088Sdrh 
582f46f905aSdrh   if( eDest==SRT_Sorter ) return;
583ffbc3088Sdrh   pOrderBy = p->pOrderBy;
584ffbc3088Sdrh   nCol = pOrderBy->nExpr;
585ffbc3088Sdrh   pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) );
586ffbc3088Sdrh   if( pInfo==0 ) return;
587ffbc3088Sdrh   pInfo->aSortOrder = (char*)&pInfo->aColl[nCol];
588ffbc3088Sdrh   pInfo->nField = nCol;
589ffbc3088Sdrh   for(i=0; i<nCol; i++){
5900202b29eSdanielk1977     /* If a collation sequence was specified explicity, then it
5910202b29eSdanielk1977     ** is stored in pOrderBy->a[i].zName. Otherwise, use the default
5920202b29eSdanielk1977     ** collation type for the expression.
5930202b29eSdanielk1977     */
5947cedc8d4Sdanielk1977     pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr);
5950202b29eSdanielk1977     if( !pInfo->aColl[i] ){
596ffbc3088Sdrh       pInfo->aColl[i] = db->pDfltColl;
5970202b29eSdanielk1977     }
598ffbc3088Sdrh     pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder;
599ffbc3088Sdrh   }
600ffbc3088Sdrh   sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF);
6014adee20fSdanielk1977   addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1);
602bab39e13Sdrh   codeLimiter(v, p, addr, end2, 1);
603c926afbcSdrh   switch( eDest ){
604c926afbcSdrh     case SRT_Table:
605c926afbcSdrh     case SRT_TempTable: {
6064adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0);
6074adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
6084adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0);
609c926afbcSdrh       break;
610c926afbcSdrh     }
61193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
612c926afbcSdrh     case SRT_Set: {
613c926afbcSdrh       assert( nColumn==1 );
6144adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
6154adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6164adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
617ededfd5eSdanielk1977       sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC);
6180f69c1e3Sdanielk1977       sqlite3VdbeAddOp(v, OP_String8, 0, 0);
619e014a838Sdanielk1977       sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0);
620c926afbcSdrh       break;
621c926afbcSdrh     }
62251522cd3Sdrh     case SRT_Exists:
623c926afbcSdrh     case SRT_Mem: {
624c926afbcSdrh       assert( nColumn==1 );
6254adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
6264adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Goto, 0, end1);
627c926afbcSdrh       break;
628c926afbcSdrh     }
62993758c8dSdanielk1977 #endif
630ce665cf6Sdrh     case SRT_Callback:
631ac82fcf5Sdrh     case SRT_Subroutine: {
632ac82fcf5Sdrh       int i;
63384ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0);
63484ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
635ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
6364adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Column, -1-i, i);
637ac82fcf5Sdrh       }
638ce665cf6Sdrh       if( eDest==SRT_Callback ){
639ce665cf6Sdrh         sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
640ce665cf6Sdrh       }else{
6414adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
642ce665cf6Sdrh       }
64384ac9d02Sdanielk1977       sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
644ac82fcf5Sdrh       break;
645ac82fcf5Sdrh     }
646c926afbcSdrh     default: {
647f46f905aSdrh       /* Do nothing */
648c926afbcSdrh       break;
649c926afbcSdrh     }
650c926afbcSdrh   }
6514adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Goto, 0, addr);
6524adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end2);
6534adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
6544adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, end1);
6554adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_SortReset, 0, 0);
656d8bc7086Sdrh }
657d8bc7086Sdrh 
658d8bc7086Sdrh /*
659517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
660517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
661e78e8284Sdrh **
662517eb646Sdanielk1977 ** If the declaration type is the exact datatype definition extracted from
663517eb646Sdanielk1977 ** the original CREATE TABLE statement if the expression is a column.
664e78e8284Sdrh **
665517eb646Sdanielk1977 ** The declaration type for an expression is either TEXT, NUMERIC or ANY.
666517eb646Sdanielk1977 ** The declaration type for a ROWID field is INTEGER.
667fcb78a49Sdrh */
668b3bce662Sdanielk1977 static const char *columnType(NameContext *pNC, Expr *pExpr){
66900e279d9Sdanielk1977   char const *zType;
670517eb646Sdanielk1977   int j;
671b3bce662Sdanielk1977   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
6725338a5f7Sdanielk1977 
6735338a5f7Sdanielk1977   /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
6745338a5f7Sdanielk1977   ** and LIMIT clauses.  But pExpr originates in the result set of a
6755338a5f7Sdanielk1977   ** SELECT.  So pExpr can never contain an AS operator.
6765338a5f7Sdanielk1977   */
6775338a5f7Sdanielk1977   assert( pExpr->op!=TK_AS );
6785338a5f7Sdanielk1977 
67900e279d9Sdanielk1977   switch( pExpr->op ){
68000e279d9Sdanielk1977     case TK_COLUMN: {
681b3bce662Sdanielk1977       Table *pTab = 0;
682517eb646Sdanielk1977       int iCol = pExpr->iColumn;
683b3bce662Sdanielk1977       while( pNC && !pTab ){
684b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
685b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
686b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
6876a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
688b3bce662Sdanielk1977         }else{
689b3bce662Sdanielk1977           pNC = pNC->pNext;
690b3bce662Sdanielk1977         }
691b3bce662Sdanielk1977       }
692b3bce662Sdanielk1977       assert( pTab );
693fcb78a49Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
694fcb78a49Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
695fcb78a49Sdrh       if( iCol<0 ){
696fcb78a49Sdrh         zType = "INTEGER";
697fcb78a49Sdrh       }else{
698fcb78a49Sdrh         zType = pTab->aCol[iCol].zType;
699fcb78a49Sdrh       }
70000e279d9Sdanielk1977       break;
701736c22b8Sdrh     }
70293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
70300e279d9Sdanielk1977     case TK_SELECT: {
704b3bce662Sdanielk1977       NameContext sNC;
70500e279d9Sdanielk1977       Select *pS = pExpr->pSelect;
706b3bce662Sdanielk1977       sNC.pSrcList = pExpr->pSelect->pSrc;
707b3bce662Sdanielk1977       sNC.pNext = pNC;
708b3bce662Sdanielk1977       zType = columnType(&sNC, pS->pEList->a[0].pExpr);
70900e279d9Sdanielk1977       break;
710fcb78a49Sdrh     }
71193758c8dSdanielk1977 #endif
71200e279d9Sdanielk1977     default:
71300e279d9Sdanielk1977       zType = 0;
71400e279d9Sdanielk1977   }
71500e279d9Sdanielk1977 
716517eb646Sdanielk1977   return zType;
717517eb646Sdanielk1977 }
718517eb646Sdanielk1977 
719517eb646Sdanielk1977 /*
720517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
721517eb646Sdanielk1977 ** in the result set.
722517eb646Sdanielk1977 */
723517eb646Sdanielk1977 static void generateColumnTypes(
724517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
725517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
726517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
727517eb646Sdanielk1977 ){
728517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
729517eb646Sdanielk1977   int i;
730b3bce662Sdanielk1977   NameContext sNC;
731b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
732517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
733517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
734b3bce662Sdanielk1977     const char *zType = columnType(&sNC, p);
73500e279d9Sdanielk1977     if( zType==0 ) continue;
736fbcd585fSdanielk1977     /* The vdbe must make it's own copy of the column-type, in case the
737fbcd585fSdanielk1977     ** schema is reset before this virtual machine is deleted.
738fbcd585fSdanielk1977     */
739fbcd585fSdanielk1977     sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
740fcb78a49Sdrh   }
741fcb78a49Sdrh }
742fcb78a49Sdrh 
743fcb78a49Sdrh /*
744fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
745fcb78a49Sdrh ** in the result set.  This information is used to provide the
746fcabd464Sdrh ** azCol[] values in the callback.
74782c3d636Sdrh */
748832508b7Sdrh static void generateColumnNames(
749832508b7Sdrh   Parse *pParse,      /* Parser context */
750ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
751832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
752832508b7Sdrh ){
753d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
7546a3ea0e6Sdrh   int i, j;
7559bb575fdSdrh   sqlite3 *db = pParse->db;
756fcabd464Sdrh   int fullNames, shortNames;
757fcabd464Sdrh 
758fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
7593cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
7603cf86063Sdanielk1977   if( pParse->explain ){
76161de0d1bSdanielk1977     return;
7623cf86063Sdanielk1977   }
7635338a5f7Sdanielk1977 #endif
7643cf86063Sdanielk1977 
765d6502758Sdrh   assert( v!=0 );
7666f8a503dSdanielk1977   if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return;
767d8bc7086Sdrh   pParse->colNamesSet = 1;
768fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
769fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
77022322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
77182c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
77282c3d636Sdrh     Expr *p;
7735a38705eSdrh     p = pEList->a[i].pExpr;
7745a38705eSdrh     if( p==0 ) continue;
77582c3d636Sdrh     if( pEList->a[i].zName ){
77682c3d636Sdrh       char *zName = pEList->a[i].zName;
777d8123366Sdanielk1977       sqlite3VdbeSetColName(v, i, zName, strlen(zName));
77882c3d636Sdrh       continue;
77982c3d636Sdrh     }
780fa173a76Sdrh     if( p->op==TK_COLUMN && pTabList ){
7816a3ea0e6Sdrh       Table *pTab;
78297665873Sdrh       char *zCol;
7838aff1015Sdrh       int iCol = p->iColumn;
7846a3ea0e6Sdrh       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
7856a3ea0e6Sdrh       assert( j<pTabList->nSrc );
7866a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
7878aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
78897665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
789b1363206Sdrh       if( iCol<0 ){
79047a6db2bSdrh         zCol = "rowid";
791b1363206Sdrh       }else{
792b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
793b1363206Sdrh       }
794fcabd464Sdrh       if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
7953cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
796fcabd464Sdrh       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
79782c3d636Sdrh         char *zName = 0;
79882c3d636Sdrh         char *zTab;
79982c3d636Sdrh 
8006a3ea0e6Sdrh         zTab = pTabList->a[j].zAlias;
801fcabd464Sdrh         if( fullNames || zTab==0 ) zTab = pTab->zName;
8024adee20fSdanielk1977         sqlite3SetString(&zName, zTab, ".", zCol, 0);
8033cf86063Sdanielk1977         sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC);
80482c3d636Sdrh       }else{
80547a6db2bSdrh         sqlite3VdbeSetColName(v, i, zCol, strlen(zCol));
80682c3d636Sdrh       }
8076977fea8Sdrh     }else if( p->span.z && p->span.z[0] ){
8083cf86063Sdanielk1977       sqlite3VdbeSetColName(v, i, p->span.z, p->span.n);
8093cf86063Sdanielk1977       /* sqlite3VdbeCompressSpace(v, addr); */
8101bee3d7bSdrh     }else{
8111bee3d7bSdrh       char zName[30];
8121bee3d7bSdrh       assert( p->op!=TK_COLUMN || pTabList==0 );
8131bee3d7bSdrh       sprintf(zName, "column%d", i+1);
8143cf86063Sdanielk1977       sqlite3VdbeSetColName(v, i, zName, 0);
81582c3d636Sdrh     }
81682c3d636Sdrh   }
81776d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
8185080aaa7Sdrh }
81982c3d636Sdrh 
82093758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
82182c3d636Sdrh /*
822d8bc7086Sdrh ** Name of the connection operator, used for error messages.
823d8bc7086Sdrh */
824d8bc7086Sdrh static const char *selectOpName(int id){
825d8bc7086Sdrh   char *z;
826d8bc7086Sdrh   switch( id ){
827d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
828d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
829d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
830d8bc7086Sdrh     default:           z = "UNION";       break;
831d8bc7086Sdrh   }
832d8bc7086Sdrh   return z;
833d8bc7086Sdrh }
83493758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
835d8bc7086Sdrh 
836d8bc7086Sdrh /*
837315555caSdrh ** Forward declaration
838315555caSdrh */
8399b3187e1Sdrh static int prepSelectStmt(Parse*, Select*);
840315555caSdrh 
841315555caSdrh /*
84222f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes
84322f70c32Sdrh ** the result set of that SELECT.
84422f70c32Sdrh */
8454adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
84622f70c32Sdrh   Table *pTab;
847b733d037Sdrh   int i, j;
84822f70c32Sdrh   ExprList *pEList;
849290c1948Sdrh   Column *aCol, *pCol;
85022f70c32Sdrh 
8519b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
85222f70c32Sdrh     return 0;
85322f70c32Sdrh   }
854142bdf40Sdanielk1977   if( sqlite3SelectResolve(pParse, pSelect, 0) ){
855142bdf40Sdanielk1977     return 0;
856142bdf40Sdanielk1977   }
85722f70c32Sdrh   pTab = sqliteMalloc( sizeof(Table) );
85822f70c32Sdrh   if( pTab==0 ){
85922f70c32Sdrh     return 0;
86022f70c32Sdrh   }
86122f70c32Sdrh   pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
86222f70c32Sdrh   pEList = pSelect->pEList;
86322f70c32Sdrh   pTab->nCol = pEList->nExpr;
864417be79cSdrh   assert( pTab->nCol>0 );
865b733d037Sdrh   pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
866290c1948Sdrh   for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
86779d5f63fSdrh     Expr *p, *pR;
868517eb646Sdanielk1977     char *zType;
86991bb0eedSdrh     char *zName;
87079d5f63fSdrh     char *zBasename;
87179d5f63fSdrh     int cnt;
872b3bce662Sdanielk1977     NameContext sNC;
87379d5f63fSdrh 
87479d5f63fSdrh     /* Get an appropriate name for the column
87579d5f63fSdrh     */
87679d5f63fSdrh     p = pEList->a[i].pExpr;
877290c1948Sdrh     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
87891bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
87979d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
88091bb0eedSdrh       zName = sqliteStrDup(zName);
881517eb646Sdanielk1977     }else if( p->op==TK_DOT
882b733d037Sdrh               && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
88379d5f63fSdrh       /* For columns of the from A.B use B as the name */
88491bb0eedSdrh       zName = sqlite3MPrintf("%T", &pR->token);
885b733d037Sdrh     }else if( p->span.z && p->span.z[0] ){
88679d5f63fSdrh       /* Use the original text of the column expression as its name */
88791bb0eedSdrh       zName = sqlite3MPrintf("%T", &p->span);
88822f70c32Sdrh     }else{
88979d5f63fSdrh       /* If all else fails, make up a name */
89091bb0eedSdrh       zName = sqlite3MPrintf("column%d", i+1);
89122f70c32Sdrh     }
89291bb0eedSdrh     sqlite3Dequote(zName);
893*dd5b2fa5Sdrh     if( sqlite3_malloc_failed ){
894*dd5b2fa5Sdrh       sqliteFree(zName);
895*dd5b2fa5Sdrh       sqlite3DeleteTable(0, pTab);
896*dd5b2fa5Sdrh       return 0;
897*dd5b2fa5Sdrh     }
89879d5f63fSdrh 
89979d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
90079d5f63fSdrh     ** append a integer to the name so that it becomes unique.
90179d5f63fSdrh     */
90279d5f63fSdrh     zBasename = zName;
90379d5f63fSdrh     for(j=cnt=0; j<i; j++){
90479d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
90579d5f63fSdrh         zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt);
90679d5f63fSdrh         j = -1;
907*dd5b2fa5Sdrh         if( zName==0 ) break;
90879d5f63fSdrh       }
90979d5f63fSdrh     }
91079d5f63fSdrh     if( zBasename!=zName ){
91179d5f63fSdrh       sqliteFree(zBasename);
91279d5f63fSdrh     }
91391bb0eedSdrh     pCol->zName = zName;
914e014a838Sdanielk1977 
91579d5f63fSdrh     /* Get the typename, type affinity, and collating sequence for the
91679d5f63fSdrh     ** column.
91779d5f63fSdrh     */
918b3bce662Sdanielk1977     sNC.pSrcList = pSelect->pSrc;
919b3bce662Sdanielk1977     zType = sqliteStrDup(columnType(&sNC, p));
920290c1948Sdrh     pCol->zType = zType;
921c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
922290c1948Sdrh     pCol->pColl = sqlite3ExprCollSeq(pParse, p);
923290c1948Sdrh     if( !pCol->pColl ){
924290c1948Sdrh       pCol->pColl = pParse->db->pDfltColl;
9250202b29eSdanielk1977     }
92622f70c32Sdrh   }
92722f70c32Sdrh   pTab->iPKey = -1;
92822f70c32Sdrh   return pTab;
92922f70c32Sdrh }
93022f70c32Sdrh 
93122f70c32Sdrh /*
9329b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following
9339b3187e1Sdrh ** things:
934d8bc7086Sdrh **
9359b3187e1Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
9369b3187e1Sdrh **         element of the FROM clause.
9379b3187e1Sdrh **
9389b3187e1Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
9399b3187e1Sdrh **         defines FROM clause.  When views appear in the FROM clause,
94063eb5f29Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
94163eb5f29Sdrh **         that implements the view.  A copy is made of the view's SELECT
94263eb5f29Sdrh **         statement so that we can freely modify or delete that statement
94363eb5f29Sdrh **         without worrying about messing up the presistent representation
94463eb5f29Sdrh **         of the view.
945d8bc7086Sdrh **
9469b3187e1Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
947ad2d8307Sdrh **         on joins and the ON and USING clause of joins.
948ad2d8307Sdrh **
9499b3187e1Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
95054473229Sdrh **         for instances of the "*" operator or the TABLE.* operator.
95154473229Sdrh **         If found, expand each "*" to be every column in every table
95254473229Sdrh **         and TABLE.* to be every column in TABLE.
953d8bc7086Sdrh **
954d8bc7086Sdrh ** Return 0 on success.  If there are problems, leave an error message
955d8bc7086Sdrh ** in pParse and return non-zero.
956d8bc7086Sdrh */
9579b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){
95854473229Sdrh   int i, j, k, rc;
959ad3cab52Sdrh   SrcList *pTabList;
960daffd0e5Sdrh   ExprList *pEList;
961a76b5dfcSdrh   Table *pTab;
962290c1948Sdrh   struct SrcList_item *pFrom;
963daffd0e5Sdrh 
964e94ddc9eSdanielk1977   if( p==0 || p->pSrc==0 || sqlite3_malloc_failed ) return 1;
965daffd0e5Sdrh   pTabList = p->pSrc;
966daffd0e5Sdrh   pEList = p->pEList;
967d8bc7086Sdrh 
9689b3187e1Sdrh   /* Make sure cursor numbers have been assigned to all entries in
9699b3187e1Sdrh   ** the FROM clause of the SELECT statement.
9709b3187e1Sdrh   */
9719b3187e1Sdrh   sqlite3SrcListAssignCursors(pParse, p->pSrc);
9729b3187e1Sdrh 
9739b3187e1Sdrh   /* Look up every table named in the FROM clause of the select.  If
9749b3187e1Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
9759b3187e1Sdrh   ** then create a transient table structure to describe the subquery.
976d8bc7086Sdrh   */
977290c1948Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
9789b3187e1Sdrh     if( pFrom->pTab!=0 ){
9799b3187e1Sdrh       /* This statement has already been prepared.  There is no need
9809b3187e1Sdrh       ** to go further. */
9819b3187e1Sdrh       assert( i==0 );
982d8bc7086Sdrh       return 0;
983d8bc7086Sdrh     }
984290c1948Sdrh     if( pFrom->zName==0 ){
98593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
98622f70c32Sdrh       /* A sub-query in the FROM clause of a SELECT */
987290c1948Sdrh       assert( pFrom->pSelect!=0 );
988290c1948Sdrh       if( pFrom->zAlias==0 ){
98991bb0eedSdrh         pFrom->zAlias =
99091bb0eedSdrh           sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
991ad2d8307Sdrh       }
992290c1948Sdrh       pFrom->pTab = pTab =
993290c1948Sdrh         sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
99422f70c32Sdrh       if( pTab==0 ){
995daffd0e5Sdrh         return 1;
996daffd0e5Sdrh       }
9975cf590c1Sdrh       /* The isTransient flag indicates that the Table structure has been
9985cf590c1Sdrh       ** dynamically allocated and may be freed at any time.  In other words,
9995cf590c1Sdrh       ** pTab is not pointing to a persistent table structure that defines
10005cf590c1Sdrh       ** part of the schema. */
100122f70c32Sdrh       pTab->isTransient = 1;
100293758c8dSdanielk1977 #endif
100322f70c32Sdrh     }else{
1004a76b5dfcSdrh       /* An ordinary table or view name in the FROM clause */
1005290c1948Sdrh       pFrom->pTab = pTab =
1006290c1948Sdrh         sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
1007a76b5dfcSdrh       if( pTab==0 ){
1008d8bc7086Sdrh         return 1;
1009d8bc7086Sdrh       }
101093758c8dSdanielk1977 #ifndef SQLITE_OMIT_VIEW
1011a76b5dfcSdrh       if( pTab->pSelect ){
101263eb5f29Sdrh         /* We reach here if the named table is a really a view */
10134adee20fSdanielk1977         if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1014417be79cSdrh           return 1;
1015417be79cSdrh         }
1016290c1948Sdrh         /* If pFrom->pSelect!=0 it means we are dealing with a
101763eb5f29Sdrh         ** view within a view.  The SELECT structure has already been
101863eb5f29Sdrh         ** copied by the outer view so we can skip the copy step here
101963eb5f29Sdrh         ** in the inner view.
102063eb5f29Sdrh         */
1021290c1948Sdrh         if( pFrom->pSelect==0 ){
1022290c1948Sdrh           pFrom->pSelect = sqlite3SelectDup(pTab->pSelect);
1023a76b5dfcSdrh         }
1024d8bc7086Sdrh       }
102593758c8dSdanielk1977 #endif
102622f70c32Sdrh     }
102763eb5f29Sdrh   }
1028d8bc7086Sdrh 
1029ad2d8307Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
1030ad2d8307Sdrh   */
1031ad2d8307Sdrh   if( sqliteProcessJoin(pParse, p) ) return 1;
1032ad2d8307Sdrh 
10337c917d19Sdrh   /* For every "*" that occurs in the column list, insert the names of
103454473229Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
103554473229Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
10367c917d19Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
10377c917d19Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
10387c917d19Sdrh   ** each one to the list of all columns in all tables.
103954473229Sdrh   **
104054473229Sdrh   ** The first loop just checks to see if there are any "*" operators
104154473229Sdrh   ** that need expanding.
1042d8bc7086Sdrh   */
10437c917d19Sdrh   for(k=0; k<pEList->nExpr; k++){
104454473229Sdrh     Expr *pE = pEList->a[k].pExpr;
104554473229Sdrh     if( pE->op==TK_ALL ) break;
104654473229Sdrh     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
104754473229Sdrh          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
10487c917d19Sdrh   }
104954473229Sdrh   rc = 0;
10507c917d19Sdrh   if( k<pEList->nExpr ){
105154473229Sdrh     /*
105254473229Sdrh     ** If we get here it means the result set contains one or more "*"
105354473229Sdrh     ** operators that need to be expanded.  Loop through each expression
105454473229Sdrh     ** in the result set and expand them one by one.
105554473229Sdrh     */
10567c917d19Sdrh     struct ExprList_item *a = pEList->a;
10577c917d19Sdrh     ExprList *pNew = 0;
10587c917d19Sdrh     for(k=0; k<pEList->nExpr; k++){
105954473229Sdrh       Expr *pE = a[k].pExpr;
106054473229Sdrh       if( pE->op!=TK_ALL &&
106154473229Sdrh            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
106254473229Sdrh         /* This particular expression does not need to be expanded.
106354473229Sdrh         */
10644adee20fSdanielk1977         pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0);
10657c917d19Sdrh         pNew->a[pNew->nExpr-1].zName = a[k].zName;
10667c917d19Sdrh         a[k].pExpr = 0;
10677c917d19Sdrh         a[k].zName = 0;
10687c917d19Sdrh       }else{
106954473229Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
107054473229Sdrh         ** expanded. */
107154473229Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
1072cf55b7aeSdrh         char *zTName;            /* text of name of TABLE */
107354473229Sdrh         if( pE->op==TK_DOT && pE->pLeft ){
1074cf55b7aeSdrh           zTName = sqlite3NameFromToken(&pE->pLeft->token);
107554473229Sdrh         }else{
1076cf55b7aeSdrh           zTName = 0;
107754473229Sdrh         }
1078290c1948Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
1079290c1948Sdrh           Table *pTab = pFrom->pTab;
1080290c1948Sdrh           char *zTabName = pFrom->zAlias;
108154473229Sdrh           if( zTabName==0 || zTabName[0]==0 ){
108254473229Sdrh             zTabName = pTab->zName;
108354473229Sdrh           }
1084cf55b7aeSdrh           if( zTName && (zTabName==0 || zTabName[0]==0 ||
1085cf55b7aeSdrh                  sqlite3StrICmp(zTName, zTabName)!=0) ){
108654473229Sdrh             continue;
108754473229Sdrh           }
108854473229Sdrh           tableSeen = 1;
1089d8bc7086Sdrh           for(j=0; j<pTab->nCol; j++){
109022f70c32Sdrh             Expr *pExpr, *pLeft, *pRight;
1091ad2d8307Sdrh             char *zName = pTab->aCol[j].zName;
1092ad2d8307Sdrh 
109391bb0eedSdrh             if( i>0 ){
109491bb0eedSdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
109591bb0eedSdrh               if( (pLeft->jointype & JT_NATURAL)!=0 &&
109691bb0eedSdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
1097ad2d8307Sdrh                 /* In a NATURAL join, omit the join columns from the
1098ad2d8307Sdrh                 ** table on the right */
1099ad2d8307Sdrh                 continue;
1100ad2d8307Sdrh               }
110191bb0eedSdrh               if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){
1102ad2d8307Sdrh                 /* In a join with a USING clause, omit columns in the
1103ad2d8307Sdrh                 ** using clause from the table on the right. */
1104ad2d8307Sdrh                 continue;
1105ad2d8307Sdrh               }
110691bb0eedSdrh             }
11074adee20fSdanielk1977             pRight = sqlite3Expr(TK_ID, 0, 0, 0);
110822f70c32Sdrh             if( pRight==0 ) break;
110991bb0eedSdrh             setToken(&pRight->token, zName);
11104b59ab5eSdrh             if( zTabName && pTabList->nSrc>1 ){
11114adee20fSdanielk1977               pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
11124adee20fSdanielk1977               pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
111322f70c32Sdrh               if( pExpr==0 ) break;
111491bb0eedSdrh               setToken(&pLeft->token, zTabName);
111591bb0eedSdrh               setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
11166977fea8Sdrh               pExpr->span.dyn = 1;
11176977fea8Sdrh               pExpr->token.z = 0;
11186977fea8Sdrh               pExpr->token.n = 0;
11196977fea8Sdrh               pExpr->token.dyn = 0;
112022f70c32Sdrh             }else{
112122f70c32Sdrh               pExpr = pRight;
11226977fea8Sdrh               pExpr->span = pExpr->token;
112322f70c32Sdrh             }
112479d5f63fSdrh             pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
1125d8bc7086Sdrh           }
1126d8bc7086Sdrh         }
112754473229Sdrh         if( !tableSeen ){
1128cf55b7aeSdrh           if( zTName ){
1129cf55b7aeSdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
1130f5db2d3eSdrh           }else{
11314adee20fSdanielk1977             sqlite3ErrorMsg(pParse, "no tables specified");
1132f5db2d3eSdrh           }
113354473229Sdrh           rc = 1;
113454473229Sdrh         }
1135cf55b7aeSdrh         sqliteFree(zTName);
11367c917d19Sdrh       }
11377c917d19Sdrh     }
11384adee20fSdanielk1977     sqlite3ExprListDelete(pEList);
11397c917d19Sdrh     p->pEList = pNew;
1140d8bc7086Sdrh   }
114154473229Sdrh   return rc;
1142d8bc7086Sdrh }
1143d8bc7086Sdrh 
1144d8bc7086Sdrh /*
1145ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
1146ff78bd2fSdrh ** in a select structure.  It just sets the pointers to NULL.  This
1147ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
1148ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer.
1149ff78bd2fSdrh **
1150ff78bd2fSdrh ** This routine is called on the Select structure that defines a
1151ff78bd2fSdrh ** VIEW in order to undo any bindings to tables.  This is necessary
1152ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command.
11535cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field
11545cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the
11555cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used.
1156ff78bd2fSdrh */
11575338a5f7Sdanielk1977 #if 0
11584adee20fSdanielk1977 void sqlite3SelectUnbind(Select *p){
1159ff78bd2fSdrh   int i;
1160ad3cab52Sdrh   SrcList *pSrc = p->pSrc;
116191bb0eedSdrh   struct SrcList_item *pItem;
1162ff78bd2fSdrh   Table *pTab;
1163ff78bd2fSdrh   if( p==0 ) return;
116491bb0eedSdrh   for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
116591bb0eedSdrh     if( (pTab = pItem->pTab)!=0 ){
1166ff78bd2fSdrh       if( pTab->isTransient ){
11674adee20fSdanielk1977         sqlite3DeleteTable(0, pTab);
1168ff78bd2fSdrh       }
116991bb0eedSdrh       pItem->pTab = 0;
117091bb0eedSdrh       if( pItem->pSelect ){
117191bb0eedSdrh         sqlite3SelectUnbind(pItem->pSelect);
1172ff78bd2fSdrh       }
1173ff78bd2fSdrh     }
1174ff78bd2fSdrh   }
1175ff78bd2fSdrh }
11765338a5f7Sdanielk1977 #endif
1177ff78bd2fSdrh 
117893758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1179ff78bd2fSdrh /*
1180d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with
1181d8bc7086Sdrh ** columns in a result.  For each ORDER BY expression, the opcode of
1182967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of
1183d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable
1184d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter.
1185d8bc7086Sdrh **
1186d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first.  A match
1187d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT.
1188d8bc7086Sdrh **
1189d8bc7086Sdrh ** Any entry that does not match is flagged as an error.  The number
1190d8bc7086Sdrh ** of errors is returned.
1191d8bc7086Sdrh */
1192d8bc7086Sdrh static int matchOrderbyToColumn(
1193d8bc7086Sdrh   Parse *pParse,          /* A place to leave error messages */
1194d8bc7086Sdrh   Select *pSelect,        /* Match to result columns of this SELECT */
1195d8bc7086Sdrh   ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
1196e4de1febSdrh   int iTable,             /* Insert this value in iTable */
1197d8bc7086Sdrh   int mustComplete        /* If TRUE all ORDER BYs must match */
1198d8bc7086Sdrh ){
1199d8bc7086Sdrh   int nErr = 0;
1200d8bc7086Sdrh   int i, j;
1201d8bc7086Sdrh   ExprList *pEList;
1202d8bc7086Sdrh 
1203daffd0e5Sdrh   if( pSelect==0 || pOrderBy==0 ) return 1;
1204d8bc7086Sdrh   if( mustComplete ){
1205d8bc7086Sdrh     for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
1206d8bc7086Sdrh   }
12079b3187e1Sdrh   if( prepSelectStmt(pParse, pSelect) ){
1208d8bc7086Sdrh     return 1;
1209d8bc7086Sdrh   }
1210d8bc7086Sdrh   if( pSelect->pPrior ){
121192cd52f5Sdrh     if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
121292cd52f5Sdrh       return 1;
121392cd52f5Sdrh     }
1214d8bc7086Sdrh   }
1215d8bc7086Sdrh   pEList = pSelect->pEList;
1216d8bc7086Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
1217d8bc7086Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
1218e4de1febSdrh     int iCol = -1;
1219d8bc7086Sdrh     if( pOrderBy->a[i].done ) continue;
12204adee20fSdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
1221e4de1febSdrh       if( iCol<=0 || iCol>pEList->nExpr ){
12224adee20fSdanielk1977         sqlite3ErrorMsg(pParse,
1223da93d238Sdrh           "ORDER BY position %d should be between 1 and %d",
1224e4de1febSdrh           iCol, pEList->nExpr);
1225e4de1febSdrh         nErr++;
1226e4de1febSdrh         break;
1227e4de1febSdrh       }
1228fcb78a49Sdrh       if( !mustComplete ) continue;
1229e4de1febSdrh       iCol--;
1230e4de1febSdrh     }
1231e4de1febSdrh     for(j=0; iCol<0 && j<pEList->nExpr; j++){
12324cfa7934Sdrh       if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
1233a76b5dfcSdrh         char *zName, *zLabel;
1234a76b5dfcSdrh         zName = pEList->a[j].zName;
1235a99db3b6Sdrh         zLabel = sqlite3NameFromToken(&pE->token);
1236a99db3b6Sdrh         assert( zLabel!=0 );
12374adee20fSdanielk1977         if( sqlite3StrICmp(zName, zLabel)==0 ){
1238e4de1febSdrh           iCol = j;
1239d8bc7086Sdrh         }
12406e142f54Sdrh         sqliteFree(zLabel);
1241d8bc7086Sdrh       }
12424adee20fSdanielk1977       if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){
1243e4de1febSdrh         iCol = j;
1244d8bc7086Sdrh       }
1245e4de1febSdrh     }
1246e4de1febSdrh     if( iCol>=0 ){
1247967e8b73Sdrh       pE->op = TK_COLUMN;
1248e4de1febSdrh       pE->iColumn = iCol;
1249d8bc7086Sdrh       pE->iTable = iTable;
1250a58fdfb1Sdanielk1977       pE->iAgg = -1;
1251d8bc7086Sdrh       pOrderBy->a[i].done = 1;
1252d8bc7086Sdrh     }
1253e4de1febSdrh     if( iCol<0 && mustComplete ){
12544adee20fSdanielk1977       sqlite3ErrorMsg(pParse,
1255da93d238Sdrh         "ORDER BY term number %d does not match any result column", i+1);
1256d8bc7086Sdrh       nErr++;
1257d8bc7086Sdrh       break;
1258d8bc7086Sdrh     }
1259d8bc7086Sdrh   }
1260d8bc7086Sdrh   return nErr;
1261d8bc7086Sdrh }
126293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
1263d8bc7086Sdrh 
1264d8bc7086Sdrh /*
1265d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1266d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1267d8bc7086Sdrh */
12684adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1269d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1270d8bc7086Sdrh   if( v==0 ){
12714adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1272d8bc7086Sdrh   }
1273d8bc7086Sdrh   return v;
1274d8bc7086Sdrh }
1275d8bc7086Sdrh 
1276d8bc7086Sdrh /*
12777b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1278a2dc3b1aSdanielk1977 ** pLimit and pOffset expressions.  nLimit and nOffset hold the expressions
12797b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1280a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1281a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1282a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1283a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
12847b58daeaSdrh **
12857b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if
12867b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset.  iLimit and
12877b58daeaSdrh ** iOffset should have been preset to appropriate default values
12887b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
12897b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get
12907b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
12917b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
12927b58daeaSdrh ** SELECT statements.
12937b58daeaSdrh */
12947b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){
12957b58daeaSdrh   /*
12967b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
12977b58daeaSdrh   ** contraversy about what the correct behavior should be.
12987b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
12997b58daeaSdrh   ** no rows.
13007b58daeaSdrh   */
1301a2dc3b1aSdanielk1977   if( p->pLimit ){
13027b58daeaSdrh     int iMem = pParse->nMem++;
13034adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
13047b58daeaSdrh     if( v==0 ) return;
1305a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pLimit);
1306a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1307a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
13084adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1309ad6d9460Sdrh     VdbeComment((v, "# LIMIT counter"));
13107b58daeaSdrh     p->iLimit = iMem;
13117b58daeaSdrh   }
1312a2dc3b1aSdanielk1977   if( p->pOffset ){
13137b58daeaSdrh     int iMem = pParse->nMem++;
13144adee20fSdanielk1977     Vdbe *v = sqlite3GetVdbe(pParse);
13157b58daeaSdrh     if( v==0 ) return;
1316a2dc3b1aSdanielk1977     sqlite3ExprCode(pParse, p->pOffset);
1317a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
1318a2dc3b1aSdanielk1977     sqlite3VdbeAddOp(v, OP_Negative, 0, 0);
13194adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1);
1320ad6d9460Sdrh     VdbeComment((v, "# OFFSET counter"));
13217b58daeaSdrh     p->iOffset = iMem;
13227b58daeaSdrh   }
13237b58daeaSdrh }
13247b58daeaSdrh 
13257b58daeaSdrh /*
1326d3d39e93Sdrh ** Generate VDBE instructions that will open a transient table that
1327d3d39e93Sdrh ** will be used for an index or to store keyed results for a compound
1328d3d39e93Sdrh ** select.  In other words, open a transient table that needs a
1329d3d39e93Sdrh ** KeyInfo structure.  The number of columns in the KeyInfo is determined
1330d3d39e93Sdrh ** by the result set of the SELECT statement in the second argument.
1331d3d39e93Sdrh **
1332dc1bdc4fSdanielk1977 ** Specifically, this routine is called to open an index table for
1333dc1bdc4fSdanielk1977 ** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not
1334dc1bdc4fSdanielk1977 ** UNION ALL).
1335dc1bdc4fSdanielk1977 **
1336d3d39e93Sdrh ** Make the new table a KeyAsData table if keyAsData is true.
1337dc1bdc4fSdanielk1977 **
1338dc1bdc4fSdanielk1977 ** The value returned is the address of the OP_OpenTemp instruction.
1339d3d39e93Sdrh */
1340dc1bdc4fSdanielk1977 static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){
1341d3d39e93Sdrh   KeyInfo *pKeyInfo;
1342736c22b8Sdrh   int nColumn;
13439bb575fdSdrh   sqlite3 *db = pParse->db;
1344d3d39e93Sdrh   int i;
1345d3d39e93Sdrh   Vdbe *v = pParse->pVdbe;
1346dc1bdc4fSdanielk1977   int addr;
1347d3d39e93Sdrh 
13489b3187e1Sdrh   if( prepSelectStmt(pParse, p) ){
1349dc1bdc4fSdanielk1977     return 0;
1350736c22b8Sdrh   }
1351736c22b8Sdrh   nColumn = p->pEList->nExpr;
1352d3d39e93Sdrh   pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) );
1353dc1bdc4fSdanielk1977   if( pKeyInfo==0 ) return 0;
135491bb0eedSdrh   pKeyInfo->enc = db->enc;
1355d3d39e93Sdrh   pKeyInfo->nField = nColumn;
1356d3d39e93Sdrh   for(i=0; i<nColumn; i++){
1357dc1bdc4fSdanielk1977     pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
1358dc1bdc4fSdanielk1977     if( !pKeyInfo->aColl[i] ){
1359d3d39e93Sdrh       pKeyInfo->aColl[i] = db->pDfltColl;
1360d3d39e93Sdrh     }
1361dc1bdc4fSdanielk1977   }
1362dc1bdc4fSdanielk1977   addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0,
1363dc1bdc4fSdanielk1977       (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
1364d3d39e93Sdrh   if( keyAsData ){
1365d3d39e93Sdrh     sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
1366d3d39e93Sdrh   }
1367dc1bdc4fSdanielk1977   return addr;
1368dc1bdc4fSdanielk1977 }
1369dc1bdc4fSdanielk1977 
1370b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1371fbc4ee7bSdrh /*
13728cdbf836Sdrh ** Add the address "addr" to the set of all OpenTemp opcode addresses
13738cdbf836Sdrh ** that are being accumulated in p->ppOpenTemp.
1374fbc4ee7bSdrh */
13758cdbf836Sdrh static int multiSelectOpenTempAddr(Select *p, int addr){
13768cdbf836Sdrh   IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0);
1377fbc4ee7bSdrh   if( pList==0 ){
1378dc1bdc4fSdanielk1977     return SQLITE_NOMEM;
1379dc1bdc4fSdanielk1977   }
1380fbc4ee7bSdrh   pList->a[pList->nId-1].idx = addr;
1381dc1bdc4fSdanielk1977   return SQLITE_OK;
1382dc1bdc4fSdanielk1977 }
1383b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1384dc1bdc4fSdanielk1977 
1385b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1386fbc4ee7bSdrh /*
1387fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1388fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1389fbc4ee7bSdrh ** the column has no default collating sequence.
1390fbc4ee7bSdrh **
1391fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1392fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1393fbc4ee7bSdrh */
1394dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1395fbc4ee7bSdrh   CollSeq *pRet;
1396dc1bdc4fSdanielk1977   if( p->pPrior ){
1397dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1398fbc4ee7bSdrh   }else{
1399fbc4ee7bSdrh     pRet = 0;
1400dc1bdc4fSdanielk1977   }
1401fbc4ee7bSdrh   if( pRet==0 ){
1402dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1403dc1bdc4fSdanielk1977   }
1404dc1bdc4fSdanielk1977   return pRet;
1405d3d39e93Sdrh }
1406b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1407d3d39e93Sdrh 
1408b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1409d3d39e93Sdrh /*
141082c3d636Sdrh ** This routine is called to process a query that is really the union
141182c3d636Sdrh ** or intersection of two or more separate queries.
1412c926afbcSdrh **
1413e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1414e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1415e78e8284Sdrh ** in which case this routine will be called recursively.
1416e78e8284Sdrh **
1417e78e8284Sdrh ** The results of the total query are to be written into a destination
1418e78e8284Sdrh ** of type eDest with parameter iParm.
1419e78e8284Sdrh **
1420e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1421e78e8284Sdrh **
1422e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1423e78e8284Sdrh **
1424e78e8284Sdrh ** This statement is parsed up as follows:
1425e78e8284Sdrh **
1426e78e8284Sdrh **     SELECT c FROM t3
1427e78e8284Sdrh **      |
1428e78e8284Sdrh **      `----->  SELECT b FROM t2
1429e78e8284Sdrh **                |
14304b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1431e78e8284Sdrh **
1432e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1433e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1434e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1435e78e8284Sdrh **
1436e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1437e78e8284Sdrh ** individual selects always group from left to right.
143882c3d636Sdrh */
143984ac9d02Sdanielk1977 static int multiSelect(
1440fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1441fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1442fbc4ee7bSdrh   int eDest,            /* \___  Store query results as specified */
1443fbc4ee7bSdrh   int iParm,            /* /     by these two parameters.         */
144484ac9d02Sdanielk1977   char *aff             /* If eDest is SRT_Union, the affinity string */
144584ac9d02Sdanielk1977 ){
144684ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
144710e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
144810e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
1449fbc4ee7bSdrh   IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */
14508cdbf836Sdrh   int aAddr[5];         /* Addresses of SetNumColumns operators */
14518cdbf836Sdrh   int nAddr = 0;        /* Number used */
14528cdbf836Sdrh   int nCol;             /* Number of columns in the result set */
145382c3d636Sdrh 
14547b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1455fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
145682c3d636Sdrh   */
145784ac9d02Sdanielk1977   if( p==0 || p->pPrior==0 ){
145884ac9d02Sdanielk1977     rc = 1;
145984ac9d02Sdanielk1977     goto multi_select_end;
146084ac9d02Sdanielk1977   }
1461d8bc7086Sdrh   pPrior = p->pPrior;
1462d8bc7086Sdrh   if( pPrior->pOrderBy ){
14634adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1464da93d238Sdrh       selectOpName(p->op));
146584ac9d02Sdanielk1977     rc = 1;
146684ac9d02Sdanielk1977     goto multi_select_end;
146782c3d636Sdrh   }
1468a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
14694adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
14707b58daeaSdrh       selectOpName(p->op));
147184ac9d02Sdanielk1977     rc = 1;
147284ac9d02Sdanielk1977     goto multi_select_end;
14737b58daeaSdrh   }
147482c3d636Sdrh 
1475d8bc7086Sdrh   /* Make sure we have a valid query engine.  If not, create a new one.
1476d8bc7086Sdrh   */
14774adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
147884ac9d02Sdanielk1977   if( v==0 ){
147984ac9d02Sdanielk1977     rc = 1;
148084ac9d02Sdanielk1977     goto multi_select_end;
148184ac9d02Sdanielk1977   }
1482d8bc7086Sdrh 
14838cdbf836Sdrh   /* If *p this is the right-most select statement, then initialize
14848cdbf836Sdrh   ** p->ppOpenTemp to point to pOpenTemp.  If *p is not the right most
14858cdbf836Sdrh   ** statement then p->ppOpenTemp will have already been initialized
14868cdbf836Sdrh   ** by a prior call to this same procedure.  Pass along the pOpenTemp
14878cdbf836Sdrh   ** pointer to pPrior, the next statement to our left.
1488fbc4ee7bSdrh   */
1489fbc4ee7bSdrh   if( p->ppOpenTemp==0 ){
1490fbc4ee7bSdrh     p->ppOpenTemp = &pOpenTemp;
1491fbc4ee7bSdrh   }
1492fbc4ee7bSdrh   pPrior->ppOpenTemp = p->ppOpenTemp;
1493fbc4ee7bSdrh 
14941cc3d75fSdrh   /* Create the destination temporary table if necessary
14951cc3d75fSdrh   */
14961cc3d75fSdrh   if( eDest==SRT_TempTable ){
1497b4964b72Sdanielk1977     assert( p->pEList );
14984adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
14998cdbf836Sdrh     assert( nAddr==0 );
15008cdbf836Sdrh     aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0);
15011cc3d75fSdrh     eDest = SRT_Table;
15021cc3d75fSdrh   }
15031cc3d75fSdrh 
1504f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1505d8bc7086Sdrh   */
150682c3d636Sdrh   switch( p->op ){
1507f46f905aSdrh     case TK_ALL: {
1508f46f905aSdrh       if( p->pOrderBy==0 ){
1509a2dc3b1aSdanielk1977         assert( !pPrior->pLimit );
1510a2dc3b1aSdanielk1977         pPrior->pLimit = p->pLimit;
1511a2dc3b1aSdanielk1977         pPrior->pOffset = p->pOffset;
1512b3bce662Sdanielk1977         rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
151384ac9d02Sdanielk1977         if( rc ){
151484ac9d02Sdanielk1977           goto multi_select_end;
151584ac9d02Sdanielk1977         }
1516f46f905aSdrh         p->pPrior = 0;
15177b58daeaSdrh         p->iLimit = pPrior->iLimit;
15187b58daeaSdrh         p->iOffset = pPrior->iOffset;
1519a2dc3b1aSdanielk1977         p->pLimit = 0;
1520a2dc3b1aSdanielk1977         p->pOffset = 0;
1521b3bce662Sdanielk1977         rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
1522f46f905aSdrh         p->pPrior = pPrior;
152384ac9d02Sdanielk1977         if( rc ){
152484ac9d02Sdanielk1977           goto multi_select_end;
152584ac9d02Sdanielk1977         }
1526f46f905aSdrh         break;
1527f46f905aSdrh       }
1528f46f905aSdrh       /* For UNION ALL ... ORDER BY fall through to the next case */
1529f46f905aSdrh     }
153082c3d636Sdrh     case TK_EXCEPT:
153182c3d636Sdrh     case TK_UNION: {
1532d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1533742f947bSdanielk1977       int op = 0;      /* One of the SRT_ operations to apply to self */
1534d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1535a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1536c926afbcSdrh       ExprList *pOrderBy;     /* The ORDER BY clause for the right SELECT */
1537dc1bdc4fSdanielk1977       int addr;
153882c3d636Sdrh 
1539d8bc7086Sdrh       priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
1540a2dc3b1aSdanielk1977       if( eDest==priorOp && p->pOrderBy==0 && !p->pLimit && !p->pOffset ){
1541d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1542c926afbcSdrh         ** right.
1543d8bc7086Sdrh         */
154482c3d636Sdrh         unionTab = iParm;
154582c3d636Sdrh       }else{
1546d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1547d8bc7086Sdrh         ** intermediate results.
1548d8bc7086Sdrh         */
154982c3d636Sdrh         unionTab = pParse->nTab++;
1550d8bc7086Sdrh         if( p->pOrderBy
1551d8bc7086Sdrh         && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
155284ac9d02Sdanielk1977           rc = 1;
155384ac9d02Sdanielk1977           goto multi_select_end;
1554d8bc7086Sdrh         }
1555dc1bdc4fSdanielk1977         addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0);
1556d8bc7086Sdrh         if( p->op!=TK_ALL ){
15578cdbf836Sdrh           rc = multiSelectOpenTempAddr(p, addr);
1558dc1bdc4fSdanielk1977           if( rc!=SQLITE_OK ){
1559dc1bdc4fSdanielk1977             goto multi_select_end;
1560dc1bdc4fSdanielk1977           }
1561dc1bdc4fSdanielk1977           sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1);
156282c3d636Sdrh         }
15638cdbf836Sdrh 	assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
15648cdbf836Sdrh         aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
156584ac9d02Sdanielk1977         assert( p->pEList );
1566d8bc7086Sdrh       }
1567d8bc7086Sdrh 
1568d8bc7086Sdrh       /* Code the SELECT statements to our left
1569d8bc7086Sdrh       */
1570b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
1571b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
157284ac9d02Sdanielk1977       if( rc ){
157384ac9d02Sdanielk1977         goto multi_select_end;
157484ac9d02Sdanielk1977       }
1575d8bc7086Sdrh 
1576d8bc7086Sdrh       /* Code the current SELECT statement
1577d8bc7086Sdrh       */
1578d8bc7086Sdrh       switch( p->op ){
1579d8bc7086Sdrh          case TK_EXCEPT:  op = SRT_Except;   break;
1580d8bc7086Sdrh          case TK_UNION:   op = SRT_Union;    break;
1581d8bc7086Sdrh          case TK_ALL:     op = SRT_Table;    break;
1582d8bc7086Sdrh       }
158382c3d636Sdrh       p->pPrior = 0;
1584c926afbcSdrh       pOrderBy = p->pOrderBy;
1585c926afbcSdrh       p->pOrderBy = 0;
1586a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1587a2dc3b1aSdanielk1977       p->pLimit = 0;
1588a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1589a2dc3b1aSdanielk1977       p->pOffset = 0;
1590b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
159182c3d636Sdrh       p->pPrior = pPrior;
1592c926afbcSdrh       p->pOrderBy = pOrderBy;
1593a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1594a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1595a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1596be5fd490Sdrh       p->iLimit = -1;
1597be5fd490Sdrh       p->iOffset = -1;
159884ac9d02Sdanielk1977       if( rc ){
159984ac9d02Sdanielk1977         goto multi_select_end;
160084ac9d02Sdanielk1977       }
160184ac9d02Sdanielk1977 
1602d8bc7086Sdrh 
1603d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1604d8bc7086Sdrh       ** it is that we currently need.
1605d8bc7086Sdrh       */
1606c926afbcSdrh       if( eDest!=priorOp || unionTab!=iParm ){
16076b56344dSdrh         int iCont, iBreak, iStart;
160882c3d636Sdrh         assert( p->pEList );
160941202ccaSdrh         if( eDest==SRT_Callback ){
16106a3ea0e6Sdrh           generateColumnNames(pParse, 0, p->pEList);
161141202ccaSdrh         }
16124adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
16134adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
16144adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
16157b58daeaSdrh         computeLimitRegisters(pParse, p);
16164adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
161738640e15Sdrh         rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1618d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
161984ac9d02Sdanielk1977                              iCont, iBreak, 0);
162084ac9d02Sdanielk1977         if( rc ){
162184ac9d02Sdanielk1977           rc = 1;
162284ac9d02Sdanielk1977           goto multi_select_end;
162384ac9d02Sdanielk1977         }
16244adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
16254adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
16264adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
16274adee20fSdanielk1977         sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
162882c3d636Sdrh       }
162982c3d636Sdrh       break;
163082c3d636Sdrh     }
163182c3d636Sdrh     case TK_INTERSECT: {
163282c3d636Sdrh       int tab1, tab2;
16336b56344dSdrh       int iCont, iBreak, iStart;
1634a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1635dc1bdc4fSdanielk1977       int addr;
163682c3d636Sdrh 
1637d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
16386206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1639d8bc7086Sdrh       ** by allocating the tables we will need.
1640d8bc7086Sdrh       */
164182c3d636Sdrh       tab1 = pParse->nTab++;
164282c3d636Sdrh       tab2 = pParse->nTab++;
1643d8bc7086Sdrh       if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
164484ac9d02Sdanielk1977         rc = 1;
164584ac9d02Sdanielk1977         goto multi_select_end;
1646d8bc7086Sdrh       }
1647dc1bdc4fSdanielk1977 
1648dc1bdc4fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0);
16498cdbf836Sdrh       rc = multiSelectOpenTempAddr(p, addr);
1650dc1bdc4fSdanielk1977       if( rc!=SQLITE_OK ){
1651dc1bdc4fSdanielk1977         goto multi_select_end;
1652dc1bdc4fSdanielk1977       }
1653dc1bdc4fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
16548cdbf836Sdrh       assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
16558cdbf836Sdrh       aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
165684ac9d02Sdanielk1977       assert( p->pEList );
1657d8bc7086Sdrh 
1658d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1659d8bc7086Sdrh       */
1660b3bce662Sdanielk1977       rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
166184ac9d02Sdanielk1977       if( rc ){
166284ac9d02Sdanielk1977         goto multi_select_end;
166384ac9d02Sdanielk1977       }
1664d8bc7086Sdrh 
1665d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1666d8bc7086Sdrh       */
1667dc1bdc4fSdanielk1977       addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
16688cdbf836Sdrh       rc = multiSelectOpenTempAddr(p, addr);
1669dc1bdc4fSdanielk1977       if( rc!=SQLITE_OK ){
1670dc1bdc4fSdanielk1977         goto multi_select_end;
1671dc1bdc4fSdanielk1977       }
1672dc1bdc4fSdanielk1977       sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1);
16738cdbf836Sdrh       assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
16748cdbf836Sdrh       aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
167582c3d636Sdrh       p->pPrior = 0;
1676a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1677a2dc3b1aSdanielk1977       p->pLimit = 0;
1678a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1679a2dc3b1aSdanielk1977       p->pOffset = 0;
1680b3bce662Sdanielk1977       rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
168182c3d636Sdrh       p->pPrior = pPrior;
1682a2dc3b1aSdanielk1977       sqlite3ExprDelete(p->pLimit);
1683a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1684a2dc3b1aSdanielk1977       p->pOffset = pOffset;
168584ac9d02Sdanielk1977       if( rc ){
168684ac9d02Sdanielk1977         goto multi_select_end;
168784ac9d02Sdanielk1977       }
1688d8bc7086Sdrh 
1689d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1690d8bc7086Sdrh       ** tables.
1691d8bc7086Sdrh       */
169282c3d636Sdrh       assert( p->pEList );
169341202ccaSdrh       if( eDest==SRT_Callback ){
16946a3ea0e6Sdrh         generateColumnNames(pParse, 0, p->pEList);
169541202ccaSdrh       }
16964adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
16974adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
16984adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
16997b58daeaSdrh       computeLimitRegisters(pParse, p);
17004adee20fSdanielk1977       iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0);
17014adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
170238640e15Sdrh       rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1703d8bc7086Sdrh                              p->pOrderBy, -1, eDest, iParm,
170484ac9d02Sdanielk1977                              iCont, iBreak, 0);
170584ac9d02Sdanielk1977       if( rc ){
170684ac9d02Sdanielk1977         rc = 1;
170784ac9d02Sdanielk1977         goto multi_select_end;
170884ac9d02Sdanielk1977       }
17094adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
17104adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
17114adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
17124adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
17134adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
171482c3d636Sdrh       break;
171582c3d636Sdrh     }
171682c3d636Sdrh   }
17178cdbf836Sdrh 
17188cdbf836Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
17198cdbf836Sdrh   ** in their result sets.
17208cdbf836Sdrh   */
172182c3d636Sdrh   assert( p->pEList && pPrior->pEList );
172282c3d636Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
17234adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1724da93d238Sdrh       " do not have the same number of result columns", selectOpName(p->op));
172584ac9d02Sdanielk1977     rc = 1;
172684ac9d02Sdanielk1977     goto multi_select_end;
17272282792aSdrh   }
172884ac9d02Sdanielk1977 
17298cdbf836Sdrh   /* Set the number of columns in temporary tables
17308cdbf836Sdrh   */
17318cdbf836Sdrh   nCol = p->pEList->nExpr;
17328cdbf836Sdrh   while( nAddr>0 ){
17338cdbf836Sdrh     nAddr--;
17348cdbf836Sdrh     sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol);
17358cdbf836Sdrh   }
17368cdbf836Sdrh 
1737fbc4ee7bSdrh   /* Compute collating sequences used by either the ORDER BY clause or
1738fbc4ee7bSdrh   ** by any temporary tables needed to implement the compound select.
1739fbc4ee7bSdrh   ** Attach the KeyInfo structure to all temporary tables.  Invoke the
1740fbc4ee7bSdrh   ** ORDER BY processing if there is an ORDER BY clause.
17418cdbf836Sdrh   **
17428cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
17438cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
17448cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
17458cdbf836Sdrh   ** no temp tables are required.
1746fbc4ee7bSdrh   */
1747dc1bdc4fSdanielk1977   if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){
1748fbc4ee7bSdrh     int i;                        /* Loop counter */
1749fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
1750fbc4ee7bSdrh 
17518cdbf836Sdrh     assert( p->ppOpenTemp == &pOpenTemp );
1752fbc4ee7bSdrh     pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*));
1753dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1754dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1755dc1bdc4fSdanielk1977       goto multi_select_end;
1756dc1bdc4fSdanielk1977     }
1757dc1bdc4fSdanielk1977 
1758dc1bdc4fSdanielk1977     pKeyInfo->enc = pParse->db->enc;
1759dc1bdc4fSdanielk1977     pKeyInfo->nField = nCol;
1760dc1bdc4fSdanielk1977 
1761dc1bdc4fSdanielk1977     for(i=0; i<nCol; i++){
1762dc1bdc4fSdanielk1977       pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i);
1763dc1bdc4fSdanielk1977       if( !pKeyInfo->aColl[i] ){
1764dc1bdc4fSdanielk1977         pKeyInfo->aColl[i] = pParse->db->pDfltColl;
1765dc1bdc4fSdanielk1977       }
1766dc1bdc4fSdanielk1977     }
1767dc1bdc4fSdanielk1977 
1768dc1bdc4fSdanielk1977     for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){
1769dc1bdc4fSdanielk1977       int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO);
1770dc1bdc4fSdanielk1977       int addr = pOpenTemp->a[i].idx;
1771dc1bdc4fSdanielk1977       sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type);
1772dc1bdc4fSdanielk1977     }
1773dc1bdc4fSdanielk1977 
1774dc1bdc4fSdanielk1977     if( p->pOrderBy ){
1775fbc4ee7bSdrh       struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
1776fbc4ee7bSdrh       for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
1777fbc4ee7bSdrh         Expr *pExpr = pOrderByTerm->pExpr;
1778fbc4ee7bSdrh         char *zName = pOrderByTerm->zName;
1779dc1bdc4fSdanielk1977         assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
1780b3bce662Sdanielk1977         /* assert( !pExpr->pColl ); */
1781dc1bdc4fSdanielk1977         if( zName ){
1782dc1bdc4fSdanielk1977           pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
178384ac9d02Sdanielk1977         }else{
1784dc1bdc4fSdanielk1977           pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
178584ac9d02Sdanielk1977         }
178684ac9d02Sdanielk1977       }
1787dc1bdc4fSdanielk1977       generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
1788dc1bdc4fSdanielk1977     }
1789dc1bdc4fSdanielk1977 
1790dc1bdc4fSdanielk1977     if( !pOpenTemp ){
1791dc1bdc4fSdanielk1977       /* This happens for UNION ALL ... ORDER BY */
1792dc1bdc4fSdanielk1977       sqliteFree(pKeyInfo);
1793dc1bdc4fSdanielk1977     }
1794dc1bdc4fSdanielk1977   }
1795dc1bdc4fSdanielk1977 
1796dc1bdc4fSdanielk1977 multi_select_end:
1797dc1bdc4fSdanielk1977   if( pOpenTemp ){
1798dc1bdc4fSdanielk1977     sqlite3IdListDelete(pOpenTemp);
1799dc1bdc4fSdanielk1977   }
1800dc1bdc4fSdanielk1977   p->ppOpenTemp = 0;
180184ac9d02Sdanielk1977   return rc;
18022282792aSdrh }
1803b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
18042282792aSdrh 
1805b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
18062282792aSdrh /*
1807832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
18086a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
180984e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
18106a3ea0e6Sdrh ** unchanged.)
1811832508b7Sdrh **
1812832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
1813832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
1814832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
1815832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
1816832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
1817832508b7Sdrh ** of the subquery rather the result set of the subquery.
1818832508b7Sdrh */
18196a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
1820b3bce662Sdanielk1977 static void substSelect(Select *, int, ExprList *);  /* Forward Decl */
18216a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
1822832508b7Sdrh   if( pExpr==0 ) return;
182350350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
182450350a15Sdrh     if( pExpr->iColumn<0 ){
182550350a15Sdrh       pExpr->op = TK_NULL;
182650350a15Sdrh     }else{
1827832508b7Sdrh       Expr *pNew;
182884e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
1829832508b7Sdrh       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
1830832508b7Sdrh       pNew = pEList->a[pExpr->iColumn].pExpr;
1831832508b7Sdrh       assert( pNew!=0 );
1832832508b7Sdrh       pExpr->op = pNew->op;
1833d94a6698Sdrh       assert( pExpr->pLeft==0 );
18344adee20fSdanielk1977       pExpr->pLeft = sqlite3ExprDup(pNew->pLeft);
1835d94a6698Sdrh       assert( pExpr->pRight==0 );
18364adee20fSdanielk1977       pExpr->pRight = sqlite3ExprDup(pNew->pRight);
1837d94a6698Sdrh       assert( pExpr->pList==0 );
18384adee20fSdanielk1977       pExpr->pList = sqlite3ExprListDup(pNew->pList);
1839832508b7Sdrh       pExpr->iTable = pNew->iTable;
1840832508b7Sdrh       pExpr->iColumn = pNew->iColumn;
1841832508b7Sdrh       pExpr->iAgg = pNew->iAgg;
18424adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->token, &pNew->token);
18434adee20fSdanielk1977       sqlite3TokenCopy(&pExpr->span, &pNew->span);
1844a1cb183dSdanielk1977       pExpr->pSelect = sqlite3SelectDup(pNew->pSelect);
1845a1cb183dSdanielk1977       pExpr->flags = pNew->flags;
184650350a15Sdrh     }
1847832508b7Sdrh   }else{
18486a3ea0e6Sdrh     substExpr(pExpr->pLeft, iTable, pEList);
18496a3ea0e6Sdrh     substExpr(pExpr->pRight, iTable, pEList);
1850b3bce662Sdanielk1977     substSelect(pExpr->pSelect, iTable, pEList);
18516a3ea0e6Sdrh     substExprList(pExpr->pList, iTable, pEList);
1852832508b7Sdrh   }
1853832508b7Sdrh }
1854b3bce662Sdanielk1977 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
1855832508b7Sdrh   int i;
1856832508b7Sdrh   if( pList==0 ) return;
1857832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
18586a3ea0e6Sdrh     substExpr(pList->a[i].pExpr, iTable, pEList);
1859832508b7Sdrh   }
1860832508b7Sdrh }
1861b3bce662Sdanielk1977 static void substSelect(Select *p, int iTable, ExprList *pEList){
1862b3bce662Sdanielk1977   if( !p ) return;
1863b3bce662Sdanielk1977   substExprList(p->pEList, iTable, pEList);
1864b3bce662Sdanielk1977   substExprList(p->pGroupBy, iTable, pEList);
1865b3bce662Sdanielk1977   substExprList(p->pOrderBy, iTable, pEList);
1866b3bce662Sdanielk1977   substExpr(p->pHaving, iTable, pEList);
1867b3bce662Sdanielk1977   substExpr(p->pWhere, iTable, pEList);
1868b3bce662Sdanielk1977 }
1869b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */
1870832508b7Sdrh 
1871b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
1872832508b7Sdrh /*
18731350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
18741350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
18751350b030Sdrh ** occurs.
18761350b030Sdrh **
18771350b030Sdrh ** To understand the concept of flattening, consider the following
18781350b030Sdrh ** query:
18791350b030Sdrh **
18801350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
18811350b030Sdrh **
18821350b030Sdrh ** The default way of implementing this query is to execute the
18831350b030Sdrh ** subquery first and store the results in a temporary table, then
18841350b030Sdrh ** run the outer query on that temporary table.  This requires two
18851350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
18861350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
1887832508b7Sdrh ** optimized.
18881350b030Sdrh **
1889832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
18901350b030Sdrh ** a single flat select, like this:
18911350b030Sdrh **
18921350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
18931350b030Sdrh **
18941350b030Sdrh ** The code generated for this simpification gives the same result
1895832508b7Sdrh ** but only has to scan the data once.  And because indices might
1896832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
1897832508b7Sdrh ** avoided.
18981350b030Sdrh **
1899832508b7Sdrh ** Flattening is only attempted if all of the following are true:
19001350b030Sdrh **
1901832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
19021350b030Sdrh **
1903832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
1904832508b7Sdrh **
19058af4d3acSdrh **   (3)  The subquery is not the right operand of a left outer join, or
19068af4d3acSdrh **        the subquery is not itself a join.  (Ticket #306)
1907832508b7Sdrh **
1908832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
1909832508b7Sdrh **
1910832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
1911832508b7Sdrh **        aggregates.
1912832508b7Sdrh **
1913832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
1914832508b7Sdrh **        DISTINCT.
1915832508b7Sdrh **
191608192d5fSdrh **   (7)  The subquery has a FROM clause.
191708192d5fSdrh **
1918df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
1919df199a25Sdrh **
1920df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
1921df199a25Sdrh **        aggregates.
1922df199a25Sdrh **
1923df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
1924df199a25Sdrh **        use LIMIT.
1925df199a25Sdrh **
1926174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
1927174b6195Sdrh **
19283fc673e6Sdrh **  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
19293fc673e6Sdrh **        subquery has no WHERE clause.  (added by ticket #350)
19303fc673e6Sdrh **
1931832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
1932832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
1933832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
1934832508b7Sdrh **
1935665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
1936832508b7Sdrh ** If flattening is attempted this routine returns 1.
1937832508b7Sdrh **
1938832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
1939832508b7Sdrh ** the subquery before this routine runs.
19401350b030Sdrh */
19418c74a8caSdrh static int flattenSubquery(
19428c74a8caSdrh   Parse *pParse,       /* The parsing context */
19438c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
19448c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
19458c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
19468c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
19478c74a8caSdrh ){
19480bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
1949ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
1950ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
19510bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
19526a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
195391bb0eedSdrh   int i;              /* Loop counter */
195491bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
195591bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
19561350b030Sdrh 
1957832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
1958832508b7Sdrh   */
1959832508b7Sdrh   if( p==0 ) return 0;
1960832508b7Sdrh   pSrc = p->pSrc;
1961ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
196291bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
196391bb0eedSdrh   pSub = pSubitem->pSelect;
1964832508b7Sdrh   assert( pSub!=0 );
1965832508b7Sdrh   if( isAgg && subqueryIsAgg ) return 0;
1966ad3cab52Sdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
1967832508b7Sdrh   pSubSrc = pSub->pSrc;
1968832508b7Sdrh   assert( pSubSrc );
1969a2dc3b1aSdanielk1977   if( (pSub->pLimit && p->pLimit) || pSub->pOffset ||
1970a2dc3b1aSdanielk1977       (pSub->pLimit && isAgg) ) return 0;
1971c31c2eb8Sdrh   if( pSubSrc->nSrc==0 ) return 0;
1972a2dc3b1aSdanielk1977   if( pSub->isDistinct && (pSrc->nSrc>1 || isAgg) ){
1973df199a25Sdrh      return 0;
1974df199a25Sdrh   }
1975a2dc3b1aSdanielk1977   if( p->isDistinct && subqueryIsAgg ) return 0;
1976174b6195Sdrh   if( p->pOrderBy && pSub->pOrderBy ) return 0;
1977832508b7Sdrh 
19788af4d3acSdrh   /* Restriction 3:  If the subquery is a join, make sure the subquery is
19798af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
19808af4d3acSdrh   ** is not allowed:
19818af4d3acSdrh   **
19828af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
19838af4d3acSdrh   **
19848af4d3acSdrh   ** If we flatten the above, we would get
19858af4d3acSdrh   **
19868af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
19878af4d3acSdrh   **
19888af4d3acSdrh   ** which is not at all the same thing.
19898af4d3acSdrh   */
19908af4d3acSdrh   if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
19918af4d3acSdrh     return 0;
19928af4d3acSdrh   }
19938af4d3acSdrh 
19943fc673e6Sdrh   /* Restriction 12:  If the subquery is the right operand of a left outer
19953fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
19963fc673e6Sdrh   ** An examples of why this is not allowed:
19973fc673e6Sdrh   **
19983fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
19993fc673e6Sdrh   **
20003fc673e6Sdrh   ** If we flatten the above, we would get
20013fc673e6Sdrh   **
20023fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
20033fc673e6Sdrh   **
20043fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
20053fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
20063fc673e6Sdrh   */
20073fc673e6Sdrh   if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
20083fc673e6Sdrh       && pSub->pWhere!=0 ){
20093fc673e6Sdrh     return 0;
20103fc673e6Sdrh   }
20113fc673e6Sdrh 
20120bb28106Sdrh   /* If we reach this point, it means flattening is permitted for the
201363eb5f29Sdrh   ** iFrom-th entry of the FROM clause in the outer query.
2014832508b7Sdrh   */
2015c31c2eb8Sdrh 
2016c31c2eb8Sdrh   /* Move all of the FROM elements of the subquery into the
2017c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2018c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2019c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2020c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2021c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2022c31c2eb8Sdrh   ** elements we are now copying in.
2023c31c2eb8Sdrh   */
202491bb0eedSdrh   iParent = pSubitem->iCursor;
2025c31c2eb8Sdrh   {
2026c31c2eb8Sdrh     int nSubSrc = pSubSrc->nSrc;
202791bb0eedSdrh     int jointype = pSubitem->jointype;
202891bb0eedSdrh     Table *pTab = pSubitem->pTab;
2029c31c2eb8Sdrh 
203091bb0eedSdrh     if( pTab && pTab->isTransient ){
203191bb0eedSdrh       sqlite3DeleteTable(0, pSubitem->pTab);
2032c31c2eb8Sdrh     }
203391bb0eedSdrh     sqliteFree(pSubitem->zDatabase);
203491bb0eedSdrh     sqliteFree(pSubitem->zName);
203591bb0eedSdrh     sqliteFree(pSubitem->zAlias);
2036c31c2eb8Sdrh     if( nSubSrc>1 ){
2037c31c2eb8Sdrh       int extra = nSubSrc - 1;
2038c31c2eb8Sdrh       for(i=1; i<nSubSrc; i++){
20394adee20fSdanielk1977         pSrc = sqlite3SrcListAppend(pSrc, 0, 0);
2040c31c2eb8Sdrh       }
2041c31c2eb8Sdrh       p->pSrc = pSrc;
2042c31c2eb8Sdrh       for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
2043c31c2eb8Sdrh         pSrc->a[i] = pSrc->a[i-extra];
2044c31c2eb8Sdrh       }
2045c31c2eb8Sdrh     }
2046c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2047c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2048c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2049c31c2eb8Sdrh     }
20508af4d3acSdrh     pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
2051c31c2eb8Sdrh   }
2052c31c2eb8Sdrh 
2053c31c2eb8Sdrh   /* Now begin substituting subquery result set expressions for
2054c31c2eb8Sdrh   ** references to the iParent in the outer query.
2055c31c2eb8Sdrh   **
2056c31c2eb8Sdrh   ** Example:
2057c31c2eb8Sdrh   **
2058c31c2eb8Sdrh   **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2059c31c2eb8Sdrh   **   \                     \_____________ subquery __________/          /
2060c31c2eb8Sdrh   **    \_____________________ outer query ______________________________/
2061c31c2eb8Sdrh   **
2062c31c2eb8Sdrh   ** We look at every expression in the outer query and every place we see
2063c31c2eb8Sdrh   ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2064c31c2eb8Sdrh   */
20656a3ea0e6Sdrh   substExprList(p->pEList, iParent, pSub->pEList);
2066832508b7Sdrh   pList = p->pEList;
2067832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
20686977fea8Sdrh     Expr *pExpr;
20696977fea8Sdrh     if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
20706977fea8Sdrh       pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
2071832508b7Sdrh     }
2072832508b7Sdrh   }
20731b2e0329Sdrh   if( isAgg ){
20746a3ea0e6Sdrh     substExprList(p->pGroupBy, iParent, pSub->pEList);
20756a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
20761b2e0329Sdrh   }
2077174b6195Sdrh   if( pSub->pOrderBy ){
2078174b6195Sdrh     assert( p->pOrderBy==0 );
2079174b6195Sdrh     p->pOrderBy = pSub->pOrderBy;
2080174b6195Sdrh     pSub->pOrderBy = 0;
2081174b6195Sdrh   }else if( p->pOrderBy ){
20826a3ea0e6Sdrh     substExprList(p->pOrderBy, iParent, pSub->pEList);
2083174b6195Sdrh   }
2084832508b7Sdrh   if( pSub->pWhere ){
20854adee20fSdanielk1977     pWhere = sqlite3ExprDup(pSub->pWhere);
2086832508b7Sdrh   }else{
2087832508b7Sdrh     pWhere = 0;
2088832508b7Sdrh   }
2089832508b7Sdrh   if( subqueryIsAgg ){
2090832508b7Sdrh     assert( p->pHaving==0 );
20911b2e0329Sdrh     p->pHaving = p->pWhere;
20921b2e0329Sdrh     p->pWhere = pWhere;
20936a3ea0e6Sdrh     substExpr(p->pHaving, iParent, pSub->pEList);
209491bb0eedSdrh     p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving));
20951b2e0329Sdrh     assert( p->pGroupBy==0 );
20964adee20fSdanielk1977     p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy);
2097832508b7Sdrh   }else{
20986a3ea0e6Sdrh     substExpr(p->pWhere, iParent, pSub->pEList);
209991bb0eedSdrh     p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere);
2100832508b7Sdrh   }
2101c31c2eb8Sdrh 
2102c31c2eb8Sdrh   /* The flattened query is distinct if either the inner or the
2103c31c2eb8Sdrh   ** outer query is distinct.
2104c31c2eb8Sdrh   */
2105832508b7Sdrh   p->isDistinct = p->isDistinct || pSub->isDistinct;
21068c74a8caSdrh 
2107a58fdfb1Sdanielk1977   /*
2108a58fdfb1Sdanielk1977   ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2109a58fdfb1Sdanielk1977   */
2110a2dc3b1aSdanielk1977   if( pSub->pLimit ){
2111a2dc3b1aSdanielk1977     p->pLimit = pSub->pLimit;
2112a2dc3b1aSdanielk1977     pSub->pLimit = 0;
2113df199a25Sdrh   }
21148c74a8caSdrh 
2115c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2116c31c2eb8Sdrh   ** success.
2117c31c2eb8Sdrh   */
21184adee20fSdanielk1977   sqlite3SelectDelete(pSub);
2119832508b7Sdrh   return 1;
21201350b030Sdrh }
2121b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */
21221350b030Sdrh 
21231350b030Sdrh /*
21249562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it
21259562b551Sdrh ** is a simple min() or max() query.  If it is and this query can be
21269562b551Sdrh ** satisfied using a single seek to the beginning or end of an index,
2127e78e8284Sdrh ** then generate the code for this SELECT and return 1.  If this is not a
21289562b551Sdrh ** simple min() or max() query, then return 0;
21299562b551Sdrh **
21309562b551Sdrh ** A simply min() or max() query looks like this:
21319562b551Sdrh **
21329562b551Sdrh **    SELECT min(a) FROM table;
21339562b551Sdrh **    SELECT max(a) FROM table;
21349562b551Sdrh **
21359562b551Sdrh ** The query may have only a single table in its FROM argument.  There
21369562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
21379562b551Sdrh ** be the min() or max() of a single column of the table.  The column
21389562b551Sdrh ** in the min() or max() function must be indexed.
21399562b551Sdrh **
21404adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select().
21419562b551Sdrh ** See the header comment on that routine for additional information.
21429562b551Sdrh */
21439562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
21449562b551Sdrh   Expr *pExpr;
21459562b551Sdrh   int iCol;
21469562b551Sdrh   Table *pTab;
21479562b551Sdrh   Index *pIdx;
21489562b551Sdrh   int base;
21499562b551Sdrh   Vdbe *v;
21509562b551Sdrh   int seekOp;
21519562b551Sdrh   int cont;
21526e17529eSdrh   ExprList *pEList, *pList, eList;
21539562b551Sdrh   struct ExprList_item eListItem;
21546e17529eSdrh   SrcList *pSrc;
21556e17529eSdrh 
21569562b551Sdrh   /* Check to see if this query is a simple min() or max() query.  Return
21579562b551Sdrh   ** zero if it is  not.
21589562b551Sdrh   */
21599562b551Sdrh   if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
21606e17529eSdrh   pSrc = p->pSrc;
21616e17529eSdrh   if( pSrc->nSrc!=1 ) return 0;
21626e17529eSdrh   pEList = p->pEList;
21636e17529eSdrh   if( pEList->nExpr!=1 ) return 0;
21646e17529eSdrh   pExpr = pEList->a[0].pExpr;
21659562b551Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
21666e17529eSdrh   pList = pExpr->pList;
21676e17529eSdrh   if( pList==0 || pList->nExpr!=1 ) return 0;
21686977fea8Sdrh   if( pExpr->token.n!=3 ) return 0;
21694adee20fSdanielk1977   if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){
21700bce8354Sdrh     seekOp = OP_Rewind;
21714adee20fSdanielk1977   }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){
21720bce8354Sdrh     seekOp = OP_Last;
21730bce8354Sdrh   }else{
21740bce8354Sdrh     return 0;
21750bce8354Sdrh   }
21766e17529eSdrh   pExpr = pList->a[0].pExpr;
21779562b551Sdrh   if( pExpr->op!=TK_COLUMN ) return 0;
21789562b551Sdrh   iCol = pExpr->iColumn;
21796e17529eSdrh   pTab = pSrc->a[0].pTab;
21809562b551Sdrh 
21819562b551Sdrh   /* If we get to here, it means the query is of the correct form.
218217f71934Sdrh   ** Check to make sure we have an index and make pIdx point to the
218317f71934Sdrh   ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
218417f71934Sdrh   ** key column, no index is necessary so set pIdx to NULL.  If no
218517f71934Sdrh   ** usable index is found, return 0.
21869562b551Sdrh   */
21879562b551Sdrh   if( iCol<0 ){
21889562b551Sdrh     pIdx = 0;
21899562b551Sdrh   }else{
2190dc1bdc4fSdanielk1977     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
21919562b551Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
21929562b551Sdrh       assert( pIdx->nColumn>=1 );
2193dc1bdc4fSdanielk1977       if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break;
21949562b551Sdrh     }
21959562b551Sdrh     if( pIdx==0 ) return 0;
21969562b551Sdrh   }
21979562b551Sdrh 
2198e5f50722Sdrh   /* Identify column types if we will be using the callback.  This
21999562b551Sdrh   ** step is skipped if the output is going to a table or a memory cell.
2200e5f50722Sdrh   ** The column names have already been generated in the calling function.
22019562b551Sdrh   */
22024adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
22039562b551Sdrh   if( v==0 ) return 0;
22049562b551Sdrh 
22050c37e630Sdrh   /* If the output is destined for a temporary table, open that table.
22060c37e630Sdrh   */
22070c37e630Sdrh   if( eDest==SRT_TempTable ){
22084adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2209b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1);
22100c37e630Sdrh   }
22110c37e630Sdrh 
221217f71934Sdrh   /* Generating code to find the min or the max.  Basically all we have
221317f71934Sdrh   ** to do is find the first or the last entry in the chosen index.  If
221417f71934Sdrh   ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
221517f71934Sdrh   ** or last entry in the main table.
22169562b551Sdrh   */
22174adee20fSdanielk1977   sqlite3CodeVerifySchema(pParse, pTab->iDb);
22186e17529eSdrh   base = pSrc->a[0].iCursor;
22197b58daeaSdrh   computeLimitRegisters(pParse, p);
22206e17529eSdrh   if( pSrc->a[0].pSelect==0 ){
2221ad6d9460Sdrh     sqlite3OpenTableForReading(v, base, pTab);
22226e17529eSdrh   }
22234adee20fSdanielk1977   cont = sqlite3VdbeMakeLabel(v);
22249562b551Sdrh   if( pIdx==0 ){
22254adee20fSdanielk1977     sqlite3VdbeAddOp(v, seekOp, base, 0);
22269562b551Sdrh   }else{
22273719d7f9Sdanielk1977     /* Even though the cursor used to open the index here is closed
22283719d7f9Sdanielk1977     ** as soon as a single value has been read from it, allocate it
22293719d7f9Sdanielk1977     ** using (pParse->nTab++) to prevent the cursor id from being
22303719d7f9Sdanielk1977     ** reused. This is important for statements of the form
22313719d7f9Sdanielk1977     ** "INSERT INTO x SELECT max() FROM x".
22323719d7f9Sdanielk1977     */
22333719d7f9Sdanielk1977     int iIdx;
22343719d7f9Sdanielk1977     iIdx = pParse->nTab++;
22354adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
22363719d7f9Sdanielk1977     sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum,
2237d3d39e93Sdrh                    (char*)&pIdx->keyInfo, P3_KEYINFO);
22389eb516c0Sdrh     if( seekOp==OP_Rewind ){
22391af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_String, 0, 0);
22401af3fdb4Sdrh       sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
22411af3fdb4Sdrh       seekOp = OP_MoveGt;
22429eb516c0Sdrh     }
22433719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
22443719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, OP_IdxRecno, iIdx, 0);
22453719d7f9Sdanielk1977     sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
22467cf6e4deSdrh     sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
22479562b551Sdrh   }
22485cf8e8c7Sdrh   eList.nExpr = 1;
22495cf8e8c7Sdrh   memset(&eListItem, 0, sizeof(eListItem));
22505cf8e8c7Sdrh   eList.a = &eListItem;
22515cf8e8c7Sdrh   eList.a[0].pExpr = pExpr;
225284ac9d02Sdanielk1977   selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0);
22534adee20fSdanielk1977   sqlite3VdbeResolveLabel(v, cont);
22544adee20fSdanielk1977   sqlite3VdbeAddOp(v, OP_Close, base, 0);
22556e17529eSdrh 
22569562b551Sdrh   return 1;
22579562b551Sdrh }
22589562b551Sdrh 
22599562b551Sdrh /*
2260290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
2261290c1948Sdrh ** the number of errors seen.
2262290c1948Sdrh **
2263290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions.  If any expression
2264290c1948Sdrh ** is an integer constant, then that expression is replaced by the
2265290c1948Sdrh ** corresponding entry in the result set.
2266290c1948Sdrh */
2267290c1948Sdrh static int processOrderGroupBy(
2268b3bce662Sdanielk1977   NameContext *pNC,     /* Name context of the SELECT statement. */
2269290c1948Sdrh   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
2270290c1948Sdrh   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
2271290c1948Sdrh ){
2272290c1948Sdrh   int i;
2273b3bce662Sdanielk1977   ExprList *pEList = pNC->pEList;     /* The result set of the SELECT */
2274b3bce662Sdanielk1977   Parse *pParse = pNC->pParse;     /* The result set of the SELECT */
2275b3bce662Sdanielk1977   assert( pEList );
2276b3bce662Sdanielk1977 
2277290c1948Sdrh   if( pOrderBy==0 ) return 0;
2278290c1948Sdrh   for(i=0; i<pOrderBy->nExpr; i++){
2279290c1948Sdrh     int iCol;
2280290c1948Sdrh     Expr *pE = pOrderBy->a[i].pExpr;
2281b3bce662Sdanielk1977     if( sqlite3ExprIsInteger(pE, &iCol) ){
2282b3bce662Sdanielk1977       if( iCol>0 && iCol<=pEList->nExpr ){
2283290c1948Sdrh         sqlite3ExprDelete(pE);
2284290c1948Sdrh         pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
2285b3bce662Sdanielk1977       }else{
2286290c1948Sdrh         sqlite3ErrorMsg(pParse,
2287290c1948Sdrh            "%s BY column number %d out of range - should be "
2288290c1948Sdrh            "between 1 and %d", zType, iCol, pEList->nExpr);
2289290c1948Sdrh         return 1;
2290290c1948Sdrh       }
2291290c1948Sdrh     }
2292b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(pNC, pE) ){
2293b3bce662Sdanielk1977       return 1;
2294b3bce662Sdanielk1977     }
2295b3bce662Sdanielk1977     if( sqlite3ExprIsConstant(pE) ){
2296b3bce662Sdanielk1977       sqlite3ErrorMsg(pParse,
2297b3bce662Sdanielk1977           "%s BY terms must not be non-integer constants", zType);
2298b3bce662Sdanielk1977       return 1;
2299b3bce662Sdanielk1977     }
2300290c1948Sdrh   }
2301290c1948Sdrh   return 0;
2302290c1948Sdrh }
2303290c1948Sdrh 
2304290c1948Sdrh /*
2305b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the
2306b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved
2307b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext
2308b3bce662Sdanielk1977 ** of the parent SELECT.
2309b3bce662Sdanielk1977 */
2310b3bce662Sdanielk1977 int sqlite3SelectResolve(
2311b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
2312b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
2313b3bce662Sdanielk1977   NameContext *pOuterNC  /* The outer name context. May be NULL. */
2314b3bce662Sdanielk1977 ){
2315b3bce662Sdanielk1977   ExprList *pEList;          /* Result set. */
2316b3bce662Sdanielk1977   int i;                     /* For-loop variable used in multiple places */
2317b3bce662Sdanielk1977   NameContext sNC;           /* Local name-context */
2318b3bce662Sdanielk1977 
2319b3bce662Sdanielk1977   /* If this routine has run before, return immediately. */
2320b3bce662Sdanielk1977   if( p->isResolved ){
2321b3bce662Sdanielk1977     assert( !pOuterNC );
2322b3bce662Sdanielk1977     return SQLITE_OK;
2323b3bce662Sdanielk1977   }
2324b3bce662Sdanielk1977   p->isResolved = 1;
2325b3bce662Sdanielk1977 
2326b3bce662Sdanielk1977   /* If there have already been errors, do nothing. */
2327b3bce662Sdanielk1977   if( pParse->nErr>0 ){
2328b3bce662Sdanielk1977     return SQLITE_ERROR;
2329b3bce662Sdanielk1977   }
2330b3bce662Sdanielk1977 
2331b3bce662Sdanielk1977   /* Prepare the select statement. This call will allocate all cursors
2332b3bce662Sdanielk1977   ** required to handle the tables and subqueries in the FROM clause.
2333b3bce662Sdanielk1977   */
2334b3bce662Sdanielk1977   if( prepSelectStmt(pParse, p) ){
2335b3bce662Sdanielk1977     return SQLITE_ERROR;
2336b3bce662Sdanielk1977   }
2337b3bce662Sdanielk1977 
2338a2dc3b1aSdanielk1977   /* Resolve the expressions in the LIMIT and OFFSET clauses. These
2339a2dc3b1aSdanielk1977   ** are not allowed to refer to any names, so pass an empty NameContext.
2340a2dc3b1aSdanielk1977   */
2341b3bce662Sdanielk1977   sNC.pParse = pParse;
2342b3bce662Sdanielk1977   sNC.hasAgg = 0;
2343b3bce662Sdanielk1977   sNC.nErr = 0;
2344b3bce662Sdanielk1977   sNC.nRef = 0;
2345b3bce662Sdanielk1977   sNC.pEList = 0;
2346a2dc3b1aSdanielk1977   sNC.allowAgg = 0;
2347a2dc3b1aSdanielk1977   sNC.pSrcList = 0;
2348a2dc3b1aSdanielk1977   sNC.pNext = 0;
2349a2dc3b1aSdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
2350a2dc3b1aSdanielk1977       sqlite3ExprResolveNames(&sNC, p->pOffset) ){
2351a2dc3b1aSdanielk1977     return SQLITE_ERROR;
2352a2dc3b1aSdanielk1977   }
2353a2dc3b1aSdanielk1977 
2354a2dc3b1aSdanielk1977   /* Set up the local name-context to pass to ExprResolveNames() to
2355a2dc3b1aSdanielk1977   ** resolve the expression-list.
2356a2dc3b1aSdanielk1977   */
2357a2dc3b1aSdanielk1977   sNC.allowAgg = 1;
2358a2dc3b1aSdanielk1977   sNC.pSrcList = p->pSrc;
2359a2dc3b1aSdanielk1977   sNC.pNext = pOuterNC;
2360b3bce662Sdanielk1977 
2361b3bce662Sdanielk1977   /* NameContext.nDepth stores the depth of recursion for this query. For
2362b3bce662Sdanielk1977   ** an outer query (e.g. SELECT * FROM sqlite_master) this is 1. For
2363b3bce662Sdanielk1977   ** a subquery it is 2. For a subquery of a subquery, 3. And so on.
2364b3bce662Sdanielk1977   ** Parse.nMaxDepth is the maximum depth for any subquery resolved so
2365b3bce662Sdanielk1977   ** far. This is used to determine the number of aggregate contexts
2366b3bce662Sdanielk1977   ** required at runtime.
2367b3bce662Sdanielk1977   */
2368b3bce662Sdanielk1977   sNC.nDepth = (pOuterNC?pOuterNC->nDepth+1:1);
2369b3bce662Sdanielk1977   if( sNC.nDepth>pParse->nMaxDepth ){
2370b3bce662Sdanielk1977     pParse->nMaxDepth = sNC.nDepth;
2371b3bce662Sdanielk1977   }
2372b3bce662Sdanielk1977 
2373b3bce662Sdanielk1977   /* Resolve names in the result set. */
2374b3bce662Sdanielk1977   pEList = p->pEList;
2375b3bce662Sdanielk1977   if( !pEList ) return SQLITE_ERROR;
2376b3bce662Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
2377b3bce662Sdanielk1977     Expr *pX = pEList->a[i].pExpr;
2378b3bce662Sdanielk1977     if( sqlite3ExprResolveNames(&sNC, pX) ){
2379b3bce662Sdanielk1977       return SQLITE_ERROR;
2380b3bce662Sdanielk1977     }
2381b3bce662Sdanielk1977   }
2382b3bce662Sdanielk1977 
2383b3bce662Sdanielk1977   /* If there are no aggregate functions in the result-set, and no GROUP BY
2384b3bce662Sdanielk1977   ** expression, do not allow aggregates in any of the other expressions.
2385b3bce662Sdanielk1977   */
2386b3bce662Sdanielk1977   assert( !p->isAgg );
2387b3bce662Sdanielk1977   if( p->pGroupBy || sNC.hasAgg ){
2388b3bce662Sdanielk1977     p->isAgg = 1;
2389b3bce662Sdanielk1977   }else{
2390b3bce662Sdanielk1977     sNC.allowAgg = 0;
2391b3bce662Sdanielk1977   }
2392b3bce662Sdanielk1977 
2393b3bce662Sdanielk1977   /* If a HAVING clause is present, then there must be a GROUP BY clause.
2394b3bce662Sdanielk1977   */
2395b3bce662Sdanielk1977   if( p->pHaving && !p->pGroupBy ){
2396b3bce662Sdanielk1977     sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
2397b3bce662Sdanielk1977     return SQLITE_ERROR;
2398b3bce662Sdanielk1977   }
2399b3bce662Sdanielk1977 
2400b3bce662Sdanielk1977   /* Add the expression list to the name-context before parsing the
2401b3bce662Sdanielk1977   ** other expressions in the SELECT statement. This is so that
2402b3bce662Sdanielk1977   ** expressions in the WHERE clause (etc.) can refer to expressions by
2403b3bce662Sdanielk1977   ** aliases in the result set.
2404b3bce662Sdanielk1977   **
2405b3bce662Sdanielk1977   ** Minor point: If this is the case, then the expression will be
2406b3bce662Sdanielk1977   ** re-evaluated for each reference to it.
2407b3bce662Sdanielk1977   */
2408b3bce662Sdanielk1977   sNC.pEList = p->pEList;
2409b3bce662Sdanielk1977   if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
2410b3bce662Sdanielk1977       sqlite3ExprResolveNames(&sNC, p->pHaving) ||
2411b3bce662Sdanielk1977       processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
2412b3bce662Sdanielk1977       processOrderGroupBy(&sNC, p->pGroupBy, "GROUP")
2413b3bce662Sdanielk1977   ){
2414b3bce662Sdanielk1977     return SQLITE_ERROR;
2415b3bce662Sdanielk1977   }
2416b3bce662Sdanielk1977 
2417b3bce662Sdanielk1977   return SQLITE_OK;
2418b3bce662Sdanielk1977 }
2419b3bce662Sdanielk1977 
2420b3bce662Sdanielk1977 /*
2421b3bce662Sdanielk1977 ** An instance of the following struct is used by sqlite3Select()
2422b3bce662Sdanielk1977 ** to save aggregate related information from the Parse object
2423b3bce662Sdanielk1977 ** at the start of each call and to restore it at the end. See
2424b3bce662Sdanielk1977 ** saveAggregateInfo() and restoreAggregateInfo().
2425b3bce662Sdanielk1977 */
2426b3bce662Sdanielk1977 struct AggregateInfo {
2427b3bce662Sdanielk1977   int nAgg;
2428b3bce662Sdanielk1977   AggExpr *aAgg;
2429b3bce662Sdanielk1977 };
2430b3bce662Sdanielk1977 typedef struct AggregateInfo AggregateInfo;
2431b3bce662Sdanielk1977 
2432b3bce662Sdanielk1977 /*
2433b3bce662Sdanielk1977 ** Copy aggregate related information from the Parse structure
2434b3bce662Sdanielk1977 ** into the AggregateInfo structure. Zero the aggregate related
2435b3bce662Sdanielk1977 ** values in the Parse struct.
2436b3bce662Sdanielk1977 */
2437b3bce662Sdanielk1977 static void saveAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2438b3bce662Sdanielk1977   pInfo->aAgg = pParse->aAgg;
2439b3bce662Sdanielk1977   pInfo->nAgg = pParse->nAgg;
2440b3bce662Sdanielk1977   pParse->aAgg = 0;
2441b3bce662Sdanielk1977   pParse->nAgg = 0;
2442b3bce662Sdanielk1977 }
2443b3bce662Sdanielk1977 
2444b3bce662Sdanielk1977 /*
2445b3bce662Sdanielk1977 ** Copy aggregate related information from the AggregateInfo struct
2446b3bce662Sdanielk1977 ** back into the Parse structure. The aggregate related information
2447b3bce662Sdanielk1977 ** currently stored in the Parse structure is deleted.
2448b3bce662Sdanielk1977 */
2449b3bce662Sdanielk1977 static void restoreAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
2450b3bce662Sdanielk1977   sqliteFree(pParse->aAgg);
2451b3bce662Sdanielk1977   pParse->aAgg = pInfo->aAgg;
2452b3bce662Sdanielk1977   pParse->nAgg = pInfo->nAgg;
2453b3bce662Sdanielk1977 }
2454b3bce662Sdanielk1977 
2455b3bce662Sdanielk1977 /*
24569bb61fe7Sdrh ** Generate code for the given SELECT statement.
24579bb61fe7Sdrh **
2458fef5208cSdrh ** The results are distributed in various ways depending on the
2459fef5208cSdrh ** value of eDest and iParm.
2460fef5208cSdrh **
2461fef5208cSdrh **     eDest Value       Result
2462fef5208cSdrh **     ------------    -------------------------------------------
2463fef5208cSdrh **     SRT_Callback    Invoke the callback for each row of the result.
2464fef5208cSdrh **
2465fef5208cSdrh **     SRT_Mem         Store first result in memory cell iParm
2466fef5208cSdrh **
2467e014a838Sdanielk1977 **     SRT_Set         Store results as keys of table iParm.
2468fef5208cSdrh **
246982c3d636Sdrh **     SRT_Union       Store results as a key in a temporary table iParm
247082c3d636Sdrh **
24714b11c6d3Sjplyon **     SRT_Except      Remove results from the temporary table iParm.
2472c4a3c779Sdrh **
2473c4a3c779Sdrh **     SRT_Table       Store results in temporary table iParm
24749bb61fe7Sdrh **
2475e78e8284Sdrh ** The table above is incomplete.  Additional eDist value have be added
2476e78e8284Sdrh ** since this comment was written.  See the selectInnerLoop() function for
2477e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings.
2478e78e8284Sdrh **
24799bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
24809bb61fe7Sdrh ** encountered, then an appropriate error message is left in
24819bb61fe7Sdrh ** pParse->zErrMsg.
24829bb61fe7Sdrh **
24839bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
24849bb61fe7Sdrh ** calling function needs to do that.
24851b2e0329Sdrh **
24861b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this
24871b2e0329Sdrh ** SELECT is a subquery.  This routine may try to combine this SELECT
24881b2e0329Sdrh ** with its parent to form a single flat query.  In so doing, it might
24891b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query.
24901b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it
24911b2e0329Sdrh ** can be changed.
2492e78e8284Sdrh **
2493e78e8284Sdrh ** Example 1:   The meaning of the pParent parameter.
2494e78e8284Sdrh **
2495e78e8284Sdrh **    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
2496e78e8284Sdrh **    \                      \_______ subquery _______/        /
2497e78e8284Sdrh **     \                                                      /
2498e78e8284Sdrh **      \____________________ outer query ___________________/
2499e78e8284Sdrh **
2500e78e8284Sdrh ** This routine is called for the outer query first.   For that call,
2501e78e8284Sdrh ** pParent will be NULL.  During the processing of the outer query, this
2502e78e8284Sdrh ** routine is called recursively to handle the subquery.  For the recursive
2503e78e8284Sdrh ** call, pParent will point to the outer query.  Because the subquery is
2504e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will
2505e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.)
25069bb61fe7Sdrh */
25074adee20fSdanielk1977 int sqlite3Select(
2508cce7d176Sdrh   Parse *pParse,         /* The parser context */
25099bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
2510e78e8284Sdrh   int eDest,             /* How to dispose of the results */
2511e78e8284Sdrh   int iParm,             /* A parameter used by the eDest disposal method */
2512832508b7Sdrh   Select *pParent,       /* Another SELECT for which this is a sub-query */
2513832508b7Sdrh   int parentTab,         /* Index in pParent->pSrc of this query */
251484ac9d02Sdanielk1977   int *pParentAgg,       /* True if pParent uses aggregate functions */
2515b3bce662Sdanielk1977   char *aff              /* If eDest is SRT_Union, the affinity string */
2516cce7d176Sdrh ){
2517d8bc7086Sdrh   int i;
2518cce7d176Sdrh   WhereInfo *pWInfo;
2519cce7d176Sdrh   Vdbe *v;
2520b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
2521a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
2522ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
25239bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
25249bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
25252282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
25262282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
252719a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
252819a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
25291d83f052Sdrh   int rc = 1;            /* Value to return from this function */
2530b3bce662Sdanielk1977   AggregateInfo sAggInfo;
25319bb61fe7Sdrh 
25326f8a503dSdanielk1977   if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
25334adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
2534daffd0e5Sdrh 
2535b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
253682c3d636Sdrh   /* If there is are a sequence of queries, do the earlier ones first.
253782c3d636Sdrh   */
253882c3d636Sdrh   if( p->pPrior ){
253984ac9d02Sdanielk1977     return multiSelect(pParse, p, eDest, iParm, aff);
254082c3d636Sdrh   }
2541b7f9164eSdrh #endif
254282c3d636Sdrh 
2543b3bce662Sdanielk1977   saveAggregateInfo(pParse, &sAggInfo);
2544b3bce662Sdanielk1977   pOrderBy = p->pOrderBy;
2545b3bce662Sdanielk1977   if( eDest==SRT_Union || eDest==SRT_Except || eDest==SRT_Discard ){
2546b3bce662Sdanielk1977     p->pOrderBy = 0;
2547b3bce662Sdanielk1977   }
2548b3bce662Sdanielk1977   if( sqlite3SelectResolve(pParse, p, 0) ){
2549b3bce662Sdanielk1977     goto select_end;
2550b3bce662Sdanielk1977   }
2551b3bce662Sdanielk1977   p->pOrderBy = pOrderBy;
2552b3bce662Sdanielk1977 
255382c3d636Sdrh   /* Make local copies of the parameters for this query.
255482c3d636Sdrh   */
25559bb61fe7Sdrh   pTabList = p->pSrc;
25569bb61fe7Sdrh   pWhere = p->pWhere;
25572282792aSdrh   pGroupBy = p->pGroupBy;
25582282792aSdrh   pHaving = p->pHaving;
2559b3bce662Sdanielk1977   isAgg = p->isAgg;
256019a775c2Sdrh   isDistinct = p->isDistinct;
2561b3bce662Sdanielk1977   pEList = p->pEList;
2562b3bce662Sdanielk1977   if( pEList==0 ) goto select_end;
25639bb61fe7Sdrh 
25649bb61fe7Sdrh   /*
25659bb61fe7Sdrh   ** Do not even attempt to generate any code if we have already seen
25669bb61fe7Sdrh   ** errors before this routine starts.
25679bb61fe7Sdrh   */
25681d83f052Sdrh   if( pParse->nErr>0 ) goto select_end;
2569cce7d176Sdrh 
25702282792aSdrh   /* If writing to memory or generating a set
25712282792aSdrh   ** only a single column may be output.
257219a775c2Sdrh   */
257351522cd3Sdrh   assert( eDest!=SRT_Exists || pEList->nExpr==1 );
257493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
2575fef5208cSdrh   if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
25764adee20fSdanielk1977     sqlite3ErrorMsg(pParse, "only a single result allowed for "
2577da93d238Sdrh        "a SELECT that is part of an expression");
25781d83f052Sdrh     goto select_end;
257919a775c2Sdrh   }
258093758c8dSdanielk1977 #endif
258119a775c2Sdrh 
2582c926afbcSdrh   /* ORDER BY is ignored for some destinations.
25832282792aSdrh   */
2584c926afbcSdrh   switch( eDest ){
2585c926afbcSdrh     case SRT_Union:
2586c926afbcSdrh     case SRT_Except:
2587c926afbcSdrh     case SRT_Discard:
2588acd4c695Sdrh       pOrderBy = 0;
2589c926afbcSdrh       break;
2590c926afbcSdrh     default:
2591c926afbcSdrh       break;
25922282792aSdrh   }
25932282792aSdrh 
2594d820cb1bSdrh   /* Begin generating code.
2595d820cb1bSdrh   */
25964adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
2597d820cb1bSdrh   if( v==0 ) goto select_end;
2598d820cb1bSdrh 
2599e78e8284Sdrh   /* Identify column names if we will be using them in a callback.  This
2600e78e8284Sdrh   ** step is skipped if the output is going to some other destination.
26010bb28106Sdrh   */
26020bb28106Sdrh   if( eDest==SRT_Callback ){
26036a3ea0e6Sdrh     generateColumnNames(pParse, pTabList, pEList);
26040bb28106Sdrh   }
26050bb28106Sdrh 
2606d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
2607d820cb1bSdrh   */
260851522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2609ad3cab52Sdrh   for(i=0; i<pTabList->nSrc; i++){
2610742f947bSdanielk1977     const char *zSavedAuthContext = 0;
2611c31c2eb8Sdrh     int needRestoreContext;
2612c31c2eb8Sdrh 
2613a76b5dfcSdrh     if( pTabList->a[i].pSelect==0 ) continue;
26145cf590c1Sdrh     if( pTabList->a[i].zName!=0 ){
26155cf590c1Sdrh       zSavedAuthContext = pParse->zAuthContext;
26165cf590c1Sdrh       pParse->zAuthContext = pTabList->a[i].zName;
2617c31c2eb8Sdrh       needRestoreContext = 1;
2618c31c2eb8Sdrh     }else{
2619c31c2eb8Sdrh       needRestoreContext = 0;
26205cf590c1Sdrh     }
26214adee20fSdanielk1977     sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable,
2622b3bce662Sdanielk1977                  pTabList->a[i].iCursor, p, i, &isAgg, 0);
2623c31c2eb8Sdrh     if( needRestoreContext ){
26245cf590c1Sdrh       pParse->zAuthContext = zSavedAuthContext;
26255cf590c1Sdrh     }
2626832508b7Sdrh     pTabList = p->pSrc;
2627832508b7Sdrh     pWhere = p->pWhere;
2628c31c2eb8Sdrh     if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
2629832508b7Sdrh       pOrderBy = p->pOrderBy;
2630acd4c695Sdrh     }
2631832508b7Sdrh     pGroupBy = p->pGroupBy;
2632832508b7Sdrh     pHaving = p->pHaving;
2633832508b7Sdrh     isDistinct = p->isDistinct;
26341b2e0329Sdrh   }
263551522cd3Sdrh #endif
26361b2e0329Sdrh 
26376e17529eSdrh   /* Check for the special case of a min() or max() function by itself
26386e17529eSdrh   ** in the result set.
26396e17529eSdrh   */
26406e17529eSdrh   if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
26416e17529eSdrh     rc = 0;
26426e17529eSdrh     goto select_end;
26436e17529eSdrh   }
26446e17529eSdrh 
26451b2e0329Sdrh   /* Check to see if this is a subquery that can be "flattened" into its parent.
26461b2e0329Sdrh   ** If flattening is a possiblity, do so and return immediately.
26471b2e0329Sdrh   */
2648b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW
26491b2e0329Sdrh   if( pParent && pParentAgg &&
26508c74a8caSdrh       flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
26511b2e0329Sdrh     if( isAgg ) *pParentAgg = 1;
2652b3bce662Sdanielk1977     goto select_end;
26531b2e0329Sdrh   }
2654b7f9164eSdrh #endif
2655832508b7Sdrh 
26567cedc8d4Sdanielk1977   /* If there is an ORDER BY clause, resolve any collation sequences
26577cedc8d4Sdanielk1977   ** names that have been explicitly specified.
26587cedc8d4Sdanielk1977   */
26597cedc8d4Sdanielk1977   if( pOrderBy ){
26607cedc8d4Sdanielk1977     for(i=0; i<pOrderBy->nExpr; i++){
26617cedc8d4Sdanielk1977       if( pOrderBy->a[i].zName ){
26627cedc8d4Sdanielk1977         pOrderBy->a[i].pExpr->pColl =
26637cedc8d4Sdanielk1977             sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1);
26647cedc8d4Sdanielk1977       }
26657cedc8d4Sdanielk1977     }
26667cedc8d4Sdanielk1977     if( pParse->nErr ){
26677cedc8d4Sdanielk1977       goto select_end;
26687cedc8d4Sdanielk1977     }
26697cedc8d4Sdanielk1977   }
26707cedc8d4Sdanielk1977 
26717b58daeaSdrh   /* Set the limiter.
26727b58daeaSdrh   */
26737b58daeaSdrh   computeLimitRegisters(pParse, p);
26747b58daeaSdrh 
26752d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
26762d0794e3Sdrh   */
26772d0794e3Sdrh   if( eDest==SRT_TempTable ){
26784adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
2679b4964b72Sdanielk1977     sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
26802d0794e3Sdrh   }
26812d0794e3Sdrh 
26822282792aSdrh   /* Do an analysis of aggregate expressions.
2683efb7251dSdrh   */
2684bb999ef6Sdrh   if( isAgg || pGroupBy ){
2685a58fdfb1Sdanielk1977     NameContext sNC;
2686a58fdfb1Sdanielk1977     memset(&sNC, 0, sizeof(sNC));
2687a58fdfb1Sdanielk1977     sNC.pParse = pParse;
2688a58fdfb1Sdanielk1977     sNC.pSrcList = pTabList;
2689a58fdfb1Sdanielk1977 
26900bce8354Sdrh     assert( pParse->nAgg==0 );
2691bb999ef6Sdrh     isAgg = 1;
26922282792aSdrh     for(i=0; i<pEList->nExpr; i++){
2693a58fdfb1Sdanielk1977       if( sqlite3ExprAnalyzeAggregates(&sNC, pEList->a[i].pExpr) ){
26941d83f052Sdrh         goto select_end;
26952282792aSdrh       }
26962282792aSdrh     }
26972282792aSdrh     if( pGroupBy ){
26982282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
2699a58fdfb1Sdanielk1977         if( sqlite3ExprAnalyzeAggregates(&sNC, pGroupBy->a[i].pExpr) ){
27001d83f052Sdrh           goto select_end;
27012282792aSdrh         }
27022282792aSdrh       }
27032282792aSdrh     }
2704a58fdfb1Sdanielk1977     if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
27051d83f052Sdrh       goto select_end;
27062282792aSdrh     }
2707191b690eSdrh     if( pOrderBy ){
2708191b690eSdrh       for(i=0; i<pOrderBy->nExpr; i++){
2709a58fdfb1Sdanielk1977         if( sqlite3ExprAnalyzeAggregates(&sNC, pOrderBy->a[i].pExpr) ){
27101d83f052Sdrh           goto select_end;
2711191b690eSdrh         }
2712191b690eSdrh       }
2713191b690eSdrh     }
2714efb7251dSdrh   }
2715efb7251dSdrh 
27162282792aSdrh   /* Reset the aggregator
2717cce7d176Sdrh   */
2718cce7d176Sdrh   if( isAgg ){
2719e159fdf2Sdanielk1977     int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg);
2720e5095355Sdrh     for(i=0; i<pParse->nAgg; i++){
27210bce8354Sdrh       FuncDef *pFunc;
27220bce8354Sdrh       if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
2723f9b596ebSdrh         sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF);
2724e5095355Sdrh       }
2725e5095355Sdrh     }
2726e159fdf2Sdanielk1977     if( pGroupBy ){
2727ce2663ccSdanielk1977       int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*);
2728ce2663ccSdanielk1977       KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz);
2729ce2663ccSdanielk1977       if( 0==pKey ){
2730ce2663ccSdanielk1977         goto select_end;
2731ce2663ccSdanielk1977       }
2732ce2663ccSdanielk1977       pKey->enc = pParse->db->enc;
2733ce2663ccSdanielk1977       pKey->nField = pGroupBy->nExpr;
2734ce2663ccSdanielk1977       for(i=0; i<pGroupBy->nExpr; i++){
2735ce2663ccSdanielk1977         pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr);
2736ce2663ccSdanielk1977         if( !pKey->aColl[i] ){
2737ce2663ccSdanielk1977           pKey->aColl[i] = pParse->db->pDfltColl;
2738ce2663ccSdanielk1977         }
2739ce2663ccSdanielk1977       }
2740ce2663ccSdanielk1977       sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF);
27411bee3d7bSdrh     }
2742cce7d176Sdrh   }
2743cce7d176Sdrh 
274451522cd3Sdrh   /* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists
274519a775c2Sdrh   */
274651522cd3Sdrh   if( eDest==SRT_Mem || eDest==SRT_Exists ){
274751522cd3Sdrh     sqlite3VdbeAddOp(v, eDest==SRT_Mem ? OP_String8 : OP_Integer, 0, 0);
27484adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
274919a775c2Sdrh   }
275019a775c2Sdrh 
2751832508b7Sdrh   /* Open a temporary table to use for the distinct set.
2752cce7d176Sdrh   */
275319a775c2Sdrh   if( isDistinct ){
2754832508b7Sdrh     distinct = pParse->nTab++;
2755d3d39e93Sdrh     openTempIndex(pParse, p, distinct, 0);
2756832508b7Sdrh   }else{
2757832508b7Sdrh     distinct = -1;
2758efb7251dSdrh   }
2759832508b7Sdrh 
2760832508b7Sdrh   /* Begin the database scan
2761832508b7Sdrh   */
2762e6f85e71Sdrh   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,
2763e4e72072Sdrh                              pGroupBy ? 0 : &pOrderBy, p->pFetch);
27641d83f052Sdrh   if( pWInfo==0 ) goto select_end;
2765cce7d176Sdrh 
27662282792aSdrh   /* Use the standard inner loop if we are not dealing with
27672282792aSdrh   ** aggregates
2768cce7d176Sdrh   */
2769da9d6c45Sdrh   if( !isAgg ){
2770df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
277184ac9d02Sdanielk1977                     iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
27721d83f052Sdrh        goto select_end;
2773cce7d176Sdrh     }
2774da9d6c45Sdrh   }
2775cce7d176Sdrh 
2776e3184744Sdrh   /* If we are dealing with aggregates, then do the special aggregate
27772282792aSdrh   ** processing.
2778efb7251dSdrh   */
27792282792aSdrh   else{
2780268380caSdrh     AggExpr *pAgg;
2781a58fdfb1Sdanielk1977     int lbl1 = 0;
2782a58fdfb1Sdanielk1977     pParse->fillAgg = 1;
27832282792aSdrh     if( pGroupBy ){
27842282792aSdrh       for(i=0; i<pGroupBy->nExpr; i++){
27854adee20fSdanielk1977         sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr);
2786efb7251dSdrh       }
2787ededfd5eSdanielk1977       /* No affinity string is attached to the following OP_MakeRecord
2788d3d39e93Sdrh       ** because we do not need to do any coercion of datatypes. */
2789ededfd5eSdanielk1977       sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0);
27904adee20fSdanielk1977       lbl1 = sqlite3VdbeMakeLabel(v);
27914adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1);
2792a58fdfb1Sdanielk1977     }
2793268380caSdrh     for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
2794268380caSdrh       if( pAgg->isAgg ) continue;
27954adee20fSdanielk1977       sqlite3ExprCode(pParse, pAgg->pExpr);
27964adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_AggSet, 0, i);
27972282792aSdrh     }
2798a58fdfb1Sdanielk1977     pParse->fillAgg = 0;
2799a58fdfb1Sdanielk1977     if( lbl1<0 ){
28004adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, lbl1);
28012282792aSdrh     }
2802268380caSdrh     for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
28032282792aSdrh       Expr *pE;
2804268380caSdrh       int nExpr;
2805268380caSdrh       FuncDef *pDef;
2806268380caSdrh       if( !pAgg->isAgg ) continue;
2807268380caSdrh       assert( pAgg->pFunc!=0 );
2808268380caSdrh       assert( pAgg->pFunc->xStep!=0 );
2809268380caSdrh       pDef = pAgg->pFunc;
2810268380caSdrh       pE = pAgg->pExpr;
2811268380caSdrh       assert( pE!=0 );
28122282792aSdrh       assert( pE->op==TK_AGG_FUNCTION );
2813f9b596ebSdrh       nExpr = sqlite3ExprCodeExprList(pParse, pE->pList);
28144adee20fSdanielk1977       sqlite3VdbeAddOp(v, OP_Integer, i, 0);
2815dc1bdc4fSdanielk1977       if( pDef->needCollSeq ){
2816dc1bdc4fSdanielk1977         CollSeq *pColl = 0;
2817dc1bdc4fSdanielk1977         int j;
2818dc1bdc4fSdanielk1977         for(j=0; !pColl && j<nExpr; j++){
2819dc1bdc4fSdanielk1977           pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr);
2820dc1bdc4fSdanielk1977         }
2821dc1bdc4fSdanielk1977         if( !pColl ) pColl = pParse->db->pDfltColl;
2822dc1bdc4fSdanielk1977         sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
2823dc1bdc4fSdanielk1977       }
28244adee20fSdanielk1977       sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
28252282792aSdrh     }
28262282792aSdrh   }
28272282792aSdrh 
2828cce7d176Sdrh   /* End the database scan loop.
2829cce7d176Sdrh   */
28304adee20fSdanielk1977   sqlite3WhereEnd(pWInfo);
2831cce7d176Sdrh 
28322282792aSdrh   /* If we are processing aggregates, we need to set up a second loop
28332282792aSdrh   ** over all of the aggregate values and process them.
28342282792aSdrh   */
28352282792aSdrh   if( isAgg ){
28364adee20fSdanielk1977     int endagg = sqlite3VdbeMakeLabel(v);
28372282792aSdrh     int startagg;
28384adee20fSdanielk1977     startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg);
28392282792aSdrh     if( pHaving ){
28404adee20fSdanielk1977       sqlite3ExprIfFalse(pParse, pHaving, startagg, 1);
28412282792aSdrh     }
2842df199a25Sdrh     if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
284384ac9d02Sdanielk1977                     iParm, startagg, endagg, aff) ){
28441d83f052Sdrh       goto select_end;
28452282792aSdrh     }
28464adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Goto, 0, startagg);
28474adee20fSdanielk1977     sqlite3VdbeResolveLabel(v, endagg);
28484adee20fSdanielk1977     sqlite3VdbeAddOp(v, OP_Noop, 0, 0);
28492282792aSdrh   }
28502282792aSdrh 
2851cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
2852cce7d176Sdrh   ** and send them to the callback one by one.
2853cce7d176Sdrh   */
2854cce7d176Sdrh   if( pOrderBy ){
2855ffbc3088Sdrh     generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
2856cce7d176Sdrh   }
28576a535340Sdrh 
285893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
2859f620b4e2Sdrh   /* If this was a subquery, we have now converted the subquery into a
2860f620b4e2Sdrh   ** temporary table.  So delete the subquery structure from the parent
2861f620b4e2Sdrh   ** to prevent this subquery from being evaluated again and to force the
2862f620b4e2Sdrh   ** the use of the temporary table.
2863f620b4e2Sdrh   */
2864f620b4e2Sdrh   if( pParent ){
2865f620b4e2Sdrh     assert( pParent->pSrc->nSrc>parentTab );
2866f620b4e2Sdrh     assert( pParent->pSrc->a[parentTab].pSelect==p );
28674adee20fSdanielk1977     sqlite3SelectDelete(p);
2868f620b4e2Sdrh     pParent->pSrc->a[parentTab].pSelect = 0;
2869f620b4e2Sdrh   }
287093758c8dSdanielk1977 #endif
2871f620b4e2Sdrh 
28721d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
28731d83f052Sdrh   ** to indicate no errors.
28741d83f052Sdrh   */
28751d83f052Sdrh   rc = 0;
28761d83f052Sdrh 
28771d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
28781d83f052Sdrh   ** successful coding of the SELECT.
28791d83f052Sdrh   */
28801d83f052Sdrh select_end:
2881b3bce662Sdanielk1977   restoreAggregateInfo(pParse, &sAggInfo);
28821d83f052Sdrh   return rc;
2883cce7d176Sdrh }
2884