xref: /sqlite-3.40.0/src/select.c (revision 91fc4a0c)
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 */
15cce7d176Sdrh #include "sqliteInt.h"
16cce7d176Sdrh 
17315555caSdrh 
18cce7d176Sdrh /*
19eda639e1Sdrh ** Delete all the content of a Select structure but do not deallocate
20eda639e1Sdrh ** the select structure itself.
21eda639e1Sdrh */
22633e6d57Sdrh static void clearSelect(sqlite3 *db, Select *p){
23633e6d57Sdrh   sqlite3ExprListDelete(db, p->pEList);
24633e6d57Sdrh   sqlite3SrcListDelete(db, p->pSrc);
25633e6d57Sdrh   sqlite3ExprDelete(db, p->pWhere);
26633e6d57Sdrh   sqlite3ExprListDelete(db, p->pGroupBy);
27633e6d57Sdrh   sqlite3ExprDelete(db, p->pHaving);
28633e6d57Sdrh   sqlite3ExprListDelete(db, p->pOrderBy);
29633e6d57Sdrh   sqlite3SelectDelete(db, p->pPrior);
30633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
31633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
32eda639e1Sdrh }
33eda639e1Sdrh 
341013c932Sdrh /*
351013c932Sdrh ** Initialize a SelectDest structure.
361013c932Sdrh */
371013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
38ea678832Sdrh   pDest->eDest = (u8)eDest;
391013c932Sdrh   pDest->iParm = iParm;
401013c932Sdrh   pDest->affinity = 0;
411013c932Sdrh   pDest->iMem = 0;
42ad27e761Sdrh   pDest->nMem = 0;
431013c932Sdrh }
441013c932Sdrh 
45eda639e1Sdrh 
46eda639e1Sdrh /*
479bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that
489bb61fe7Sdrh ** structure.
49cce7d176Sdrh */
504adee20fSdanielk1977 Select *sqlite3SelectNew(
5117435752Sdrh   Parse *pParse,        /* Parsing context */
52daffd0e5Sdrh   ExprList *pEList,     /* which columns to include in the result */
53ad3cab52Sdrh   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
54daffd0e5Sdrh   Expr *pWhere,         /* the WHERE clause */
55daffd0e5Sdrh   ExprList *pGroupBy,   /* the GROUP BY clause */
56daffd0e5Sdrh   Expr *pHaving,        /* the HAVING clause */
57daffd0e5Sdrh   ExprList *pOrderBy,   /* the ORDER BY clause */
589bbca4c1Sdrh   int isDistinct,       /* true if the DISTINCT keyword is present */
59a2dc3b1aSdanielk1977   Expr *pLimit,         /* LIMIT value.  NULL means not used */
60a2dc3b1aSdanielk1977   Expr *pOffset         /* OFFSET value.  NULL means no offset */
619bb61fe7Sdrh ){
629bb61fe7Sdrh   Select *pNew;
63eda639e1Sdrh   Select standin;
6417435752Sdrh   sqlite3 *db = pParse->db;
6517435752Sdrh   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
66d72a276eSdrh   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
67daffd0e5Sdrh   if( pNew==0 ){
68eda639e1Sdrh     pNew = &standin;
69eda639e1Sdrh     memset(pNew, 0, sizeof(*pNew));
70eda639e1Sdrh   }
71b733d037Sdrh   if( pEList==0 ){
72b7916a78Sdrh     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
73b733d037Sdrh   }
749bb61fe7Sdrh   pNew->pEList = pEList;
759bb61fe7Sdrh   pNew->pSrc = pSrc;
769bb61fe7Sdrh   pNew->pWhere = pWhere;
779bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
789bb61fe7Sdrh   pNew->pHaving = pHaving;
799bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
807d10d5a6Sdrh   pNew->selFlags = isDistinct ? SF_Distinct : 0;
8182c3d636Sdrh   pNew->op = TK_SELECT;
82a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
83a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
84373cc2ddSdrh   assert( pOffset==0 || pLimit!=0 );
85b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
86b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
87b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
880a846f96Sdrh   if( db->mallocFailed ) {
89633e6d57Sdrh     clearSelect(db, pNew);
900a846f96Sdrh     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
91eda639e1Sdrh     pNew = 0;
92daffd0e5Sdrh   }
939bb61fe7Sdrh   return pNew;
949bb61fe7Sdrh }
959bb61fe7Sdrh 
969bb61fe7Sdrh /*
97eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
98eda639e1Sdrh */
99633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
100eda639e1Sdrh   if( p ){
101633e6d57Sdrh     clearSelect(db, p);
102633e6d57Sdrh     sqlite3DbFree(db, p);
103eda639e1Sdrh   }
104eda639e1Sdrh }
105eda639e1Sdrh 
106eda639e1Sdrh /*
10701f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
10801f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
10901f3f253Sdrh ** in terms of the following bit values:
11001f3f253Sdrh **
11101f3f253Sdrh **     JT_INNER
1123dec223cSdrh **     JT_CROSS
11301f3f253Sdrh **     JT_OUTER
11401f3f253Sdrh **     JT_NATURAL
11501f3f253Sdrh **     JT_LEFT
11601f3f253Sdrh **     JT_RIGHT
11701f3f253Sdrh **
11801f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
11901f3f253Sdrh **
12001f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
12101f3f253Sdrh ** a join type, but put an error in the pParse structure.
12201f3f253Sdrh */
1234adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
12401f3f253Sdrh   int jointype = 0;
12501f3f253Sdrh   Token *apAll[3];
12601f3f253Sdrh   Token *p;
127373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
128373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
1295719628aSdrh   static const struct {
130373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
131373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
132373cc2ddSdrh     u8 code;     /* Join type mask */
133373cc2ddSdrh   } aKeyword[] = {
134373cc2ddSdrh     /* natural */ { 0,  7, JT_NATURAL                },
135373cc2ddSdrh     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
136373cc2ddSdrh     /* outer   */ { 10, 5, JT_OUTER                  },
137373cc2ddSdrh     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
138373cc2ddSdrh     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
139373cc2ddSdrh     /* inner   */ { 23, 5, JT_INNER                  },
140373cc2ddSdrh     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
14101f3f253Sdrh   };
14201f3f253Sdrh   int i, j;
14301f3f253Sdrh   apAll[0] = pA;
14401f3f253Sdrh   apAll[1] = pB;
14501f3f253Sdrh   apAll[2] = pC;
146195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
14701f3f253Sdrh     p = apAll[i];
148373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
149373cc2ddSdrh       if( p->n==aKeyword[j].nChar
150373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
151373cc2ddSdrh         jointype |= aKeyword[j].code;
15201f3f253Sdrh         break;
15301f3f253Sdrh       }
15401f3f253Sdrh     }
155373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
156373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
15701f3f253Sdrh       jointype |= JT_ERROR;
15801f3f253Sdrh       break;
15901f3f253Sdrh     }
16001f3f253Sdrh   }
161ad2d8307Sdrh   if(
162ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
163195e6967Sdrh      (jointype & JT_ERROR)!=0
164ad2d8307Sdrh   ){
165a9671a22Sdrh     const char *zSp = " ";
166a9671a22Sdrh     assert( pB!=0 );
167a9671a22Sdrh     if( pC==0 ){ zSp++; }
168ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
169a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
17001f3f253Sdrh     jointype = JT_INNER;
171373cc2ddSdrh   }else if( (jointype & JT_OUTER)!=0
172373cc2ddSdrh          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
1734adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
174da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
175195e6967Sdrh     jointype = JT_INNER;
17601f3f253Sdrh   }
17701f3f253Sdrh   return jointype;
17801f3f253Sdrh }
17901f3f253Sdrh 
18001f3f253Sdrh /*
181ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
182ad2d8307Sdrh ** is not contained in the table.
183ad2d8307Sdrh */
184ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
185ad2d8307Sdrh   int i;
186ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1874adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
188ad2d8307Sdrh   }
189ad2d8307Sdrh   return -1;
190ad2d8307Sdrh }
191ad2d8307Sdrh 
192ad2d8307Sdrh /*
193f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the
194f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which
195f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form:
196f7b0b0adSdan **
197f7b0b0adSdan **    (tab1.col1 = tab2.col2)
198f7b0b0adSdan **
199f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
200f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
201f7b0b0adSdan ** column iColRight of tab2.
202ad2d8307Sdrh */
203ad2d8307Sdrh static void addWhereTerm(
20417435752Sdrh   Parse *pParse,                  /* Parsing context */
205f7b0b0adSdan   SrcList *pSrc,                  /* List of tables in FROM clause */
206f7b0b0adSdan   int iSrc,                       /* Index of first table to join in pSrc */
207f7b0b0adSdan   int iColLeft,                   /* Index of column in first table */
208f7b0b0adSdan   int iColRight,                  /* Index of column in second table */
209f7b0b0adSdan   int isOuterJoin,                /* True if this is an OUTER join */
210f7b0b0adSdan   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
211ad2d8307Sdrh ){
212f7b0b0adSdan   sqlite3 *db = pParse->db;
213f7b0b0adSdan   Expr *pE1;
214f7b0b0adSdan   Expr *pE2;
215f7b0b0adSdan   Expr *pEq;
216ad2d8307Sdrh 
217f7b0b0adSdan   assert( pSrc->nSrc>(iSrc+1) );
218f7b0b0adSdan   assert( pSrc->a[iSrc].pTab );
219f7b0b0adSdan   assert( pSrc->a[iSrc+1].pTab );
220f7b0b0adSdan 
221f7b0b0adSdan   pE1 = sqlite3CreateColumnExpr(db, pSrc, iSrc, iColLeft);
222f7b0b0adSdan   pE2 = sqlite3CreateColumnExpr(db, pSrc, iSrc+1, iColRight);
223f7b0b0adSdan 
224f7b0b0adSdan   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
225f7b0b0adSdan   if( pEq && isOuterJoin ){
226f7b0b0adSdan     ExprSetProperty(pEq, EP_FromJoin);
227f7b0b0adSdan     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
228f7b0b0adSdan     ExprSetIrreducible(pEq);
229f7b0b0adSdan     pEq->iRightJoinTable = (i16)pE2->iTable;
230030530deSdrh   }
231f7b0b0adSdan   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
232ad2d8307Sdrh }
233ad2d8307Sdrh 
234ad2d8307Sdrh /*
2351f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
23622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
23722d6a53aSdrh ** expression.
2381cc093c2Sdrh **
239e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2401cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2411f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2421f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2431f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2441f16230bSdrh ** originated in the ON or USING clause.
24522d6a53aSdrh **
24622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
24722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
24822d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
24922d6a53aSdrh ** for cases like this:
25022d6a53aSdrh **
25122d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
25222d6a53aSdrh **
25322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
25422d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
25522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
25622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
25722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
25822d6a53aSdrh ** the output, which is incorrect.
2591cc093c2Sdrh */
26022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
2611cc093c2Sdrh   while( p ){
2621f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
26333e619fcSdrh     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
26433e619fcSdrh     ExprSetIrreducible(p);
265cf697396Sshane     p->iRightJoinTable = (i16)iTable;
26622d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
2671cc093c2Sdrh     p = p->pRight;
2681cc093c2Sdrh   }
2691cc093c2Sdrh }
2701cc093c2Sdrh 
2711cc093c2Sdrh /*
272ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
273ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
274ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
275ad2d8307Sdrh **
27691bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
27791bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
27891bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
27991bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
28091bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
28191bb0eedSdrh ** also attached to the left entry.
28291bb0eedSdrh **
283ad2d8307Sdrh ** This routine returns the number of errors encountered.
284ad2d8307Sdrh */
285ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
28691bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
28791bb0eedSdrh   int i, j;                       /* Loop counters */
28891bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
28991bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
290ad2d8307Sdrh 
29191bb0eedSdrh   pSrc = p->pSrc;
29291bb0eedSdrh   pLeft = &pSrc->a[0];
29391bb0eedSdrh   pRight = &pLeft[1];
29491bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
29591bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
29691bb0eedSdrh     Table *pRightTab = pRight->pTab;
297ad27e761Sdrh     int isOuter;
29891bb0eedSdrh 
2991c767f0dSdrh     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
300ad27e761Sdrh     isOuter = (pRight->jointype & JT_OUTER)!=0;
301ad2d8307Sdrh 
302ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
303ad2d8307Sdrh     ** every column that the two tables have in common.
304ad2d8307Sdrh     */
30561dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
30661dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3074adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
308ad2d8307Sdrh            "an ON or USING clause", 0);
309ad2d8307Sdrh         return 1;
310ad2d8307Sdrh       }
31191bb0eedSdrh       for(j=0; j<pLeftTab->nCol; j++){
31291bb0eedSdrh         char *zName = pLeftTab->aCol[j].zName;
313f7b0b0adSdan         int iRightCol = columnIndex(pRightTab, zName);
314f7b0b0adSdan         if( iRightCol>=0 ){
315f7b0b0adSdan           addWhereTerm(pParse, pSrc, i, j, iRightCol, isOuter, &p->pWhere);
316ad2d8307Sdrh         }
317ad2d8307Sdrh       }
318ad2d8307Sdrh     }
319ad2d8307Sdrh 
320ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
321ad2d8307Sdrh     */
32261dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3234adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
324da93d238Sdrh         "clauses in the same join");
325ad2d8307Sdrh       return 1;
326ad2d8307Sdrh     }
327ad2d8307Sdrh 
328ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
32991bb0eedSdrh     ** an AND operator.
330ad2d8307Sdrh     */
33161dfc31dSdrh     if( pRight->pOn ){
332ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
33317435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
33461dfc31dSdrh       pRight->pOn = 0;
335ad2d8307Sdrh     }
336ad2d8307Sdrh 
337ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
338ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
339ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
340ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
341ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
342ad2d8307Sdrh     ** not contained in both tables to be joined.
343ad2d8307Sdrh     */
34461dfc31dSdrh     if( pRight->pUsing ){
34561dfc31dSdrh       IdList *pList = pRight->pUsing;
346ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
34791bb0eedSdrh         char *zName = pList->a[j].zName;
348f7b0b0adSdan         int iLeftCol = columnIndex(pLeftTab, zName);
349f7b0b0adSdan         int iRightCol = columnIndex(pRightTab, zName);
350f7b0b0adSdan         if( iLeftCol<0 || iRightCol<0 ){
3514adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
35291bb0eedSdrh             "not present in both tables", zName);
353ad2d8307Sdrh           return 1;
354ad2d8307Sdrh         }
355f7b0b0adSdan         addWhereTerm(pParse, pSrc, i, iLeftCol, iRightCol, isOuter, &p->pWhere);
356ad2d8307Sdrh       }
357ad2d8307Sdrh     }
358ad2d8307Sdrh   }
359ad2d8307Sdrh   return 0;
360ad2d8307Sdrh }
361ad2d8307Sdrh 
362ad2d8307Sdrh /*
363c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
364c926afbcSdrh ** stack into the sorter.
365c926afbcSdrh */
366d59ba6ceSdrh static void pushOntoSorter(
367d59ba6ceSdrh   Parse *pParse,         /* Parser context */
368d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
369b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
370b7654111Sdrh   int regData            /* Register holding data to be sorted */
371d59ba6ceSdrh ){
372d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
373892d3179Sdrh   int nExpr = pOrderBy->nExpr;
374892d3179Sdrh   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
375892d3179Sdrh   int regRecord = sqlite3GetTempReg(pParse);
376ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
377191b54cbSdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
378892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
379b21e7c70Sdrh   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
3801db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
381892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
382892d3179Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
383892d3179Sdrh   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
38492b01d53Sdrh   if( pSelect->iLimit ){
38515007a99Sdrh     int addr1, addr2;
386b7654111Sdrh     int iLimit;
3870acb7e48Sdrh     if( pSelect->iOffset ){
388b7654111Sdrh       iLimit = pSelect->iOffset+1;
389b7654111Sdrh     }else{
390b7654111Sdrh       iLimit = pSelect->iLimit;
391b7654111Sdrh     }
392b7654111Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
393b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
3943c84ddffSdrh     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
395d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
3963c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
3973c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
39815007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
39992b01d53Sdrh     pSelect->iLimit = 0;
400d59ba6ceSdrh   }
401c926afbcSdrh }
402c926afbcSdrh 
403c926afbcSdrh /*
404ec7429aeSdrh ** Add code to implement the OFFSET
405ea48eb2eSdrh */
406ec7429aeSdrh static void codeOffset(
407bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
408ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
409b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
410ea48eb2eSdrh ){
41192b01d53Sdrh   if( p->iOffset && iContinue!=0 ){
41215007a99Sdrh     int addr;
4138558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
4143c84ddffSdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
41566a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
416d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
41715007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
418ea48eb2eSdrh   }
419ea48eb2eSdrh }
420ea48eb2eSdrh 
421ea48eb2eSdrh /*
42298757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
42398757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
424a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
425a2a49dc9Sdrh ** if the current N values are new.
426a2a49dc9Sdrh **
427a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
428a2a49dc9Sdrh ** stack if the top N elements are not distinct.
429a2a49dc9Sdrh */
430a2a49dc9Sdrh static void codeDistinct(
4312dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
432a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
433a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
434477df4b3Sdrh   int N,             /* Number of elements */
435a2a49dc9Sdrh   int iMem           /* First element */
436a2a49dc9Sdrh ){
4372dcef11bSdrh   Vdbe *v;
4382dcef11bSdrh   int r1;
4392dcef11bSdrh 
4402dcef11bSdrh   v = pParse->pVdbe;
4412dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
442*91fc4a0cSdrh   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
4431db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
4442dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
4452dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
446a2a49dc9Sdrh }
447a2a49dc9Sdrh 
448a2a49dc9Sdrh /*
449e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
450e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
451e305f43fSdrh ** column.  We do this in a subroutine because the error occurs in multiple
452e305f43fSdrh ** places.
453e305f43fSdrh */
4546c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
4556c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
4566c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
4576c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
4586c8c8ce0Sdanielk1977 ){
4596c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
460e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
461e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
462e305f43fSdrh        "a SELECT that is part of an expression");
463e305f43fSdrh     return 1;
464e305f43fSdrh   }else{
465e305f43fSdrh     return 0;
466e305f43fSdrh   }
467e305f43fSdrh }
468c99130fdSdrh 
469c99130fdSdrh /*
4702282792aSdrh ** This routine generates the code for the inside of the inner loop
4712282792aSdrh ** of a SELECT.
47282c3d636Sdrh **
47338640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
47438640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
47538640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
47638640e15Sdrh ** datatypes for each column.
4772282792aSdrh */
478d2b3e23bSdrh static void selectInnerLoop(
4792282792aSdrh   Parse *pParse,          /* The parser context */
480df199a25Sdrh   Select *p,              /* The complete select statement being coded */
4812282792aSdrh   ExprList *pEList,       /* List of values being extracted */
48282c3d636Sdrh   int srcTab,             /* Pull data from this table */
483967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
4842282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
4852282792aSdrh   int distinct,           /* If >=0, make sure results are distinct */
4866c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
4872282792aSdrh   int iContinue,          /* Jump here to continue with next row */
488a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
4892282792aSdrh ){
4902282792aSdrh   Vdbe *v = pParse->pVdbe;
491d847eaadSdrh   int i;
492ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
493d847eaadSdrh   int regResult;              /* Start of memory holding result set */
494d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
495d847eaadSdrh   int iParm = pDest->iParm;   /* First argument to disposal method */
496d847eaadSdrh   int nResultCol;             /* Number of result columns */
49738640e15Sdrh 
4981c767f0dSdrh   assert( v );
4991c767f0dSdrh   if( NEVER(v==0) ) return;
50038640e15Sdrh   assert( pEList!=0 );
501e49b146fSdrh   hasDistinct = distinct>=0;
502ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
503b7654111Sdrh     codeOffset(v, p, iContinue);
504df199a25Sdrh   }
505df199a25Sdrh 
506967e8b73Sdrh   /* Pull the requested columns.
5072282792aSdrh   */
50838640e15Sdrh   if( nColumn>0 ){
509d847eaadSdrh     nResultCol = nColumn;
510a2a49dc9Sdrh   }else{
511d847eaadSdrh     nResultCol = pEList->nExpr;
512a2a49dc9Sdrh   }
5131ece7325Sdrh   if( pDest->iMem==0 ){
5140acb7e48Sdrh     pDest->iMem = pParse->nMem+1;
515ad27e761Sdrh     pDest->nMem = nResultCol;
5160acb7e48Sdrh     pParse->nMem += nResultCol;
5171c767f0dSdrh   }else{
5181c767f0dSdrh     assert( pDest->nMem==nResultCol );
5191013c932Sdrh   }
5201ece7325Sdrh   regResult = pDest->iMem;
521a2a49dc9Sdrh   if( nColumn>0 ){
522967e8b73Sdrh     for(i=0; i<nColumn; i++){
523d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
52482c3d636Sdrh     }
5259ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5269ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5279ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
5289ed1dfa8Sdanielk1977     */
529ceea3321Sdrh     sqlite3ExprCacheClear(pParse);
5307d10d5a6Sdrh     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
531a2a49dc9Sdrh   }
532d847eaadSdrh   nColumn = nResultCol;
5332282792aSdrh 
534daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
535daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
536daffd0e5Sdrh   ** part of the result.
5372282792aSdrh   */
538ea48eb2eSdrh   if( hasDistinct ){
539f8875400Sdrh     assert( pEList!=0 );
540f8875400Sdrh     assert( pEList->nExpr==nColumn );
541d847eaadSdrh     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
542ea48eb2eSdrh     if( pOrderBy==0 ){
543b7654111Sdrh       codeOffset(v, p, iContinue);
544ea48eb2eSdrh     }
5452282792aSdrh   }
54682c3d636Sdrh 
5476c8c8ce0Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
548d2b3e23bSdrh     return;
549e305f43fSdrh   }
550e305f43fSdrh 
551c926afbcSdrh   switch( eDest ){
55282c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
55382c3d636Sdrh     ** table iParm.
5542282792aSdrh     */
55513449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
556c926afbcSdrh     case SRT_Union: {
5579cbf3425Sdrh       int r1;
5589cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
559d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
5609cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
5619cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
562c926afbcSdrh       break;
563c926afbcSdrh     }
56482c3d636Sdrh 
56582c3d636Sdrh     /* Construct a record from the query result, but instead of
56682c3d636Sdrh     ** saving that record, use it as a key to delete elements from
56782c3d636Sdrh     ** the temporary table iParm.
56882c3d636Sdrh     */
569c926afbcSdrh     case SRT_Except: {
570e14006d0Sdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
571c926afbcSdrh       break;
572c926afbcSdrh     }
5735338a5f7Sdanielk1977 #endif
5745338a5f7Sdanielk1977 
5755338a5f7Sdanielk1977     /* Store the result as data using a unique key.
5765338a5f7Sdanielk1977     */
5775338a5f7Sdanielk1977     case SRT_Table:
578b9bb7c18Sdrh     case SRT_EphemTab: {
579b7654111Sdrh       int r1 = sqlite3GetTempReg(pParse);
580373cc2ddSdrh       testcase( eDest==SRT_Table );
581373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
582d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
5835338a5f7Sdanielk1977       if( pOrderBy ){
584b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
5855338a5f7Sdanielk1977       }else{
586b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
587b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
588b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
589b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
590b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
5915338a5f7Sdanielk1977       }
592b7654111Sdrh       sqlite3ReleaseTempReg(pParse, r1);
5935338a5f7Sdanielk1977       break;
5945338a5f7Sdanielk1977     }
5952282792aSdrh 
59693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
5972282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
5982282792aSdrh     ** then there should be a single item on the stack.  Write this
5992282792aSdrh     ** item into the set table with bogus data.
6002282792aSdrh     */
601c926afbcSdrh     case SRT_Set: {
602967e8b73Sdrh       assert( nColumn==1 );
6036c8c8ce0Sdanielk1977       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
604c926afbcSdrh       if( pOrderBy ){
605de941c60Sdrh         /* At first glance you would think we could optimize out the
606de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
607de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
608de941c60Sdrh         ** case the order does matter */
609d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
610c926afbcSdrh       }else{
611b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
612d847eaadSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
613da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
614b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
615b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
616c926afbcSdrh       }
617c926afbcSdrh       break;
618c926afbcSdrh     }
61982c3d636Sdrh 
620504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
621ec7429aeSdrh     */
622ec7429aeSdrh     case SRT_Exists: {
6234c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
624ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
625ec7429aeSdrh       break;
626ec7429aeSdrh     }
627ec7429aeSdrh 
6282282792aSdrh     /* If this is a scalar select that is part of an expression, then
6292282792aSdrh     ** store the results in the appropriate memory cell and break out
6302282792aSdrh     ** of the scan loop.
6312282792aSdrh     */
632c926afbcSdrh     case SRT_Mem: {
633967e8b73Sdrh       assert( nColumn==1 );
634c926afbcSdrh       if( pOrderBy ){
635d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
636c926afbcSdrh       }else{
637b21e7c70Sdrh         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
638ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
639c926afbcSdrh       }
640c926afbcSdrh       break;
641c926afbcSdrh     }
64293758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
6432282792aSdrh 
644c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
645c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
646c182d163Sdrh     ** popping the data from the stack.
647f46f905aSdrh     */
648e00ee6ebSdrh     case SRT_Coroutine:
6497d10d5a6Sdrh     case SRT_Output: {
650373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
651373cc2ddSdrh       testcase( eDest==SRT_Output );
652f46f905aSdrh       if( pOrderBy ){
653b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
654d847eaadSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
655b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
656b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
657e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
65892b01d53Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
659c182d163Sdrh       }else{
660d847eaadSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
661da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
662ac82fcf5Sdrh       }
663142e30dfSdrh       break;
664142e30dfSdrh     }
665142e30dfSdrh 
6666a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
667d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
668d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
669d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
670d7489c39Sdrh     ** about the actual results of the select.
671d7489c39Sdrh     */
672c926afbcSdrh     default: {
673f46f905aSdrh       assert( eDest==SRT_Discard );
674c926afbcSdrh       break;
675c926afbcSdrh     }
67693758c8dSdanielk1977 #endif
677c926afbcSdrh   }
678ec7429aeSdrh 
679ec7429aeSdrh   /* Jump to the end of the loop if the LIMIT is reached.
680ec7429aeSdrh   */
681e49b146fSdrh   if( p->iLimit ){
682e49b146fSdrh     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
683e49b146fSdrh                             ** pushOntoSorter() would have cleared p->iLimit */
6849b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
685ec7429aeSdrh   }
68682c3d636Sdrh }
68782c3d636Sdrh 
68882c3d636Sdrh /*
689dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
690dece1a84Sdrh ** the collating sequence for each expression in that expression list.
691dece1a84Sdrh **
6920342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
6930342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
6940342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
6950342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
6960342b1f5Sdrh ** index to implement a DISTINCT test.
6970342b1f5Sdrh **
698dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
699dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
70066a5167bSdrh ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
70166a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
702dece1a84Sdrh */
703dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
704dece1a84Sdrh   sqlite3 *db = pParse->db;
705dece1a84Sdrh   int nExpr;
706dece1a84Sdrh   KeyInfo *pInfo;
707dece1a84Sdrh   struct ExprList_item *pItem;
708dece1a84Sdrh   int i;
709dece1a84Sdrh 
710dece1a84Sdrh   nExpr = pList->nExpr;
71117435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
712dece1a84Sdrh   if( pInfo ){
7132646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
714ea678832Sdrh     pInfo->nField = (u16)nExpr;
71514db2665Sdanielk1977     pInfo->enc = ENC(db);
7162aca5846Sdrh     pInfo->db = db;
717dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
718dece1a84Sdrh       CollSeq *pColl;
719dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
720dece1a84Sdrh       if( !pColl ){
721dece1a84Sdrh         pColl = db->pDfltColl;
722dece1a84Sdrh       }
723dece1a84Sdrh       pInfo->aColl[i] = pColl;
724dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
725dece1a84Sdrh     }
726dece1a84Sdrh   }
727dece1a84Sdrh   return pInfo;
728dece1a84Sdrh }
729dece1a84Sdrh 
730dece1a84Sdrh 
731dece1a84Sdrh /*
732d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
733d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
734d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
735d8bc7086Sdrh ** routine generates the code needed to do that.
736d8bc7086Sdrh */
737c926afbcSdrh static void generateSortTail(
738cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
739c926afbcSdrh   Select *p,        /* The SELECT statement */
740c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
741c926afbcSdrh   int nColumn,      /* Number of columns of data */
7426c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
743c926afbcSdrh ){
744dc5ea5c7Sdrh   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
745dc5ea5c7Sdrh   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
746d8bc7086Sdrh   int addr;
7470342b1f5Sdrh   int iTab;
74861fc595fSdrh   int pseudoTab = 0;
7490342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
750ffbc3088Sdrh 
7516c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
7526c8c8ce0Sdanielk1977   int iParm = pDest->iParm;
7536c8c8ce0Sdanielk1977 
7542d401ab8Sdrh   int regRow;
7552d401ab8Sdrh   int regRowid;
7562d401ab8Sdrh 
7579d2985c7Sdrh   iTab = pOrderBy->iECursor;
7583e9ca094Sdrh   regRow = sqlite3GetTempReg(pParse);
7597d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
760cdd536f0Sdrh     pseudoTab = pParse->nTab++;
7613e9ca094Sdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
7623e9ca094Sdrh     regRowid = 0;
7633e9ca094Sdrh   }else{
7643e9ca094Sdrh     regRowid = sqlite3GetTempReg(pParse);
765cdd536f0Sdrh   }
766dc5ea5c7Sdrh   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
767dc5ea5c7Sdrh   codeOffset(v, p, addrContinue);
7682d401ab8Sdrh   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
769c926afbcSdrh   switch( eDest ){
770c926afbcSdrh     case SRT_Table:
771b9bb7c18Sdrh     case SRT_EphemTab: {
7721c767f0dSdrh       testcase( eDest==SRT_Table );
7731c767f0dSdrh       testcase( eDest==SRT_EphemTab );
7742d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
7752d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
7762d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
777c926afbcSdrh       break;
778c926afbcSdrh     }
77993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
780c926afbcSdrh     case SRT_Set: {
781c926afbcSdrh       assert( nColumn==1 );
782a7a8e14bSdanielk1977       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
783da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
784a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
785c926afbcSdrh       break;
786c926afbcSdrh     }
787c926afbcSdrh     case SRT_Mem: {
788c926afbcSdrh       assert( nColumn==1 );
789b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
790ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
791c926afbcSdrh       break;
792c926afbcSdrh     }
79393758c8dSdanielk1977 #endif
794373cc2ddSdrh     default: {
795ac82fcf5Sdrh       int i;
796373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
7971c767f0dSdrh       testcase( eDest==SRT_Output );
7981c767f0dSdrh       testcase( eDest==SRT_Coroutine );
799ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
8009882d999Sdanielk1977         assert( regRow!=pDest->iMem+i );
8011013c932Sdrh         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
8023e9ca094Sdrh         if( i==0 ){
8033e9ca094Sdrh           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
8043e9ca094Sdrh         }
805ac82fcf5Sdrh       }
8067d10d5a6Sdrh       if( eDest==SRT_Output ){
8071013c932Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
808da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
809a9671a22Sdrh       }else{
81092b01d53Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
811ce665cf6Sdrh       }
812ac82fcf5Sdrh       break;
813ac82fcf5Sdrh     }
814c926afbcSdrh   }
8152d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRow);
8162d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
817ec7429aeSdrh 
818a9671a22Sdrh   /* LIMIT has been implemented by the pushOntoSorter() routine.
819ec7429aeSdrh   */
820a9671a22Sdrh   assert( p->iLimit==0 );
821ec7429aeSdrh 
822ec7429aeSdrh   /* The bottom of the loop
823ec7429aeSdrh   */
824dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
82566a5167bSdrh   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
826dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
8277d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
82866a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
829cdd536f0Sdrh   }
830d8bc7086Sdrh }
831d8bc7086Sdrh 
832d8bc7086Sdrh /*
833517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
834517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
835e78e8284Sdrh **
836955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
837955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
838955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
839955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
840955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
841955de52cSdanielk1977 ** considered a column by this function.
842e78e8284Sdrh **
843955de52cSdanielk1977 **   SELECT col FROM tbl;
844955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
845955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
846955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
847955de52cSdanielk1977 **
848955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
849fcb78a49Sdrh */
850955de52cSdanielk1977 static const char *columnType(
851955de52cSdanielk1977   NameContext *pNC,
852955de52cSdanielk1977   Expr *pExpr,
853955de52cSdanielk1977   const char **pzOriginDb,
854955de52cSdanielk1977   const char **pzOriginTab,
855955de52cSdanielk1977   const char **pzOriginCol
856955de52cSdanielk1977 ){
857955de52cSdanielk1977   char const *zType = 0;
858955de52cSdanielk1977   char const *zOriginDb = 0;
859955de52cSdanielk1977   char const *zOriginTab = 0;
860955de52cSdanielk1977   char const *zOriginCol = 0;
861517eb646Sdanielk1977   int j;
862373cc2ddSdrh   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
8635338a5f7Sdanielk1977 
86400e279d9Sdanielk1977   switch( pExpr->op ){
86530bcf5dbSdrh     case TK_AGG_COLUMN:
86600e279d9Sdanielk1977     case TK_COLUMN: {
867955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
868955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
869955de52cSdanielk1977       ** database table or a subquery.
870955de52cSdanielk1977       */
871955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
872955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
873955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
874373cc2ddSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
875373cc2ddSdrh       testcase( pExpr->op==TK_COLUMN );
87643bc88bbSdan       while( pNC && !pTab ){
877b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
878b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
879b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
8806a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
881955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
882b3bce662Sdanielk1977         }else{
883b3bce662Sdanielk1977           pNC = pNC->pNext;
884b3bce662Sdanielk1977         }
885b3bce662Sdanielk1977       }
886955de52cSdanielk1977 
88743bc88bbSdan       if( pTab==0 ){
888417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
889417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
890417168adSdrh         ** trigger code is generated and so this condition is no longer
89143bc88bbSdan         ** possible. However, it can still be true for statements like
89243bc88bbSdan         ** the following:
89343bc88bbSdan         **
89443bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
89543bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
89643bc88bbSdan         **
89743bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
89843bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
89943bc88bbSdan         ** though it should really be "INTEGER".
90043bc88bbSdan         **
90143bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
90243bc88bbSdan         ** used. When columnType() is called on the expression
90343bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
90443bc88bbSdan         ** branch below.  */
9057e62779aSdrh         break;
9067e62779aSdrh       }
907955de52cSdanielk1977 
90843bc88bbSdan       assert( pTab && pExpr->pTab==pTab );
909955de52cSdanielk1977       if( pS ){
910955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
911955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
912955de52cSdanielk1977         ** data for the result-set column of the sub-select.
913955de52cSdanielk1977         */
9141c767f0dSdrh         if( ALWAYS(iCol>=0 && iCol<pS->pEList->nExpr) ){
915955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
916955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
917955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
918955de52cSdanielk1977           */
919955de52cSdanielk1977           NameContext sNC;
920955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
921955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
92243bc88bbSdan           sNC.pNext = pNC;
923955de52cSdanielk1977           sNC.pParse = pNC->pParse;
924955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
925955de52cSdanielk1977         }
9261c767f0dSdrh       }else if( ALWAYS(pTab->pSchema) ){
927955de52cSdanielk1977         /* A real table */
928955de52cSdanielk1977         assert( !pS );
929fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
930fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
931fcb78a49Sdrh         if( iCol<0 ){
932fcb78a49Sdrh           zType = "INTEGER";
933955de52cSdanielk1977           zOriginCol = "rowid";
934fcb78a49Sdrh         }else{
935fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
936955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
937955de52cSdanielk1977         }
938955de52cSdanielk1977         zOriginTab = pTab->zName;
939955de52cSdanielk1977         if( pNC->pParse ){
940955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
941955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
942955de52cSdanielk1977         }
943fcb78a49Sdrh       }
94400e279d9Sdanielk1977       break;
945736c22b8Sdrh     }
94693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
94700e279d9Sdanielk1977     case TK_SELECT: {
948955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
949955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
950955de52cSdanielk1977       ** statement.
951955de52cSdanielk1977       */
952b3bce662Sdanielk1977       NameContext sNC;
9536ab3a2ecSdanielk1977       Select *pS = pExpr->x.pSelect;
954955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
9556ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
956955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
957b3bce662Sdanielk1977       sNC.pNext = pNC;
958955de52cSdanielk1977       sNC.pParse = pNC->pParse;
959955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
96000e279d9Sdanielk1977       break;
961fcb78a49Sdrh     }
96293758c8dSdanielk1977 #endif
96300e279d9Sdanielk1977   }
96400e279d9Sdanielk1977 
965955de52cSdanielk1977   if( pzOriginDb ){
966955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
967955de52cSdanielk1977     *pzOriginDb = zOriginDb;
968955de52cSdanielk1977     *pzOriginTab = zOriginTab;
969955de52cSdanielk1977     *pzOriginCol = zOriginCol;
970955de52cSdanielk1977   }
971517eb646Sdanielk1977   return zType;
972517eb646Sdanielk1977 }
973517eb646Sdanielk1977 
974517eb646Sdanielk1977 /*
975517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
976517eb646Sdanielk1977 ** in the result set.
977517eb646Sdanielk1977 */
978517eb646Sdanielk1977 static void generateColumnTypes(
979517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
980517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
981517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
982517eb646Sdanielk1977 ){
9833f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
984517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
985517eb646Sdanielk1977   int i;
986b3bce662Sdanielk1977   NameContext sNC;
987b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
988955de52cSdanielk1977   sNC.pParse = pParse;
989517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
990517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
9913f913576Sdrh     const char *zType;
9923f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
993955de52cSdanielk1977     const char *zOrigDb = 0;
994955de52cSdanielk1977     const char *zOrigTab = 0;
995955de52cSdanielk1977     const char *zOrigCol = 0;
9963f913576Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
997955de52cSdanielk1977 
99885b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
9994b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
10004b1ae99dSdanielk1977     ** virtual machine is deleted.
1001fbcd585fSdanielk1977     */
100210fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
100310fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
100410fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
10053f913576Sdrh #else
10063f913576Sdrh     zType = columnType(&sNC, p, 0, 0, 0);
10073f913576Sdrh #endif
100810fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1009fcb78a49Sdrh   }
10103f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */
1011fcb78a49Sdrh }
1012fcb78a49Sdrh 
1013fcb78a49Sdrh /*
1014fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1015fcb78a49Sdrh ** in the result set.  This information is used to provide the
1016fcabd464Sdrh ** azCol[] values in the callback.
101782c3d636Sdrh */
1018832508b7Sdrh static void generateColumnNames(
1019832508b7Sdrh   Parse *pParse,      /* Parser context */
1020ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1021832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1022832508b7Sdrh ){
1023d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
10246a3ea0e6Sdrh   int i, j;
10259bb575fdSdrh   sqlite3 *db = pParse->db;
1026fcabd464Sdrh   int fullNames, shortNames;
1027fcabd464Sdrh 
1028fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
10293cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
10303cf86063Sdanielk1977   if( pParse->explain ){
103161de0d1bSdanielk1977     return;
10323cf86063Sdanielk1977   }
10335338a5f7Sdanielk1977 #endif
10343cf86063Sdanielk1977 
1035e2f02bacSdrh   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
1036d8bc7086Sdrh   pParse->colNamesSet = 1;
1037fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1038fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
103922322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
104082c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
104182c3d636Sdrh     Expr *p;
10425a38705eSdrh     p = pEList->a[i].pExpr;
1043373cc2ddSdrh     if( NEVER(p==0) ) continue;
104482c3d636Sdrh     if( pEList->a[i].zName ){
104582c3d636Sdrh       char *zName = pEList->a[i].zName;
104610fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1047f018cc2eSdrh     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
10486a3ea0e6Sdrh       Table *pTab;
104997665873Sdrh       char *zCol;
10508aff1015Sdrh       int iCol = p->iColumn;
1051e2f02bacSdrh       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1052e2f02bacSdrh         if( pTabList->a[j].iCursor==p->iTable ) break;
1053e2f02bacSdrh       }
10546a3ea0e6Sdrh       assert( j<pTabList->nSrc );
10556a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
10568aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
105797665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1058b1363206Sdrh       if( iCol<0 ){
105947a6db2bSdrh         zCol = "rowid";
1060b1363206Sdrh       }else{
1061b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1062b1363206Sdrh       }
1063e49b146fSdrh       if( !shortNames && !fullNames ){
106410fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1065b7916a78Sdrh             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
10661c767f0dSdrh       }else if( fullNames ){
106782c3d636Sdrh         char *zName = 0;
10681c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
106910fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
107082c3d636Sdrh       }else{
107110fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
107282c3d636Sdrh       }
10731bee3d7bSdrh     }else{
107410fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1075b7916a78Sdrh           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
107682c3d636Sdrh     }
107782c3d636Sdrh   }
107876d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
10795080aaa7Sdrh }
108082c3d636Sdrh 
108193758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
108282c3d636Sdrh /*
1083d8bc7086Sdrh ** Name of the connection operator, used for error messages.
1084d8bc7086Sdrh */
1085d8bc7086Sdrh static const char *selectOpName(int id){
1086d8bc7086Sdrh   char *z;
1087d8bc7086Sdrh   switch( id ){
1088d8bc7086Sdrh     case TK_ALL:       z = "UNION ALL";   break;
1089d8bc7086Sdrh     case TK_INTERSECT: z = "INTERSECT";   break;
1090d8bc7086Sdrh     case TK_EXCEPT:    z = "EXCEPT";      break;
1091d8bc7086Sdrh     default:           z = "UNION";       break;
1092d8bc7086Sdrh   }
1093d8bc7086Sdrh   return z;
1094d8bc7086Sdrh }
109593758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1096d8bc7086Sdrh 
1097d8bc7086Sdrh /*
10987d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions
10997d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
11007d10d5a6Sdrh ** column names for a table that would hold the expression list.
11017d10d5a6Sdrh **
11027d10d5a6Sdrh ** All column names will be unique.
11037d10d5a6Sdrh **
11047d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
11057d10d5a6Sdrh ** and other fields of Column are zeroed.
11067d10d5a6Sdrh **
11077d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
11087d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1109315555caSdrh */
11107d10d5a6Sdrh static int selectColumnsFromExprList(
11117d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
11127d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
11137d10d5a6Sdrh   int *pnCol,             /* Write the number of columns here */
11147d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
11157d10d5a6Sdrh ){
1116dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
1117dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
1118dc5ea5c7Sdrh   int cnt;                    /* Index added to make the name unique */
1119dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
1120dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
1121dc5ea5c7Sdrh   Expr *p;                    /* Expression for a single result column */
1122dc5ea5c7Sdrh   char *zName;                /* Column name */
1123dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
112479d5f63fSdrh 
11257d10d5a6Sdrh   *pnCol = nCol = pEList->nExpr;
11267d10d5a6Sdrh   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
11277d10d5a6Sdrh   if( aCol==0 ) return SQLITE_NOMEM;
11287d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
112979d5f63fSdrh     /* Get an appropriate name for the column
113079d5f63fSdrh     */
113179d5f63fSdrh     p = pEList->a[i].pExpr;
113233e619fcSdrh     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
113333e619fcSdrh                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
113491bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
113579d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
113617435752Sdrh       zName = sqlite3DbStrDup(db, zName);
11377d10d5a6Sdrh     }else{
1138dc5ea5c7Sdrh       Expr *pColExpr = p;  /* The expression that is the result column name */
1139dc5ea5c7Sdrh       Table *pTab;         /* Table associated with this expression */
1140dc5ea5c7Sdrh       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
1141373cc2ddSdrh       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
114293a960a0Sdrh         /* For columns use the column name name */
1143dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
1144373cc2ddSdrh         pTab = pColExpr->pTab;
1145f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1146f0209f74Sdrh         zName = sqlite3MPrintf(db, "%s",
1147f0209f74Sdrh                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1148b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
114933e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
115033e619fcSdrh         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
115193a960a0Sdrh       }else{
115279d5f63fSdrh         /* Use the original text of the column expression as its name */
1153b7916a78Sdrh         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
11547d10d5a6Sdrh       }
115522f70c32Sdrh     }
11567ce72f69Sdrh     if( db->mallocFailed ){
1157633e6d57Sdrh       sqlite3DbFree(db, zName);
11587ce72f69Sdrh       break;
1159dd5b2fa5Sdrh     }
116079d5f63fSdrh 
116179d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
116279d5f63fSdrh     ** append a integer to the name so that it becomes unique.
116379d5f63fSdrh     */
1164ea678832Sdrh     nName = sqlite3Strlen30(zName);
116579d5f63fSdrh     for(j=cnt=0; j<i; j++){
116679d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1167633e6d57Sdrh         char *zNewName;
11682564ef97Sdrh         zName[nName] = 0;
1169633e6d57Sdrh         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1170633e6d57Sdrh         sqlite3DbFree(db, zName);
1171633e6d57Sdrh         zName = zNewName;
117279d5f63fSdrh         j = -1;
1173dd5b2fa5Sdrh         if( zName==0 ) break;
117479d5f63fSdrh       }
117579d5f63fSdrh     }
117691bb0eedSdrh     pCol->zName = zName;
11777d10d5a6Sdrh   }
11787d10d5a6Sdrh   if( db->mallocFailed ){
11797d10d5a6Sdrh     for(j=0; j<i; j++){
11807d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
11817d10d5a6Sdrh     }
11827d10d5a6Sdrh     sqlite3DbFree(db, aCol);
11837d10d5a6Sdrh     *paCol = 0;
11847d10d5a6Sdrh     *pnCol = 0;
11857d10d5a6Sdrh     return SQLITE_NOMEM;
11867d10d5a6Sdrh   }
11877d10d5a6Sdrh   return SQLITE_OK;
11887d10d5a6Sdrh }
1189e014a838Sdanielk1977 
11907d10d5a6Sdrh /*
11917d10d5a6Sdrh ** Add type and collation information to a column list based on
11927d10d5a6Sdrh ** a SELECT statement.
11937d10d5a6Sdrh **
11947d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
11957d10d5a6Sdrh ** The column list has only names, not types or collations.  This
11967d10d5a6Sdrh ** routine goes through and adds the types and collations.
11977d10d5a6Sdrh **
1198b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
11997d10d5a6Sdrh ** statement be resolved.
120079d5f63fSdrh */
12017d10d5a6Sdrh static void selectAddColumnTypeAndCollation(
12027d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
12037d10d5a6Sdrh   int nCol,             /* Number of columns */
12047d10d5a6Sdrh   Column *aCol,         /* List of columns */
12057d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
12067d10d5a6Sdrh ){
12077d10d5a6Sdrh   sqlite3 *db = pParse->db;
12087d10d5a6Sdrh   NameContext sNC;
12097d10d5a6Sdrh   Column *pCol;
12107d10d5a6Sdrh   CollSeq *pColl;
12117d10d5a6Sdrh   int i;
12127d10d5a6Sdrh   Expr *p;
12137d10d5a6Sdrh   struct ExprList_item *a;
12147d10d5a6Sdrh 
12157d10d5a6Sdrh   assert( pSelect!=0 );
12167d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
12177d10d5a6Sdrh   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
12187d10d5a6Sdrh   if( db->mallocFailed ) return;
1219c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1220b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
12217d10d5a6Sdrh   a = pSelect->pEList->a;
12227d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
12237d10d5a6Sdrh     p = a[i].pExpr;
12247d10d5a6Sdrh     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1225c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1226c4a64facSdrh     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
1227b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1228b3bf556eSdanielk1977     if( pColl ){
122917435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
12300202b29eSdanielk1977     }
123122f70c32Sdrh   }
12327d10d5a6Sdrh }
12337d10d5a6Sdrh 
12347d10d5a6Sdrh /*
12357d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
12367d10d5a6Sdrh ** the result set of that SELECT.
12377d10d5a6Sdrh */
12387d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
12397d10d5a6Sdrh   Table *pTab;
12407d10d5a6Sdrh   sqlite3 *db = pParse->db;
12417d10d5a6Sdrh   int savedFlags;
12427d10d5a6Sdrh 
12437d10d5a6Sdrh   savedFlags = db->flags;
12447d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
12457d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
12467d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
12477d10d5a6Sdrh   if( pParse->nErr ) return 0;
12487d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
12497d10d5a6Sdrh   db->flags = savedFlags;
12507d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
12517d10d5a6Sdrh   if( pTab==0 ){
12527d10d5a6Sdrh     return 0;
12537d10d5a6Sdrh   }
1254373cc2ddSdrh   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1255373cc2ddSdrh   ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
1256373cc2ddSdrh   assert( db->lookaside.bEnabled==0 );
1257373cc2ddSdrh   pTab->dbMem = 0;
12587d10d5a6Sdrh   pTab->nRef = 1;
12597d10d5a6Sdrh   pTab->zName = 0;
12607d10d5a6Sdrh   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
12617d10d5a6Sdrh   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
126222f70c32Sdrh   pTab->iPKey = -1;
12637ce72f69Sdrh   if( db->mallocFailed ){
12647ce72f69Sdrh     sqlite3DeleteTable(pTab);
12657ce72f69Sdrh     return 0;
12667ce72f69Sdrh   }
126722f70c32Sdrh   return pTab;
126822f70c32Sdrh }
126922f70c32Sdrh 
127022f70c32Sdrh /*
1271d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1272d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1273d8bc7086Sdrh */
12744adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1275d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1276d8bc7086Sdrh   if( v==0 ){
12774adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1278949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE
1279949f9cd5Sdrh     if( v ){
1280949f9cd5Sdrh       sqlite3VdbeAddOp0(v, OP_Trace);
1281949f9cd5Sdrh     }
1282949f9cd5Sdrh #endif
1283d8bc7086Sdrh   }
1284d8bc7086Sdrh   return v;
1285d8bc7086Sdrh }
1286d8bc7086Sdrh 
128715007a99Sdrh 
1288d8bc7086Sdrh /*
12897b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1290ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
12917b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1292a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1293a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1294a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1295a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
12967b58daeaSdrh **
1297d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1298ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
12997b58daeaSdrh ** iOffset should have been preset to appropriate default values
13007b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1301ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
13027b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
13037b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
13047b58daeaSdrh ** SELECT statements.
13057b58daeaSdrh */
1306ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
130702afc861Sdrh   Vdbe *v = 0;
130802afc861Sdrh   int iLimit = 0;
130915007a99Sdrh   int iOffset;
13109b918ed1Sdrh   int addr1, n;
13110acb7e48Sdrh   if( p->iLimit ) return;
131215007a99Sdrh 
13137b58daeaSdrh   /*
13147b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
13157b58daeaSdrh   ** contraversy about what the correct behavior should be.
13167b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
13177b58daeaSdrh   ** no rows.
13187b58daeaSdrh   */
1319ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
1320373cc2ddSdrh   assert( p->pOffset==0 || p->pLimit!=0 );
1321a2dc3b1aSdanielk1977   if( p->pLimit ){
13220a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
132315007a99Sdrh     v = sqlite3GetVdbe(pParse);
1324373cc2ddSdrh     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
13259b918ed1Sdrh     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
13269b918ed1Sdrh       if( n==0 ){
13279b918ed1Sdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
13289b918ed1Sdrh       }else{
13299b918ed1Sdrh         sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
13309b918ed1Sdrh         VdbeComment((v, "LIMIT counter"));
13319b918ed1Sdrh       }
13329b918ed1Sdrh     }else{
1333b7654111Sdrh       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1334b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1335d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
13363c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
13379b918ed1Sdrh     }
1338a2dc3b1aSdanielk1977     if( p->pOffset ){
13390a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
1340b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1341b7654111Sdrh       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1342b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1343d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
13443c84ddffSdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1345b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
134615007a99Sdrh       sqlite3VdbeJumpHere(v, addr1);
1347b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1348d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1349b7654111Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1350b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1351b7654111Sdrh       sqlite3VdbeJumpHere(v, addr1);
1352b7654111Sdrh     }
1353d59ba6ceSdrh   }
13547b58daeaSdrh }
13557b58daeaSdrh 
1356b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1357fbc4ee7bSdrh /*
1358fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1359fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1360fbc4ee7bSdrh ** the column has no default collating sequence.
1361fbc4ee7bSdrh **
1362fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1363fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1364fbc4ee7bSdrh */
1365dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1366fbc4ee7bSdrh   CollSeq *pRet;
1367dc1bdc4fSdanielk1977   if( p->pPrior ){
1368dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1369fbc4ee7bSdrh   }else{
1370fbc4ee7bSdrh     pRet = 0;
1371dc1bdc4fSdanielk1977   }
137210c081adSdrh   assert( iCol>=0 );
137310c081adSdrh   if( pRet==0 && iCol<p->pEList->nExpr ){
1374dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1375dc1bdc4fSdanielk1977   }
1376dc1bdc4fSdanielk1977   return pRet;
1377d3d39e93Sdrh }
1378b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1379d3d39e93Sdrh 
1380b21e7c70Sdrh /* Forward reference */
1381b21e7c70Sdrh static int multiSelectOrderBy(
1382b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
1383b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
1384a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
1385b21e7c70Sdrh );
1386b21e7c70Sdrh 
1387b21e7c70Sdrh 
1388b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1389d3d39e93Sdrh /*
139016ee60ffSdrh ** This routine is called to process a compound query form from
139116ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
139216ee60ffSdrh ** INTERSECT
1393c926afbcSdrh **
1394e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1395e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1396e78e8284Sdrh ** in which case this routine will be called recursively.
1397e78e8284Sdrh **
1398e78e8284Sdrh ** The results of the total query are to be written into a destination
1399e78e8284Sdrh ** of type eDest with parameter iParm.
1400e78e8284Sdrh **
1401e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1402e78e8284Sdrh **
1403e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1404e78e8284Sdrh **
1405e78e8284Sdrh ** This statement is parsed up as follows:
1406e78e8284Sdrh **
1407e78e8284Sdrh **     SELECT c FROM t3
1408e78e8284Sdrh **      |
1409e78e8284Sdrh **      `----->  SELECT b FROM t2
1410e78e8284Sdrh **                |
14114b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1412e78e8284Sdrh **
1413e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1414e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1415e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1416e78e8284Sdrh **
1417e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1418e78e8284Sdrh ** individual selects always group from left to right.
141982c3d636Sdrh */
142084ac9d02Sdanielk1977 static int multiSelect(
1421fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1422fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1423a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
142484ac9d02Sdanielk1977 ){
142584ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
142610e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
142710e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
14281013c932Sdrh   SelectDest dest;      /* Alternative data destination */
1429eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
1430633e6d57Sdrh   sqlite3 *db;          /* Database connection */
143182c3d636Sdrh 
14327b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1433fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
143482c3d636Sdrh   */
1435701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
1436633e6d57Sdrh   db = pParse->db;
1437d8bc7086Sdrh   pPrior = p->pPrior;
14380342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
14390342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1440bc10377aSdrh   dest = *pDest;
1441d8bc7086Sdrh   if( pPrior->pOrderBy ){
14424adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1443da93d238Sdrh       selectOpName(p->op));
144484ac9d02Sdanielk1977     rc = 1;
144584ac9d02Sdanielk1977     goto multi_select_end;
144682c3d636Sdrh   }
1447a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
14484adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
14497b58daeaSdrh       selectOpName(p->op));
145084ac9d02Sdanielk1977     rc = 1;
145184ac9d02Sdanielk1977     goto multi_select_end;
14527b58daeaSdrh   }
145382c3d636Sdrh 
14544adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1455701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
1456d8bc7086Sdrh 
14571cc3d75fSdrh   /* Create the destination temporary table if necessary
14581cc3d75fSdrh   */
14596c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
1460b4964b72Sdanielk1977     assert( p->pEList );
1461f6e369a1Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
14626c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
14631cc3d75fSdrh   }
14641cc3d75fSdrh 
1465f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
1466f6e369a1Sdrh   ** in their result sets.
1467f6e369a1Sdrh   */
1468f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
1469f6e369a1Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
1470f6e369a1Sdrh     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1471f6e369a1Sdrh       " do not have the same number of result columns", selectOpName(p->op));
1472f6e369a1Sdrh     rc = 1;
1473f6e369a1Sdrh     goto multi_select_end;
1474f6e369a1Sdrh   }
1475f6e369a1Sdrh 
1476a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
1477a9671a22Sdrh   */
1478f6e369a1Sdrh   if( p->pOrderBy ){
1479a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
1480f6e369a1Sdrh   }
1481f6e369a1Sdrh 
1482f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1483d8bc7086Sdrh   */
148482c3d636Sdrh   switch( p->op ){
1485f46f905aSdrh     case TK_ALL: {
1486ec7429aeSdrh       int addr = 0;
1487a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
1488a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
1489a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
14907d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
1491ad68cb6bSdanielk1977       p->pLimit = 0;
1492ad68cb6bSdanielk1977       p->pOffset = 0;
149384ac9d02Sdanielk1977       if( rc ){
149484ac9d02Sdanielk1977         goto multi_select_end;
149584ac9d02Sdanielk1977       }
1496f46f905aSdrh       p->pPrior = 0;
14977b58daeaSdrh       p->iLimit = pPrior->iLimit;
14987b58daeaSdrh       p->iOffset = pPrior->iOffset;
149992b01d53Sdrh       if( p->iLimit ){
15003c84ddffSdrh         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1501d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
1502ec7429aeSdrh       }
15037d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
1504373cc2ddSdrh       testcase( rc!=SQLITE_OK );
1505eca7e01aSdanielk1977       pDelete = p->pPrior;
1506f46f905aSdrh       p->pPrior = pPrior;
1507ec7429aeSdrh       if( addr ){
1508ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
1509ec7429aeSdrh       }
1510f46f905aSdrh       break;
1511f46f905aSdrh     }
151282c3d636Sdrh     case TK_EXCEPT:
151382c3d636Sdrh     case TK_UNION: {
1514d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1515ea678832Sdrh       u8 op = 0;       /* One of the SRT_ operations to apply to self */
1516d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1517a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1518dc1bdc4fSdanielk1977       int addr;
15196c8c8ce0Sdanielk1977       SelectDest uniondest;
152082c3d636Sdrh 
1521373cc2ddSdrh       testcase( p->op==TK_EXCEPT );
1522373cc2ddSdrh       testcase( p->op==TK_UNION );
152393a960a0Sdrh       priorOp = SRT_Union;
1524e2f02bacSdrh       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
1525d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1526c926afbcSdrh         ** right.
1527d8bc7086Sdrh         */
1528e2f02bacSdrh         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
1529e2f02bacSdrh                                      ** of a 3-way or more compound */
1530e2f02bacSdrh         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
1531e2f02bacSdrh         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
15326c8c8ce0Sdanielk1977         unionTab = dest.iParm;
153382c3d636Sdrh       }else{
1534d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1535d8bc7086Sdrh         ** intermediate results.
1536d8bc7086Sdrh         */
153782c3d636Sdrh         unionTab = pParse->nTab++;
153893a960a0Sdrh         assert( p->pOrderBy==0 );
153966a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
1540b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
1541b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
15427d10d5a6Sdrh         p->pRightmost->selFlags |= SF_UsesEphemeral;
154384ac9d02Sdanielk1977         assert( p->pEList );
1544d8bc7086Sdrh       }
1545d8bc7086Sdrh 
1546d8bc7086Sdrh       /* Code the SELECT statements to our left
1547d8bc7086Sdrh       */
1548b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
15491013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
15507d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
155184ac9d02Sdanielk1977       if( rc ){
155284ac9d02Sdanielk1977         goto multi_select_end;
155384ac9d02Sdanielk1977       }
1554d8bc7086Sdrh 
1555d8bc7086Sdrh       /* Code the current SELECT statement
1556d8bc7086Sdrh       */
15574cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
15584cfb22f7Sdrh         op = SRT_Except;
15594cfb22f7Sdrh       }else{
15604cfb22f7Sdrh         assert( p->op==TK_UNION );
15614cfb22f7Sdrh         op = SRT_Union;
1562d8bc7086Sdrh       }
156382c3d636Sdrh       p->pPrior = 0;
1564a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1565a2dc3b1aSdanielk1977       p->pLimit = 0;
1566a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1567a2dc3b1aSdanielk1977       p->pOffset = 0;
15686c8c8ce0Sdanielk1977       uniondest.eDest = op;
15697d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
1570373cc2ddSdrh       testcase( rc!=SQLITE_OK );
15715bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
15725bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
1573633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
1574eca7e01aSdanielk1977       pDelete = p->pPrior;
157582c3d636Sdrh       p->pPrior = pPrior;
1576a9671a22Sdrh       p->pOrderBy = 0;
1577633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1578a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1579a2dc3b1aSdanielk1977       p->pOffset = pOffset;
158092b01d53Sdrh       p->iLimit = 0;
158192b01d53Sdrh       p->iOffset = 0;
1582d8bc7086Sdrh 
1583d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1584d8bc7086Sdrh       ** it is that we currently need.
1585d8bc7086Sdrh       */
1586373cc2ddSdrh       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
1587373cc2ddSdrh       if( dest.eDest!=priorOp ){
15886b56344dSdrh         int iCont, iBreak, iStart;
158982c3d636Sdrh         assert( p->pEList );
15907d10d5a6Sdrh         if( dest.eDest==SRT_Output ){
159192378253Sdrh           Select *pFirst = p;
159292378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
159392378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
159441202ccaSdrh         }
15954adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
15964adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1597ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
159866a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
15994adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
1600d2b3e23bSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1601a9671a22Sdrh                         0, -1, &dest, iCont, iBreak);
16024adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
160366a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
16044adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
160566a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
160682c3d636Sdrh       }
160782c3d636Sdrh       break;
160882c3d636Sdrh     }
1609373cc2ddSdrh     default: assert( p->op==TK_INTERSECT ); {
161082c3d636Sdrh       int tab1, tab2;
16116b56344dSdrh       int iCont, iBreak, iStart;
1612a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1613dc1bdc4fSdanielk1977       int addr;
16141013c932Sdrh       SelectDest intersectdest;
16159cbf3425Sdrh       int r1;
161682c3d636Sdrh 
1617d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
16186206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1619d8bc7086Sdrh       ** by allocating the tables we will need.
1620d8bc7086Sdrh       */
162182c3d636Sdrh       tab1 = pParse->nTab++;
162282c3d636Sdrh       tab2 = pParse->nTab++;
162393a960a0Sdrh       assert( p->pOrderBy==0 );
1624dc1bdc4fSdanielk1977 
162566a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
1626b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
1627b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
16287d10d5a6Sdrh       p->pRightmost->selFlags |= SF_UsesEphemeral;
162984ac9d02Sdanielk1977       assert( p->pEList );
1630d8bc7086Sdrh 
1631d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1632d8bc7086Sdrh       */
16331013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
16347d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
163584ac9d02Sdanielk1977       if( rc ){
163684ac9d02Sdanielk1977         goto multi_select_end;
163784ac9d02Sdanielk1977       }
1638d8bc7086Sdrh 
1639d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1640d8bc7086Sdrh       */
164166a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
1642b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
1643b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
164482c3d636Sdrh       p->pPrior = 0;
1645a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1646a2dc3b1aSdanielk1977       p->pLimit = 0;
1647a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1648a2dc3b1aSdanielk1977       p->pOffset = 0;
16496c8c8ce0Sdanielk1977       intersectdest.iParm = tab2;
16507d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
1651373cc2ddSdrh       testcase( rc!=SQLITE_OK );
1652eca7e01aSdanielk1977       pDelete = p->pPrior;
165382c3d636Sdrh       p->pPrior = pPrior;
1654633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1655a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1656a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1657d8bc7086Sdrh 
1658d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1659d8bc7086Sdrh       ** tables.
1660d8bc7086Sdrh       */
166182c3d636Sdrh       assert( p->pEList );
16627d10d5a6Sdrh       if( dest.eDest==SRT_Output ){
166392378253Sdrh         Select *pFirst = p;
166492378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
166592378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
166641202ccaSdrh       }
16674adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
16684adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
1669ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
167066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
16719cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
16729cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
16738cff69dfSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
16749cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1675d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1676a9671a22Sdrh                       0, -1, &dest, iCont, iBreak);
16774adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
167866a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
16794adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
168066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
168166a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
168282c3d636Sdrh       break;
168382c3d636Sdrh     }
168482c3d636Sdrh   }
16858cdbf836Sdrh 
1686a9671a22Sdrh   /* Compute collating sequences used by
1687a9671a22Sdrh   ** temporary tables needed to implement the compound select.
1688a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
16898cdbf836Sdrh   **
16908cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
16918cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
16928cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
16938cdbf836Sdrh   ** no temp tables are required.
1694fbc4ee7bSdrh   */
16957d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
1696fbc4ee7bSdrh     int i;                        /* Loop counter */
1697fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
16980342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
1699f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
170093a960a0Sdrh     int nCol;                     /* Number of columns in result set */
1701fbc4ee7bSdrh 
17020342b1f5Sdrh     assert( p->pRightmost==p );
170393a960a0Sdrh     nCol = p->pEList->nExpr;
1704633e6d57Sdrh     pKeyInfo = sqlite3DbMallocZero(db,
1705a9671a22Sdrh                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
1706dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1707dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1708dc1bdc4fSdanielk1977       goto multi_select_end;
1709dc1bdc4fSdanielk1977     }
1710dc1bdc4fSdanielk1977 
1711633e6d57Sdrh     pKeyInfo->enc = ENC(db);
1712ea678832Sdrh     pKeyInfo->nField = (u16)nCol;
1713dc1bdc4fSdanielk1977 
17140342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
17150342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
17160342b1f5Sdrh       if( 0==*apColl ){
1717633e6d57Sdrh         *apColl = db->pDfltColl;
1718dc1bdc4fSdanielk1977       }
1719dc1bdc4fSdanielk1977     }
1720dc1bdc4fSdanielk1977 
17210342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
17220342b1f5Sdrh       for(i=0; i<2; i++){
1723b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
17240342b1f5Sdrh         if( addr<0 ){
17250342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
17260342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
1727b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
17280342b1f5Sdrh           break;
17290342b1f5Sdrh         }
17300342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
173166a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
17320ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
17330342b1f5Sdrh       }
1734dc1bdc4fSdanielk1977     }
1735633e6d57Sdrh     sqlite3DbFree(db, pKeyInfo);
1736dc1bdc4fSdanielk1977   }
1737dc1bdc4fSdanielk1977 
1738dc1bdc4fSdanielk1977 multi_select_end:
17391013c932Sdrh   pDest->iMem = dest.iMem;
1740ad27e761Sdrh   pDest->nMem = dest.nMem;
1741633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
174284ac9d02Sdanielk1977   return rc;
17432282792aSdrh }
1744b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
17452282792aSdrh 
1746b21e7c70Sdrh /*
1747b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
1748b21e7c70Sdrh ** SELECT statment.
17490acb7e48Sdrh **
17500acb7e48Sdrh ** The data to be output is contained in pIn->iMem.  There are
17510acb7e48Sdrh ** pIn->nMem columns to be output.  pDest is where the output should
17520acb7e48Sdrh ** be sent.
17530acb7e48Sdrh **
17540acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
17550acb7e48Sdrh ** return address.
17560acb7e48Sdrh **
17570acb7e48Sdrh ** If regPrev>0 then it is a the first register in a vector that
17580acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
17590acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
17600acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
17610acb7e48Sdrh ** keys.
17620acb7e48Sdrh **
17630acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
17640acb7e48Sdrh ** iBreak.
1765b21e7c70Sdrh */
17660acb7e48Sdrh static int generateOutputSubroutine(
176792b01d53Sdrh   Parse *pParse,          /* Parsing context */
176892b01d53Sdrh   Select *p,              /* The SELECT statement */
176992b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
177092b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
177192b01d53Sdrh   int regReturn,          /* The return address register */
17720acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
17730acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
17740acb7e48Sdrh   int p4type,             /* The p4 type for pKeyInfo */
177592b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
1776b21e7c70Sdrh ){
1777b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
177892b01d53Sdrh   int iContinue;
177992b01d53Sdrh   int addr;
1780b21e7c70Sdrh 
178192b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
178292b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
17830acb7e48Sdrh 
17840acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
17850acb7e48Sdrh   */
17860acb7e48Sdrh   if( regPrev ){
17870acb7e48Sdrh     int j1, j2;
17880acb7e48Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
17890acb7e48Sdrh     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
17900acb7e48Sdrh                               (char*)pKeyInfo, p4type);
17910acb7e48Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
17920acb7e48Sdrh     sqlite3VdbeJumpHere(v, j1);
17930acb7e48Sdrh     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
17940acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
17950acb7e48Sdrh   }
17961f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
17970acb7e48Sdrh 
17980acb7e48Sdrh   /* Suppress the the first OFFSET entries if there is an OFFSET clause
17990acb7e48Sdrh   */
180092b01d53Sdrh   codeOffset(v, p, iContinue);
1801b21e7c70Sdrh 
1802b21e7c70Sdrh   switch( pDest->eDest ){
1803b21e7c70Sdrh     /* Store the result as data using a unique key.
1804b21e7c70Sdrh     */
1805b21e7c70Sdrh     case SRT_Table:
1806b21e7c70Sdrh     case SRT_EphemTab: {
1807b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
1808b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
1809373cc2ddSdrh       testcase( pDest->eDest==SRT_Table );
1810373cc2ddSdrh       testcase( pDest->eDest==SRT_EphemTab );
181192b01d53Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
181292b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
181392b01d53Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
1814b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1815b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
1816b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1817b21e7c70Sdrh       break;
1818b21e7c70Sdrh     }
1819b21e7c70Sdrh 
1820b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
1821b21e7c70Sdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1822b21e7c70Sdrh     ** then there should be a single item on the stack.  Write this
1823b21e7c70Sdrh     ** item into the set table with bogus data.
1824b21e7c70Sdrh     */
1825b21e7c70Sdrh     case SRT_Set: {
18266fccc35aSdrh       int r1;
182792b01d53Sdrh       assert( pIn->nMem==1 );
182892b01d53Sdrh       p->affinity =
182992b01d53Sdrh          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
1830b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
183192b01d53Sdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
183292b01d53Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
183392b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
1834b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1835b21e7c70Sdrh       break;
1836b21e7c70Sdrh     }
1837b21e7c70Sdrh 
183885e9e22bSdrh #if 0  /* Never occurs on an ORDER BY query */
1839b21e7c70Sdrh     /* If any row exist in the result set, record that fact and abort.
1840b21e7c70Sdrh     */
1841b21e7c70Sdrh     case SRT_Exists: {
184292b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
1843b21e7c70Sdrh       /* The LIMIT clause will terminate the loop for us */
1844b21e7c70Sdrh       break;
1845b21e7c70Sdrh     }
184685e9e22bSdrh #endif
1847b21e7c70Sdrh 
1848b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
1849b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
1850b21e7c70Sdrh     ** of the scan loop.
1851b21e7c70Sdrh     */
1852b21e7c70Sdrh     case SRT_Mem: {
185392b01d53Sdrh       assert( pIn->nMem==1 );
185492b01d53Sdrh       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
1855b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
1856b21e7c70Sdrh       break;
1857b21e7c70Sdrh     }
1858b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1859b21e7c70Sdrh 
18607d10d5a6Sdrh     /* The results are stored in a sequence of registers
18617d10d5a6Sdrh     ** starting at pDest->iMem.  Then the co-routine yields.
1862b21e7c70Sdrh     */
186392b01d53Sdrh     case SRT_Coroutine: {
186492b01d53Sdrh       if( pDest->iMem==0 ){
186592b01d53Sdrh         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
186692b01d53Sdrh         pDest->nMem = pIn->nMem;
1867b21e7c70Sdrh       }
186892b01d53Sdrh       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
186992b01d53Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
187092b01d53Sdrh       break;
187192b01d53Sdrh     }
187292b01d53Sdrh 
1873ccfcbceaSdrh     /* If none of the above, then the result destination must be
1874ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
1875ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
1876ccfcbceaSdrh     **
1877ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
1878ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
1879ccfcbceaSdrh     ** return the next row of result.
18807d10d5a6Sdrh     */
1881ccfcbceaSdrh     default: {
1882ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
188392b01d53Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
188492b01d53Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
1885b21e7c70Sdrh       break;
1886b21e7c70Sdrh     }
1887b21e7c70Sdrh   }
188892b01d53Sdrh 
188992b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
189092b01d53Sdrh   */
189192b01d53Sdrh   if( p->iLimit ){
18929b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
189392b01d53Sdrh   }
189492b01d53Sdrh 
189592b01d53Sdrh   /* Generate the subroutine return
189692b01d53Sdrh   */
18970acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
189892b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
189992b01d53Sdrh 
190092b01d53Sdrh   return addr;
1901b21e7c70Sdrh }
1902b21e7c70Sdrh 
1903b21e7c70Sdrh /*
1904b21e7c70Sdrh ** Alternative compound select code generator for cases when there
1905b21e7c70Sdrh ** is an ORDER BY clause.
1906b21e7c70Sdrh **
1907b21e7c70Sdrh ** We assume a query of the following form:
1908b21e7c70Sdrh **
1909b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
1910b21e7c70Sdrh **
1911b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
1912b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
1913b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
1914b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
1915b21e7c70Sdrh ** selectB) there are 7 subroutines:
1916b21e7c70Sdrh **
1917b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
1918b21e7c70Sdrh **             of the compound query.
1919b21e7c70Sdrh **
1920b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
1921b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
1922b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
1923b21e7c70Sdrh **             appears only in B.)
1924b21e7c70Sdrh **
1925b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
1926b21e7c70Sdrh **
1927b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
1928b21e7c70Sdrh **
1929b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
1930b21e7c70Sdrh **
1931b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
1932b21e7c70Sdrh **
1933b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
1934b21e7c70Sdrh **
1935b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
1936b21e7c70Sdrh ** <operator> is used:
1937b21e7c70Sdrh **
1938b21e7c70Sdrh **
1939b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
1940b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
1941b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
1942b21e7c70Sdrh **
19430acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
1944b21e7c70Sdrh **
1945b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
1946b21e7c70Sdrh **
19470acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
1948b21e7c70Sdrh **
19490acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
19500acb7e48Sdrh **
19510acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
19520acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
19530acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
19540acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
19550acb7e48Sdrh **
19560acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
19570acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
19580acb7e48Sdrh ** output value.  A comparison is made against this value and the output
19590acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
1960b21e7c70Sdrh **
1961b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
1962b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
1963b21e7c70Sdrh **
1964b21e7c70Sdrh **          goto Init
1965b21e7c70Sdrh **     coA: coroutine for left query (A)
1966b21e7c70Sdrh **     coB: coroutine for right query (B)
1967b21e7c70Sdrh **    outA: output one row of A
1968b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
1969b21e7c70Sdrh **    EofA: ...
1970b21e7c70Sdrh **    EofB: ...
1971b21e7c70Sdrh **    AltB: ...
1972b21e7c70Sdrh **    AeqB: ...
1973b21e7c70Sdrh **    AgtB: ...
1974b21e7c70Sdrh **    Init: initialize coroutine registers
1975b21e7c70Sdrh **          yield coA
1976b21e7c70Sdrh **          if eof(A) goto EofA
1977b21e7c70Sdrh **          yield coB
1978b21e7c70Sdrh **          if eof(B) goto EofB
1979b21e7c70Sdrh **    Cmpr: Compare A, B
1980b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
1981b21e7c70Sdrh **     End: ...
1982b21e7c70Sdrh **
1983b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
1984b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
1985b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
1986b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
1987b21e7c70Sdrh */
1988de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1989b21e7c70Sdrh static int multiSelectOrderBy(
1990b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
1991b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
1992a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
1993b21e7c70Sdrh ){
19940acb7e48Sdrh   int i, j;             /* Loop counters */
1995b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
1996b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
1997b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
1998b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
199992b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
200092b01d53Sdrh   int regEofA;          /* Flag to indicate when select-A is complete */
200192b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
200292b01d53Sdrh   int regEofB;          /* Flag to indicate when select-B is complete */
200392b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
200492b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
200592b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
200692b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
200792b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
2008b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
200992b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
201092b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
201192b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
201292b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
201392b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
201492b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
201592b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
20160acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
201792b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
201892b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
201992b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
202092b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
20210acb7e48Sdrh   int j1;               /* Jump instructions that get retargetted */
202292b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
202396067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
20240acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
20250acb7e48Sdrh   sqlite3 *db;          /* Database connection */
20260acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
20270acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
20280acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
2029b21e7c70Sdrh 
203092b01d53Sdrh   assert( p->pOrderBy!=0 );
203196067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
20320acb7e48Sdrh   db = pParse->db;
203392b01d53Sdrh   v = pParse->pVdbe;
2034ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
203592b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
203692b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
20370acb7e48Sdrh 
2038b21e7c70Sdrh 
203992b01d53Sdrh   /* Patch up the ORDER BY clause
204092b01d53Sdrh   */
204192b01d53Sdrh   op = p->op;
2042b21e7c70Sdrh   pPrior = p->pPrior;
204392b01d53Sdrh   assert( pPrior->pOrderBy==0 );
20440acb7e48Sdrh   pOrderBy = p->pOrderBy;
204593a960a0Sdrh   assert( pOrderBy );
20460acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
204793a960a0Sdrh 
20480acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
20490acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
20500acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
20510acb7e48Sdrh   */
20520acb7e48Sdrh   if( op!=TK_ALL ){
20530acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
20547d10d5a6Sdrh       struct ExprList_item *pItem;
20557d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
20567d10d5a6Sdrh         assert( pItem->iCol>0 );
20577d10d5a6Sdrh         if( pItem->iCol==i ) break;
20580acb7e48Sdrh       }
20590acb7e48Sdrh       if( j==nOrderBy ){
2060b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
20610acb7e48Sdrh         if( pNew==0 ) return SQLITE_NOMEM;
20620acb7e48Sdrh         pNew->flags |= EP_IntValue;
206333e619fcSdrh         pNew->u.iValue = i;
2064b7916a78Sdrh         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2065ea678832Sdrh         pOrderBy->a[nOrderBy++].iCol = (u16)i;
20660acb7e48Sdrh       }
20670acb7e48Sdrh     }
20680acb7e48Sdrh   }
20690acb7e48Sdrh 
20700acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
207110c081adSdrh   ** the permutation used to determine if the next
20720acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
20730acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
20740acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
20750acb7e48Sdrh   ** collation.
20760acb7e48Sdrh   */
20770acb7e48Sdrh   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
20780acb7e48Sdrh   if( aPermute ){
20797d10d5a6Sdrh     struct ExprList_item *pItem;
20807d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
20817d10d5a6Sdrh       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
20827d10d5a6Sdrh       aPermute[i] = pItem->iCol - 1;
20830acb7e48Sdrh     }
20840acb7e48Sdrh     pKeyMerge =
20850acb7e48Sdrh       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
20860acb7e48Sdrh     if( pKeyMerge ){
20870acb7e48Sdrh       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
2088ea678832Sdrh       pKeyMerge->nField = (u16)nOrderBy;
20890acb7e48Sdrh       pKeyMerge->enc = ENC(db);
20900acb7e48Sdrh       for(i=0; i<nOrderBy; i++){
20910acb7e48Sdrh         CollSeq *pColl;
20920acb7e48Sdrh         Expr *pTerm = pOrderBy->a[i].pExpr;
20930acb7e48Sdrh         if( pTerm->flags & EP_ExpCollate ){
20940acb7e48Sdrh           pColl = pTerm->pColl;
20950acb7e48Sdrh         }else{
20960acb7e48Sdrh           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
20970acb7e48Sdrh           pTerm->flags |= EP_ExpCollate;
20980acb7e48Sdrh           pTerm->pColl = pColl;
20990acb7e48Sdrh         }
21000acb7e48Sdrh         pKeyMerge->aColl[i] = pColl;
21010acb7e48Sdrh         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
21020acb7e48Sdrh       }
21030acb7e48Sdrh     }
21040acb7e48Sdrh   }else{
21050acb7e48Sdrh     pKeyMerge = 0;
21060acb7e48Sdrh   }
21070acb7e48Sdrh 
21080acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
21090acb7e48Sdrh   */
21100acb7e48Sdrh   p->pOrderBy = pOrderBy;
21116ab3a2ecSdanielk1977   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
21120acb7e48Sdrh 
21130acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
21140acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
21150acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
21160acb7e48Sdrh   */
21170acb7e48Sdrh   if( op==TK_ALL ){
21180acb7e48Sdrh     regPrev = 0;
21190acb7e48Sdrh   }else{
21200acb7e48Sdrh     int nExpr = p->pEList->nExpr;
21211c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
21220acb7e48Sdrh     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
21230acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
21240acb7e48Sdrh     pKeyDup = sqlite3DbMallocZero(db,
21250acb7e48Sdrh                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
21260acb7e48Sdrh     if( pKeyDup ){
21270acb7e48Sdrh       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
2128ea678832Sdrh       pKeyDup->nField = (u16)nExpr;
21290acb7e48Sdrh       pKeyDup->enc = ENC(db);
21300acb7e48Sdrh       for(i=0; i<nExpr; i++){
21310acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
21320acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
21330acb7e48Sdrh       }
21340acb7e48Sdrh     }
21350acb7e48Sdrh   }
213692b01d53Sdrh 
213792b01d53Sdrh   /* Separate the left and the right query from one another
213892b01d53Sdrh   */
213992b01d53Sdrh   p->pPrior = 0;
214092b01d53Sdrh   pPrior->pRightmost = 0;
21417d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
21420acb7e48Sdrh   if( pPrior->pPrior==0 ){
21437d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
21440acb7e48Sdrh   }
214592b01d53Sdrh 
214692b01d53Sdrh   /* Compute the limit registers */
214792b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
21480acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
214992b01d53Sdrh     regLimitA = ++pParse->nMem;
215092b01d53Sdrh     regLimitB = ++pParse->nMem;
215192b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
215292b01d53Sdrh                                   regLimitA);
215392b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
215492b01d53Sdrh   }else{
215592b01d53Sdrh     regLimitA = regLimitB = 0;
215692b01d53Sdrh   }
2157633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
21580acb7e48Sdrh   p->pLimit = 0;
2159633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
21600acb7e48Sdrh   p->pOffset = 0;
216192b01d53Sdrh 
2162b21e7c70Sdrh   regAddrA = ++pParse->nMem;
2163b21e7c70Sdrh   regEofA = ++pParse->nMem;
2164b21e7c70Sdrh   regAddrB = ++pParse->nMem;
2165b21e7c70Sdrh   regEofB = ++pParse->nMem;
2166b21e7c70Sdrh   regOutA = ++pParse->nMem;
2167b21e7c70Sdrh   regOutB = ++pParse->nMem;
2168b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2169b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2170b21e7c70Sdrh 
217192b01d53Sdrh   /* Jump past the various subroutines and coroutines to the main
217292b01d53Sdrh   ** merge loop
217392b01d53Sdrh   */
2174b21e7c70Sdrh   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
2175b21e7c70Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v);
217692b01d53Sdrh 
21770acb7e48Sdrh 
217892b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
21790acb7e48Sdrh   ** left of the compound operator - the "A" select.
21800acb7e48Sdrh   */
2181b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
218292b01d53Sdrh   pPrior->iLimit = regLimitA;
21837d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
2184b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
218592b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2186b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for left SELECT"));
2187b21e7c70Sdrh 
218892b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
218992b01d53Sdrh   ** the right - the "B" select
219092b01d53Sdrh   */
2191b21e7c70Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v);
2192b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
219392b01d53Sdrh   savedLimit = p->iLimit;
219492b01d53Sdrh   savedOffset = p->iOffset;
219592b01d53Sdrh   p->iLimit = regLimitB;
219692b01d53Sdrh   p->iOffset = 0;
21977d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
219892b01d53Sdrh   p->iLimit = savedLimit;
219992b01d53Sdrh   p->iOffset = savedOffset;
2200b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
220192b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2202b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for right SELECT"));
2203b21e7c70Sdrh 
220492b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
22050acb7e48Sdrh   ** select as the next output row of the compound select.
220692b01d53Sdrh   */
2207b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
22080acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
22090acb7e48Sdrh                  p, &destA, pDest, regOutA,
22100acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
2211b21e7c70Sdrh 
221292b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
22130acb7e48Sdrh   ** select as the next output row of the compound select.
221492b01d53Sdrh   */
22150acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
2216b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
22170acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
22180acb7e48Sdrh                  p, &destB, pDest, regOutB,
22190acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
22200acb7e48Sdrh   }
2221b21e7c70Sdrh 
222292b01d53Sdrh   /* Generate a subroutine to run when the results from select A
222392b01d53Sdrh   ** are exhausted and only data in select B remains.
222492b01d53Sdrh   */
222592b01d53Sdrh   VdbeNoopComment((v, "eof-A subroutine"));
222692b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
22270acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
222892b01d53Sdrh   }else{
22290acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
2230b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
223192b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
22320acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
2233b21e7c70Sdrh   }
2234b21e7c70Sdrh 
223592b01d53Sdrh   /* Generate a subroutine to run when the results from select B
223692b01d53Sdrh   ** are exhausted and only data in select A remains.
223792b01d53Sdrh   */
2238b21e7c70Sdrh   if( op==TK_INTERSECT ){
223992b01d53Sdrh     addrEofB = addrEofA;
2240b21e7c70Sdrh   }else{
224192b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
22420acb7e48Sdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
2243b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
224492b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
22450acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2246b21e7c70Sdrh   }
2247b21e7c70Sdrh 
224892b01d53Sdrh   /* Generate code to handle the case of A<B
224992b01d53Sdrh   */
2250b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
22510acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
225292b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2253b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
225492b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2255b21e7c70Sdrh 
225692b01d53Sdrh   /* Generate code to handle the case of A==B
225792b01d53Sdrh   */
2258b21e7c70Sdrh   if( op==TK_ALL ){
2259b21e7c70Sdrh     addrAeqB = addrAltB;
22600acb7e48Sdrh   }else if( op==TK_INTERSECT ){
22610acb7e48Sdrh     addrAeqB = addrAltB;
22620acb7e48Sdrh     addrAltB++;
226392b01d53Sdrh   }else{
2264b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
22650acb7e48Sdrh     addrAeqB =
226692b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
226792b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
226892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
226992b01d53Sdrh   }
2270b21e7c70Sdrh 
227192b01d53Sdrh   /* Generate code to handle the case of A>B
227292b01d53Sdrh   */
2273b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
2274b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
2275b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
2276b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
227792b01d53Sdrh   }
22780acb7e48Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2279b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
228092b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2281b21e7c70Sdrh 
228292b01d53Sdrh   /* This code runs once to initialize everything.
228392b01d53Sdrh   */
2284b21e7c70Sdrh   sqlite3VdbeJumpHere(v, j1);
2285b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
2286b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
228792b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
22880acb7e48Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
2289b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2290b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
229192b01d53Sdrh 
229292b01d53Sdrh   /* Implement the main merge loop
229392b01d53Sdrh   */
229492b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
22950acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
22960acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
22970acb7e48Sdrh                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
2298b21e7c70Sdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
229992b01d53Sdrh 
23000acb7e48Sdrh   /* Release temporary registers
23010acb7e48Sdrh   */
23020acb7e48Sdrh   if( regPrev ){
23030acb7e48Sdrh     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
23040acb7e48Sdrh   }
23050acb7e48Sdrh 
230692b01d53Sdrh   /* Jump to the this point in order to terminate the query.
230792b01d53Sdrh   */
2308b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
2309b21e7c70Sdrh 
231092b01d53Sdrh   /* Set the number of output columns
231192b01d53Sdrh   */
23127d10d5a6Sdrh   if( pDest->eDest==SRT_Output ){
23130acb7e48Sdrh     Select *pFirst = pPrior;
231492b01d53Sdrh     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
231592b01d53Sdrh     generateColumnNames(pParse, 0, pFirst->pEList);
2316b21e7c70Sdrh   }
231792b01d53Sdrh 
23180acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
23190acb7e48Sdrh   ** by the calling function */
23205e7ad508Sdanielk1977   if( p->pPrior ){
2321633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
23225e7ad508Sdanielk1977   }
23230acb7e48Sdrh   p->pPrior = pPrior;
232492b01d53Sdrh 
232592b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
232692b01d53Sdrh   **** subqueries ****/
232792b01d53Sdrh   return SQLITE_OK;
232892b01d53Sdrh }
2329de3e41e3Sdanielk1977 #endif
2330b21e7c70Sdrh 
23313514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
233217435752Sdrh /* Forward Declarations */
233317435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
233417435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
233517435752Sdrh 
23362282792aSdrh /*
2337832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
23386a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
233984e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
23406a3ea0e6Sdrh ** unchanged.)
2341832508b7Sdrh **
2342832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2343832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2344832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2345832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2346832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2347832508b7Sdrh ** of the subquery rather the result set of the subquery.
2348832508b7Sdrh */
2349b7916a78Sdrh static Expr *substExpr(
235017435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
235117435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
235217435752Sdrh   int iTable,         /* Table to be substituted */
235317435752Sdrh   ExprList *pEList    /* Substitute expressions */
235417435752Sdrh ){
2355b7916a78Sdrh   if( pExpr==0 ) return 0;
235650350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
235750350a15Sdrh     if( pExpr->iColumn<0 ){
235850350a15Sdrh       pExpr->op = TK_NULL;
235950350a15Sdrh     }else{
2360832508b7Sdrh       Expr *pNew;
236184e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
23626ab3a2ecSdanielk1977       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
2363b7916a78Sdrh       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
236438210ac5Sdrh       if( pNew && pExpr->pColl ){
23650a458e5eSdanielk1977         pNew->pColl = pExpr->pColl;
23660a458e5eSdanielk1977       }
2367b7916a78Sdrh       sqlite3ExprDelete(db, pExpr);
2368b7916a78Sdrh       pExpr = pNew;
236950350a15Sdrh     }
2370832508b7Sdrh   }else{
2371b7916a78Sdrh     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
2372b7916a78Sdrh     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
23736ab3a2ecSdanielk1977     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
23746ab3a2ecSdanielk1977       substSelect(db, pExpr->x.pSelect, iTable, pEList);
23756ab3a2ecSdanielk1977     }else{
23766ab3a2ecSdanielk1977       substExprList(db, pExpr->x.pList, iTable, pEList);
23776ab3a2ecSdanielk1977     }
2378832508b7Sdrh   }
2379b7916a78Sdrh   return pExpr;
2380832508b7Sdrh }
238117435752Sdrh static void substExprList(
238217435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
238317435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
238417435752Sdrh   int iTable,          /* Table to be substituted */
238517435752Sdrh   ExprList *pEList     /* Substitute values */
238617435752Sdrh ){
2387832508b7Sdrh   int i;
2388832508b7Sdrh   if( pList==0 ) return;
2389832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
2390b7916a78Sdrh     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
2391832508b7Sdrh   }
2392832508b7Sdrh }
239317435752Sdrh static void substSelect(
239417435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
239517435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
239617435752Sdrh   int iTable,          /* Table to be replaced */
239717435752Sdrh   ExprList *pEList     /* Substitute values */
239817435752Sdrh ){
2399588a9a1aSdrh   SrcList *pSrc;
2400588a9a1aSdrh   struct SrcList_item *pItem;
2401588a9a1aSdrh   int i;
2402b3bce662Sdanielk1977   if( !p ) return;
240317435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
240417435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
240517435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
2406b7916a78Sdrh   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
2407b7916a78Sdrh   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
240817435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2409588a9a1aSdrh   pSrc = p->pSrc;
2410e2f02bacSdrh   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
2411e2f02bacSdrh   if( ALWAYS(pSrc) ){
2412588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2413588a9a1aSdrh       substSelect(db, pItem->pSelect, iTable, pEList);
2414588a9a1aSdrh     }
2415588a9a1aSdrh   }
2416b3bce662Sdanielk1977 }
24173514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2418832508b7Sdrh 
24193514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2420832508b7Sdrh /*
24211350b030Sdrh ** This routine attempts to flatten subqueries in order to speed
24221350b030Sdrh ** execution.  It returns 1 if it makes changes and 0 if no flattening
24231350b030Sdrh ** occurs.
24241350b030Sdrh **
24251350b030Sdrh ** To understand the concept of flattening, consider the following
24261350b030Sdrh ** query:
24271350b030Sdrh **
24281350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
24291350b030Sdrh **
24301350b030Sdrh ** The default way of implementing this query is to execute the
24311350b030Sdrh ** subquery first and store the results in a temporary table, then
24321350b030Sdrh ** run the outer query on that temporary table.  This requires two
24331350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
24341350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2435832508b7Sdrh ** optimized.
24361350b030Sdrh **
2437832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
24381350b030Sdrh ** a single flat select, like this:
24391350b030Sdrh **
24401350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
24411350b030Sdrh **
24421350b030Sdrh ** The code generated for this simpification gives the same result
2443832508b7Sdrh ** but only has to scan the data once.  And because indices might
2444832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2445832508b7Sdrh ** avoided.
24461350b030Sdrh **
2447832508b7Sdrh ** Flattening is only attempted if all of the following are true:
24481350b030Sdrh **
2449832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
24501350b030Sdrh **
2451832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2452832508b7Sdrh **
24532b300d5dSdrh **   (3)  The subquery is not the right operand of a left outer join
24542b300d5dSdrh **        (Originally ticket #306.  Strenghtened by ticket #3300)
2455832508b7Sdrh **
2456832508b7Sdrh **   (4)  The subquery is not DISTINCT or the outer query is not a join.
2457832508b7Sdrh **
2458832508b7Sdrh **   (5)  The subquery is not DISTINCT or the outer query does not use
2459832508b7Sdrh **        aggregates.
2460832508b7Sdrh **
2461832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2462832508b7Sdrh **        DISTINCT.
2463832508b7Sdrh **
246408192d5fSdrh **   (7)  The subquery has a FROM clause.
246508192d5fSdrh **
2466df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2467df199a25Sdrh **
2468df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2469df199a25Sdrh **        aggregates.
2470df199a25Sdrh **
2471df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2472df199a25Sdrh **        use LIMIT.
2473df199a25Sdrh **
2474174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2475174b6195Sdrh **
24762b300d5dSdrh **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
24772b300d5dSdrh **        a separate restriction deriving from ticket #350.
24783fc673e6Sdrh **
2479ac83963aSdrh **  (13)  The subquery and outer query do not both use LIMIT
2480ac83963aSdrh **
2481ac83963aSdrh **  (14)  The subquery does not use OFFSET
2482ac83963aSdrh **
2483ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2484ad91c6cdSdrh **        subquery does not have both an ORDER BY and a LIMIT clause.
2485ad91c6cdSdrh **        (See ticket #2339)
2486ad91c6cdSdrh **
2487c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
2488c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2489c52e355dSdrh **        until we introduced the group_concat() function.
2490c52e355dSdrh **
2491f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
24924914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
2493f23329a2Sdanielk1977 **        the parent query:
2494f23329a2Sdanielk1977 **
2495f23329a2Sdanielk1977 **          * is not itself part of a compound select,
2496f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
2497f23329a2Sdanielk1977 **          * has no other tables or sub-selects in the FROM clause.
2498f23329a2Sdanielk1977 **
24994914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
25004914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
25014914cf92Sdanielk1977 **        LIMIT and OFFSET clauses.
2502f23329a2Sdanielk1977 **
250349fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
250449fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
250549fc1f60Sdanielk1977 **        columns of the sub-query.
250649fc1f60Sdanielk1977 **
2507229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
2508229cf702Sdrh **        have a WHERE clause.
2509229cf702Sdrh **
2510e8902a70Sdrh **  (20)  If the sub-query is a compound select, then it must not use
2511e8902a70Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
2512e8902a70Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
2513e8902a70Sdrh **        appear as unmodified result columns in the outer query.  But
2514e8902a70Sdrh **        have other optimizations in mind to deal with that case.
2515e8902a70Sdrh **
2516832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2517832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2518832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2519832508b7Sdrh **
2520665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2521832508b7Sdrh ** If flattening is attempted this routine returns 1.
2522832508b7Sdrh **
2523832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2524832508b7Sdrh ** the subquery before this routine runs.
25251350b030Sdrh */
25268c74a8caSdrh static int flattenSubquery(
2527524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
25288c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
25298c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
25308c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
25318c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
25328c74a8caSdrh ){
2533524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
2534f23329a2Sdanielk1977   Select *pParent;
25350bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2536f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
2537ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2538ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
25390bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
25406a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
254191bb0eedSdrh   int i;              /* Loop counter */
254291bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
254391bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
2544524cc21eSdanielk1977   sqlite3 *db = pParse->db;
25451350b030Sdrh 
2546832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2547832508b7Sdrh   */
2548a78c22c4Sdrh   assert( p!=0 );
2549a78c22c4Sdrh   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
2550832508b7Sdrh   pSrc = p->pSrc;
2551ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
255291bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
255349fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
255491bb0eedSdrh   pSub = pSubitem->pSelect;
2555832508b7Sdrh   assert( pSub!=0 );
2556ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2557ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2558832508b7Sdrh   pSubSrc = pSub->pSrc;
2559832508b7Sdrh   assert( pSubSrc );
2560ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2561ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2562ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2563ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2564ac83963aSdrh   ** and (14). */
2565ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2566ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2567ad91c6cdSdrh   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
2568ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2569ad91c6cdSdrh   }
2570ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
25717d10d5a6Sdrh   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
2572ac83963aSdrh          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
2573df199a25Sdrh      return 0;
2574df199a25Sdrh   }
25757d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
25767d10d5a6Sdrh      return 0;         /* Restriction (6)  */
25777d10d5a6Sdrh   }
25787d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
2579ac83963aSdrh      return 0;                                           /* Restriction (11) */
2580ac83963aSdrh   }
2581c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2582229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
2583832508b7Sdrh 
25842b300d5dSdrh   /* OBSOLETE COMMENT 1:
25852b300d5dSdrh   ** Restriction 3:  If the subquery is a join, make sure the subquery is
25868af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
25878af4d3acSdrh   ** is not allowed:
25888af4d3acSdrh   **
25898af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
25908af4d3acSdrh   **
25918af4d3acSdrh   ** If we flatten the above, we would get
25928af4d3acSdrh   **
25938af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
25948af4d3acSdrh   **
25958af4d3acSdrh   ** which is not at all the same thing.
25962b300d5dSdrh   **
25972b300d5dSdrh   ** OBSOLETE COMMENT 2:
25982b300d5dSdrh   ** Restriction 12:  If the subquery is the right operand of a left outer
25993fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
26003fc673e6Sdrh   ** An examples of why this is not allowed:
26013fc673e6Sdrh   **
26023fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
26033fc673e6Sdrh   **
26043fc673e6Sdrh   ** If we flatten the above, we would get
26053fc673e6Sdrh   **
26063fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
26073fc673e6Sdrh   **
26083fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
26093fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
26102b300d5dSdrh   **
26112b300d5dSdrh   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
26122b300d5dSdrh   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
26132b300d5dSdrh   ** is fraught with danger.  Best to avoid the whole thing.  If the
26142b300d5dSdrh   ** subquery is the right term of a LEFT JOIN, then do not flatten.
26153fc673e6Sdrh   */
26162b300d5dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 ){
26173fc673e6Sdrh     return 0;
26183fc673e6Sdrh   }
26193fc673e6Sdrh 
2620f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
2621f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
2622f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
2623f23329a2Sdanielk1977   ** queries.
2624f23329a2Sdanielk1977   */
2625f23329a2Sdanielk1977   if( pSub->pPrior ){
2626e8902a70Sdrh     if( pSub->pOrderBy ){
2627e8902a70Sdrh       return 0;  /* Restriction 20 */
2628e8902a70Sdrh     }
2629e2f02bacSdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
2630f23329a2Sdanielk1977       return 0;
2631f23329a2Sdanielk1977     }
2632f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
2633ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2634ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
26357d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
263680b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
2637ccfcbceaSdrh        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
263880b3c548Sdanielk1977       ){
2639f23329a2Sdanielk1977         return 0;
2640f23329a2Sdanielk1977       }
2641f23329a2Sdanielk1977     }
264249fc1f60Sdanielk1977 
264349fc1f60Sdanielk1977     /* Restriction 18. */
264449fc1f60Sdanielk1977     if( p->pOrderBy ){
264549fc1f60Sdanielk1977       int ii;
264649fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
26477d10d5a6Sdrh         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
264849fc1f60Sdanielk1977       }
264949fc1f60Sdanielk1977     }
2650f23329a2Sdanielk1977   }
2651f23329a2Sdanielk1977 
26527d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
26537d10d5a6Sdrh 
26547d10d5a6Sdrh   /* Authorize the subquery */
2655524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
2656524cc21eSdanielk1977   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
2657524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
2658524cc21eSdanielk1977 
26597d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
26607d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
26617d10d5a6Sdrh   ** be of the form:
2662f23329a2Sdanielk1977   **
2663f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
2664f23329a2Sdanielk1977   **
2665f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
2666a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
2667f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
2668f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
2669f23329a2Sdanielk1977   ** select statements in the compound sub-query.
2670a78c22c4Sdrh   **
2671a78c22c4Sdrh   ** Example:
2672a78c22c4Sdrh   **
2673a78c22c4Sdrh   **     SELECT a+1 FROM (
2674a78c22c4Sdrh   **        SELECT x FROM tab
2675a78c22c4Sdrh   **        UNION ALL
2676a78c22c4Sdrh   **        SELECT y FROM tab
2677a78c22c4Sdrh   **        UNION ALL
2678a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
2679a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
2680a78c22c4Sdrh   **
2681a78c22c4Sdrh   ** Transformed into:
2682a78c22c4Sdrh   **
2683a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
2684a78c22c4Sdrh   **     UNION ALL
2685a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
2686a78c22c4Sdrh   **     UNION ALL
2687a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
2688a78c22c4Sdrh   **     ORDER BY 1
2689a78c22c4Sdrh   **
2690a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
2691f23329a2Sdanielk1977   */
2692f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
2693f23329a2Sdanielk1977     Select *pNew;
2694f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
26954b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
2696f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
2697f23329a2Sdanielk1977     p->pOrderBy = 0;
2698f23329a2Sdanielk1977     p->pSrc = 0;
2699f23329a2Sdanielk1977     p->pPrior = 0;
27004b86ef1dSdanielk1977     p->pLimit = 0;
27016ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
27024b86ef1dSdanielk1977     p->pLimit = pLimit;
2703a78c22c4Sdrh     p->pOrderBy = pOrderBy;
2704a78c22c4Sdrh     p->pSrc = pSrc;
2705a78c22c4Sdrh     p->op = TK_ALL;
2706f23329a2Sdanielk1977     p->pRightmost = 0;
2707a78c22c4Sdrh     if( pNew==0 ){
2708a78c22c4Sdrh       pNew = pPrior;
2709a78c22c4Sdrh     }else{
2710a78c22c4Sdrh       pNew->pPrior = pPrior;
2711f23329a2Sdanielk1977       pNew->pRightmost = 0;
2712f23329a2Sdanielk1977     }
2713a78c22c4Sdrh     p->pPrior = pNew;
2714a78c22c4Sdrh     if( db->mallocFailed ) return 1;
2715a78c22c4Sdrh   }
2716f23329a2Sdanielk1977 
27177d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
27187d10d5a6Sdrh   ** in the outer query.
2719832508b7Sdrh   */
2720f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
2721c31c2eb8Sdrh 
2722a78c22c4Sdrh   /* Delete the transient table structure associated with the
2723a78c22c4Sdrh   ** subquery
2724a78c22c4Sdrh   */
2725a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zDatabase);
2726a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zName);
2727a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zAlias);
2728a78c22c4Sdrh   pSubitem->zDatabase = 0;
2729a78c22c4Sdrh   pSubitem->zName = 0;
2730a78c22c4Sdrh   pSubitem->zAlias = 0;
2731a78c22c4Sdrh   pSubitem->pSelect = 0;
2732a78c22c4Sdrh 
2733a78c22c4Sdrh   /* Defer deleting the Table object associated with the
2734a78c22c4Sdrh   ** subquery until code generation is
2735a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
2736a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
2737ccfcbceaSdrh   **
2738ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
2739a78c22c4Sdrh   */
2740ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
2741a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
2742a78c22c4Sdrh     if( pTabToDel->nRef==1 ){
274365a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
274465a7cd16Sdan       pTabToDel->pNextZombie = pToplevel->pZombieTab;
274565a7cd16Sdan       pToplevel->pZombieTab = pTabToDel;
2746a78c22c4Sdrh     }else{
2747a78c22c4Sdrh       pTabToDel->nRef--;
2748a78c22c4Sdrh     }
2749a78c22c4Sdrh     pSubitem->pTab = 0;
2750a78c22c4Sdrh   }
2751a78c22c4Sdrh 
2752a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
2753a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
2754a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
2755a78c22c4Sdrh   ** then this loop only runs once.
2756a78c22c4Sdrh   **
2757a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
2758c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
2759c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
2760c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
2761c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
2762c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
2763c31c2eb8Sdrh   ** elements we are now copying in.
2764c31c2eb8Sdrh   */
2765a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
2766a78c22c4Sdrh     int nSubSrc;
2767ea678832Sdrh     u8 jointype = 0;
2768a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
2769a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
2770a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
2771588a9a1aSdrh 
2772a78c22c4Sdrh     if( pSrc ){
2773a78c22c4Sdrh       assert( pParent==p );  /* First time through the loop */
2774a78c22c4Sdrh       jointype = pSubitem->jointype;
2775588a9a1aSdrh     }else{
2776a78c22c4Sdrh       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
2777a78c22c4Sdrh       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
2778cfa063b3Sdrh       if( pSrc==0 ){
2779a78c22c4Sdrh         assert( db->mallocFailed );
2780a78c22c4Sdrh         break;
2781cfa063b3Sdrh       }
2782c31c2eb8Sdrh     }
2783a78c22c4Sdrh 
2784a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
2785a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
2786a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
2787a78c22c4Sdrh     ** of the subquery.
2788a78c22c4Sdrh     **
2789a78c22c4Sdrh     ** Example:
2790a78c22c4Sdrh     **
2791a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
2792a78c22c4Sdrh     **
2793a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
2794a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
2795a78c22c4Sdrh     ** block of code will expand the out query to 4 slots.  The middle
2796a78c22c4Sdrh     ** slot is expanded to two slots in order to make space for the
2797a78c22c4Sdrh     ** two elements in the FROM clause of the subquery.
2798a78c22c4Sdrh     */
2799a78c22c4Sdrh     if( nSubSrc>1 ){
2800a78c22c4Sdrh       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
2801a78c22c4Sdrh       if( db->mallocFailed ){
2802a78c22c4Sdrh         break;
2803c31c2eb8Sdrh       }
2804c31c2eb8Sdrh     }
2805a78c22c4Sdrh 
2806a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
2807a78c22c4Sdrh     ** outer query.
2808a78c22c4Sdrh     */
2809c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
2810c3a8402aSdrh       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
2811c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
2812c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
2813c31c2eb8Sdrh     }
281461dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
2815c31c2eb8Sdrh 
2816c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
2817c31c2eb8Sdrh     ** references to the iParent in the outer query.
2818c31c2eb8Sdrh     **
2819c31c2eb8Sdrh     ** Example:
2820c31c2eb8Sdrh     **
2821c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
2822c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
2823c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
2824c31c2eb8Sdrh     **
2825c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
2826c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
2827c31c2eb8Sdrh     */
2828f23329a2Sdanielk1977     pList = pParent->pEList;
2829832508b7Sdrh     for(i=0; i<pList->nExpr; i++){
2830ccfcbceaSdrh       if( pList->a[i].zName==0 ){
2831b7916a78Sdrh         const char *zSpan = pList->a[i].zSpan;
2832d6b8c434Sdrh         if( ALWAYS(zSpan) ){
2833b7916a78Sdrh           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
2834832508b7Sdrh         }
2835832508b7Sdrh       }
2836ccfcbceaSdrh     }
2837f23329a2Sdanielk1977     substExprList(db, pParent->pEList, iParent, pSub->pEList);
28381b2e0329Sdrh     if( isAgg ){
2839f23329a2Sdanielk1977       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
2840b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
28411b2e0329Sdrh     }
2842174b6195Sdrh     if( pSub->pOrderBy ){
2843f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
2844f23329a2Sdanielk1977       pParent->pOrderBy = pSub->pOrderBy;
2845174b6195Sdrh       pSub->pOrderBy = 0;
2846f23329a2Sdanielk1977     }else if( pParent->pOrderBy ){
2847f23329a2Sdanielk1977       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
2848174b6195Sdrh     }
2849832508b7Sdrh     if( pSub->pWhere ){
28506ab3a2ecSdanielk1977       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
2851832508b7Sdrh     }else{
2852832508b7Sdrh       pWhere = 0;
2853832508b7Sdrh     }
2854832508b7Sdrh     if( subqueryIsAgg ){
2855f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
2856f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
2857f23329a2Sdanielk1977       pParent->pWhere = pWhere;
2858b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
2859f23329a2Sdanielk1977       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
28606ab3a2ecSdanielk1977                                   sqlite3ExprDup(db, pSub->pHaving, 0));
2861f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
28626ab3a2ecSdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
2863832508b7Sdrh     }else{
2864b7916a78Sdrh       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
2865f23329a2Sdanielk1977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
2866832508b7Sdrh     }
2867c31c2eb8Sdrh 
2868c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
2869c31c2eb8Sdrh     ** outer query is distinct.
2870c31c2eb8Sdrh     */
28717d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
28728c74a8caSdrh 
2873a58fdfb1Sdanielk1977     /*
2874a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
2875ac83963aSdrh     **
2876ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
2877ac83963aSdrh     ** does not work if either limit is negative.
2878a58fdfb1Sdanielk1977     */
2879a2dc3b1aSdanielk1977     if( pSub->pLimit ){
2880f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
2881a2dc3b1aSdanielk1977       pSub->pLimit = 0;
2882df199a25Sdrh     }
2883f23329a2Sdanielk1977   }
28848c74a8caSdrh 
2885c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
2886c31c2eb8Sdrh   ** success.
2887c31c2eb8Sdrh   */
2888633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
2889f23329a2Sdanielk1977 
2890832508b7Sdrh   return 1;
28911350b030Sdrh }
28923514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
28931350b030Sdrh 
28941350b030Sdrh /*
2895a9d1ccb9Sdanielk1977 ** Analyze the SELECT statement passed as an argument to see if it
289608c88eb0Sdrh ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
2897a9d1ccb9Sdanielk1977 ** it is, or 0 otherwise. At present, a query is considered to be
2898a9d1ccb9Sdanielk1977 ** a min()/max() query if:
2899a9d1ccb9Sdanielk1977 **
2900738bdcfbSdanielk1977 **   1. There is a single object in the FROM clause.
2901738bdcfbSdanielk1977 **
2902738bdcfbSdanielk1977 **   2. There is a single expression in the result set, and it is
2903738bdcfbSdanielk1977 **      either min(x) or max(x), where x is a column reference.
2904a9d1ccb9Sdanielk1977 */
29054f21c4afSdrh static u8 minMaxQuery(Select *p){
2906a9d1ccb9Sdanielk1977   Expr *pExpr;
2907a9d1ccb9Sdanielk1977   ExprList *pEList = p->pEList;
2908a9d1ccb9Sdanielk1977 
290908c88eb0Sdrh   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
2910a9d1ccb9Sdanielk1977   pExpr = pEList->a[0].pExpr;
291143152cf8Sdrh   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
291243152cf8Sdrh   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
29136ab3a2ecSdanielk1977   pEList = pExpr->x.pList;
291443152cf8Sdrh   if( pEList==0 || pEList->nExpr!=1 ) return 0;
291508c88eb0Sdrh   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
291633e619fcSdrh   assert( !ExprHasProperty(pExpr, EP_IntValue) );
291733e619fcSdrh   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
291808c88eb0Sdrh     return WHERE_ORDERBY_MIN;
291933e619fcSdrh   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
292008c88eb0Sdrh     return WHERE_ORDERBY_MAX;
2921a9d1ccb9Sdanielk1977   }
292208c88eb0Sdrh   return WHERE_ORDERBY_NORMAL;
2923a9d1ccb9Sdanielk1977 }
2924a9d1ccb9Sdanielk1977 
2925a9d1ccb9Sdanielk1977 /*
2926a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
2927a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This
2928a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
2929a5533162Sdanielk1977 **
2930a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
2931a5533162Sdanielk1977 **
2932a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
2933a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
2934a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned.
2935a5533162Sdanielk1977 */
2936a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
2937a5533162Sdanielk1977   Table *pTab;
2938a5533162Sdanielk1977   Expr *pExpr;
2939a5533162Sdanielk1977 
2940a5533162Sdanielk1977   assert( !p->pGroupBy );
2941a5533162Sdanielk1977 
29427a895a80Sdanielk1977   if( p->pWhere || p->pEList->nExpr!=1
2943a5533162Sdanielk1977    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
2944a5533162Sdanielk1977   ){
2945a5533162Sdanielk1977     return 0;
2946a5533162Sdanielk1977   }
2947a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
2948a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
294902f33725Sdanielk1977   assert( pTab && !pTab->pSelect && pExpr );
295002f33725Sdanielk1977 
295102f33725Sdanielk1977   if( IsVirtual(pTab) ) return 0;
2952a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
2953a5533162Sdanielk1977   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
2954a5533162Sdanielk1977   if( pExpr->flags&EP_Distinct ) return 0;
2955a5533162Sdanielk1977 
2956a5533162Sdanielk1977   return pTab;
2957a5533162Sdanielk1977 }
2958a5533162Sdanielk1977 
2959a5533162Sdanielk1977 /*
2960b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
2961b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
2962b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
2963b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
2964b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
2965b1c685b0Sdanielk1977 */
2966b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
2967b1c685b0Sdanielk1977   if( pFrom->pTab && pFrom->zIndex ){
2968b1c685b0Sdanielk1977     Table *pTab = pFrom->pTab;
2969b1c685b0Sdanielk1977     char *zIndex = pFrom->zIndex;
2970b1c685b0Sdanielk1977     Index *pIdx;
2971b1c685b0Sdanielk1977     for(pIdx=pTab->pIndex;
2972b1c685b0Sdanielk1977         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
2973b1c685b0Sdanielk1977         pIdx=pIdx->pNext
2974b1c685b0Sdanielk1977     );
2975b1c685b0Sdanielk1977     if( !pIdx ){
2976b1c685b0Sdanielk1977       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
2977b1c685b0Sdanielk1977       return SQLITE_ERROR;
2978b1c685b0Sdanielk1977     }
2979b1c685b0Sdanielk1977     pFrom->pIndex = pIdx;
2980b1c685b0Sdanielk1977   }
2981b1c685b0Sdanielk1977   return SQLITE_OK;
2982b1c685b0Sdanielk1977 }
2983b1c685b0Sdanielk1977 
2984b1c685b0Sdanielk1977 /*
29857d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
29867d10d5a6Sdrh ** "Expanding" means to do the following:
29877d10d5a6Sdrh **
29887d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
29897d10d5a6Sdrh **         element of the FROM clause.
29907d10d5a6Sdrh **
29917d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
29927d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
29937d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
29947d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
29957d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
29967d10d5a6Sdrh **         without worrying about messing up the presistent representation
29977d10d5a6Sdrh **         of the view.
29987d10d5a6Sdrh **
29997d10d5a6Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
30007d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
30017d10d5a6Sdrh **
30027d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
30037d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
30047d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
30057d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
30067d10d5a6Sdrh **
3007b3bce662Sdanielk1977 */
30087d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
30097d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
30107d10d5a6Sdrh   int i, j, k;
30117d10d5a6Sdrh   SrcList *pTabList;
30127d10d5a6Sdrh   ExprList *pEList;
30137d10d5a6Sdrh   struct SrcList_item *pFrom;
30147d10d5a6Sdrh   sqlite3 *db = pParse->db;
30157d10d5a6Sdrh 
30167d10d5a6Sdrh   if( db->mallocFailed  ){
30177d10d5a6Sdrh     return WRC_Abort;
30187d10d5a6Sdrh   }
301943152cf8Sdrh   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
30207d10d5a6Sdrh     return WRC_Prune;
30217d10d5a6Sdrh   }
30227d10d5a6Sdrh   p->selFlags |= SF_Expanded;
30237d10d5a6Sdrh   pTabList = p->pSrc;
30247d10d5a6Sdrh   pEList = p->pEList;
30257d10d5a6Sdrh 
30267d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
30277d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
30287d10d5a6Sdrh   */
30297d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
30307d10d5a6Sdrh 
30317d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
30327d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
30337d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
30347d10d5a6Sdrh   */
30357d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
30367d10d5a6Sdrh     Table *pTab;
30377d10d5a6Sdrh     if( pFrom->pTab!=0 ){
30387d10d5a6Sdrh       /* This statement has already been prepared.  There is no need
30397d10d5a6Sdrh       ** to go further. */
30407d10d5a6Sdrh       assert( i==0 );
30417d10d5a6Sdrh       return WRC_Prune;
30427d10d5a6Sdrh     }
30437d10d5a6Sdrh     if( pFrom->zName==0 ){
30447d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
30457d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
30467d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
30477d10d5a6Sdrh       assert( pSel!=0 );
30487d10d5a6Sdrh       assert( pFrom->pTab==0 );
30497d10d5a6Sdrh       sqlite3WalkSelect(pWalker, pSel);
30507d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
30517d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
3052d9da78a2Sdrh       pTab->dbMem = db->lookaside.bEnabled ? db : 0;
30537d10d5a6Sdrh       pTab->nRef = 1;
30547d10d5a6Sdrh       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
30557d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
30567d10d5a6Sdrh       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
30577d10d5a6Sdrh       pTab->iPKey = -1;
30587d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
30597d10d5a6Sdrh #endif
30607d10d5a6Sdrh     }else{
30617d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
30627d10d5a6Sdrh       assert( pFrom->pTab==0 );
30637d10d5a6Sdrh       pFrom->pTab = pTab =
30647d10d5a6Sdrh         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
30657d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
30667d10d5a6Sdrh       pTab->nRef++;
30677d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
30687d10d5a6Sdrh       if( pTab->pSelect || IsVirtual(pTab) ){
30697d10d5a6Sdrh         /* We reach here if the named table is a really a view */
30707d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
307143152cf8Sdrh         assert( pFrom->pSelect==0 );
30726ab3a2ecSdanielk1977         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
30737d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
30747d10d5a6Sdrh       }
30757d10d5a6Sdrh #endif
30767d10d5a6Sdrh     }
307785574e31Sdanielk1977 
307885574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
3079b1c685b0Sdanielk1977     if( sqlite3IndexedByLookup(pParse, pFrom) ){
308085574e31Sdanielk1977       return WRC_Abort;
308185574e31Sdanielk1977     }
30827d10d5a6Sdrh   }
30837d10d5a6Sdrh 
30847d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
30857d10d5a6Sdrh   */
30867d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
30877d10d5a6Sdrh     return WRC_Abort;
30887d10d5a6Sdrh   }
30897d10d5a6Sdrh 
30907d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
30917d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
30927d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
30937d10d5a6Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
30947d10d5a6Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
30957d10d5a6Sdrh   ** each one to the list of all columns in all tables.
30967d10d5a6Sdrh   **
30977d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
30987d10d5a6Sdrh   ** that need expanding.
30997d10d5a6Sdrh   */
31007d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
31017d10d5a6Sdrh     Expr *pE = pEList->a[k].pExpr;
31027d10d5a6Sdrh     if( pE->op==TK_ALL ) break;
310343152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
310443152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
310543152cf8Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
31067d10d5a6Sdrh   }
31077d10d5a6Sdrh   if( k<pEList->nExpr ){
31087d10d5a6Sdrh     /*
31097d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
31107d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
31117d10d5a6Sdrh     ** in the result set and expand them one by one.
31127d10d5a6Sdrh     */
31137d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
31147d10d5a6Sdrh     ExprList *pNew = 0;
31157d10d5a6Sdrh     int flags = pParse->db->flags;
31167d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
31177d10d5a6Sdrh                       && (flags & SQLITE_ShortColNames)==0;
31187d10d5a6Sdrh 
31197d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
31207d10d5a6Sdrh       Expr *pE = a[k].pExpr;
312143152cf8Sdrh       assert( pE->op!=TK_DOT || pE->pRight!=0 );
312243152cf8Sdrh       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
31237d10d5a6Sdrh         /* This particular expression does not need to be expanded.
31247d10d5a6Sdrh         */
3125b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
31267d10d5a6Sdrh         if( pNew ){
31277d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
3128b7916a78Sdrh           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
3129b7916a78Sdrh           a[k].zName = 0;
3130b7916a78Sdrh           a[k].zSpan = 0;
31317d10d5a6Sdrh         }
31327d10d5a6Sdrh         a[k].pExpr = 0;
31337d10d5a6Sdrh       }else{
31347d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
31357d10d5a6Sdrh         ** expanded. */
31367d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
31377d10d5a6Sdrh         char *zTName;            /* text of name of TABLE */
313843152cf8Sdrh         if( pE->op==TK_DOT ){
313943152cf8Sdrh           assert( pE->pLeft!=0 );
314033e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
314133e619fcSdrh           zTName = pE->pLeft->u.zToken;
31427d10d5a6Sdrh         }else{
31437d10d5a6Sdrh           zTName = 0;
31447d10d5a6Sdrh         }
31457d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
31467d10d5a6Sdrh           Table *pTab = pFrom->pTab;
31477d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
314843152cf8Sdrh           if( zTabName==0 ){
31497d10d5a6Sdrh             zTabName = pTab->zName;
31507d10d5a6Sdrh           }
31517d10d5a6Sdrh           if( db->mallocFailed ) break;
31527d10d5a6Sdrh           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
31537d10d5a6Sdrh             continue;
31547d10d5a6Sdrh           }
31557d10d5a6Sdrh           tableSeen = 1;
31567d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
31577d10d5a6Sdrh             Expr *pExpr, *pRight;
31587d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
3159b7916a78Sdrh             char *zColname;  /* The computed column name */
3160b7916a78Sdrh             char *zToFree;   /* Malloced string that needs to be freed */
3161b7916a78Sdrh             Token sColname;  /* Computed column name as a token */
31627d10d5a6Sdrh 
31637d10d5a6Sdrh             /* If a column is marked as 'hidden' (currently only possible
31647d10d5a6Sdrh             ** for virtual tables), do not include it in the expanded
31657d10d5a6Sdrh             ** result-set list.
31667d10d5a6Sdrh             */
31677d10d5a6Sdrh             if( IsHiddenColumn(&pTab->aCol[j]) ){
31687d10d5a6Sdrh               assert(IsVirtual(pTab));
31697d10d5a6Sdrh               continue;
31707d10d5a6Sdrh             }
31717d10d5a6Sdrh 
3172da55c48aSdrh             if( i>0 && zTName==0 ){
31737d10d5a6Sdrh               struct SrcList_item *pLeft = &pTabList->a[i-1];
31747d10d5a6Sdrh               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
31757d10d5a6Sdrh                         columnIndex(pLeft->pTab, zName)>=0 ){
31767d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
31777d10d5a6Sdrh                 ** table on the right */
31787d10d5a6Sdrh                 continue;
31797d10d5a6Sdrh               }
31807d10d5a6Sdrh               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
31817d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
31827d10d5a6Sdrh                 ** using clause from the table on the right. */
31837d10d5a6Sdrh                 continue;
31847d10d5a6Sdrh               }
31857d10d5a6Sdrh             }
3186b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
3187b7916a78Sdrh             zColname = zName;
3188b7916a78Sdrh             zToFree = 0;
31897d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
3190b7916a78Sdrh               Expr *pLeft;
3191b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
31927d10d5a6Sdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
3193b7916a78Sdrh               if( longNames ){
3194b7916a78Sdrh                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
3195b7916a78Sdrh                 zToFree = zColname;
3196b7916a78Sdrh               }
31977d10d5a6Sdrh             }else{
31987d10d5a6Sdrh               pExpr = pRight;
31997d10d5a6Sdrh             }
3200b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
3201b7916a78Sdrh             sColname.z = zColname;
3202b7916a78Sdrh             sColname.n = sqlite3Strlen30(zColname);
3203b7916a78Sdrh             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
3204b7916a78Sdrh             sqlite3DbFree(db, zToFree);
32057d10d5a6Sdrh           }
32067d10d5a6Sdrh         }
32077d10d5a6Sdrh         if( !tableSeen ){
32087d10d5a6Sdrh           if( zTName ){
32097d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
32107d10d5a6Sdrh           }else{
32117d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
32127d10d5a6Sdrh           }
32137d10d5a6Sdrh         }
32147d10d5a6Sdrh       }
32157d10d5a6Sdrh     }
32167d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
32177d10d5a6Sdrh     p->pEList = pNew;
32187d10d5a6Sdrh   }
32197d10d5a6Sdrh #if SQLITE_MAX_COLUMN
32207d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
32217d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
32227d10d5a6Sdrh   }
32237d10d5a6Sdrh #endif
32247d10d5a6Sdrh   return WRC_Continue;
32257d10d5a6Sdrh }
32267d10d5a6Sdrh 
32277d10d5a6Sdrh /*
32287d10d5a6Sdrh ** No-op routine for the parse-tree walker.
32297d10d5a6Sdrh **
32307d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
32317d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
32327d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
32337d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
32347d10d5a6Sdrh ** subquery in the parser tree.
32357d10d5a6Sdrh */
323662c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
323762c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
32387d10d5a6Sdrh   return WRC_Continue;
32397d10d5a6Sdrh }
32407d10d5a6Sdrh 
32417d10d5a6Sdrh /*
32427d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
32437d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
32447d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
32457d10d5a6Sdrh **
32467d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
32477d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
32487d10d5a6Sdrh ** name resolution is performed.
32497d10d5a6Sdrh **
32507d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
32517d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
32527d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
32537d10d5a6Sdrh */
32547d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
32557d10d5a6Sdrh   Walker w;
32567d10d5a6Sdrh   w.xSelectCallback = selectExpander;
32577d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
32587d10d5a6Sdrh   w.pParse = pParse;
32597d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
32607d10d5a6Sdrh }
32617d10d5a6Sdrh 
32627d10d5a6Sdrh 
32637d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
32647d10d5a6Sdrh /*
32657d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
32667d10d5a6Sdrh ** interface.
32677d10d5a6Sdrh **
32687d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
32697d10d5a6Sdrh ** information to the Table structure that represents the result set
32707d10d5a6Sdrh ** of that subquery.
32717d10d5a6Sdrh **
32727d10d5a6Sdrh ** The Table structure that represents the result set was constructed
32737d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
32747d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
32757d10d5a6Sdrh ** routine is called after identifier resolution.
32767d10d5a6Sdrh */
32777d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
32787d10d5a6Sdrh   Parse *pParse;
32797d10d5a6Sdrh   int i;
32807d10d5a6Sdrh   SrcList *pTabList;
32817d10d5a6Sdrh   struct SrcList_item *pFrom;
32827d10d5a6Sdrh 
32839d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
328443152cf8Sdrh   assert( (p->selFlags & SF_HasTypeInfo)==0 );
32857d10d5a6Sdrh   p->selFlags |= SF_HasTypeInfo;
32867d10d5a6Sdrh   pParse = pWalker->pParse;
32877d10d5a6Sdrh   pTabList = p->pSrc;
32887d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
32897d10d5a6Sdrh     Table *pTab = pFrom->pTab;
329043152cf8Sdrh     if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
32917d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
32927d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
32937d10d5a6Sdrh       assert( pSel );
32947d10d5a6Sdrh       while( pSel->pPrior ) pSel = pSel->pPrior;
32957d10d5a6Sdrh       selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
32967d10d5a6Sdrh     }
32977d10d5a6Sdrh   }
32987d10d5a6Sdrh   return WRC_Continue;
32997d10d5a6Sdrh }
33007d10d5a6Sdrh #endif
33017d10d5a6Sdrh 
33027d10d5a6Sdrh 
33037d10d5a6Sdrh /*
33047d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
33057d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
33067d10d5a6Sdrh ** SELECT statement.
33077d10d5a6Sdrh **
33087d10d5a6Sdrh ** Use this routine after name resolution.
33097d10d5a6Sdrh */
33107d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
33117d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
33127d10d5a6Sdrh   Walker w;
33137d10d5a6Sdrh   w.xSelectCallback = selectAddSubqueryTypeInfo;
33147d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
33157d10d5a6Sdrh   w.pParse = pParse;
33167d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
33177d10d5a6Sdrh #endif
33187d10d5a6Sdrh }
33197d10d5a6Sdrh 
33207d10d5a6Sdrh 
33217d10d5a6Sdrh /*
33227d10d5a6Sdrh ** This routine sets of a SELECT statement for processing.  The
33237d10d5a6Sdrh ** following is accomplished:
33247d10d5a6Sdrh **
33257d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
33267d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
33277d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
33287d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
33297d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
33307d10d5a6Sdrh **
33317d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
33327d10d5a6Sdrh */
33337d10d5a6Sdrh void sqlite3SelectPrep(
3334b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
3335b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
33367d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
3337b3bce662Sdanielk1977 ){
33387d10d5a6Sdrh   sqlite3 *db;
333943152cf8Sdrh   if( NEVER(p==0) ) return;
33407d10d5a6Sdrh   db = pParse->db;
33417d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
33427d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
33437d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
33447d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
33457d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
33467d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
3347f6bbe022Sdrh }
3348b3bce662Sdanielk1977 
3349b3bce662Sdanielk1977 /*
335013449892Sdrh ** Reset the aggregate accumulator.
335113449892Sdrh **
335213449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
335313449892Sdrh ** intermediate results while calculating an aggregate.  This
335413449892Sdrh ** routine simply stores NULLs in all of those memory cells.
3355b3bce662Sdanielk1977 */
335613449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
335713449892Sdrh   Vdbe *v = pParse->pVdbe;
335813449892Sdrh   int i;
3359c99130fdSdrh   struct AggInfo_func *pFunc;
336013449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
336113449892Sdrh     return;
336213449892Sdrh   }
336313449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
33644c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
336513449892Sdrh   }
3366c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
33674c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
3368c99130fdSdrh     if( pFunc->iDistinct>=0 ){
3369c99130fdSdrh       Expr *pE = pFunc->pExpr;
33706ab3a2ecSdanielk1977       assert( !ExprHasProperty(pE, EP_xIsSelect) );
33716ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
33720daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
33730daa002cSdrh            "argument");
3374c99130fdSdrh         pFunc->iDistinct = -1;
3375c99130fdSdrh       }else{
33766ab3a2ecSdanielk1977         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
337766a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
337866a5167bSdrh                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3379c99130fdSdrh       }
3380c99130fdSdrh     }
338113449892Sdrh   }
3382b3bce662Sdanielk1977 }
3383b3bce662Sdanielk1977 
3384b3bce662Sdanielk1977 /*
338513449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
338613449892Sdrh ** in the AggInfo structure.
3387b3bce662Sdanielk1977 */
338813449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
338913449892Sdrh   Vdbe *v = pParse->pVdbe;
339013449892Sdrh   int i;
339113449892Sdrh   struct AggInfo_func *pF;
339213449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
33936ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
33946ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
339566a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
339666a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3397b3bce662Sdanielk1977   }
339813449892Sdrh }
339913449892Sdrh 
340013449892Sdrh /*
340113449892Sdrh ** Update the accumulator memory cells for an aggregate based on
340213449892Sdrh ** the current cursor position.
340313449892Sdrh */
340413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
340513449892Sdrh   Vdbe *v = pParse->pVdbe;
340613449892Sdrh   int i;
340713449892Sdrh   struct AggInfo_func *pF;
340813449892Sdrh   struct AggInfo_col *pC;
340913449892Sdrh 
341013449892Sdrh   pAggInfo->directMode = 1;
3411ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
341213449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
341313449892Sdrh     int nArg;
3414c99130fdSdrh     int addrNext = 0;
341598757157Sdrh     int regAgg;
34166ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
34176ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
341813449892Sdrh     if( pList ){
341913449892Sdrh       nArg = pList->nExpr;
3420892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
3421191b54cbSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
342213449892Sdrh     }else{
342313449892Sdrh       nArg = 0;
342498757157Sdrh       regAgg = 0;
342513449892Sdrh     }
3426c99130fdSdrh     if( pF->iDistinct>=0 ){
3427c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
3428c99130fdSdrh       assert( nArg==1 );
34292dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
3430c99130fdSdrh     }
3431e82f5d04Sdrh     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
343213449892Sdrh       CollSeq *pColl = 0;
343313449892Sdrh       struct ExprList_item *pItem;
343413449892Sdrh       int j;
3435e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
343643617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
343713449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
343813449892Sdrh       }
343913449892Sdrh       if( !pColl ){
344013449892Sdrh         pColl = pParse->db->pDfltColl;
344113449892Sdrh       }
344266a5167bSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
344313449892Sdrh     }
344498757157Sdrh     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
344566a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3446ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
3447892d3179Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
3448da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
3449c99130fdSdrh     if( addrNext ){
3450c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
3451ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
3452c99130fdSdrh     }
345313449892Sdrh   }
345413449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
3455389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
345613449892Sdrh   }
345713449892Sdrh   pAggInfo->directMode = 0;
3458ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
345913449892Sdrh }
346013449892Sdrh 
3461b3bce662Sdanielk1977 /*
34627d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
34639bb61fe7Sdrh **
3464fef5208cSdrh ** The results are distributed in various ways depending on the
34656c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest
34666c8c8ce0Sdanielk1977 ** as follows:
3467fef5208cSdrh **
34686c8c8ce0Sdanielk1977 **     pDest->eDest    Result
3469fef5208cSdrh **     ------------    -------------------------------------------
34707d10d5a6Sdrh **     SRT_Output      Generate a row of output (using the OP_ResultRow
34717d10d5a6Sdrh **                     opcode) for each row in the result set.
3472fef5208cSdrh **
34737d10d5a6Sdrh **     SRT_Mem         Only valid if the result is a single column.
34747d10d5a6Sdrh **                     Store the first column of the first result row
34757d10d5a6Sdrh **                     in register pDest->iParm then abandon the rest
34767d10d5a6Sdrh **                     of the query.  This destination implies "LIMIT 1".
3477fef5208cSdrh **
34787d10d5a6Sdrh **     SRT_Set         The result must be a single column.  Store each
34797d10d5a6Sdrh **                     row of result as the key in table pDest->iParm.
34807d10d5a6Sdrh **                     Apply the affinity pDest->affinity before storing
34817d10d5a6Sdrh **                     results.  Used to implement "IN (SELECT ...)".
3482fef5208cSdrh **
34836c8c8ce0Sdanielk1977 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
348482c3d636Sdrh **
34856c8c8ce0Sdanielk1977 **     SRT_Except      Remove results from the temporary table pDest->iParm.
3486c4a3c779Sdrh **
34877d10d5a6Sdrh **     SRT_Table       Store results in temporary table pDest->iParm.
34887d10d5a6Sdrh **                     This is like SRT_EphemTab except that the table
34897d10d5a6Sdrh **                     is assumed to already be open.
34909bb61fe7Sdrh **
34916c8c8ce0Sdanielk1977 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
34926c8c8ce0Sdanielk1977 **                     the result there. The cursor is left open after
34937d10d5a6Sdrh **                     returning.  This is like SRT_Table except that
34947d10d5a6Sdrh **                     this destination uses OP_OpenEphemeral to create
34957d10d5a6Sdrh **                     the table first.
34966c8c8ce0Sdanielk1977 **
34977d10d5a6Sdrh **     SRT_Coroutine   Generate a co-routine that returns a new row of
34987d10d5a6Sdrh **                     results each time it is invoked.  The entry point
34997d10d5a6Sdrh **                     of the co-routine is stored in register pDest->iParm.
35006c8c8ce0Sdanielk1977 **
35016c8c8ce0Sdanielk1977 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
35026c8c8ce0Sdanielk1977 **                     set is not empty.
35036c8c8ce0Sdanielk1977 **
35047d10d5a6Sdrh **     SRT_Discard     Throw the results away.  This is used by SELECT
35057d10d5a6Sdrh **                     statements within triggers whose only purpose is
35067d10d5a6Sdrh **                     the side-effects of functions.
3507e78e8284Sdrh **
35089bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
35099bb61fe7Sdrh ** encountered, then an appropriate error message is left in
35109bb61fe7Sdrh ** pParse->zErrMsg.
35119bb61fe7Sdrh **
35129bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
35139bb61fe7Sdrh ** calling function needs to do that.
35149bb61fe7Sdrh */
35154adee20fSdanielk1977 int sqlite3Select(
3516cce7d176Sdrh   Parse *pParse,         /* The parser context */
35179bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
35187d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
3519cce7d176Sdrh ){
352013449892Sdrh   int i, j;              /* Loop counters */
352113449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
352213449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3523b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3524a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3525ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
35269bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
35279bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
35282282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
35292282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
353019a775c2Sdrh   int isDistinct;        /* True if the DISTINCT keyword is present */
353119a775c2Sdrh   int distinct;          /* Table to use for the distinct set */
35321d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3533b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
353413449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3535ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
353617435752Sdrh   sqlite3 *db;           /* The database connection */
35379bb61fe7Sdrh 
353817435752Sdrh   db = pParse->db;
353917435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
35406f7adc8aSdrh     return 1;
35416f7adc8aSdrh   }
35424adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
354313449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3544daffd0e5Sdrh 
35456c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
35469ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
35479ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
3548ccfcbceaSdrh     /* If ORDER BY makes no difference in the output then neither does
3549ccfcbceaSdrh     ** DISTINCT so it can be removed too. */
3550ccfcbceaSdrh     sqlite3ExprListDelete(db, p->pOrderBy);
3551ccfcbceaSdrh     p->pOrderBy = 0;
35527d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
35539a99334dSdrh   }
35547d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
3555ccfcbceaSdrh   pOrderBy = p->pOrderBy;
3556b27b7f5dSdrh   pTabList = p->pSrc;
3557b27b7f5dSdrh   pEList = p->pEList;
3558956f4319Sdanielk1977   if( pParse->nErr || db->mallocFailed ){
35599a99334dSdrh     goto select_end;
35609a99334dSdrh   }
35617d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
356243152cf8Sdrh   assert( pEList!=0 );
3563cce7d176Sdrh 
3564d820cb1bSdrh   /* Begin generating code.
3565d820cb1bSdrh   */
35664adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3567d820cb1bSdrh   if( v==0 ) goto select_end;
3568d820cb1bSdrh 
3569d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3570d820cb1bSdrh   */
357151522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3572f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
357313449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
35741013c932Sdrh     SelectDest dest;
3575daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
3576f23329a2Sdanielk1977     int isAggSub;
3577c31c2eb8Sdrh 
3578daf79acbSdanielk1977     if( pSub==0 || pItem->isPopulated ) continue;
3579daf79acbSdanielk1977 
3580fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3581fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3582fc976065Sdanielk1977     ** may contain expression trees of at most
3583fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3584fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3585fc976065Sdanielk1977     ** an exact limit.
3586fc976065Sdanielk1977     */
3587fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
3588daf79acbSdanielk1977 
3589daf79acbSdanielk1977     /* Check to see if the subquery can be absorbed into the parent. */
35907d10d5a6Sdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
3591524cc21eSdanielk1977     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
3592f23329a2Sdanielk1977       if( isAggSub ){
35937d10d5a6Sdrh         isAgg = 1;
35947d10d5a6Sdrh         p->selFlags |= SF_Aggregate;
3595daf79acbSdanielk1977       }
3596daf79acbSdanielk1977       i = -1;
3597daf79acbSdanielk1977     }else{
35981013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
35997d10d5a6Sdrh       assert( pItem->isPopulated==0 );
36007d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
36017d10d5a6Sdrh       pItem->isPopulated = 1;
3602daf79acbSdanielk1977     }
360343152cf8Sdrh     if( /*pParse->nErr ||*/ db->mallocFailed ){
3604cfa063b3Sdrh       goto select_end;
3605cfa063b3Sdrh     }
3606fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
3607832508b7Sdrh     pTabList = p->pSrc;
36086c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
3609832508b7Sdrh       pOrderBy = p->pOrderBy;
3610acd4c695Sdrh     }
3611daf79acbSdanielk1977   }
3612daf79acbSdanielk1977   pEList = p->pEList;
3613daf79acbSdanielk1977 #endif
3614daf79acbSdanielk1977   pWhere = p->pWhere;
3615832508b7Sdrh   pGroupBy = p->pGroupBy;
3616832508b7Sdrh   pHaving = p->pHaving;
36177d10d5a6Sdrh   isDistinct = (p->selFlags & SF_Distinct)!=0;
3618832508b7Sdrh 
3619f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
3620f23329a2Sdanielk1977   /* If there is are a sequence of queries, do the earlier ones first.
3621f23329a2Sdanielk1977   */
3622f23329a2Sdanielk1977   if( p->pPrior ){
3623f23329a2Sdanielk1977     if( p->pRightmost==0 ){
3624f23329a2Sdanielk1977       Select *pLoop, *pRight = 0;
3625f23329a2Sdanielk1977       int cnt = 0;
3626f23329a2Sdanielk1977       int mxSelect;
3627f23329a2Sdanielk1977       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
3628f23329a2Sdanielk1977         pLoop->pRightmost = p;
3629f23329a2Sdanielk1977         pLoop->pNext = pRight;
3630f23329a2Sdanielk1977         pRight = pLoop;
3631f23329a2Sdanielk1977       }
3632f23329a2Sdanielk1977       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
3633f23329a2Sdanielk1977       if( mxSelect && cnt>mxSelect ){
3634f23329a2Sdanielk1977         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
3635f23329a2Sdanielk1977         return 1;
3636f23329a2Sdanielk1977       }
3637f23329a2Sdanielk1977     }
3638a9671a22Sdrh     return multiSelect(pParse, p, pDest);
3639f23329a2Sdanielk1977   }
3640f23329a2Sdanielk1977 #endif
3641f23329a2Sdanielk1977 
36424914cf92Sdanielk1977   /* If writing to memory or generating a set
36434914cf92Sdanielk1977   ** only a single column may be output.
36444914cf92Sdanielk1977   */
36454914cf92Sdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
36464914cf92Sdanielk1977   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
36474914cf92Sdanielk1977     goto select_end;
36484914cf92Sdanielk1977   }
36494914cf92Sdanielk1977 #endif
36504914cf92Sdanielk1977 
36510318d441Sdanielk1977   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
36527d10d5a6Sdrh   ** GROUP BY might use an index, DISTINCT never does.
36533c4809a2Sdanielk1977   */
365443152cf8Sdrh   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
365543152cf8Sdrh   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
36566ab3a2ecSdanielk1977     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
36573c4809a2Sdanielk1977     pGroupBy = p->pGroupBy;
36587d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
36593c4809a2Sdanielk1977     isDistinct = 0;
36603c4809a2Sdanielk1977   }
36613c4809a2Sdanielk1977 
36628b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
36638b4c40d8Sdrh   ** index might end up being unused if the data can be
36649d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
3665b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
36669d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
36679d2985c7Sdrh   ** variable is used to facilitate that change.
36687cedc8d4Sdanielk1977   */
36697cedc8d4Sdanielk1977   if( pOrderBy ){
36700342b1f5Sdrh     KeyInfo *pKeyInfo;
36710342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
36729d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
3673b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
367466a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
367566a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
367666a5167bSdrh                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
36779d2985c7Sdrh   }else{
36789d2985c7Sdrh     addrSortIndex = -1;
36797cedc8d4Sdanielk1977   }
36807cedc8d4Sdanielk1977 
36812d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
36822d0794e3Sdrh   */
36836c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
368466a5167bSdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
36852d0794e3Sdrh   }
36862d0794e3Sdrh 
3687f42bacc2Sdrh   /* Set the limiter.
3688f42bacc2Sdrh   */
3689f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
3690f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
3691f42bacc2Sdrh 
3692dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
3693cce7d176Sdrh   */
369419a775c2Sdrh   if( isDistinct ){
36950342b1f5Sdrh     KeyInfo *pKeyInfo;
36963c4809a2Sdanielk1977     assert( isAgg || pGroupBy );
3697832508b7Sdrh     distinct = pParse->nTab++;
36980342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
369966a5167bSdrh     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
370066a5167bSdrh                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3701832508b7Sdrh   }else{
3702832508b7Sdrh     distinct = -1;
3703efb7251dSdrh   }
3704832508b7Sdrh 
370513449892Sdrh   /* Aggregate and non-aggregate queries are handled differently */
370613449892Sdrh   if( !isAgg && pGroupBy==0 ){
370713449892Sdrh     /* This case is for non-aggregate queries
370813449892Sdrh     ** Begin the database scan
3709832508b7Sdrh     */
3710336a5300Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
37111d83f052Sdrh     if( pWInfo==0 ) goto select_end;
3712cce7d176Sdrh 
3713b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
3714b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
37159d2985c7Sdrh     ** into an OP_Noop.
37169d2985c7Sdrh     */
37179d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
3718f8875400Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
3719b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
37209d2985c7Sdrh     }
37219d2985c7Sdrh 
372213449892Sdrh     /* Use the standard inner loop
3723cce7d176Sdrh     */
37243c4809a2Sdanielk1977     assert(!isDistinct);
3725d2b3e23bSdrh     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
3726a9671a22Sdrh                     pWInfo->iContinue, pWInfo->iBreak);
37272282792aSdrh 
3728cce7d176Sdrh     /* End the database scan loop.
3729cce7d176Sdrh     */
37304adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
373113449892Sdrh   }else{
373213449892Sdrh     /* This is the processing for aggregate queries */
373313449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
373413449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
373513449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
373613449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
373713449892Sdrh                         ** one row of the input to the aggregator has been
373813449892Sdrh                         ** processed */
373913449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
374013449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
3741d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
3742d176611bSdrh 
3743d176611bSdrh     /* Remove any and all aliases between the result set and the
3744d176611bSdrh     ** GROUP BY clause.
3745d176611bSdrh     */
3746d176611bSdrh     if( pGroupBy ){
3747dc5ea5c7Sdrh       int k;                        /* Loop counter */
3748d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
3749d176611bSdrh 
3750dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
3751d176611bSdrh         pItem->iAlias = 0;
3752d176611bSdrh       }
3753dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
3754d176611bSdrh         pItem->iAlias = 0;
3755d176611bSdrh       }
3756d176611bSdrh     }
3757cce7d176Sdrh 
375813449892Sdrh 
3759d176611bSdrh     /* Create a label to jump to when we want to abort the query */
376013449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
376113449892Sdrh 
376213449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
376313449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
376413449892Sdrh     ** SELECT statement.
37652282792aSdrh     */
376613449892Sdrh     memset(&sNC, 0, sizeof(sNC));
376713449892Sdrh     sNC.pParse = pParse;
376813449892Sdrh     sNC.pSrcList = pTabList;
376913449892Sdrh     sNC.pAggInfo = &sAggInfo;
377013449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
37719d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
3772d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
3773d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
3774d2b3e23bSdrh     if( pHaving ){
3775d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
377613449892Sdrh     }
377713449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
377813449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
37796ab3a2ecSdanielk1977       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
37806ab3a2ecSdanielk1977       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
378113449892Sdrh     }
378217435752Sdrh     if( db->mallocFailed ) goto select_end;
378313449892Sdrh 
378413449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
37853c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
378613449892Sdrh     */
378713449892Sdrh     if( pGroupBy ){
378813449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
3789d176611bSdrh       int j1;             /* A-vs-B comparision jump */
3790d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
3791d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
3792d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
3793d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
3794d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
3795d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
3796d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
379713449892Sdrh 
379813449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
379913449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
3800b9bb7c18Sdrh       ** that we do not need it after all, the OpenEphemeral instruction
380113449892Sdrh       ** will be converted into a Noop.
380213449892Sdrh       */
380313449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
380413449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
3805cd3e8f7cSdanielk1977       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
3806cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
3807cd3e8f7cSdanielk1977           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
380813449892Sdrh 
380913449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
381013449892Sdrh       */
38110a07c107Sdrh       iUseFlag = ++pParse->nMem;
38120a07c107Sdrh       iAbortFlag = ++pParse->nMem;
3813d176611bSdrh       regOutputRow = ++pParse->nMem;
3814d176611bSdrh       addrOutputRow = sqlite3VdbeMakeLabel(v);
3815d176611bSdrh       regReset = ++pParse->nMem;
3816d176611bSdrh       addrReset = sqlite3VdbeMakeLabel(v);
38170a07c107Sdrh       iAMem = pParse->nMem + 1;
381813449892Sdrh       pParse->nMem += pGroupBy->nExpr;
38190a07c107Sdrh       iBMem = pParse->nMem + 1;
382013449892Sdrh       pParse->nMem += pGroupBy->nExpr;
38214c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
3822d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
38234c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
3824d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
3825e313382eSdrh 
382613449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
382713449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
382813449892Sdrh       ** it might be a single loop that uses an index to extract information
382913449892Sdrh       ** in the right order to begin with.
383013449892Sdrh       */
38312eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3832336a5300Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
38335360ad34Sdrh       if( pWInfo==0 ) goto select_end;
383413449892Sdrh       if( pGroupBy==0 ){
383513449892Sdrh         /* The optimizer is able to deliver rows in group by order so
3836b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
383713449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
383813449892Sdrh         */
383913449892Sdrh         pGroupBy = p->pGroupBy;
384013449892Sdrh         groupBySort = 0;
384113449892Sdrh       }else{
384213449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
384313449892Sdrh         ** each row into a sorting index, terminate the first loop,
384413449892Sdrh         ** then loop over the sorting index in order to get the output
384513449892Sdrh         ** in sorted order
384613449892Sdrh         */
3847892d3179Sdrh         int regBase;
3848892d3179Sdrh         int regRecord;
3849892d3179Sdrh         int nCol;
3850892d3179Sdrh         int nGroupBy;
3851892d3179Sdrh 
385213449892Sdrh         groupBySort = 1;
3853892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
3854892d3179Sdrh         nCol = nGroupBy + 1;
3855892d3179Sdrh         j = nGroupBy+1;
385613449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3857892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
3858892d3179Sdrh             nCol++;
385913449892Sdrh             j++;
386013449892Sdrh           }
3861892d3179Sdrh         }
3862892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
3863ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
3864191b54cbSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
3865892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
3866892d3179Sdrh         j = nGroupBy+1;
3867892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
3868892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
3869892d3179Sdrh           if( pCol->iSorterColumn>=j ){
3870e55cbd72Sdrh             int r1 = j + regBase;
38716a012f04Sdrh             int r2;
3872701bb3b4Sdrh 
38736a012f04Sdrh             r2 = sqlite3ExprCodeGetColumn(pParse,
38746a012f04Sdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
38756a012f04Sdrh             if( r1!=r2 ){
38766a012f04Sdrh               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
38776a012f04Sdrh             }
38786a012f04Sdrh             j++;
3879892d3179Sdrh           }
3880892d3179Sdrh         }
3881892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
38821db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
3883892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
3884892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
3885892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
388613449892Sdrh         sqlite3WhereEnd(pWInfo);
388766a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
3888d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
388913449892Sdrh         sAggInfo.useSortingIdx = 1;
3890ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
389113449892Sdrh       }
389213449892Sdrh 
389313449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
389413449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
389513449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
389613449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
389713449892Sdrh       */
389813449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
3899ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
390013449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
390113449892Sdrh         if( groupBySort ){
39022dcef11bSdrh           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
390313449892Sdrh         }else{
390413449892Sdrh           sAggInfo.directMode = 1;
39052dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
390613449892Sdrh         }
390713449892Sdrh       }
390816ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
3909b21e7c70Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
391016ee60ffSdrh       j1 = sqlite3VdbeCurrentAddr(v);
391116ee60ffSdrh       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
391213449892Sdrh 
391313449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
3914e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
391513449892Sdrh       ** block.  If there were no changes, this block is skipped.
391613449892Sdrh       **
391713449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
391813449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
391913449892Sdrh       ** and resets the aggregate accumulator registers in preparation
392013449892Sdrh       ** for the next GROUP BY batch.
392113449892Sdrh       */
3922b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
39232eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3924d4e70ebdSdrh       VdbeComment((v, "output one row"));
39253c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
3926d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
39272eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
3928d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
392913449892Sdrh 
393013449892Sdrh       /* Update the aggregate accumulators based on the content of
393113449892Sdrh       ** the current row
393213449892Sdrh       */
393316ee60ffSdrh       sqlite3VdbeJumpHere(v, j1);
393413449892Sdrh       updateAccumulator(pParse, &sAggInfo);
39354c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
3936d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
393713449892Sdrh 
393813449892Sdrh       /* End of the loop
393913449892Sdrh       */
394013449892Sdrh       if( groupBySort ){
394166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
394213449892Sdrh       }else{
394313449892Sdrh         sqlite3WhereEnd(pWInfo);
3944f8875400Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
394513449892Sdrh       }
394613449892Sdrh 
394713449892Sdrh       /* Output the final row of result
394813449892Sdrh       */
39492eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
3950d4e70ebdSdrh       VdbeComment((v, "output final row"));
395113449892Sdrh 
3952d176611bSdrh       /* Jump over the subroutines
3953d176611bSdrh       */
3954d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
3955d176611bSdrh 
3956d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
3957d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
3958d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
3959d176611bSdrh       ** the processing calls for the query to abort, this subroutine
3960d176611bSdrh       ** increments the iAbortFlag memory location before returning in
3961d176611bSdrh       ** order to signal the caller to abort.
3962d176611bSdrh       */
3963d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
3964d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
3965d176611bSdrh       VdbeComment((v, "set abort flag"));
3966d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3967d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
3968d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
3969d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
3970d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
3971d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3972d176611bSdrh       finalizeAggFunctions(pParse, &sAggInfo);
3973d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
3974d176611bSdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
3975d176611bSdrh                       distinct, pDest,
3976d176611bSdrh                       addrOutputRow+1, addrSetAbort);
3977d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
3978d176611bSdrh       VdbeComment((v, "end groupby result generator"));
3979d176611bSdrh 
3980d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
3981d176611bSdrh       */
3982d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
3983d176611bSdrh       resetAccumulator(pParse, &sAggInfo);
3984d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
3985d176611bSdrh 
398643152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
398713449892Sdrh     else {
3988dba0137eSdanielk1977       ExprList *pDel = 0;
3989a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT
3990a5533162Sdanielk1977       Table *pTab;
3991a5533162Sdanielk1977       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
3992a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
3993a5533162Sdanielk1977         ** the SQL statement is of the form:
3994a5533162Sdanielk1977         **
3995a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
3996a5533162Sdanielk1977         **
3997a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
3998a5533162Sdanielk1977         **
3999a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
4000a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
4001a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
4002a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
4003a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
4004a5533162Sdanielk1977         */
4005a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4006a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
4007a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
4008a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
4009a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
4010a5533162Sdanielk1977         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
4011a9d1ccb9Sdanielk1977 
4012a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
4013a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
4014a5533162Sdanielk1977 
4015a5533162Sdanielk1977         /* Search for the index that has the least amount of columns. If
4016a5533162Sdanielk1977         ** there is such an index, and it has less columns than the table
4017a5533162Sdanielk1977         ** does, then we can assume that it consumes less space on disk and
4018a5533162Sdanielk1977         ** will therefore be cheaper to scan to determine the query result.
4019a5533162Sdanielk1977         ** In this case set iRoot to the root page number of the index b-tree
4020a5533162Sdanielk1977         ** and pKeyInfo to the KeyInfo structure required to navigate the
4021a5533162Sdanielk1977         ** index.
4022a5533162Sdanielk1977         **
4023a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
4024a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
4025a5533162Sdanielk1977         */
4026a5533162Sdanielk1977         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
4027a5533162Sdanielk1977           if( !pBest || pIdx->nColumn<pBest->nColumn ){
4028a5533162Sdanielk1977             pBest = pIdx;
4029a5533162Sdanielk1977           }
4030a5533162Sdanielk1977         }
4031a5533162Sdanielk1977         if( pBest && pBest->nColumn<pTab->nCol ){
4032a5533162Sdanielk1977           iRoot = pBest->tnum;
4033a5533162Sdanielk1977           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
4034a5533162Sdanielk1977         }
4035a5533162Sdanielk1977 
4036a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
4037a5533162Sdanielk1977         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
4038a5533162Sdanielk1977         if( pKeyInfo ){
4039a5533162Sdanielk1977           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
4040a5533162Sdanielk1977         }
4041a5533162Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
4042a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
4043a5533162Sdanielk1977       }else
4044a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */
4045a5533162Sdanielk1977       {
4046738bdcfbSdanielk1977         /* Check if the query is of one of the following forms:
4047738bdcfbSdanielk1977         **
4048738bdcfbSdanielk1977         **   SELECT min(x) FROM ...
4049738bdcfbSdanielk1977         **   SELECT max(x) FROM ...
4050738bdcfbSdanielk1977         **
4051738bdcfbSdanielk1977         ** If it is, then ask the code in where.c to attempt to sort results
4052738bdcfbSdanielk1977         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
4053738bdcfbSdanielk1977         ** If where.c is able to produce results sorted in this order, then
4054738bdcfbSdanielk1977         ** add vdbe code to break out of the processing loop after the
4055738bdcfbSdanielk1977         ** first iteration (since the first iteration of the loop is
4056738bdcfbSdanielk1977         ** guaranteed to operate on the row with the minimum or maximum
4057738bdcfbSdanielk1977         ** value of x, the only row required).
4058738bdcfbSdanielk1977         **
4059738bdcfbSdanielk1977         ** A special flag must be passed to sqlite3WhereBegin() to slightly
4060738bdcfbSdanielk1977         ** modify behaviour as follows:
4061738bdcfbSdanielk1977         **
4062738bdcfbSdanielk1977         **   + If the query is a "SELECT min(x)", then the loop coded by
4063738bdcfbSdanielk1977         **     where.c should not iterate over any values with a NULL value
4064738bdcfbSdanielk1977         **     for x.
4065738bdcfbSdanielk1977         **
4066738bdcfbSdanielk1977         **   + The optimizer code in where.c (the thing that decides which
4067738bdcfbSdanielk1977         **     index or indices to use) should place a different priority on
4068738bdcfbSdanielk1977         **     satisfying the 'ORDER BY' clause than it does in other cases.
4069738bdcfbSdanielk1977         **     Refer to code and comments in where.c for details.
4070738bdcfbSdanielk1977         */
4071a5533162Sdanielk1977         ExprList *pMinMax = 0;
4072a5533162Sdanielk1977         u8 flag = minMaxQuery(p);
4073a9d1ccb9Sdanielk1977         if( flag ){
40746ab3a2ecSdanielk1977           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
40756ab3a2ecSdanielk1977           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
40766ab3a2ecSdanielk1977           pDel = pMinMax;
40770e359b30Sdrh           if( pMinMax && !db->mallocFailed ){
4078ea678832Sdrh             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
4079a9d1ccb9Sdanielk1977             pMinMax->a[0].pExpr->op = TK_COLUMN;
4080a9d1ccb9Sdanielk1977           }
40811013c932Sdrh         }
4082a9d1ccb9Sdanielk1977 
408313449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
408413449892Sdrh         ** processing is much simpler since there is only a single row
408513449892Sdrh         ** of output.
408613449892Sdrh         */
408713449892Sdrh         resetAccumulator(pParse, &sAggInfo);
4088336a5300Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
4089dba0137eSdanielk1977         if( pWInfo==0 ){
4090633e6d57Sdrh           sqlite3ExprListDelete(db, pDel);
4091dba0137eSdanielk1977           goto select_end;
4092dba0137eSdanielk1977         }
409313449892Sdrh         updateAccumulator(pParse, &sAggInfo);
4094a9d1ccb9Sdanielk1977         if( !pMinMax && flag ){
4095a9d1ccb9Sdanielk1977           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
4096a5533162Sdanielk1977           VdbeComment((v, "%s() by index",
4097a5533162Sdanielk1977                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
4098a9d1ccb9Sdanielk1977         }
409913449892Sdrh         sqlite3WhereEnd(pWInfo);
410013449892Sdrh         finalizeAggFunctions(pParse, &sAggInfo);
41017a895a80Sdanielk1977       }
41027a895a80Sdanielk1977 
410313449892Sdrh       pOrderBy = 0;
410435573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
410513449892Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
4106a9671a22Sdrh                       pDest, addrEnd, addrEnd);
4107633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
410813449892Sdrh     }
410913449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
411013449892Sdrh 
411113449892Sdrh   } /* endif aggregate query */
41122282792aSdrh 
4113cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
4114cce7d176Sdrh   ** and send them to the callback one by one.
4115cce7d176Sdrh   */
4116cce7d176Sdrh   if( pOrderBy ){
41176c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
4118cce7d176Sdrh   }
41196a535340Sdrh 
4120ec7429aeSdrh   /* Jump here to skip this query
4121ec7429aeSdrh   */
4122ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
4123ec7429aeSdrh 
41241d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
41251d83f052Sdrh   ** to indicate no errors.
41261d83f052Sdrh   */
41271d83f052Sdrh   rc = 0;
41281d83f052Sdrh 
41291d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
41301d83f052Sdrh   ** successful coding of the SELECT.
41311d83f052Sdrh   */
41321d83f052Sdrh select_end:
4133955de52cSdanielk1977 
41347d10d5a6Sdrh   /* Identify column names if results of the SELECT are to be output.
4135955de52cSdanielk1977   */
41367d10d5a6Sdrh   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
4137955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
4138955de52cSdanielk1977   }
4139955de52cSdanielk1977 
4140633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
4141633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
41421d83f052Sdrh   return rc;
4143cce7d176Sdrh }
4144485f0039Sdrh 
414577a2a5e7Sdrh #if defined(SQLITE_DEBUG)
4146485f0039Sdrh /*
4147485f0039Sdrh *******************************************************************************
4148485f0039Sdrh ** The following code is used for testing and debugging only.  The code
4149485f0039Sdrh ** that follows does not appear in normal builds.
4150485f0039Sdrh **
4151485f0039Sdrh ** These routines are used to print out the content of all or part of a
4152485f0039Sdrh ** parse structures such as Select or Expr.  Such printouts are useful
4153485f0039Sdrh ** for helping to understand what is happening inside the code generator
4154485f0039Sdrh ** during the execution of complex SELECT statements.
4155485f0039Sdrh **
4156485f0039Sdrh ** These routine are not called anywhere from within the normal
4157485f0039Sdrh ** code base.  Then are intended to be called from within the debugger
4158485f0039Sdrh ** or from temporary "printf" statements inserted for debugging.
4159485f0039Sdrh */
4160dafc0ce8Sdrh void sqlite3PrintExpr(Expr *p){
416133e619fcSdrh   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
416233e619fcSdrh     sqlite3DebugPrintf("(%s", p->u.zToken);
4163485f0039Sdrh   }else{
4164485f0039Sdrh     sqlite3DebugPrintf("(%d", p->op);
4165485f0039Sdrh   }
4166485f0039Sdrh   if( p->pLeft ){
4167485f0039Sdrh     sqlite3DebugPrintf(" ");
4168485f0039Sdrh     sqlite3PrintExpr(p->pLeft);
4169485f0039Sdrh   }
4170485f0039Sdrh   if( p->pRight ){
4171485f0039Sdrh     sqlite3DebugPrintf(" ");
4172485f0039Sdrh     sqlite3PrintExpr(p->pRight);
4173485f0039Sdrh   }
4174485f0039Sdrh   sqlite3DebugPrintf(")");
4175485f0039Sdrh }
4176dafc0ce8Sdrh void sqlite3PrintExprList(ExprList *pList){
4177485f0039Sdrh   int i;
4178485f0039Sdrh   for(i=0; i<pList->nExpr; i++){
4179485f0039Sdrh     sqlite3PrintExpr(pList->a[i].pExpr);
4180485f0039Sdrh     if( i<pList->nExpr-1 ){
4181485f0039Sdrh       sqlite3DebugPrintf(", ");
4182485f0039Sdrh     }
4183485f0039Sdrh   }
4184485f0039Sdrh }
4185dafc0ce8Sdrh void sqlite3PrintSelect(Select *p, int indent){
4186485f0039Sdrh   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
4187485f0039Sdrh   sqlite3PrintExprList(p->pEList);
4188485f0039Sdrh   sqlite3DebugPrintf("\n");
4189485f0039Sdrh   if( p->pSrc ){
4190485f0039Sdrh     char *zPrefix;
4191485f0039Sdrh     int i;
4192485f0039Sdrh     zPrefix = "FROM";
4193485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
4194485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
4195485f0039Sdrh       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
4196485f0039Sdrh       zPrefix = "";
4197485f0039Sdrh       if( pItem->pSelect ){
4198485f0039Sdrh         sqlite3DebugPrintf("(\n");
4199485f0039Sdrh         sqlite3PrintSelect(pItem->pSelect, indent+10);
4200485f0039Sdrh         sqlite3DebugPrintf("%*s)", indent+8, "");
4201485f0039Sdrh       }else if( pItem->zName ){
4202485f0039Sdrh         sqlite3DebugPrintf("%s", pItem->zName);
4203485f0039Sdrh       }
4204485f0039Sdrh       if( pItem->pTab ){
4205485f0039Sdrh         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
4206485f0039Sdrh       }
4207485f0039Sdrh       if( pItem->zAlias ){
4208485f0039Sdrh         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
4209485f0039Sdrh       }
4210485f0039Sdrh       if( i<p->pSrc->nSrc-1 ){
4211485f0039Sdrh         sqlite3DebugPrintf(",");
4212485f0039Sdrh       }
4213485f0039Sdrh       sqlite3DebugPrintf("\n");
4214485f0039Sdrh     }
4215485f0039Sdrh   }
4216485f0039Sdrh   if( p->pWhere ){
4217485f0039Sdrh     sqlite3DebugPrintf("%*s WHERE ", indent, "");
4218485f0039Sdrh     sqlite3PrintExpr(p->pWhere);
4219485f0039Sdrh     sqlite3DebugPrintf("\n");
4220485f0039Sdrh   }
4221485f0039Sdrh   if( p->pGroupBy ){
4222485f0039Sdrh     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
4223485f0039Sdrh     sqlite3PrintExprList(p->pGroupBy);
4224485f0039Sdrh     sqlite3DebugPrintf("\n");
4225485f0039Sdrh   }
4226485f0039Sdrh   if( p->pHaving ){
4227485f0039Sdrh     sqlite3DebugPrintf("%*s HAVING ", indent, "");
4228485f0039Sdrh     sqlite3PrintExpr(p->pHaving);
4229485f0039Sdrh     sqlite3DebugPrintf("\n");
4230485f0039Sdrh   }
4231485f0039Sdrh   if( p->pOrderBy ){
4232485f0039Sdrh     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
4233485f0039Sdrh     sqlite3PrintExprList(p->pOrderBy);
4234485f0039Sdrh     sqlite3DebugPrintf("\n");
4235485f0039Sdrh   }
4236485f0039Sdrh }
4237485f0039Sdrh /* End of the structure debug printing code
4238485f0039Sdrh *****************************************************************************/
4239485f0039Sdrh #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
4240