xref: /sqlite-3.40.0/src/select.c (revision aa87f9a6)
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;
392b596da8Sdrh   pDest->iSDParm = iParm;
402b596da8Sdrh   pDest->affSdst = 0;
412b596da8Sdrh   pDest->iSdst = 0;
422b596da8Sdrh   pDest->nSdst = 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 */
58832ee3d4Sdrh   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
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 ){
68338ec3e1Sdrh     assert( db->mallocFailed );
69eda639e1Sdrh     pNew = &standin;
70eda639e1Sdrh     memset(pNew, 0, sizeof(*pNew));
71eda639e1Sdrh   }
72b733d037Sdrh   if( pEList==0 ){
73b7916a78Sdrh     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
74b733d037Sdrh   }
759bb61fe7Sdrh   pNew->pEList = pEList;
767b113babSdrh   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
779bb61fe7Sdrh   pNew->pSrc = pSrc;
789bb61fe7Sdrh   pNew->pWhere = pWhere;
799bb61fe7Sdrh   pNew->pGroupBy = pGroupBy;
809bb61fe7Sdrh   pNew->pHaving = pHaving;
819bb61fe7Sdrh   pNew->pOrderBy = pOrderBy;
82832ee3d4Sdrh   pNew->selFlags = selFlags;
8382c3d636Sdrh   pNew->op = TK_SELECT;
84a2dc3b1aSdanielk1977   pNew->pLimit = pLimit;
85a2dc3b1aSdanielk1977   pNew->pOffset = pOffset;
86373cc2ddSdrh   assert( pOffset==0 || pLimit!=0 );
87b9bb7c18Sdrh   pNew->addrOpenEphm[0] = -1;
88b9bb7c18Sdrh   pNew->addrOpenEphm[1] = -1;
89b9bb7c18Sdrh   pNew->addrOpenEphm[2] = -1;
900a846f96Sdrh   if( db->mallocFailed ) {
91633e6d57Sdrh     clearSelect(db, pNew);
920a846f96Sdrh     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
93eda639e1Sdrh     pNew = 0;
94a464c234Sdrh   }else{
95a464c234Sdrh     assert( pNew->pSrc!=0 || pParse->nErr>0 );
96daffd0e5Sdrh   }
97338ec3e1Sdrh   assert( pNew!=&standin );
989bb61fe7Sdrh   return pNew;
999bb61fe7Sdrh }
1009bb61fe7Sdrh 
1019bb61fe7Sdrh /*
102eda639e1Sdrh ** Delete the given Select structure and all of its substructures.
103eda639e1Sdrh */
104633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){
105eda639e1Sdrh   if( p ){
106633e6d57Sdrh     clearSelect(db, p);
107633e6d57Sdrh     sqlite3DbFree(db, p);
108eda639e1Sdrh   }
109eda639e1Sdrh }
110eda639e1Sdrh 
111eda639e1Sdrh /*
11201f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
11301f3f253Sdrh ** type of join.  Return an integer constant that expresses that type
11401f3f253Sdrh ** in terms of the following bit values:
11501f3f253Sdrh **
11601f3f253Sdrh **     JT_INNER
1173dec223cSdrh **     JT_CROSS
11801f3f253Sdrh **     JT_OUTER
11901f3f253Sdrh **     JT_NATURAL
12001f3f253Sdrh **     JT_LEFT
12101f3f253Sdrh **     JT_RIGHT
12201f3f253Sdrh **
12301f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
12401f3f253Sdrh **
12501f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return
12601f3f253Sdrh ** a join type, but put an error in the pParse structure.
12701f3f253Sdrh */
1284adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
12901f3f253Sdrh   int jointype = 0;
13001f3f253Sdrh   Token *apAll[3];
13101f3f253Sdrh   Token *p;
132373cc2ddSdrh                              /*   0123456789 123456789 123456789 123 */
133373cc2ddSdrh   static const char zKeyText[] = "naturaleftouterightfullinnercross";
1345719628aSdrh   static const struct {
135373cc2ddSdrh     u8 i;        /* Beginning of keyword text in zKeyText[] */
136373cc2ddSdrh     u8 nChar;    /* Length of the keyword in characters */
137373cc2ddSdrh     u8 code;     /* Join type mask */
138373cc2ddSdrh   } aKeyword[] = {
139373cc2ddSdrh     /* natural */ { 0,  7, JT_NATURAL                },
140373cc2ddSdrh     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
141373cc2ddSdrh     /* outer   */ { 10, 5, JT_OUTER                  },
142373cc2ddSdrh     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
143373cc2ddSdrh     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
144373cc2ddSdrh     /* inner   */ { 23, 5, JT_INNER                  },
145373cc2ddSdrh     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
14601f3f253Sdrh   };
14701f3f253Sdrh   int i, j;
14801f3f253Sdrh   apAll[0] = pA;
14901f3f253Sdrh   apAll[1] = pB;
15001f3f253Sdrh   apAll[2] = pC;
151195e6967Sdrh   for(i=0; i<3 && apAll[i]; i++){
15201f3f253Sdrh     p = apAll[i];
153373cc2ddSdrh     for(j=0; j<ArraySize(aKeyword); j++){
154373cc2ddSdrh       if( p->n==aKeyword[j].nChar
155373cc2ddSdrh           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
156373cc2ddSdrh         jointype |= aKeyword[j].code;
15701f3f253Sdrh         break;
15801f3f253Sdrh       }
15901f3f253Sdrh     }
160373cc2ddSdrh     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
161373cc2ddSdrh     if( j>=ArraySize(aKeyword) ){
16201f3f253Sdrh       jointype |= JT_ERROR;
16301f3f253Sdrh       break;
16401f3f253Sdrh     }
16501f3f253Sdrh   }
166ad2d8307Sdrh   if(
167ad2d8307Sdrh      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
168195e6967Sdrh      (jointype & JT_ERROR)!=0
169ad2d8307Sdrh   ){
170a9671a22Sdrh     const char *zSp = " ";
171a9671a22Sdrh     assert( pB!=0 );
172a9671a22Sdrh     if( pC==0 ){ zSp++; }
173ae29ffbeSdrh     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
174a9671a22Sdrh        "%T %T%s%T", pA, pB, zSp, pC);
17501f3f253Sdrh     jointype = JT_INNER;
176373cc2ddSdrh   }else if( (jointype & JT_OUTER)!=0
177373cc2ddSdrh          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
1784adee20fSdanielk1977     sqlite3ErrorMsg(pParse,
179da93d238Sdrh       "RIGHT and FULL OUTER JOINs are not currently supported");
180195e6967Sdrh     jointype = JT_INNER;
18101f3f253Sdrh   }
18201f3f253Sdrh   return jointype;
18301f3f253Sdrh }
18401f3f253Sdrh 
18501f3f253Sdrh /*
186ad2d8307Sdrh ** Return the index of a column in a table.  Return -1 if the column
187ad2d8307Sdrh ** is not contained in the table.
188ad2d8307Sdrh */
189ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){
190ad2d8307Sdrh   int i;
191ad2d8307Sdrh   for(i=0; i<pTab->nCol; i++){
1924adee20fSdanielk1977     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
193ad2d8307Sdrh   }
194ad2d8307Sdrh   return -1;
195ad2d8307Sdrh }
196ad2d8307Sdrh 
197ad2d8307Sdrh /*
1982179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a
1992179b434Sdrh ** table that has a column named zCol.
2002179b434Sdrh **
2012179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index
2022179b434Sdrh ** of the matching column and return TRUE.
2032179b434Sdrh **
2042179b434Sdrh ** If not found, return FALSE.
2052179b434Sdrh */
2062179b434Sdrh static int tableAndColumnIndex(
2072179b434Sdrh   SrcList *pSrc,       /* Array of tables to search */
2082179b434Sdrh   int N,               /* Number of tables in pSrc->a[] to search */
2092179b434Sdrh   const char *zCol,    /* Name of the column we are looking for */
2102179b434Sdrh   int *piTab,          /* Write index of pSrc->a[] here */
2112179b434Sdrh   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
2122179b434Sdrh ){
2132179b434Sdrh   int i;               /* For looping over tables in pSrc */
2142179b434Sdrh   int iCol;            /* Index of column matching zCol */
2152179b434Sdrh 
2162179b434Sdrh   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
2172179b434Sdrh   for(i=0; i<N; i++){
2182179b434Sdrh     iCol = columnIndex(pSrc->a[i].pTab, zCol);
2192179b434Sdrh     if( iCol>=0 ){
2202179b434Sdrh       if( piTab ){
2212179b434Sdrh         *piTab = i;
2222179b434Sdrh         *piCol = iCol;
2232179b434Sdrh       }
2242179b434Sdrh       return 1;
2252179b434Sdrh     }
2262179b434Sdrh   }
2272179b434Sdrh   return 0;
2282179b434Sdrh }
2292179b434Sdrh 
2302179b434Sdrh /*
231f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the
232f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which
233f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form:
234f7b0b0adSdan **
235f7b0b0adSdan **    (tab1.col1 = tab2.col2)
236f7b0b0adSdan **
237f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
238f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
239f7b0b0adSdan ** column iColRight of tab2.
240ad2d8307Sdrh */
241ad2d8307Sdrh static void addWhereTerm(
24217435752Sdrh   Parse *pParse,                  /* Parsing context */
243f7b0b0adSdan   SrcList *pSrc,                  /* List of tables in FROM clause */
2442179b434Sdrh   int iLeft,                      /* Index of first table to join in pSrc */
245f7b0b0adSdan   int iColLeft,                   /* Index of column in first table */
2462179b434Sdrh   int iRight,                     /* Index of second table in pSrc */
247f7b0b0adSdan   int iColRight,                  /* Index of column in second table */
248f7b0b0adSdan   int isOuterJoin,                /* True if this is an OUTER join */
249f7b0b0adSdan   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
250ad2d8307Sdrh ){
251f7b0b0adSdan   sqlite3 *db = pParse->db;
252f7b0b0adSdan   Expr *pE1;
253f7b0b0adSdan   Expr *pE2;
254f7b0b0adSdan   Expr *pEq;
255ad2d8307Sdrh 
2562179b434Sdrh   assert( iLeft<iRight );
2572179b434Sdrh   assert( pSrc->nSrc>iRight );
2582179b434Sdrh   assert( pSrc->a[iLeft].pTab );
2592179b434Sdrh   assert( pSrc->a[iRight].pTab );
260f7b0b0adSdan 
2612179b434Sdrh   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
2622179b434Sdrh   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
263f7b0b0adSdan 
264f7b0b0adSdan   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
265f7b0b0adSdan   if( pEq && isOuterJoin ){
266f7b0b0adSdan     ExprSetProperty(pEq, EP_FromJoin);
267f7b0b0adSdan     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
268f7b0b0adSdan     ExprSetIrreducible(pEq);
269f7b0b0adSdan     pEq->iRightJoinTable = (i16)pE2->iTable;
270030530deSdrh   }
271f7b0b0adSdan   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
272ad2d8307Sdrh }
273ad2d8307Sdrh 
274ad2d8307Sdrh /*
2751f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression.
27622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the
27722d6a53aSdrh ** expression.
2781cc093c2Sdrh **
279e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell
2801cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the
2811f16230bSdrh ** join restriction specified in the ON or USING clause and not a part
2821f16230bSdrh ** of the more general WHERE clause.  These terms are moved over to the
2831f16230bSdrh ** WHERE clause during join processing but we need to remember that they
2841f16230bSdrh ** originated in the ON or USING clause.
28522d6a53aSdrh **
28622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the
28722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not
28822d6a53aSdrh ** explicitly mentioned in the expression.  That information is needed
28922d6a53aSdrh ** for cases like this:
29022d6a53aSdrh **
29122d6a53aSdrh **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
29222d6a53aSdrh **
29322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5
29422d6a53aSdrh ** term until after the t2 loop of the join.  In that way, a
29522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
29622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately
29722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in
29822d6a53aSdrh ** the output, which is incorrect.
2991cc093c2Sdrh */
30022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){
3011cc093c2Sdrh   while( p ){
3021f16230bSdrh     ExprSetProperty(p, EP_FromJoin);
30333e619fcSdrh     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
30433e619fcSdrh     ExprSetIrreducible(p);
305cf697396Sshane     p->iRightJoinTable = (i16)iTable;
30622d6a53aSdrh     setJoinExpr(p->pLeft, iTable);
3071cc093c2Sdrh     p = p->pRight;
3081cc093c2Sdrh   }
3091cc093c2Sdrh }
3101cc093c2Sdrh 
3111cc093c2Sdrh /*
312ad2d8307Sdrh ** This routine processes the join information for a SELECT statement.
313ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause.
314ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms.
315ad2d8307Sdrh **
31691bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure.
31791bb0eedSdrh ** The left most table is the first entry in Select.pSrc.  The right-most
31891bb0eedSdrh ** table is the last entry.  The join operator is held in the entry to
31991bb0eedSdrh ** the left.  Thus entry 0 contains the join operator for the join between
32091bb0eedSdrh ** entries 0 and 1.  Any ON or USING clauses associated with the join are
32191bb0eedSdrh ** also attached to the left entry.
32291bb0eedSdrh **
323ad2d8307Sdrh ** This routine returns the number of errors encountered.
324ad2d8307Sdrh */
325ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){
32691bb0eedSdrh   SrcList *pSrc;                  /* All tables in the FROM clause */
32791bb0eedSdrh   int i, j;                       /* Loop counters */
32891bb0eedSdrh   struct SrcList_item *pLeft;     /* Left table being joined */
32991bb0eedSdrh   struct SrcList_item *pRight;    /* Right table being joined */
330ad2d8307Sdrh 
33191bb0eedSdrh   pSrc = p->pSrc;
33291bb0eedSdrh   pLeft = &pSrc->a[0];
33391bb0eedSdrh   pRight = &pLeft[1];
33491bb0eedSdrh   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
33591bb0eedSdrh     Table *pLeftTab = pLeft->pTab;
33691bb0eedSdrh     Table *pRightTab = pRight->pTab;
337ad27e761Sdrh     int isOuter;
33891bb0eedSdrh 
3391c767f0dSdrh     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
340ad27e761Sdrh     isOuter = (pRight->jointype & JT_OUTER)!=0;
341ad2d8307Sdrh 
342ad2d8307Sdrh     /* When the NATURAL keyword is present, add WHERE clause terms for
343ad2d8307Sdrh     ** every column that the two tables have in common.
344ad2d8307Sdrh     */
34561dfc31dSdrh     if( pRight->jointype & JT_NATURAL ){
34661dfc31dSdrh       if( pRight->pOn || pRight->pUsing ){
3474adee20fSdanielk1977         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
348ad2d8307Sdrh            "an ON or USING clause", 0);
349ad2d8307Sdrh         return 1;
350ad2d8307Sdrh       }
3512179b434Sdrh       for(j=0; j<pRightTab->nCol; j++){
3522179b434Sdrh         char *zName;   /* Name of column in the right table */
3532179b434Sdrh         int iLeft;     /* Matching left table */
3542179b434Sdrh         int iLeftCol;  /* Matching column in the left table */
3552179b434Sdrh 
3562179b434Sdrh         zName = pRightTab->aCol[j].zName;
3572179b434Sdrh         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
3582179b434Sdrh           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
3592179b434Sdrh                        isOuter, &p->pWhere);
360ad2d8307Sdrh         }
361ad2d8307Sdrh       }
362ad2d8307Sdrh     }
363ad2d8307Sdrh 
364ad2d8307Sdrh     /* Disallow both ON and USING clauses in the same join
365ad2d8307Sdrh     */
36661dfc31dSdrh     if( pRight->pOn && pRight->pUsing ){
3674adee20fSdanielk1977       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
368da93d238Sdrh         "clauses in the same join");
369ad2d8307Sdrh       return 1;
370ad2d8307Sdrh     }
371ad2d8307Sdrh 
372ad2d8307Sdrh     /* Add the ON clause to the end of the WHERE clause, connected by
37391bb0eedSdrh     ** an AND operator.
374ad2d8307Sdrh     */
37561dfc31dSdrh     if( pRight->pOn ){
376ad27e761Sdrh       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
37717435752Sdrh       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
37861dfc31dSdrh       pRight->pOn = 0;
379ad2d8307Sdrh     }
380ad2d8307Sdrh 
381ad2d8307Sdrh     /* Create extra terms on the WHERE clause for each column named
382ad2d8307Sdrh     ** in the USING clause.  Example: If the two tables to be joined are
383ad2d8307Sdrh     ** A and B and the USING clause names X, Y, and Z, then add this
384ad2d8307Sdrh     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
385ad2d8307Sdrh     ** Report an error if any column mentioned in the USING clause is
386ad2d8307Sdrh     ** not contained in both tables to be joined.
387ad2d8307Sdrh     */
38861dfc31dSdrh     if( pRight->pUsing ){
38961dfc31dSdrh       IdList *pList = pRight->pUsing;
390ad2d8307Sdrh       for(j=0; j<pList->nId; j++){
3912179b434Sdrh         char *zName;     /* Name of the term in the USING clause */
3922179b434Sdrh         int iLeft;       /* Table on the left with matching column name */
3932179b434Sdrh         int iLeftCol;    /* Column number of matching column on the left */
3942179b434Sdrh         int iRightCol;   /* Column number of matching column on the right */
3952179b434Sdrh 
3962179b434Sdrh         zName = pList->a[j].zName;
3972179b434Sdrh         iRightCol = columnIndex(pRightTab, zName);
3982179b434Sdrh         if( iRightCol<0
3992179b434Sdrh          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
4002179b434Sdrh         ){
4014adee20fSdanielk1977           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
40291bb0eedSdrh             "not present in both tables", zName);
403ad2d8307Sdrh           return 1;
404ad2d8307Sdrh         }
4052179b434Sdrh         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
4062179b434Sdrh                      isOuter, &p->pWhere);
407ad2d8307Sdrh       }
408ad2d8307Sdrh     }
409ad2d8307Sdrh   }
410ad2d8307Sdrh   return 0;
411ad2d8307Sdrh }
412ad2d8307Sdrh 
413ad2d8307Sdrh /*
414c926afbcSdrh ** Insert code into "v" that will push the record on the top of the
415c926afbcSdrh ** stack into the sorter.
416c926afbcSdrh */
417d59ba6ceSdrh static void pushOntoSorter(
418d59ba6ceSdrh   Parse *pParse,         /* Parser context */
419d59ba6ceSdrh   ExprList *pOrderBy,    /* The ORDER BY clause */
420b7654111Sdrh   Select *pSelect,       /* The whole SELECT statement */
421b7654111Sdrh   int regData            /* Register holding data to be sorted */
422d59ba6ceSdrh ){
423d59ba6ceSdrh   Vdbe *v = pParse->pVdbe;
424892d3179Sdrh   int nExpr = pOrderBy->nExpr;
425892d3179Sdrh   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
426892d3179Sdrh   int regRecord = sqlite3GetTempReg(pParse);
427c6aff30cSdrh   int op;
428ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
429191b54cbSdrh   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
430892d3179Sdrh   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
431b21e7c70Sdrh   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
4321db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
433c6aff30cSdrh   if( pSelect->selFlags & SF_UseSorter ){
434c6aff30cSdrh     op = OP_SorterInsert;
435c6aff30cSdrh   }else{
436c6aff30cSdrh     op = OP_IdxInsert;
437c6aff30cSdrh   }
438c6aff30cSdrh   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
439892d3179Sdrh   sqlite3ReleaseTempReg(pParse, regRecord);
440892d3179Sdrh   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
44192b01d53Sdrh   if( pSelect->iLimit ){
44215007a99Sdrh     int addr1, addr2;
443b7654111Sdrh     int iLimit;
4440acb7e48Sdrh     if( pSelect->iOffset ){
445b7654111Sdrh       iLimit = pSelect->iOffset+1;
446b7654111Sdrh     }else{
447b7654111Sdrh       iLimit = pSelect->iLimit;
448b7654111Sdrh     }
449b7654111Sdrh     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
450b7654111Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
4513c84ddffSdrh     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
452d59ba6ceSdrh     sqlite3VdbeJumpHere(v, addr1);
4533c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
4543c84ddffSdrh     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
45515007a99Sdrh     sqlite3VdbeJumpHere(v, addr2);
456d59ba6ceSdrh   }
457c926afbcSdrh }
458c926afbcSdrh 
459c926afbcSdrh /*
460ec7429aeSdrh ** Add code to implement the OFFSET
461ea48eb2eSdrh */
462ec7429aeSdrh static void codeOffset(
463bab39e13Sdrh   Vdbe *v,          /* Generate code into this VM */
464ea48eb2eSdrh   Select *p,        /* The SELECT statement being coded */
465b7654111Sdrh   int iContinue     /* Jump here to skip the current record */
466ea48eb2eSdrh ){
46792b01d53Sdrh   if( p->iOffset && iContinue!=0 ){
46815007a99Sdrh     int addr;
4698558cde1Sdrh     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
4703c84ddffSdrh     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
47166a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
472d4e70ebdSdrh     VdbeComment((v, "skip OFFSET records"));
47315007a99Sdrh     sqlite3VdbeJumpHere(v, addr);
474ea48eb2eSdrh   }
475ea48eb2eSdrh }
476ea48eb2eSdrh 
477ea48eb2eSdrh /*
47898757157Sdrh ** Add code that will check to make sure the N registers starting at iMem
47998757157Sdrh ** form a distinct entry.  iTab is a sorting index that holds previously
480a2a49dc9Sdrh ** seen combinations of the N values.  A new entry is made in iTab
481a2a49dc9Sdrh ** if the current N values are new.
482a2a49dc9Sdrh **
483a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the
484a2a49dc9Sdrh ** stack if the top N elements are not distinct.
485a2a49dc9Sdrh */
486a2a49dc9Sdrh static void codeDistinct(
4872dcef11bSdrh   Parse *pParse,     /* Parsing and code generating context */
488a2a49dc9Sdrh   int iTab,          /* A sorting index used to test for distinctness */
489a2a49dc9Sdrh   int addrRepeat,    /* Jump to here if not distinct */
490477df4b3Sdrh   int N,             /* Number of elements */
491a2a49dc9Sdrh   int iMem           /* First element */
492a2a49dc9Sdrh ){
4932dcef11bSdrh   Vdbe *v;
4942dcef11bSdrh   int r1;
4952dcef11bSdrh 
4962dcef11bSdrh   v = pParse->pVdbe;
4972dcef11bSdrh   r1 = sqlite3GetTempReg(pParse);
49891fc4a0cSdrh   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
4991db639ceSdrh   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
5002dcef11bSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
5012dcef11bSdrh   sqlite3ReleaseTempReg(pParse, r1);
502a2a49dc9Sdrh }
503a2a49dc9Sdrh 
504bb7dd683Sdrh #ifndef SQLITE_OMIT_SUBQUERY
505a2a49dc9Sdrh /*
506e305f43fSdrh ** Generate an error message when a SELECT is used within a subexpression
507e305f43fSdrh ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
508bb7dd683Sdrh ** column.  We do this in a subroutine because the error used to occur
509bb7dd683Sdrh ** in multiple places.  (The error only occurs in one place now, but we
510bb7dd683Sdrh ** retain the subroutine to minimize code disruption.)
511e305f43fSdrh */
5126c8c8ce0Sdanielk1977 static int checkForMultiColumnSelectError(
5136c8c8ce0Sdanielk1977   Parse *pParse,       /* Parse context. */
5146c8c8ce0Sdanielk1977   SelectDest *pDest,   /* Destination of SELECT results */
5156c8c8ce0Sdanielk1977   int nExpr            /* Number of result columns returned by SELECT */
5166c8c8ce0Sdanielk1977 ){
5176c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
518e305f43fSdrh   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
519e305f43fSdrh     sqlite3ErrorMsg(pParse, "only a single result allowed for "
520e305f43fSdrh        "a SELECT that is part of an expression");
521e305f43fSdrh     return 1;
522e305f43fSdrh   }else{
523e305f43fSdrh     return 0;
524e305f43fSdrh   }
525e305f43fSdrh }
526bb7dd683Sdrh #endif
527c99130fdSdrh 
528c99130fdSdrh /*
529e8e4af76Sdrh ** An instance of the following object is used to record information about
530e8e4af76Sdrh ** how to process the DISTINCT keyword, to simplify passing that information
531e8e4af76Sdrh ** into the selectInnerLoop() routine.
532e8e4af76Sdrh */
533e8e4af76Sdrh typedef struct DistinctCtx DistinctCtx;
534e8e4af76Sdrh struct DistinctCtx {
535e8e4af76Sdrh   u8 isTnct;      /* True if the DISTINCT keyword is present */
536e8e4af76Sdrh   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
537e8e4af76Sdrh   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
538e8e4af76Sdrh   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
539e8e4af76Sdrh };
540e8e4af76Sdrh 
541e8e4af76Sdrh /*
5422282792aSdrh ** This routine generates the code for the inside of the inner loop
5432282792aSdrh ** of a SELECT.
54482c3d636Sdrh **
54538640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions
54638640e15Sdrh ** are evaluated in order to get the data for this row.  If nColumn>0
54738640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the
54838640e15Sdrh ** datatypes for each column.
5492282792aSdrh */
550d2b3e23bSdrh static void selectInnerLoop(
5512282792aSdrh   Parse *pParse,          /* The parser context */
552df199a25Sdrh   Select *p,              /* The complete select statement being coded */
5532282792aSdrh   ExprList *pEList,       /* List of values being extracted */
55482c3d636Sdrh   int srcTab,             /* Pull data from this table */
555967e8b73Sdrh   int nColumn,            /* Number of columns in the source table */
5562282792aSdrh   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
557e8e4af76Sdrh   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
5586c8c8ce0Sdanielk1977   SelectDest *pDest,      /* How to dispose of the results */
5592282792aSdrh   int iContinue,          /* Jump here to continue with next row */
560a9671a22Sdrh   int iBreak              /* Jump here to break out of the inner loop */
5612282792aSdrh ){
5622282792aSdrh   Vdbe *v = pParse->pVdbe;
563d847eaadSdrh   int i;
564ea48eb2eSdrh   int hasDistinct;        /* True if the DISTINCT keyword is present */
565d847eaadSdrh   int regResult;              /* Start of memory holding result set */
566d847eaadSdrh   int eDest = pDest->eDest;   /* How to dispose of results */
5672b596da8Sdrh   int iParm = pDest->iSDParm; /* First argument to disposal method */
568d847eaadSdrh   int nResultCol;             /* Number of result columns */
56938640e15Sdrh 
5701c767f0dSdrh   assert( v );
5711c767f0dSdrh   if( NEVER(v==0) ) return;
57238640e15Sdrh   assert( pEList!=0 );
573e8e4af76Sdrh   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
574ea48eb2eSdrh   if( pOrderBy==0 && !hasDistinct ){
575b7654111Sdrh     codeOffset(v, p, iContinue);
576df199a25Sdrh   }
577df199a25Sdrh 
578967e8b73Sdrh   /* Pull the requested columns.
5792282792aSdrh   */
58038640e15Sdrh   if( nColumn>0 ){
581d847eaadSdrh     nResultCol = nColumn;
582a2a49dc9Sdrh   }else{
583d847eaadSdrh     nResultCol = pEList->nExpr;
584a2a49dc9Sdrh   }
5852b596da8Sdrh   if( pDest->iSdst==0 ){
5862b596da8Sdrh     pDest->iSdst = pParse->nMem+1;
5872b596da8Sdrh     pDest->nSdst = nResultCol;
5880acb7e48Sdrh     pParse->nMem += nResultCol;
5891c767f0dSdrh   }else{
5902b596da8Sdrh     assert( pDest->nSdst==nResultCol );
5911013c932Sdrh   }
5922b596da8Sdrh   regResult = pDest->iSdst;
593a2a49dc9Sdrh   if( nColumn>0 ){
594967e8b73Sdrh     for(i=0; i<nColumn; i++){
595d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
59682c3d636Sdrh     }
5979ed1dfa8Sdanielk1977   }else if( eDest!=SRT_Exists ){
5989ed1dfa8Sdanielk1977     /* If the destination is an EXISTS(...) expression, the actual
5999ed1dfa8Sdanielk1977     ** values returned by the SELECT are not required.
6009ed1dfa8Sdanielk1977     */
601ceea3321Sdrh     sqlite3ExprCacheClear(pParse);
6027d10d5a6Sdrh     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
603a2a49dc9Sdrh   }
604d847eaadSdrh   nColumn = nResultCol;
6052282792aSdrh 
606daffd0e5Sdrh   /* If the DISTINCT keyword was present on the SELECT statement
607daffd0e5Sdrh   ** and this row has been seen before, then do not make this row
608daffd0e5Sdrh   ** part of the result.
6092282792aSdrh   */
610ea48eb2eSdrh   if( hasDistinct ){
611f8875400Sdrh     assert( pEList!=0 );
612f8875400Sdrh     assert( pEList->nExpr==nColumn );
613e8e4af76Sdrh     switch( pDistinct->eTnctType ){
614e8e4af76Sdrh       case WHERE_DISTINCT_ORDERED: {
615e8e4af76Sdrh         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
616e8e4af76Sdrh         int iJump;              /* Jump destination */
617e8e4af76Sdrh         int regPrev;            /* Previous row content */
618e8e4af76Sdrh 
619e8e4af76Sdrh         /* Allocate space for the previous row */
620e8e4af76Sdrh         regPrev = pParse->nMem+1;
621e8e4af76Sdrh         pParse->nMem += nColumn;
622e8e4af76Sdrh 
623e8e4af76Sdrh         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
624e8e4af76Sdrh         ** sets the MEM_Cleared bit on the first register of the
625e8e4af76Sdrh         ** previous value.  This will cause the OP_Ne below to always
626e8e4af76Sdrh         ** fail on the first iteration of the loop even if the first
627e8e4af76Sdrh         ** row is all NULLs.
628e8e4af76Sdrh         */
629e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
630e8e4af76Sdrh         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
631e8e4af76Sdrh         pOp->opcode = OP_Null;
632e8e4af76Sdrh         pOp->p1 = 1;
633e8e4af76Sdrh         pOp->p2 = regPrev;
634e8e4af76Sdrh 
635e8e4af76Sdrh         iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
636e8e4af76Sdrh         for(i=0; i<nColumn; i++){
637e8e4af76Sdrh           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
638e8e4af76Sdrh           if( i<nColumn-1 ){
639e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
640e8e4af76Sdrh           }else{
641e8e4af76Sdrh             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
642e8e4af76Sdrh           }
643e8e4af76Sdrh           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
644e8e4af76Sdrh           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
645e8e4af76Sdrh         }
646e8e4af76Sdrh         assert( sqlite3VdbeCurrentAddr(v)==iJump );
647e8e4af76Sdrh         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
648e8e4af76Sdrh         break;
649e8e4af76Sdrh       }
650e8e4af76Sdrh 
651e8e4af76Sdrh       case WHERE_DISTINCT_UNIQUE: {
652e8e4af76Sdrh         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
653e8e4af76Sdrh         break;
654e8e4af76Sdrh       }
655e8e4af76Sdrh 
656e8e4af76Sdrh       default: {
657e8e4af76Sdrh         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
658e8e4af76Sdrh         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
659e8e4af76Sdrh         break;
660e8e4af76Sdrh       }
661e8e4af76Sdrh     }
662ea48eb2eSdrh     if( pOrderBy==0 ){
663b7654111Sdrh       codeOffset(v, p, iContinue);
664ea48eb2eSdrh     }
6652282792aSdrh   }
66682c3d636Sdrh 
667c926afbcSdrh   switch( eDest ){
66882c3d636Sdrh     /* In this mode, write each query result to the key of the temporary
66982c3d636Sdrh     ** table iParm.
6702282792aSdrh     */
67113449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
672c926afbcSdrh     case SRT_Union: {
6739cbf3425Sdrh       int r1;
6749cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
675d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6769cbf3425Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
6779cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
678c926afbcSdrh       break;
679c926afbcSdrh     }
68082c3d636Sdrh 
68182c3d636Sdrh     /* Construct a record from the query result, but instead of
68282c3d636Sdrh     ** saving that record, use it as a key to delete elements from
68382c3d636Sdrh     ** the temporary table iParm.
68482c3d636Sdrh     */
685c926afbcSdrh     case SRT_Except: {
686e14006d0Sdrh       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
687c926afbcSdrh       break;
688c926afbcSdrh     }
6895338a5f7Sdanielk1977 #endif
6905338a5f7Sdanielk1977 
6915338a5f7Sdanielk1977     /* Store the result as data using a unique key.
6925338a5f7Sdanielk1977     */
6935338a5f7Sdanielk1977     case SRT_Table:
694b9bb7c18Sdrh     case SRT_EphemTab: {
695b7654111Sdrh       int r1 = sqlite3GetTempReg(pParse);
696373cc2ddSdrh       testcase( eDest==SRT_Table );
697373cc2ddSdrh       testcase( eDest==SRT_EphemTab );
698d847eaadSdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
6995338a5f7Sdanielk1977       if( pOrderBy ){
700b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
7015338a5f7Sdanielk1977       }else{
702b7654111Sdrh         int r2 = sqlite3GetTempReg(pParse);
703b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
704b7654111Sdrh         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
705b7654111Sdrh         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
706b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r2);
7075338a5f7Sdanielk1977       }
708b7654111Sdrh       sqlite3ReleaseTempReg(pParse, r1);
7095338a5f7Sdanielk1977       break;
7105338a5f7Sdanielk1977     }
7112282792aSdrh 
71293758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
7132282792aSdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
7142282792aSdrh     ** then there should be a single item on the stack.  Write this
7152282792aSdrh     ** item into the set table with bogus data.
7162282792aSdrh     */
717c926afbcSdrh     case SRT_Set: {
718967e8b73Sdrh       assert( nColumn==1 );
719634d81deSdrh       pDest->affSdst =
720634d81deSdrh                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
721c926afbcSdrh       if( pOrderBy ){
722de941c60Sdrh         /* At first glance you would think we could optimize out the
723de941c60Sdrh         ** ORDER BY in this case since the order of entries in the set
724de941c60Sdrh         ** does not matter.  But there might be a LIMIT clause, in which
725de941c60Sdrh         ** case the order does matter */
726d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
727c926afbcSdrh       }else{
728b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
729634d81deSdrh         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
730da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
731b7654111Sdrh         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
732b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
733c926afbcSdrh       }
734c926afbcSdrh       break;
735c926afbcSdrh     }
73682c3d636Sdrh 
737504b6989Sdrh     /* If any row exist in the result set, record that fact and abort.
738ec7429aeSdrh     */
739ec7429aeSdrh     case SRT_Exists: {
7404c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
741ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
742ec7429aeSdrh       break;
743ec7429aeSdrh     }
744ec7429aeSdrh 
7452282792aSdrh     /* If this is a scalar select that is part of an expression, then
7462282792aSdrh     ** store the results in the appropriate memory cell and break out
7472282792aSdrh     ** of the scan loop.
7482282792aSdrh     */
749c926afbcSdrh     case SRT_Mem: {
750967e8b73Sdrh       assert( nColumn==1 );
751c926afbcSdrh       if( pOrderBy ){
752d847eaadSdrh         pushOntoSorter(pParse, pOrderBy, p, regResult);
753c926afbcSdrh       }else{
754b21e7c70Sdrh         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
755ec7429aeSdrh         /* The LIMIT clause will jump out of the loop for us */
756c926afbcSdrh       }
757c926afbcSdrh       break;
758c926afbcSdrh     }
75993758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
7602282792aSdrh 
761c182d163Sdrh     /* Send the data to the callback function or to a subroutine.  In the
762c182d163Sdrh     ** case of a subroutine, the subroutine itself is responsible for
763c182d163Sdrh     ** popping the data from the stack.
764f46f905aSdrh     */
765e00ee6ebSdrh     case SRT_Coroutine:
7667d10d5a6Sdrh     case SRT_Output: {
767373cc2ddSdrh       testcase( eDest==SRT_Coroutine );
768373cc2ddSdrh       testcase( eDest==SRT_Output );
769f46f905aSdrh       if( pOrderBy ){
770b7654111Sdrh         int r1 = sqlite3GetTempReg(pParse);
771d847eaadSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
772b7654111Sdrh         pushOntoSorter(pParse, pOrderBy, p, r1);
773b7654111Sdrh         sqlite3ReleaseTempReg(pParse, r1);
774e00ee6ebSdrh       }else if( eDest==SRT_Coroutine ){
7752b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
776c182d163Sdrh       }else{
777d847eaadSdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
778da250ea5Sdrh         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
779ac82fcf5Sdrh       }
780142e30dfSdrh       break;
781142e30dfSdrh     }
782142e30dfSdrh 
7836a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER)
784d7489c39Sdrh     /* Discard the results.  This is used for SELECT statements inside
785d7489c39Sdrh     ** the body of a TRIGGER.  The purpose of such selects is to call
786d7489c39Sdrh     ** user-defined functions that have side effects.  We do not care
787d7489c39Sdrh     ** about the actual results of the select.
788d7489c39Sdrh     */
789c926afbcSdrh     default: {
790f46f905aSdrh       assert( eDest==SRT_Discard );
791c926afbcSdrh       break;
792c926afbcSdrh     }
79393758c8dSdanielk1977 #endif
794c926afbcSdrh   }
795ec7429aeSdrh 
7965e87be87Sdrh   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
7975e87be87Sdrh   ** there is a sorter, in which case the sorter has already limited
7985e87be87Sdrh   ** the output for us.
799ec7429aeSdrh   */
8005e87be87Sdrh   if( pOrderBy==0 && p->iLimit ){
8019b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
802ec7429aeSdrh   }
80382c3d636Sdrh }
80482c3d636Sdrh 
80582c3d636Sdrh /*
806dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records
807dece1a84Sdrh ** the collating sequence for each expression in that expression list.
808dece1a84Sdrh **
8090342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
8100342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to
8110342b1f5Sdrh ** implement that clause.  If the ExprList is the result set of a SELECT
8120342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual
8130342b1f5Sdrh ** index to implement a DISTINCT test.
8140342b1f5Sdrh **
815dece1a84Sdrh ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
816dece1a84Sdrh ** function is responsible for seeing that this structure is eventually
81766a5167bSdrh ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
81866a5167bSdrh ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
819dece1a84Sdrh */
820dece1a84Sdrh static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
821dece1a84Sdrh   sqlite3 *db = pParse->db;
822dece1a84Sdrh   int nExpr;
823dece1a84Sdrh   KeyInfo *pInfo;
824dece1a84Sdrh   struct ExprList_item *pItem;
825dece1a84Sdrh   int i;
826dece1a84Sdrh 
827dece1a84Sdrh   nExpr = pList->nExpr;
82817435752Sdrh   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
829dece1a84Sdrh   if( pInfo ){
8302646da7eSdrh     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
831ea678832Sdrh     pInfo->nField = (u16)nExpr;
83214db2665Sdanielk1977     pInfo->enc = ENC(db);
8332aca5846Sdrh     pInfo->db = db;
834dece1a84Sdrh     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
835dece1a84Sdrh       CollSeq *pColl;
836dece1a84Sdrh       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
837dece1a84Sdrh       if( !pColl ){
838dece1a84Sdrh         pColl = db->pDfltColl;
839dece1a84Sdrh       }
840dece1a84Sdrh       pInfo->aColl[i] = pColl;
841dece1a84Sdrh       pInfo->aSortOrder[i] = pItem->sortOrder;
842dece1a84Sdrh     }
843dece1a84Sdrh   }
844dece1a84Sdrh   return pInfo;
845dece1a84Sdrh }
846dece1a84Sdrh 
8477f61e92cSdan #ifndef SQLITE_OMIT_COMPOUND_SELECT
8487f61e92cSdan /*
8497f61e92cSdan ** Name of the connection operator, used for error messages.
8507f61e92cSdan */
8517f61e92cSdan static const char *selectOpName(int id){
8527f61e92cSdan   char *z;
8537f61e92cSdan   switch( id ){
8547f61e92cSdan     case TK_ALL:       z = "UNION ALL";   break;
8557f61e92cSdan     case TK_INTERSECT: z = "INTERSECT";   break;
8567f61e92cSdan     case TK_EXCEPT:    z = "EXCEPT";      break;
8577f61e92cSdan     default:           z = "UNION";       break;
8587f61e92cSdan   }
8597f61e92cSdan   return z;
8607f61e92cSdan }
8617f61e92cSdan #endif /* SQLITE_OMIT_COMPOUND_SELECT */
8627f61e92cSdan 
8632ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
86417c0bc0cSdan /*
86517c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
86617c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
86717c0bc0cSdan ** where the caption is of the form:
86817c0bc0cSdan **
86917c0bc0cSdan **   "USE TEMP B-TREE FOR xxx"
87017c0bc0cSdan **
87117c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
87217c0bc0cSdan ** is determined by the zUsage argument.
87317c0bc0cSdan */
8742ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){
8752ce22453Sdan   if( pParse->explain==2 ){
8762ce22453Sdan     Vdbe *v = pParse->pVdbe;
8772ce22453Sdan     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
8782ce22453Sdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
8792ce22453Sdan   }
8802ce22453Sdan }
88117c0bc0cSdan 
88217c0bc0cSdan /*
883bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro
884bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
885bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that
886bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
887bb2b4418Sdan ** code with #ifndef directives.
888bb2b4418Sdan */
889bb2b4418Sdan # define explainSetInteger(a, b) a = b
890bb2b4418Sdan 
891bb2b4418Sdan #else
892bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */
893bb2b4418Sdan # define explainTempTable(y,z)
894bb2b4418Sdan # define explainSetInteger(y,z)
895bb2b4418Sdan #endif
896bb2b4418Sdan 
897bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
898bb2b4418Sdan /*
8997f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
9007f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
9017f61e92cSdan ** where the caption is of one of the two forms:
9027f61e92cSdan **
9037f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
9047f61e92cSdan **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
9057f61e92cSdan **
9067f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding
9077f61e92cSdan ** function parameters, and op is the text representation of the parameter
9087f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
9097f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
9107f61e92cSdan ** false, or the second form if it is true.
9117f61e92cSdan */
9127f61e92cSdan static void explainComposite(
9137f61e92cSdan   Parse *pParse,                  /* Parse context */
9147f61e92cSdan   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
9157f61e92cSdan   int iSub1,                      /* Subquery id 1 */
9167f61e92cSdan   int iSub2,                      /* Subquery id 2 */
9177f61e92cSdan   int bUseTmp                     /* True if a temp table was used */
9187f61e92cSdan ){
9197f61e92cSdan   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
9207f61e92cSdan   if( pParse->explain==2 ){
9217f61e92cSdan     Vdbe *v = pParse->pVdbe;
9227f61e92cSdan     char *zMsg = sqlite3MPrintf(
92330969d3fSdan         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
9247f61e92cSdan         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
9257f61e92cSdan     );
9267f61e92cSdan     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
9277f61e92cSdan   }
9287f61e92cSdan }
9292ce22453Sdan #else
93017c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */
9317f61e92cSdan # define explainComposite(v,w,x,y,z)
9322ce22453Sdan #endif
933dece1a84Sdrh 
934dece1a84Sdrh /*
935d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument,
936d8bc7086Sdrh ** then the results were placed in a sorter.  After the loop is terminated
937d8bc7086Sdrh ** we need to run the sorter and output the results.  The following
938d8bc7086Sdrh ** routine generates the code needed to do that.
939d8bc7086Sdrh */
940c926afbcSdrh static void generateSortTail(
941cdd536f0Sdrh   Parse *pParse,    /* Parsing context */
942c926afbcSdrh   Select *p,        /* The SELECT statement */
943c926afbcSdrh   Vdbe *v,          /* Generate code into this VDBE */
944c926afbcSdrh   int nColumn,      /* Number of columns of data */
9456c8c8ce0Sdanielk1977   SelectDest *pDest /* Write the sorted results here */
946c926afbcSdrh ){
947dc5ea5c7Sdrh   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
948dc5ea5c7Sdrh   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
949d8bc7086Sdrh   int addr;
9500342b1f5Sdrh   int iTab;
95161fc595fSdrh   int pseudoTab = 0;
9520342b1f5Sdrh   ExprList *pOrderBy = p->pOrderBy;
953ffbc3088Sdrh 
9546c8c8ce0Sdanielk1977   int eDest = pDest->eDest;
9552b596da8Sdrh   int iParm = pDest->iSDParm;
9566c8c8ce0Sdanielk1977 
9572d401ab8Sdrh   int regRow;
9582d401ab8Sdrh   int regRowid;
9592d401ab8Sdrh 
9609d2985c7Sdrh   iTab = pOrderBy->iECursor;
9613e9ca094Sdrh   regRow = sqlite3GetTempReg(pParse);
9627d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
963cdd536f0Sdrh     pseudoTab = pParse->nTab++;
9643e9ca094Sdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
9653e9ca094Sdrh     regRowid = 0;
9663e9ca094Sdrh   }else{
9673e9ca094Sdrh     regRowid = sqlite3GetTempReg(pParse);
968cdd536f0Sdrh   }
969c6aff30cSdrh   if( p->selFlags & SF_UseSorter ){
970c2bb3282Sdrh     int regSortOut = ++pParse->nMem;
971c6aff30cSdrh     int ptab2 = pParse->nTab++;
972c6aff30cSdrh     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
973c6aff30cSdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
974c6aff30cSdrh     codeOffset(v, p, addrContinue);
975c6aff30cSdrh     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
976c6aff30cSdrh     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
977c6aff30cSdrh     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
978c6aff30cSdrh   }else{
979dc5ea5c7Sdrh     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
980dc5ea5c7Sdrh     codeOffset(v, p, addrContinue);
9812d401ab8Sdrh     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
982c6aff30cSdrh   }
983c926afbcSdrh   switch( eDest ){
984c926afbcSdrh     case SRT_Table:
985b9bb7c18Sdrh     case SRT_EphemTab: {
9861c767f0dSdrh       testcase( eDest==SRT_Table );
9871c767f0dSdrh       testcase( eDest==SRT_EphemTab );
9882d401ab8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
9892d401ab8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
9902d401ab8Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
991c926afbcSdrh       break;
992c926afbcSdrh     }
99393758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
994c926afbcSdrh     case SRT_Set: {
995c926afbcSdrh       assert( nColumn==1 );
996634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
997634d81deSdrh                         &pDest->affSdst, 1);
998da250ea5Sdrh       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
999a7a8e14bSdanielk1977       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
1000c926afbcSdrh       break;
1001c926afbcSdrh     }
1002c926afbcSdrh     case SRT_Mem: {
1003c926afbcSdrh       assert( nColumn==1 );
1004b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
1005ec7429aeSdrh       /* The LIMIT clause will terminate the loop for us */
1006c926afbcSdrh       break;
1007c926afbcSdrh     }
100893758c8dSdanielk1977 #endif
1009373cc2ddSdrh     default: {
1010ac82fcf5Sdrh       int i;
1011373cc2ddSdrh       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
10121c767f0dSdrh       testcase( eDest==SRT_Output );
10131c767f0dSdrh       testcase( eDest==SRT_Coroutine );
1014ac82fcf5Sdrh       for(i=0; i<nColumn; i++){
10152b596da8Sdrh         assert( regRow!=pDest->iSdst+i );
10162b596da8Sdrh         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
10173e9ca094Sdrh         if( i==0 ){
10183e9ca094Sdrh           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
10193e9ca094Sdrh         }
1020ac82fcf5Sdrh       }
10217d10d5a6Sdrh       if( eDest==SRT_Output ){
10222b596da8Sdrh         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
10232b596da8Sdrh         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
1024a9671a22Sdrh       }else{
10252b596da8Sdrh         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1026ce665cf6Sdrh       }
1027ac82fcf5Sdrh       break;
1028ac82fcf5Sdrh     }
1029c926afbcSdrh   }
10302d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRow);
10312d401ab8Sdrh   sqlite3ReleaseTempReg(pParse, regRowid);
1032ec7429aeSdrh 
1033ec7429aeSdrh   /* The bottom of the loop
1034ec7429aeSdrh   */
1035dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrContinue);
1036c6aff30cSdrh   if( p->selFlags & SF_UseSorter ){
1037c6aff30cSdrh     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
1038c6aff30cSdrh   }else{
103966a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
1040c6aff30cSdrh   }
1041dc5ea5c7Sdrh   sqlite3VdbeResolveLabel(v, addrBreak);
10427d10d5a6Sdrh   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
104366a5167bSdrh     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
1044cdd536f0Sdrh   }
1045d8bc7086Sdrh }
1046d8bc7086Sdrh 
1047d8bc7086Sdrh /*
1048517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the
1049517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller.
1050e78e8284Sdrh **
1051955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the
1052955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The
1053955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1054955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The
1055955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is
1056955de52cSdanielk1977 ** considered a column by this function.
1057e78e8284Sdrh **
1058955de52cSdanielk1977 **   SELECT col FROM tbl;
1059955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl;
1060955de52cSdanielk1977 **   SELECT (SELECT col FROM tbl);
1061955de52cSdanielk1977 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
1062955de52cSdanielk1977 **
1063955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL.
1064fcb78a49Sdrh */
1065955de52cSdanielk1977 static const char *columnType(
1066955de52cSdanielk1977   NameContext *pNC,
1067955de52cSdanielk1977   Expr *pExpr,
1068955de52cSdanielk1977   const char **pzOriginDb,
1069955de52cSdanielk1977   const char **pzOriginTab,
1070955de52cSdanielk1977   const char **pzOriginCol
1071955de52cSdanielk1977 ){
1072955de52cSdanielk1977   char const *zType = 0;
1073955de52cSdanielk1977   char const *zOriginDb = 0;
1074955de52cSdanielk1977   char const *zOriginTab = 0;
1075955de52cSdanielk1977   char const *zOriginCol = 0;
1076517eb646Sdanielk1977   int j;
1077373cc2ddSdrh   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
10785338a5f7Sdanielk1977 
107900e279d9Sdanielk1977   switch( pExpr->op ){
108030bcf5dbSdrh     case TK_AGG_COLUMN:
108100e279d9Sdanielk1977     case TK_COLUMN: {
1082955de52cSdanielk1977       /* The expression is a column. Locate the table the column is being
1083955de52cSdanielk1977       ** extracted from in NameContext.pSrcList. This table may be real
1084955de52cSdanielk1977       ** database table or a subquery.
1085955de52cSdanielk1977       */
1086955de52cSdanielk1977       Table *pTab = 0;            /* Table structure column is extracted from */
1087955de52cSdanielk1977       Select *pS = 0;             /* Select the column is extracted from */
1088955de52cSdanielk1977       int iCol = pExpr->iColumn;  /* Index of column in pTab */
1089373cc2ddSdrh       testcase( pExpr->op==TK_AGG_COLUMN );
1090373cc2ddSdrh       testcase( pExpr->op==TK_COLUMN );
109143bc88bbSdan       while( pNC && !pTab ){
1092b3bce662Sdanielk1977         SrcList *pTabList = pNC->pSrcList;
1093b3bce662Sdanielk1977         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1094b3bce662Sdanielk1977         if( j<pTabList->nSrc ){
10956a3ea0e6Sdrh           pTab = pTabList->a[j].pTab;
1096955de52cSdanielk1977           pS = pTabList->a[j].pSelect;
1097b3bce662Sdanielk1977         }else{
1098b3bce662Sdanielk1977           pNC = pNC->pNext;
1099b3bce662Sdanielk1977         }
1100b3bce662Sdanielk1977       }
1101955de52cSdanielk1977 
110243bc88bbSdan       if( pTab==0 ){
1103417168adSdrh         /* At one time, code such as "SELECT new.x" within a trigger would
1104417168adSdrh         ** cause this condition to run.  Since then, we have restructured how
1105417168adSdrh         ** trigger code is generated and so this condition is no longer
110643bc88bbSdan         ** possible. However, it can still be true for statements like
110743bc88bbSdan         ** the following:
110843bc88bbSdan         **
110943bc88bbSdan         **   CREATE TABLE t1(col INTEGER);
111043bc88bbSdan         **   SELECT (SELECT t1.col) FROM FROM t1;
111143bc88bbSdan         **
111243bc88bbSdan         ** when columnType() is called on the expression "t1.col" in the
111343bc88bbSdan         ** sub-select. In this case, set the column type to NULL, even
111443bc88bbSdan         ** though it should really be "INTEGER".
111543bc88bbSdan         **
111643bc88bbSdan         ** This is not a problem, as the column type of "t1.col" is never
111743bc88bbSdan         ** used. When columnType() is called on the expression
111843bc88bbSdan         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
111943bc88bbSdan         ** branch below.  */
11207e62779aSdrh         break;
11217e62779aSdrh       }
1122955de52cSdanielk1977 
112343bc88bbSdan       assert( pTab && pExpr->pTab==pTab );
1124955de52cSdanielk1977       if( pS ){
1125955de52cSdanielk1977         /* The "table" is actually a sub-select or a view in the FROM clause
1126955de52cSdanielk1977         ** of the SELECT statement. Return the declaration type and origin
1127955de52cSdanielk1977         ** data for the result-set column of the sub-select.
1128955de52cSdanielk1977         */
11297b688edeSdrh         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
1130955de52cSdanielk1977           /* If iCol is less than zero, then the expression requests the
1131955de52cSdanielk1977           ** rowid of the sub-select or view. This expression is legal (see
1132955de52cSdanielk1977           ** test case misc2.2.2) - it always evaluates to NULL.
1133955de52cSdanielk1977           */
1134955de52cSdanielk1977           NameContext sNC;
1135955de52cSdanielk1977           Expr *p = pS->pEList->a[iCol].pExpr;
1136955de52cSdanielk1977           sNC.pSrcList = pS->pSrc;
113743bc88bbSdan           sNC.pNext = pNC;
1138955de52cSdanielk1977           sNC.pParse = pNC->pParse;
1139955de52cSdanielk1977           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
1140955de52cSdanielk1977         }
11411c767f0dSdrh       }else if( ALWAYS(pTab->pSchema) ){
1142955de52cSdanielk1977         /* A real table */
1143955de52cSdanielk1977         assert( !pS );
1144fcb78a49Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1145fcb78a49Sdrh         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1146fcb78a49Sdrh         if( iCol<0 ){
1147fcb78a49Sdrh           zType = "INTEGER";
1148955de52cSdanielk1977           zOriginCol = "rowid";
1149fcb78a49Sdrh         }else{
1150fcb78a49Sdrh           zType = pTab->aCol[iCol].zType;
1151955de52cSdanielk1977           zOriginCol = pTab->aCol[iCol].zName;
1152955de52cSdanielk1977         }
1153955de52cSdanielk1977         zOriginTab = pTab->zName;
1154955de52cSdanielk1977         if( pNC->pParse ){
1155955de52cSdanielk1977           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1156955de52cSdanielk1977           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
1157955de52cSdanielk1977         }
1158fcb78a49Sdrh       }
115900e279d9Sdanielk1977       break;
1160736c22b8Sdrh     }
116193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY
116200e279d9Sdanielk1977     case TK_SELECT: {
1163955de52cSdanielk1977       /* The expression is a sub-select. Return the declaration type and
1164955de52cSdanielk1977       ** origin info for the single column in the result set of the SELECT
1165955de52cSdanielk1977       ** statement.
1166955de52cSdanielk1977       */
1167b3bce662Sdanielk1977       NameContext sNC;
11686ab3a2ecSdanielk1977       Select *pS = pExpr->x.pSelect;
1169955de52cSdanielk1977       Expr *p = pS->pEList->a[0].pExpr;
11706ab3a2ecSdanielk1977       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1171955de52cSdanielk1977       sNC.pSrcList = pS->pSrc;
1172b3bce662Sdanielk1977       sNC.pNext = pNC;
1173955de52cSdanielk1977       sNC.pParse = pNC->pParse;
1174955de52cSdanielk1977       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
117500e279d9Sdanielk1977       break;
1176fcb78a49Sdrh     }
117793758c8dSdanielk1977 #endif
117800e279d9Sdanielk1977   }
117900e279d9Sdanielk1977 
1180955de52cSdanielk1977   if( pzOriginDb ){
1181955de52cSdanielk1977     assert( pzOriginTab && pzOriginCol );
1182955de52cSdanielk1977     *pzOriginDb = zOriginDb;
1183955de52cSdanielk1977     *pzOriginTab = zOriginTab;
1184955de52cSdanielk1977     *pzOriginCol = zOriginCol;
1185955de52cSdanielk1977   }
1186517eb646Sdanielk1977   return zType;
1187517eb646Sdanielk1977 }
1188517eb646Sdanielk1977 
1189517eb646Sdanielk1977 /*
1190517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns
1191517eb646Sdanielk1977 ** in the result set.
1192517eb646Sdanielk1977 */
1193517eb646Sdanielk1977 static void generateColumnTypes(
1194517eb646Sdanielk1977   Parse *pParse,      /* Parser context */
1195517eb646Sdanielk1977   SrcList *pTabList,  /* List of tables */
1196517eb646Sdanielk1977   ExprList *pEList    /* Expressions defining the result set */
1197517eb646Sdanielk1977 ){
11983f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE
1199517eb646Sdanielk1977   Vdbe *v = pParse->pVdbe;
1200517eb646Sdanielk1977   int i;
1201b3bce662Sdanielk1977   NameContext sNC;
1202b3bce662Sdanielk1977   sNC.pSrcList = pTabList;
1203955de52cSdanielk1977   sNC.pParse = pParse;
1204517eb646Sdanielk1977   for(i=0; i<pEList->nExpr; i++){
1205517eb646Sdanielk1977     Expr *p = pEList->a[i].pExpr;
12063f913576Sdrh     const char *zType;
12073f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA
1208955de52cSdanielk1977     const char *zOrigDb = 0;
1209955de52cSdanielk1977     const char *zOrigTab = 0;
1210955de52cSdanielk1977     const char *zOrigCol = 0;
12113f913576Sdrh     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
1212955de52cSdanielk1977 
121385b623f2Sdrh     /* The vdbe must make its own copy of the column-type and other
12144b1ae99dSdanielk1977     ** column specific strings, in case the schema is reset before this
12154b1ae99dSdanielk1977     ** virtual machine is deleted.
1216fbcd585fSdanielk1977     */
121710fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
121810fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
121910fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
12203f913576Sdrh #else
12213f913576Sdrh     zType = columnType(&sNC, p, 0, 0, 0);
12223f913576Sdrh #endif
122310fb749bSdanielk1977     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
1224fcb78a49Sdrh   }
12253f913576Sdrh #endif /* SQLITE_OMIT_DECLTYPE */
1226fcb78a49Sdrh }
1227fcb78a49Sdrh 
1228fcb78a49Sdrh /*
1229fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns
1230fcb78a49Sdrh ** in the result set.  This information is used to provide the
1231fcabd464Sdrh ** azCol[] values in the callback.
123282c3d636Sdrh */
1233832508b7Sdrh static void generateColumnNames(
1234832508b7Sdrh   Parse *pParse,      /* Parser context */
1235ad3cab52Sdrh   SrcList *pTabList,  /* List of tables */
1236832508b7Sdrh   ExprList *pEList    /* Expressions defining the result set */
1237832508b7Sdrh ){
1238d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
12396a3ea0e6Sdrh   int i, j;
12409bb575fdSdrh   sqlite3 *db = pParse->db;
1241fcabd464Sdrh   int fullNames, shortNames;
1242fcabd464Sdrh 
1243fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN
12443cf86063Sdanielk1977   /* If this is an EXPLAIN, skip this step */
12453cf86063Sdanielk1977   if( pParse->explain ){
124661de0d1bSdanielk1977     return;
12473cf86063Sdanielk1977   }
12485338a5f7Sdanielk1977 #endif
12493cf86063Sdanielk1977 
1250e2f02bacSdrh   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
1251d8bc7086Sdrh   pParse->colNamesSet = 1;
1252fcabd464Sdrh   fullNames = (db->flags & SQLITE_FullColNames)!=0;
1253fcabd464Sdrh   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
125422322fd4Sdanielk1977   sqlite3VdbeSetNumCols(v, pEList->nExpr);
125582c3d636Sdrh   for(i=0; i<pEList->nExpr; i++){
125682c3d636Sdrh     Expr *p;
12575a38705eSdrh     p = pEList->a[i].pExpr;
1258373cc2ddSdrh     if( NEVER(p==0) ) continue;
125982c3d636Sdrh     if( pEList->a[i].zName ){
126082c3d636Sdrh       char *zName = pEList->a[i].zName;
126110fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
1262f018cc2eSdrh     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
12636a3ea0e6Sdrh       Table *pTab;
126497665873Sdrh       char *zCol;
12658aff1015Sdrh       int iCol = p->iColumn;
1266e2f02bacSdrh       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
1267e2f02bacSdrh         if( pTabList->a[j].iCursor==p->iTable ) break;
1268e2f02bacSdrh       }
12696a3ea0e6Sdrh       assert( j<pTabList->nSrc );
12706a3ea0e6Sdrh       pTab = pTabList->a[j].pTab;
12718aff1015Sdrh       if( iCol<0 ) iCol = pTab->iPKey;
127297665873Sdrh       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
1273b1363206Sdrh       if( iCol<0 ){
127447a6db2bSdrh         zCol = "rowid";
1275b1363206Sdrh       }else{
1276b1363206Sdrh         zCol = pTab->aCol[iCol].zName;
1277b1363206Sdrh       }
1278e49b146fSdrh       if( !shortNames && !fullNames ){
127910fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1280b7916a78Sdrh             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
12811c767f0dSdrh       }else if( fullNames ){
128282c3d636Sdrh         char *zName = 0;
12831c767f0dSdrh         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
128410fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
128582c3d636Sdrh       }else{
128610fb749bSdanielk1977         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
128782c3d636Sdrh       }
12881bee3d7bSdrh     }else{
128910fb749bSdanielk1977       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
1290b7916a78Sdrh           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
129182c3d636Sdrh     }
129282c3d636Sdrh   }
129376d505baSdanielk1977   generateColumnTypes(pParse, pTabList, pEList);
12945080aaa7Sdrh }
129582c3d636Sdrh 
1296d8bc7086Sdrh /*
12977d10d5a6Sdrh ** Given a an expression list (which is really the list of expressions
12987d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate
12997d10d5a6Sdrh ** column names for a table that would hold the expression list.
13007d10d5a6Sdrh **
13017d10d5a6Sdrh ** All column names will be unique.
13027d10d5a6Sdrh **
13037d10d5a6Sdrh ** Only the column names are computed.  Column.zType, Column.zColl,
13047d10d5a6Sdrh ** and other fields of Column are zeroed.
13057d10d5a6Sdrh **
13067d10d5a6Sdrh ** Return SQLITE_OK on success.  If a memory allocation error occurs,
13077d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
1308315555caSdrh */
13097d10d5a6Sdrh static int selectColumnsFromExprList(
13107d10d5a6Sdrh   Parse *pParse,          /* Parsing context */
13117d10d5a6Sdrh   ExprList *pEList,       /* Expr list from which to derive column names */
1312d815f17dSdrh   i16 *pnCol,             /* Write the number of columns here */
13137d10d5a6Sdrh   Column **paCol          /* Write the new column list here */
13147d10d5a6Sdrh ){
1315dc5ea5c7Sdrh   sqlite3 *db = pParse->db;   /* Database connection */
1316dc5ea5c7Sdrh   int i, j;                   /* Loop counters */
1317dc5ea5c7Sdrh   int cnt;                    /* Index added to make the name unique */
1318dc5ea5c7Sdrh   Column *aCol, *pCol;        /* For looping over result columns */
1319dc5ea5c7Sdrh   int nCol;                   /* Number of columns in the result set */
1320dc5ea5c7Sdrh   Expr *p;                    /* Expression for a single result column */
1321dc5ea5c7Sdrh   char *zName;                /* Column name */
1322dc5ea5c7Sdrh   int nName;                  /* Size of name in zName[] */
132379d5f63fSdrh 
13248c2e0f02Sdan   if( pEList ){
13258c2e0f02Sdan     nCol = pEList->nExpr;
13268c2e0f02Sdan     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
13278c2e0f02Sdan     testcase( aCol==0 );
13288c2e0f02Sdan   }else{
13298c2e0f02Sdan     nCol = 0;
13308c2e0f02Sdan     aCol = 0;
13318c2e0f02Sdan   }
13328c2e0f02Sdan   *pnCol = nCol;
13338c2e0f02Sdan   *paCol = aCol;
13348c2e0f02Sdan 
13357d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
133679d5f63fSdrh     /* Get an appropriate name for the column
133779d5f63fSdrh     */
1338580c8c18Sdrh     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
133991bb0eedSdrh     if( (zName = pEList->a[i].zName)!=0 ){
134079d5f63fSdrh       /* If the column contains an "AS <name>" phrase, use <name> as the name */
134117435752Sdrh       zName = sqlite3DbStrDup(db, zName);
13427d10d5a6Sdrh     }else{
1343dc5ea5c7Sdrh       Expr *pColExpr = p;  /* The expression that is the result column name */
1344dc5ea5c7Sdrh       Table *pTab;         /* Table associated with this expression */
1345b07028f7Sdrh       while( pColExpr->op==TK_DOT ){
1346b07028f7Sdrh         pColExpr = pColExpr->pRight;
1347b07028f7Sdrh         assert( pColExpr!=0 );
1348b07028f7Sdrh       }
1349373cc2ddSdrh       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
135093a960a0Sdrh         /* For columns use the column name name */
1351dc5ea5c7Sdrh         int iCol = pColExpr->iColumn;
1352373cc2ddSdrh         pTab = pColExpr->pTab;
1353f0209f74Sdrh         if( iCol<0 ) iCol = pTab->iPKey;
1354f0209f74Sdrh         zName = sqlite3MPrintf(db, "%s",
1355f0209f74Sdrh                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
1356b7916a78Sdrh       }else if( pColExpr->op==TK_ID ){
135733e619fcSdrh         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
135833e619fcSdrh         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
135993a960a0Sdrh       }else{
136079d5f63fSdrh         /* Use the original text of the column expression as its name */
1361b7916a78Sdrh         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
13627d10d5a6Sdrh       }
136322f70c32Sdrh     }
13647ce72f69Sdrh     if( db->mallocFailed ){
1365633e6d57Sdrh       sqlite3DbFree(db, zName);
13667ce72f69Sdrh       break;
1367dd5b2fa5Sdrh     }
136879d5f63fSdrh 
136979d5f63fSdrh     /* Make sure the column name is unique.  If the name is not unique,
137079d5f63fSdrh     ** append a integer to the name so that it becomes unique.
137179d5f63fSdrh     */
1372ea678832Sdrh     nName = sqlite3Strlen30(zName);
137379d5f63fSdrh     for(j=cnt=0; j<i; j++){
137479d5f63fSdrh       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
1375633e6d57Sdrh         char *zNewName;
1376fb777327Sdrh         int k;
1377fb777327Sdrh         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
1378fb777327Sdrh         if( zName[k]==':' ) nName = k;
13792564ef97Sdrh         zName[nName] = 0;
1380633e6d57Sdrh         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
1381633e6d57Sdrh         sqlite3DbFree(db, zName);
1382633e6d57Sdrh         zName = zNewName;
138379d5f63fSdrh         j = -1;
1384dd5b2fa5Sdrh         if( zName==0 ) break;
138579d5f63fSdrh       }
138679d5f63fSdrh     }
138791bb0eedSdrh     pCol->zName = zName;
13887d10d5a6Sdrh   }
13897d10d5a6Sdrh   if( db->mallocFailed ){
13907d10d5a6Sdrh     for(j=0; j<i; j++){
13917d10d5a6Sdrh       sqlite3DbFree(db, aCol[j].zName);
13927d10d5a6Sdrh     }
13937d10d5a6Sdrh     sqlite3DbFree(db, aCol);
13947d10d5a6Sdrh     *paCol = 0;
13957d10d5a6Sdrh     *pnCol = 0;
13967d10d5a6Sdrh     return SQLITE_NOMEM;
13977d10d5a6Sdrh   }
13987d10d5a6Sdrh   return SQLITE_OK;
13997d10d5a6Sdrh }
1400e014a838Sdanielk1977 
14017d10d5a6Sdrh /*
14027d10d5a6Sdrh ** Add type and collation information to a column list based on
14037d10d5a6Sdrh ** a SELECT statement.
14047d10d5a6Sdrh **
14057d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList().
14067d10d5a6Sdrh ** The column list has only names, not types or collations.  This
14077d10d5a6Sdrh ** routine goes through and adds the types and collations.
14087d10d5a6Sdrh **
1409b08a67a7Sshane ** This routine requires that all identifiers in the SELECT
14107d10d5a6Sdrh ** statement be resolved.
141179d5f63fSdrh */
14127d10d5a6Sdrh static void selectAddColumnTypeAndCollation(
14137d10d5a6Sdrh   Parse *pParse,        /* Parsing contexts */
14147d10d5a6Sdrh   int nCol,             /* Number of columns */
14157d10d5a6Sdrh   Column *aCol,         /* List of columns */
14167d10d5a6Sdrh   Select *pSelect       /* SELECT used to determine types and collations */
14177d10d5a6Sdrh ){
14187d10d5a6Sdrh   sqlite3 *db = pParse->db;
14197d10d5a6Sdrh   NameContext sNC;
14207d10d5a6Sdrh   Column *pCol;
14217d10d5a6Sdrh   CollSeq *pColl;
14227d10d5a6Sdrh   int i;
14237d10d5a6Sdrh   Expr *p;
14247d10d5a6Sdrh   struct ExprList_item *a;
14257d10d5a6Sdrh 
14267d10d5a6Sdrh   assert( pSelect!=0 );
14277d10d5a6Sdrh   assert( (pSelect->selFlags & SF_Resolved)!=0 );
14287d10d5a6Sdrh   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
14297d10d5a6Sdrh   if( db->mallocFailed ) return;
1430c43e8be8Sdrh   memset(&sNC, 0, sizeof(sNC));
1431b3bce662Sdanielk1977   sNC.pSrcList = pSelect->pSrc;
14327d10d5a6Sdrh   a = pSelect->pEList->a;
14337d10d5a6Sdrh   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
14347d10d5a6Sdrh     p = a[i].pExpr;
14357d10d5a6Sdrh     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
1436c60e9b82Sdanielk1977     pCol->affinity = sqlite3ExprAffinity(p);
1437c4a64facSdrh     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
1438b3bf556eSdanielk1977     pColl = sqlite3ExprCollSeq(pParse, p);
1439b3bf556eSdanielk1977     if( pColl ){
144017435752Sdrh       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
14410202b29eSdanielk1977     }
144222f70c32Sdrh   }
14437d10d5a6Sdrh }
14447d10d5a6Sdrh 
14457d10d5a6Sdrh /*
14467d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes
14477d10d5a6Sdrh ** the result set of that SELECT.
14487d10d5a6Sdrh */
14497d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
14507d10d5a6Sdrh   Table *pTab;
14517d10d5a6Sdrh   sqlite3 *db = pParse->db;
14527d10d5a6Sdrh   int savedFlags;
14537d10d5a6Sdrh 
14547d10d5a6Sdrh   savedFlags = db->flags;
14557d10d5a6Sdrh   db->flags &= ~SQLITE_FullColNames;
14567d10d5a6Sdrh   db->flags |= SQLITE_ShortColNames;
14577d10d5a6Sdrh   sqlite3SelectPrep(pParse, pSelect, 0);
14587d10d5a6Sdrh   if( pParse->nErr ) return 0;
14597d10d5a6Sdrh   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
14607d10d5a6Sdrh   db->flags = savedFlags;
14617d10d5a6Sdrh   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
14627d10d5a6Sdrh   if( pTab==0 ){
14637d10d5a6Sdrh     return 0;
14647d10d5a6Sdrh   }
1465373cc2ddSdrh   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
1466b2468954Sdrh   ** is disabled */
1467373cc2ddSdrh   assert( db->lookaside.bEnabled==0 );
14687d10d5a6Sdrh   pTab->nRef = 1;
14697d10d5a6Sdrh   pTab->zName = 0;
14701ea87012Sdrh   pTab->nRowEst = 1000000;
14717d10d5a6Sdrh   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
14727d10d5a6Sdrh   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
147322f70c32Sdrh   pTab->iPKey = -1;
14747ce72f69Sdrh   if( db->mallocFailed ){
14751feeaed2Sdan     sqlite3DeleteTable(db, pTab);
14767ce72f69Sdrh     return 0;
14777ce72f69Sdrh   }
147822f70c32Sdrh   return pTab;
147922f70c32Sdrh }
148022f70c32Sdrh 
148122f70c32Sdrh /*
1482d8bc7086Sdrh ** Get a VDBE for the given parser context.  Create a new one if necessary.
1483d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse.
1484d8bc7086Sdrh */
14854adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){
1486d8bc7086Sdrh   Vdbe *v = pParse->pVdbe;
1487d8bc7086Sdrh   if( v==0 ){
14884adee20fSdanielk1977     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
1489949f9cd5Sdrh #ifndef SQLITE_OMIT_TRACE
1490949f9cd5Sdrh     if( v ){
1491949f9cd5Sdrh       sqlite3VdbeAddOp0(v, OP_Trace);
1492949f9cd5Sdrh     }
1493949f9cd5Sdrh #endif
1494d8bc7086Sdrh   }
1495d8bc7086Sdrh   return v;
1496d8bc7086Sdrh }
1497d8bc7086Sdrh 
149815007a99Sdrh 
1499d8bc7086Sdrh /*
15007b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the
1501ec7429aeSdrh ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
15027b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET
1503a2dc3b1aSdanielk1977 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
1504a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute
1505a2dc3b1aSdanielk1977 ** the limit and offset.  If there is no limit and/or offset, then
1506a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative.
15077b58daeaSdrh **
1508d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if
1509ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset.  iLimit and
15107b58daeaSdrh ** iOffset should have been preset to appropriate default values
15117b58daeaSdrh ** (usually but not always -1) prior to calling this routine.
1512ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
15137b58daeaSdrh ** redefined.  The UNION ALL operator uses this property to force
15147b58daeaSdrh ** the reuse of the same limit and offset registers across multiple
15157b58daeaSdrh ** SELECT statements.
15167b58daeaSdrh */
1517ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
151802afc861Sdrh   Vdbe *v = 0;
151902afc861Sdrh   int iLimit = 0;
152015007a99Sdrh   int iOffset;
15219b918ed1Sdrh   int addr1, n;
15220acb7e48Sdrh   if( p->iLimit ) return;
152315007a99Sdrh 
15247b58daeaSdrh   /*
15257b58daeaSdrh   ** "LIMIT -1" always shows all rows.  There is some
15267b58daeaSdrh   ** contraversy about what the correct behavior should be.
15277b58daeaSdrh   ** The current implementation interprets "LIMIT 0" to mean
15287b58daeaSdrh   ** no rows.
15297b58daeaSdrh   */
1530ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
1531373cc2ddSdrh   assert( p->pOffset==0 || p->pLimit!=0 );
1532a2dc3b1aSdanielk1977   if( p->pLimit ){
15330a07c107Sdrh     p->iLimit = iLimit = ++pParse->nMem;
153415007a99Sdrh     v = sqlite3GetVdbe(pParse);
1535373cc2ddSdrh     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
15369b918ed1Sdrh     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
15379b918ed1Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
15389b918ed1Sdrh       VdbeComment((v, "LIMIT counter"));
1539456e4e4fSdrh       if( n==0 ){
1540456e4e4fSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
154195aa47b1Sdrh       }else{
154295aa47b1Sdrh         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
15439b918ed1Sdrh       }
15449b918ed1Sdrh     }else{
1545b7654111Sdrh       sqlite3ExprCode(pParse, p->pLimit, iLimit);
1546b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
1547d4e70ebdSdrh       VdbeComment((v, "LIMIT counter"));
15483c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
15499b918ed1Sdrh     }
1550a2dc3b1aSdanielk1977     if( p->pOffset ){
15510a07c107Sdrh       p->iOffset = iOffset = ++pParse->nMem;
1552b7654111Sdrh       pParse->nMem++;   /* Allocate an extra register for limit+offset */
1553b7654111Sdrh       sqlite3ExprCode(pParse, p->pOffset, iOffset);
1554b7654111Sdrh       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
1555d4e70ebdSdrh       VdbeComment((v, "OFFSET counter"));
15563c84ddffSdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
1557b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
155815007a99Sdrh       sqlite3VdbeJumpHere(v, addr1);
1559b7654111Sdrh       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
1560d4e70ebdSdrh       VdbeComment((v, "LIMIT+OFFSET"));
1561b7654111Sdrh       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
1562b7654111Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
1563b7654111Sdrh       sqlite3VdbeJumpHere(v, addr1);
1564b7654111Sdrh     }
1565d59ba6ceSdrh   }
15667b58daeaSdrh }
15677b58daeaSdrh 
1568b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1569fbc4ee7bSdrh /*
1570fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of
1571fbc4ee7bSdrh ** the result set for the compound-select statement "p".  Return NULL if
1572fbc4ee7bSdrh ** the column has no default collating sequence.
1573fbc4ee7bSdrh **
1574fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the
1575fbc4ee7bSdrh ** left-most term of the select that has a collating sequence.
1576fbc4ee7bSdrh */
1577dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
1578fbc4ee7bSdrh   CollSeq *pRet;
1579dc1bdc4fSdanielk1977   if( p->pPrior ){
1580dc1bdc4fSdanielk1977     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
1581fbc4ee7bSdrh   }else{
1582fbc4ee7bSdrh     pRet = 0;
1583dc1bdc4fSdanielk1977   }
158410c081adSdrh   assert( iCol>=0 );
158510c081adSdrh   if( pRet==0 && iCol<p->pEList->nExpr ){
1586dc1bdc4fSdanielk1977     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
1587dc1bdc4fSdanielk1977   }
1588dc1bdc4fSdanielk1977   return pRet;
1589d3d39e93Sdrh }
1590b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1591d3d39e93Sdrh 
1592b21e7c70Sdrh /* Forward reference */
1593b21e7c70Sdrh static int multiSelectOrderBy(
1594b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
1595b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
1596a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
1597b21e7c70Sdrh );
1598b21e7c70Sdrh 
1599b21e7c70Sdrh 
1600b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT
1601d3d39e93Sdrh /*
160216ee60ffSdrh ** This routine is called to process a compound query form from
160316ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
160416ee60ffSdrh ** INTERSECT
1605c926afbcSdrh **
1606e78e8284Sdrh ** "p" points to the right-most of the two queries.  the query on the
1607e78e8284Sdrh ** left is p->pPrior.  The left query could also be a compound query
1608e78e8284Sdrh ** in which case this routine will be called recursively.
1609e78e8284Sdrh **
1610e78e8284Sdrh ** The results of the total query are to be written into a destination
1611e78e8284Sdrh ** of type eDest with parameter iParm.
1612e78e8284Sdrh **
1613e78e8284Sdrh ** Example 1:  Consider a three-way compound SQL statement.
1614e78e8284Sdrh **
1615e78e8284Sdrh **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
1616e78e8284Sdrh **
1617e78e8284Sdrh ** This statement is parsed up as follows:
1618e78e8284Sdrh **
1619e78e8284Sdrh **     SELECT c FROM t3
1620e78e8284Sdrh **      |
1621e78e8284Sdrh **      `----->  SELECT b FROM t2
1622e78e8284Sdrh **                |
16234b11c6d3Sjplyon **                `------>  SELECT a FROM t1
1624e78e8284Sdrh **
1625e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer.
1626e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then
1627e78e8284Sdrh ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
1628e78e8284Sdrh **
1629e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the
1630e78e8284Sdrh ** individual selects always group from left to right.
163182c3d636Sdrh */
163284ac9d02Sdanielk1977 static int multiSelect(
1633fbc4ee7bSdrh   Parse *pParse,        /* Parsing context */
1634fbc4ee7bSdrh   Select *p,            /* The right-most of SELECTs to be coded */
1635a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
163684ac9d02Sdanielk1977 ){
163784ac9d02Sdanielk1977   int rc = SQLITE_OK;   /* Success code from a subroutine */
163810e5e3cfSdrh   Select *pPrior;       /* Another SELECT immediately to our left */
163910e5e3cfSdrh   Vdbe *v;              /* Generate code to this VDBE */
16401013c932Sdrh   SelectDest dest;      /* Alternative data destination */
1641eca7e01aSdanielk1977   Select *pDelete = 0;  /* Chain of simple selects to delete */
1642633e6d57Sdrh   sqlite3 *db;          /* Database connection */
16437f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
16447f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
16457f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
16467f61e92cSdan #endif
164782c3d636Sdrh 
16487b58daeaSdrh   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
1649fbc4ee7bSdrh   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
165082c3d636Sdrh   */
1651701bb3b4Sdrh   assert( p && p->pPrior );  /* Calling function guarantees this much */
1652633e6d57Sdrh   db = pParse->db;
1653d8bc7086Sdrh   pPrior = p->pPrior;
16540342b1f5Sdrh   assert( pPrior->pRightmost!=pPrior );
16550342b1f5Sdrh   assert( pPrior->pRightmost==p->pRightmost );
1656bc10377aSdrh   dest = *pDest;
1657d8bc7086Sdrh   if( pPrior->pOrderBy ){
16584adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
1659da93d238Sdrh       selectOpName(p->op));
166084ac9d02Sdanielk1977     rc = 1;
166184ac9d02Sdanielk1977     goto multi_select_end;
166282c3d636Sdrh   }
1663a2dc3b1aSdanielk1977   if( pPrior->pLimit ){
16644adee20fSdanielk1977     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
16657b58daeaSdrh       selectOpName(p->op));
166684ac9d02Sdanielk1977     rc = 1;
166784ac9d02Sdanielk1977     goto multi_select_end;
16687b58daeaSdrh   }
166982c3d636Sdrh 
16704adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
1671701bb3b4Sdrh   assert( v!=0 );  /* The VDBE already created by calling function */
1672d8bc7086Sdrh 
16731cc3d75fSdrh   /* Create the destination temporary table if necessary
16741cc3d75fSdrh   */
16756c8c8ce0Sdanielk1977   if( dest.eDest==SRT_EphemTab ){
1676b4964b72Sdanielk1977     assert( p->pEList );
16772b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
1678d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
16796c8c8ce0Sdanielk1977     dest.eDest = SRT_Table;
16801cc3d75fSdrh   }
16811cc3d75fSdrh 
1682f6e369a1Sdrh   /* Make sure all SELECTs in the statement have the same number of elements
1683f6e369a1Sdrh   ** in their result sets.
1684f6e369a1Sdrh   */
1685f6e369a1Sdrh   assert( p->pEList && pPrior->pEList );
1686f6e369a1Sdrh   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
16877b113babSdrh     if( p->selFlags & SF_Values ){
16887b113babSdrh       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
16897b113babSdrh     }else{
1690f6e369a1Sdrh       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
1691f6e369a1Sdrh         " do not have the same number of result columns", selectOpName(p->op));
16927b113babSdrh     }
1693f6e369a1Sdrh     rc = 1;
1694f6e369a1Sdrh     goto multi_select_end;
1695f6e369a1Sdrh   }
1696f6e369a1Sdrh 
1697a9671a22Sdrh   /* Compound SELECTs that have an ORDER BY clause are handled separately.
1698a9671a22Sdrh   */
1699f6e369a1Sdrh   if( p->pOrderBy ){
1700a9671a22Sdrh     return multiSelectOrderBy(pParse, p, pDest);
1701f6e369a1Sdrh   }
1702f6e369a1Sdrh 
1703f46f905aSdrh   /* Generate code for the left and right SELECT statements.
1704d8bc7086Sdrh   */
170582c3d636Sdrh   switch( p->op ){
1706f46f905aSdrh     case TK_ALL: {
1707ec7429aeSdrh       int addr = 0;
170895aa47b1Sdrh       int nLimit;
1709a2dc3b1aSdanielk1977       assert( !pPrior->pLimit );
1710547180baSdrh       pPrior->iLimit = p->iLimit;
1711547180baSdrh       pPrior->iOffset = p->iOffset;
1712a2dc3b1aSdanielk1977       pPrior->pLimit = p->pLimit;
1713a2dc3b1aSdanielk1977       pPrior->pOffset = p->pOffset;
17147f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
17157d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &dest);
1716ad68cb6bSdanielk1977       p->pLimit = 0;
1717ad68cb6bSdanielk1977       p->pOffset = 0;
171884ac9d02Sdanielk1977       if( rc ){
171984ac9d02Sdanielk1977         goto multi_select_end;
172084ac9d02Sdanielk1977       }
1721f46f905aSdrh       p->pPrior = 0;
17227b58daeaSdrh       p->iLimit = pPrior->iLimit;
17237b58daeaSdrh       p->iOffset = pPrior->iOffset;
172492b01d53Sdrh       if( p->iLimit ){
17253c84ddffSdrh         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
1726d4e70ebdSdrh         VdbeComment((v, "Jump ahead if LIMIT reached"));
1727ec7429aeSdrh       }
17287f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
17297d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &dest);
1730373cc2ddSdrh       testcase( rc!=SQLITE_OK );
1731eca7e01aSdanielk1977       pDelete = p->pPrior;
1732f46f905aSdrh       p->pPrior = pPrior;
173395aa47b1Sdrh       p->nSelectRow += pPrior->nSelectRow;
173495aa47b1Sdrh       if( pPrior->pLimit
173595aa47b1Sdrh        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
173695aa47b1Sdrh        && p->nSelectRow > (double)nLimit
173795aa47b1Sdrh       ){
173895aa47b1Sdrh         p->nSelectRow = (double)nLimit;
173995aa47b1Sdrh       }
1740ec7429aeSdrh       if( addr ){
1741ec7429aeSdrh         sqlite3VdbeJumpHere(v, addr);
1742ec7429aeSdrh       }
1743f46f905aSdrh       break;
1744f46f905aSdrh     }
174582c3d636Sdrh     case TK_EXCEPT:
174682c3d636Sdrh     case TK_UNION: {
1747d8bc7086Sdrh       int unionTab;    /* Cursor number of the temporary table holding result */
1748ea678832Sdrh       u8 op = 0;       /* One of the SRT_ operations to apply to self */
1749d8bc7086Sdrh       int priorOp;     /* The SRT_ operation to apply to prior selects */
1750a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
1751dc1bdc4fSdanielk1977       int addr;
17526c8c8ce0Sdanielk1977       SelectDest uniondest;
175382c3d636Sdrh 
1754373cc2ddSdrh       testcase( p->op==TK_EXCEPT );
1755373cc2ddSdrh       testcase( p->op==TK_UNION );
175693a960a0Sdrh       priorOp = SRT_Union;
1757e2f02bacSdrh       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
1758d8bc7086Sdrh         /* We can reuse a temporary table generated by a SELECT to our
1759c926afbcSdrh         ** right.
1760d8bc7086Sdrh         */
1761e2f02bacSdrh         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
1762e2f02bacSdrh                                      ** of a 3-way or more compound */
1763e2f02bacSdrh         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
1764e2f02bacSdrh         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
17652b596da8Sdrh         unionTab = dest.iSDParm;
176682c3d636Sdrh       }else{
1767d8bc7086Sdrh         /* We will need to create our own temporary table to hold the
1768d8bc7086Sdrh         ** intermediate results.
1769d8bc7086Sdrh         */
177082c3d636Sdrh         unionTab = pParse->nTab++;
177193a960a0Sdrh         assert( p->pOrderBy==0 );
177266a5167bSdrh         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
1773b9bb7c18Sdrh         assert( p->addrOpenEphm[0] == -1 );
1774b9bb7c18Sdrh         p->addrOpenEphm[0] = addr;
17757d10d5a6Sdrh         p->pRightmost->selFlags |= SF_UsesEphemeral;
177684ac9d02Sdanielk1977         assert( p->pEList );
1777d8bc7086Sdrh       }
1778d8bc7086Sdrh 
1779d8bc7086Sdrh       /* Code the SELECT statements to our left
1780d8bc7086Sdrh       */
1781b3bce662Sdanielk1977       assert( !pPrior->pOrderBy );
17821013c932Sdrh       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
17837f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
17847d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &uniondest);
178584ac9d02Sdanielk1977       if( rc ){
178684ac9d02Sdanielk1977         goto multi_select_end;
178784ac9d02Sdanielk1977       }
1788d8bc7086Sdrh 
1789d8bc7086Sdrh       /* Code the current SELECT statement
1790d8bc7086Sdrh       */
17914cfb22f7Sdrh       if( p->op==TK_EXCEPT ){
17924cfb22f7Sdrh         op = SRT_Except;
17934cfb22f7Sdrh       }else{
17944cfb22f7Sdrh         assert( p->op==TK_UNION );
17954cfb22f7Sdrh         op = SRT_Union;
1796d8bc7086Sdrh       }
179782c3d636Sdrh       p->pPrior = 0;
1798a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1799a2dc3b1aSdanielk1977       p->pLimit = 0;
1800a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1801a2dc3b1aSdanielk1977       p->pOffset = 0;
18026c8c8ce0Sdanielk1977       uniondest.eDest = op;
18037f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
18047d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &uniondest);
1805373cc2ddSdrh       testcase( rc!=SQLITE_OK );
18065bd1bf2eSdrh       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
18075bd1bf2eSdrh       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
1808633e6d57Sdrh       sqlite3ExprListDelete(db, p->pOrderBy);
1809eca7e01aSdanielk1977       pDelete = p->pPrior;
181082c3d636Sdrh       p->pPrior = pPrior;
1811a9671a22Sdrh       p->pOrderBy = 0;
181295aa47b1Sdrh       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
1813633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1814a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1815a2dc3b1aSdanielk1977       p->pOffset = pOffset;
181692b01d53Sdrh       p->iLimit = 0;
181792b01d53Sdrh       p->iOffset = 0;
1818d8bc7086Sdrh 
1819d8bc7086Sdrh       /* Convert the data in the temporary table into whatever form
1820d8bc7086Sdrh       ** it is that we currently need.
1821d8bc7086Sdrh       */
18222b596da8Sdrh       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
1823373cc2ddSdrh       if( dest.eDest!=priorOp ){
18246b56344dSdrh         int iCont, iBreak, iStart;
182582c3d636Sdrh         assert( p->pEList );
18267d10d5a6Sdrh         if( dest.eDest==SRT_Output ){
182792378253Sdrh           Select *pFirst = p;
182892378253Sdrh           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
182992378253Sdrh           generateColumnNames(pParse, 0, pFirst->pEList);
183041202ccaSdrh         }
18314adee20fSdanielk1977         iBreak = sqlite3VdbeMakeLabel(v);
18324adee20fSdanielk1977         iCont = sqlite3VdbeMakeLabel(v);
1833ec7429aeSdrh         computeLimitRegisters(pParse, p, iBreak);
183466a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
18354adee20fSdanielk1977         iStart = sqlite3VdbeCurrentAddr(v);
1836d2b3e23bSdrh         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
1837e8e4af76Sdrh                         0, 0, &dest, iCont, iBreak);
18384adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iCont);
183966a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
18404adee20fSdanielk1977         sqlite3VdbeResolveLabel(v, iBreak);
184166a5167bSdrh         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
184282c3d636Sdrh       }
184382c3d636Sdrh       break;
184482c3d636Sdrh     }
1845373cc2ddSdrh     default: assert( p->op==TK_INTERSECT ); {
184682c3d636Sdrh       int tab1, tab2;
18476b56344dSdrh       int iCont, iBreak, iStart;
1848a2dc3b1aSdanielk1977       Expr *pLimit, *pOffset;
1849dc1bdc4fSdanielk1977       int addr;
18501013c932Sdrh       SelectDest intersectdest;
18519cbf3425Sdrh       int r1;
185282c3d636Sdrh 
1853d8bc7086Sdrh       /* INTERSECT is different from the others since it requires
18546206d50aSdrh       ** two temporary tables.  Hence it has its own case.  Begin
1855d8bc7086Sdrh       ** by allocating the tables we will need.
1856d8bc7086Sdrh       */
185782c3d636Sdrh       tab1 = pParse->nTab++;
185882c3d636Sdrh       tab2 = pParse->nTab++;
185993a960a0Sdrh       assert( p->pOrderBy==0 );
1860dc1bdc4fSdanielk1977 
186166a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
1862b9bb7c18Sdrh       assert( p->addrOpenEphm[0] == -1 );
1863b9bb7c18Sdrh       p->addrOpenEphm[0] = addr;
18647d10d5a6Sdrh       p->pRightmost->selFlags |= SF_UsesEphemeral;
186584ac9d02Sdanielk1977       assert( p->pEList );
1866d8bc7086Sdrh 
1867d8bc7086Sdrh       /* Code the SELECTs to our left into temporary table "tab1".
1868d8bc7086Sdrh       */
18691013c932Sdrh       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
18707f61e92cSdan       explainSetInteger(iSub1, pParse->iNextSelectId);
18717d10d5a6Sdrh       rc = sqlite3Select(pParse, pPrior, &intersectdest);
187284ac9d02Sdanielk1977       if( rc ){
187384ac9d02Sdanielk1977         goto multi_select_end;
187484ac9d02Sdanielk1977       }
1875d8bc7086Sdrh 
1876d8bc7086Sdrh       /* Code the current SELECT into temporary table "tab2"
1877d8bc7086Sdrh       */
187866a5167bSdrh       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
1879b9bb7c18Sdrh       assert( p->addrOpenEphm[1] == -1 );
1880b9bb7c18Sdrh       p->addrOpenEphm[1] = addr;
188182c3d636Sdrh       p->pPrior = 0;
1882a2dc3b1aSdanielk1977       pLimit = p->pLimit;
1883a2dc3b1aSdanielk1977       p->pLimit = 0;
1884a2dc3b1aSdanielk1977       pOffset = p->pOffset;
1885a2dc3b1aSdanielk1977       p->pOffset = 0;
18862b596da8Sdrh       intersectdest.iSDParm = tab2;
18877f61e92cSdan       explainSetInteger(iSub2, pParse->iNextSelectId);
18887d10d5a6Sdrh       rc = sqlite3Select(pParse, p, &intersectdest);
1889373cc2ddSdrh       testcase( rc!=SQLITE_OK );
1890eca7e01aSdanielk1977       pDelete = p->pPrior;
189182c3d636Sdrh       p->pPrior = pPrior;
189295aa47b1Sdrh       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
1893633e6d57Sdrh       sqlite3ExprDelete(db, p->pLimit);
1894a2dc3b1aSdanielk1977       p->pLimit = pLimit;
1895a2dc3b1aSdanielk1977       p->pOffset = pOffset;
1896d8bc7086Sdrh 
1897d8bc7086Sdrh       /* Generate code to take the intersection of the two temporary
1898d8bc7086Sdrh       ** tables.
1899d8bc7086Sdrh       */
190082c3d636Sdrh       assert( p->pEList );
19017d10d5a6Sdrh       if( dest.eDest==SRT_Output ){
190292378253Sdrh         Select *pFirst = p;
190392378253Sdrh         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
190492378253Sdrh         generateColumnNames(pParse, 0, pFirst->pEList);
190541202ccaSdrh       }
19064adee20fSdanielk1977       iBreak = sqlite3VdbeMakeLabel(v);
19074adee20fSdanielk1977       iCont = sqlite3VdbeMakeLabel(v);
1908ec7429aeSdrh       computeLimitRegisters(pParse, p, iBreak);
190966a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
19109cbf3425Sdrh       r1 = sqlite3GetTempReg(pParse);
19119cbf3425Sdrh       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
19128cff69dfSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
19139cbf3425Sdrh       sqlite3ReleaseTempReg(pParse, r1);
1914d2b3e23bSdrh       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
1915e8e4af76Sdrh                       0, 0, &dest, iCont, iBreak);
19164adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iCont);
191766a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
19184adee20fSdanielk1977       sqlite3VdbeResolveLabel(v, iBreak);
191966a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
192066a5167bSdrh       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
192182c3d636Sdrh       break;
192282c3d636Sdrh     }
192382c3d636Sdrh   }
19248cdbf836Sdrh 
19257f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
19267f61e92cSdan 
1927a9671a22Sdrh   /* Compute collating sequences used by
1928a9671a22Sdrh   ** temporary tables needed to implement the compound select.
1929a9671a22Sdrh   ** Attach the KeyInfo structure to all temporary tables.
19308cdbf836Sdrh   **
19318cdbf836Sdrh   ** This section is run by the right-most SELECT statement only.
19328cdbf836Sdrh   ** SELECT statements to the left always skip this part.  The right-most
19338cdbf836Sdrh   ** SELECT might also skip this part if it has no ORDER BY clause and
19348cdbf836Sdrh   ** no temp tables are required.
1935fbc4ee7bSdrh   */
19367d10d5a6Sdrh   if( p->selFlags & SF_UsesEphemeral ){
1937fbc4ee7bSdrh     int i;                        /* Loop counter */
1938fbc4ee7bSdrh     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
19390342b1f5Sdrh     Select *pLoop;                /* For looping through SELECT statements */
1940f68d7d17Sdrh     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
194193a960a0Sdrh     int nCol;                     /* Number of columns in result set */
1942fbc4ee7bSdrh 
19430342b1f5Sdrh     assert( p->pRightmost==p );
194493a960a0Sdrh     nCol = p->pEList->nExpr;
1945633e6d57Sdrh     pKeyInfo = sqlite3DbMallocZero(db,
1946a9671a22Sdrh                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
1947dc1bdc4fSdanielk1977     if( !pKeyInfo ){
1948dc1bdc4fSdanielk1977       rc = SQLITE_NOMEM;
1949dc1bdc4fSdanielk1977       goto multi_select_end;
1950dc1bdc4fSdanielk1977     }
1951dc1bdc4fSdanielk1977 
1952633e6d57Sdrh     pKeyInfo->enc = ENC(db);
1953ea678832Sdrh     pKeyInfo->nField = (u16)nCol;
1954dc1bdc4fSdanielk1977 
19550342b1f5Sdrh     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
19560342b1f5Sdrh       *apColl = multiSelectCollSeq(pParse, p, i);
19570342b1f5Sdrh       if( 0==*apColl ){
1958633e6d57Sdrh         *apColl = db->pDfltColl;
1959dc1bdc4fSdanielk1977       }
1960dc1bdc4fSdanielk1977     }
1961e1a022e4Sdrh     pKeyInfo->aSortOrder = (u8*)apColl;
1962dc1bdc4fSdanielk1977 
19630342b1f5Sdrh     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
19640342b1f5Sdrh       for(i=0; i<2; i++){
1965b9bb7c18Sdrh         int addr = pLoop->addrOpenEphm[i];
19660342b1f5Sdrh         if( addr<0 ){
19670342b1f5Sdrh           /* If [0] is unused then [1] is also unused.  So we can
19680342b1f5Sdrh           ** always safely abort as soon as the first unused slot is found */
1969b9bb7c18Sdrh           assert( pLoop->addrOpenEphm[1]<0 );
19700342b1f5Sdrh           break;
19710342b1f5Sdrh         }
19720342b1f5Sdrh         sqlite3VdbeChangeP2(v, addr, nCol);
197366a5167bSdrh         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
19740ee5a1e7Sdrh         pLoop->addrOpenEphm[i] = -1;
19750342b1f5Sdrh       }
1976dc1bdc4fSdanielk1977     }
1977633e6d57Sdrh     sqlite3DbFree(db, pKeyInfo);
1978dc1bdc4fSdanielk1977   }
1979dc1bdc4fSdanielk1977 
1980dc1bdc4fSdanielk1977 multi_select_end:
19812b596da8Sdrh   pDest->iSdst = dest.iSdst;
19822b596da8Sdrh   pDest->nSdst = dest.nSdst;
1983633e6d57Sdrh   sqlite3SelectDelete(db, pDelete);
198484ac9d02Sdanielk1977   return rc;
19852282792aSdrh }
1986b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */
19872282792aSdrh 
1988b21e7c70Sdrh /*
1989b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a
1990b21e7c70Sdrh ** SELECT statment.
19910acb7e48Sdrh **
19922b596da8Sdrh ** The data to be output is contained in pIn->iSdst.  There are
19932b596da8Sdrh ** pIn->nSdst columns to be output.  pDest is where the output should
19940acb7e48Sdrh ** be sent.
19950acb7e48Sdrh **
19960acb7e48Sdrh ** regReturn is the number of the register holding the subroutine
19970acb7e48Sdrh ** return address.
19980acb7e48Sdrh **
1999f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that
20000acb7e48Sdrh ** records the previous output.  mem[regPrev] is a flag that is false
20010acb7e48Sdrh ** if there has been no previous output.  If regPrev>0 then code is
20020acb7e48Sdrh ** generated to suppress duplicates.  pKeyInfo is used for comparing
20030acb7e48Sdrh ** keys.
20040acb7e48Sdrh **
20050acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to
20060acb7e48Sdrh ** iBreak.
2007b21e7c70Sdrh */
20080acb7e48Sdrh static int generateOutputSubroutine(
200992b01d53Sdrh   Parse *pParse,          /* Parsing context */
201092b01d53Sdrh   Select *p,              /* The SELECT statement */
201192b01d53Sdrh   SelectDest *pIn,        /* Coroutine supplying data */
201292b01d53Sdrh   SelectDest *pDest,      /* Where to send the data */
201392b01d53Sdrh   int regReturn,          /* The return address register */
20140acb7e48Sdrh   int regPrev,            /* Previous result register.  No uniqueness if 0 */
20150acb7e48Sdrh   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
20160acb7e48Sdrh   int p4type,             /* The p4 type for pKeyInfo */
201792b01d53Sdrh   int iBreak              /* Jump here if we hit the LIMIT */
2018b21e7c70Sdrh ){
2019b21e7c70Sdrh   Vdbe *v = pParse->pVdbe;
202092b01d53Sdrh   int iContinue;
202192b01d53Sdrh   int addr;
2022b21e7c70Sdrh 
202392b01d53Sdrh   addr = sqlite3VdbeCurrentAddr(v);
202492b01d53Sdrh   iContinue = sqlite3VdbeMakeLabel(v);
20250acb7e48Sdrh 
20260acb7e48Sdrh   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
20270acb7e48Sdrh   */
20280acb7e48Sdrh   if( regPrev ){
20290acb7e48Sdrh     int j1, j2;
2030ec86c724Sdrh     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
20312b596da8Sdrh     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
20320acb7e48Sdrh                               (char*)pKeyInfo, p4type);
20330acb7e48Sdrh     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
20340acb7e48Sdrh     sqlite3VdbeJumpHere(v, j1);
2035e8e4af76Sdrh     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
2036ec86c724Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
20370acb7e48Sdrh   }
20381f9caa41Sdanielk1977   if( pParse->db->mallocFailed ) return 0;
20390acb7e48Sdrh 
2040d5578433Smistachkin   /* Suppress the first OFFSET entries if there is an OFFSET clause
20410acb7e48Sdrh   */
204292b01d53Sdrh   codeOffset(v, p, iContinue);
2043b21e7c70Sdrh 
2044b21e7c70Sdrh   switch( pDest->eDest ){
2045b21e7c70Sdrh     /* Store the result as data using a unique key.
2046b21e7c70Sdrh     */
2047b21e7c70Sdrh     case SRT_Table:
2048b21e7c70Sdrh     case SRT_EphemTab: {
2049b21e7c70Sdrh       int r1 = sqlite3GetTempReg(pParse);
2050b21e7c70Sdrh       int r2 = sqlite3GetTempReg(pParse);
2051373cc2ddSdrh       testcase( pDest->eDest==SRT_Table );
2052373cc2ddSdrh       testcase( pDest->eDest==SRT_EphemTab );
20532b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
20542b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
20552b596da8Sdrh       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
2056b21e7c70Sdrh       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
2057b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r2);
2058b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2059b21e7c70Sdrh       break;
2060b21e7c70Sdrh     }
2061b21e7c70Sdrh 
2062b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY
2063b21e7c70Sdrh     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
2064b21e7c70Sdrh     ** then there should be a single item on the stack.  Write this
2065b21e7c70Sdrh     ** item into the set table with bogus data.
2066b21e7c70Sdrh     */
2067b21e7c70Sdrh     case SRT_Set: {
20686fccc35aSdrh       int r1;
20692b596da8Sdrh       assert( pIn->nSdst==1 );
2070634d81deSdrh       pDest->affSdst =
20712b596da8Sdrh          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
2072b21e7c70Sdrh       r1 = sqlite3GetTempReg(pParse);
2073634d81deSdrh       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
20742b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
20752b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
2076b21e7c70Sdrh       sqlite3ReleaseTempReg(pParse, r1);
2077b21e7c70Sdrh       break;
2078b21e7c70Sdrh     }
2079b21e7c70Sdrh 
208085e9e22bSdrh #if 0  /* Never occurs on an ORDER BY query */
2081b21e7c70Sdrh     /* If any row exist in the result set, record that fact and abort.
2082b21e7c70Sdrh     */
2083b21e7c70Sdrh     case SRT_Exists: {
20842b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
2085b21e7c70Sdrh       /* The LIMIT clause will terminate the loop for us */
2086b21e7c70Sdrh       break;
2087b21e7c70Sdrh     }
208885e9e22bSdrh #endif
2089b21e7c70Sdrh 
2090b21e7c70Sdrh     /* If this is a scalar select that is part of an expression, then
2091b21e7c70Sdrh     ** store the results in the appropriate memory cell and break out
2092b21e7c70Sdrh     ** of the scan loop.
2093b21e7c70Sdrh     */
2094b21e7c70Sdrh     case SRT_Mem: {
20952b596da8Sdrh       assert( pIn->nSdst==1 );
20962b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
2097b21e7c70Sdrh       /* The LIMIT clause will jump out of the loop for us */
2098b21e7c70Sdrh       break;
2099b21e7c70Sdrh     }
2100b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
2101b21e7c70Sdrh 
21027d10d5a6Sdrh     /* The results are stored in a sequence of registers
21032b596da8Sdrh     ** starting at pDest->iSdst.  Then the co-routine yields.
2104b21e7c70Sdrh     */
210592b01d53Sdrh     case SRT_Coroutine: {
21062b596da8Sdrh       if( pDest->iSdst==0 ){
21072b596da8Sdrh         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
21082b596da8Sdrh         pDest->nSdst = pIn->nSdst;
2109b21e7c70Sdrh       }
21102b596da8Sdrh       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
21112b596da8Sdrh       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
211292b01d53Sdrh       break;
211392b01d53Sdrh     }
211492b01d53Sdrh 
2115ccfcbceaSdrh     /* If none of the above, then the result destination must be
2116ccfcbceaSdrh     ** SRT_Output.  This routine is never called with any other
2117ccfcbceaSdrh     ** destination other than the ones handled above or SRT_Output.
2118ccfcbceaSdrh     **
2119ccfcbceaSdrh     ** For SRT_Output, results are stored in a sequence of registers.
2120ccfcbceaSdrh     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
2121ccfcbceaSdrh     ** return the next row of result.
21227d10d5a6Sdrh     */
2123ccfcbceaSdrh     default: {
2124ccfcbceaSdrh       assert( pDest->eDest==SRT_Output );
21252b596da8Sdrh       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
21262b596da8Sdrh       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
2127b21e7c70Sdrh       break;
2128b21e7c70Sdrh     }
2129b21e7c70Sdrh   }
213092b01d53Sdrh 
213192b01d53Sdrh   /* Jump to the end of the loop if the LIMIT is reached.
213292b01d53Sdrh   */
213392b01d53Sdrh   if( p->iLimit ){
21349b918ed1Sdrh     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
213592b01d53Sdrh   }
213692b01d53Sdrh 
213792b01d53Sdrh   /* Generate the subroutine return
213892b01d53Sdrh   */
21390acb7e48Sdrh   sqlite3VdbeResolveLabel(v, iContinue);
214092b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
214192b01d53Sdrh 
214292b01d53Sdrh   return addr;
2143b21e7c70Sdrh }
2144b21e7c70Sdrh 
2145b21e7c70Sdrh /*
2146b21e7c70Sdrh ** Alternative compound select code generator for cases when there
2147b21e7c70Sdrh ** is an ORDER BY clause.
2148b21e7c70Sdrh **
2149b21e7c70Sdrh ** We assume a query of the following form:
2150b21e7c70Sdrh **
2151b21e7c70Sdrh **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
2152b21e7c70Sdrh **
2153b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
2154b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as
2155b21e7c70Sdrh ** co-routines.  Then run the co-routines in parallel and merge the results
2156b21e7c70Sdrh ** into the output.  In addition to the two coroutines (called selectA and
2157b21e7c70Sdrh ** selectB) there are 7 subroutines:
2158b21e7c70Sdrh **
2159b21e7c70Sdrh **    outA:    Move the output of the selectA coroutine into the output
2160b21e7c70Sdrh **             of the compound query.
2161b21e7c70Sdrh **
2162b21e7c70Sdrh **    outB:    Move the output of the selectB coroutine into the output
2163b21e7c70Sdrh **             of the compound query.  (Only generated for UNION and
2164b21e7c70Sdrh **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
2165b21e7c70Sdrh **             appears only in B.)
2166b21e7c70Sdrh **
2167b21e7c70Sdrh **    AltB:    Called when there is data from both coroutines and A<B.
2168b21e7c70Sdrh **
2169b21e7c70Sdrh **    AeqB:    Called when there is data from both coroutines and A==B.
2170b21e7c70Sdrh **
2171b21e7c70Sdrh **    AgtB:    Called when there is data from both coroutines and A>B.
2172b21e7c70Sdrh **
2173b21e7c70Sdrh **    EofA:    Called when data is exhausted from selectA.
2174b21e7c70Sdrh **
2175b21e7c70Sdrh **    EofB:    Called when data is exhausted from selectB.
2176b21e7c70Sdrh **
2177b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which
2178b21e7c70Sdrh ** <operator> is used:
2179b21e7c70Sdrh **
2180b21e7c70Sdrh **
2181b21e7c70Sdrh **             UNION ALL         UNION            EXCEPT          INTERSECT
2182b21e7c70Sdrh **          -------------  -----------------  --------------  -----------------
2183b21e7c70Sdrh **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
2184b21e7c70Sdrh **
21850acb7e48Sdrh **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
2186b21e7c70Sdrh **
2187b21e7c70Sdrh **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
2188b21e7c70Sdrh **
21890acb7e48Sdrh **   EofA:   outB, nextB      outB, nextB          halt             halt
2190b21e7c70Sdrh **
21910acb7e48Sdrh **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
21920acb7e48Sdrh **
21930acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
21940acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes
21950acb7e48Sdrh ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
21960acb7e48Sdrh ** following nextX causes a jump to the end of the select processing.
21970acb7e48Sdrh **
21980acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
21990acb7e48Sdrh ** within the output subroutine.  The regPrev register set holds the previously
22000acb7e48Sdrh ** output value.  A comparison is made against this value and the output
22010acb7e48Sdrh ** is skipped if the next results would be the same as the previous.
2202b21e7c70Sdrh **
2203b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven
2204b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom.  Like this:
2205b21e7c70Sdrh **
2206b21e7c70Sdrh **          goto Init
2207b21e7c70Sdrh **     coA: coroutine for left query (A)
2208b21e7c70Sdrh **     coB: coroutine for right query (B)
2209b21e7c70Sdrh **    outA: output one row of A
2210b21e7c70Sdrh **    outB: output one row of B (UNION and UNION ALL only)
2211b21e7c70Sdrh **    EofA: ...
2212b21e7c70Sdrh **    EofB: ...
2213b21e7c70Sdrh **    AltB: ...
2214b21e7c70Sdrh **    AeqB: ...
2215b21e7c70Sdrh **    AgtB: ...
2216b21e7c70Sdrh **    Init: initialize coroutine registers
2217b21e7c70Sdrh **          yield coA
2218b21e7c70Sdrh **          if eof(A) goto EofA
2219b21e7c70Sdrh **          yield coB
2220b21e7c70Sdrh **          if eof(B) goto EofB
2221b21e7c70Sdrh **    Cmpr: Compare A, B
2222b21e7c70Sdrh **          Jump AltB, AeqB, AgtB
2223b21e7c70Sdrh **     End: ...
2224b21e7c70Sdrh **
2225b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
2226b21e7c70Sdrh ** actually called using Gosub and they do not Return.  EofA and EofB loop
2227b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
2228b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB.
2229b21e7c70Sdrh */
2230de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2231b21e7c70Sdrh static int multiSelectOrderBy(
2232b21e7c70Sdrh   Parse *pParse,        /* Parsing context */
2233b21e7c70Sdrh   Select *p,            /* The right-most of SELECTs to be coded */
2234a9671a22Sdrh   SelectDest *pDest     /* What to do with query results */
2235b21e7c70Sdrh ){
22360acb7e48Sdrh   int i, j;             /* Loop counters */
2237b21e7c70Sdrh   Select *pPrior;       /* Another SELECT immediately to our left */
2238b21e7c70Sdrh   Vdbe *v;              /* Generate code to this VDBE */
2239b21e7c70Sdrh   SelectDest destA;     /* Destination for coroutine A */
2240b21e7c70Sdrh   SelectDest destB;     /* Destination for coroutine B */
224192b01d53Sdrh   int regAddrA;         /* Address register for select-A coroutine */
224292b01d53Sdrh   int regEofA;          /* Flag to indicate when select-A is complete */
224392b01d53Sdrh   int regAddrB;         /* Address register for select-B coroutine */
224492b01d53Sdrh   int regEofB;          /* Flag to indicate when select-B is complete */
224592b01d53Sdrh   int addrSelectA;      /* Address of the select-A coroutine */
224692b01d53Sdrh   int addrSelectB;      /* Address of the select-B coroutine */
224792b01d53Sdrh   int regOutA;          /* Address register for the output-A subroutine */
224892b01d53Sdrh   int regOutB;          /* Address register for the output-B subroutine */
224992b01d53Sdrh   int addrOutA;         /* Address of the output-A subroutine */
2250b27b7f5dSdrh   int addrOutB = 0;     /* Address of the output-B subroutine */
225192b01d53Sdrh   int addrEofA;         /* Address of the select-A-exhausted subroutine */
225292b01d53Sdrh   int addrEofB;         /* Address of the select-B-exhausted subroutine */
225392b01d53Sdrh   int addrAltB;         /* Address of the A<B subroutine */
225492b01d53Sdrh   int addrAeqB;         /* Address of the A==B subroutine */
225592b01d53Sdrh   int addrAgtB;         /* Address of the A>B subroutine */
225692b01d53Sdrh   int regLimitA;        /* Limit register for select-A */
225792b01d53Sdrh   int regLimitB;        /* Limit register for select-A */
22580acb7e48Sdrh   int regPrev;          /* A range of registers to hold previous output */
225992b01d53Sdrh   int savedLimit;       /* Saved value of p->iLimit */
226092b01d53Sdrh   int savedOffset;      /* Saved value of p->iOffset */
226192b01d53Sdrh   int labelCmpr;        /* Label for the start of the merge algorithm */
226292b01d53Sdrh   int labelEnd;         /* Label for the end of the overall SELECT stmt */
22630acb7e48Sdrh   int j1;               /* Jump instructions that get retargetted */
226492b01d53Sdrh   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
226596067816Sdrh   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
22660acb7e48Sdrh   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
22670acb7e48Sdrh   sqlite3 *db;          /* Database connection */
22680acb7e48Sdrh   ExprList *pOrderBy;   /* The ORDER BY clause */
22690acb7e48Sdrh   int nOrderBy;         /* Number of terms in the ORDER BY clause */
22700acb7e48Sdrh   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
22717f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN
22727f61e92cSdan   int iSub1;            /* EQP id of left-hand query */
22737f61e92cSdan   int iSub2;            /* EQP id of right-hand query */
22747f61e92cSdan #endif
2275b21e7c70Sdrh 
227692b01d53Sdrh   assert( p->pOrderBy!=0 );
227796067816Sdrh   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
22780acb7e48Sdrh   db = pParse->db;
227992b01d53Sdrh   v = pParse->pVdbe;
2280ccfcbceaSdrh   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
228192b01d53Sdrh   labelEnd = sqlite3VdbeMakeLabel(v);
228292b01d53Sdrh   labelCmpr = sqlite3VdbeMakeLabel(v);
22830acb7e48Sdrh 
2284b21e7c70Sdrh 
228592b01d53Sdrh   /* Patch up the ORDER BY clause
228692b01d53Sdrh   */
228792b01d53Sdrh   op = p->op;
2288b21e7c70Sdrh   pPrior = p->pPrior;
228992b01d53Sdrh   assert( pPrior->pOrderBy==0 );
22900acb7e48Sdrh   pOrderBy = p->pOrderBy;
229193a960a0Sdrh   assert( pOrderBy );
22920acb7e48Sdrh   nOrderBy = pOrderBy->nExpr;
229393a960a0Sdrh 
22940acb7e48Sdrh   /* For operators other than UNION ALL we have to make sure that
22950acb7e48Sdrh   ** the ORDER BY clause covers every term of the result set.  Add
22960acb7e48Sdrh   ** terms to the ORDER BY clause as necessary.
22970acb7e48Sdrh   */
22980acb7e48Sdrh   if( op!=TK_ALL ){
22990acb7e48Sdrh     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
23007d10d5a6Sdrh       struct ExprList_item *pItem;
23017d10d5a6Sdrh       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
23024b3ac73cSdrh         assert( pItem->iOrderByCol>0 );
23034b3ac73cSdrh         if( pItem->iOrderByCol==i ) break;
23040acb7e48Sdrh       }
23050acb7e48Sdrh       if( j==nOrderBy ){
2306b7916a78Sdrh         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
23070acb7e48Sdrh         if( pNew==0 ) return SQLITE_NOMEM;
23080acb7e48Sdrh         pNew->flags |= EP_IntValue;
230933e619fcSdrh         pNew->u.iValue = i;
2310b7916a78Sdrh         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
2311a3cc3c96Sdrh         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
23120acb7e48Sdrh       }
23130acb7e48Sdrh     }
23140acb7e48Sdrh   }
23150acb7e48Sdrh 
23160acb7e48Sdrh   /* Compute the comparison permutation and keyinfo that is used with
231710c081adSdrh   ** the permutation used to determine if the next
23180acb7e48Sdrh   ** row of results comes from selectA or selectB.  Also add explicit
23190acb7e48Sdrh   ** collations to the ORDER BY clause terms so that when the subqueries
23200acb7e48Sdrh   ** to the right and the left are evaluated, they use the correct
23210acb7e48Sdrh   ** collation.
23220acb7e48Sdrh   */
23230acb7e48Sdrh   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
23240acb7e48Sdrh   if( aPermute ){
23257d10d5a6Sdrh     struct ExprList_item *pItem;
23267d10d5a6Sdrh     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
23274b3ac73cSdrh       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
23284b3ac73cSdrh       aPermute[i] = pItem->iOrderByCol - 1;
23290acb7e48Sdrh     }
23300acb7e48Sdrh     pKeyMerge =
23310acb7e48Sdrh       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
23320acb7e48Sdrh     if( pKeyMerge ){
23330acb7e48Sdrh       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
2334ea678832Sdrh       pKeyMerge->nField = (u16)nOrderBy;
23350acb7e48Sdrh       pKeyMerge->enc = ENC(db);
23360acb7e48Sdrh       for(i=0; i<nOrderBy; i++){
23370acb7e48Sdrh         CollSeq *pColl;
23380acb7e48Sdrh         Expr *pTerm = pOrderBy->a[i].pExpr;
2339ae80ddeaSdrh         if( pTerm->flags & EP_Collate ){
2340ae80ddeaSdrh           pColl = sqlite3ExprCollSeq(pParse, pTerm);
23410acb7e48Sdrh         }else{
23420acb7e48Sdrh           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
23438e049633Sdrh           if( pColl==0 ) pColl = db->pDfltColl;
23448e049633Sdrh           pOrderBy->a[i].pExpr =
23458e049633Sdrh              sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
23460acb7e48Sdrh         }
23470acb7e48Sdrh         pKeyMerge->aColl[i] = pColl;
23480acb7e48Sdrh         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
23490acb7e48Sdrh       }
23500acb7e48Sdrh     }
23510acb7e48Sdrh   }else{
23520acb7e48Sdrh     pKeyMerge = 0;
23530acb7e48Sdrh   }
23540acb7e48Sdrh 
23550acb7e48Sdrh   /* Reattach the ORDER BY clause to the query.
23560acb7e48Sdrh   */
23570acb7e48Sdrh   p->pOrderBy = pOrderBy;
23586ab3a2ecSdanielk1977   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
23590acb7e48Sdrh 
23600acb7e48Sdrh   /* Allocate a range of temporary registers and the KeyInfo needed
23610acb7e48Sdrh   ** for the logic that removes duplicate result rows when the
23620acb7e48Sdrh   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
23630acb7e48Sdrh   */
23640acb7e48Sdrh   if( op==TK_ALL ){
23650acb7e48Sdrh     regPrev = 0;
23660acb7e48Sdrh   }else{
23670acb7e48Sdrh     int nExpr = p->pEList->nExpr;
23681c0dc825Sdrh     assert( nOrderBy>=nExpr || db->mallocFailed );
2369c8ac0d16Sdrh     regPrev = pParse->nMem+1;
2370c8ac0d16Sdrh     pParse->nMem += nExpr+1;
23710acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
23720acb7e48Sdrh     pKeyDup = sqlite3DbMallocZero(db,
23730acb7e48Sdrh                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
23740acb7e48Sdrh     if( pKeyDup ){
23750acb7e48Sdrh       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
2376ea678832Sdrh       pKeyDup->nField = (u16)nExpr;
23770acb7e48Sdrh       pKeyDup->enc = ENC(db);
23780acb7e48Sdrh       for(i=0; i<nExpr; i++){
23790acb7e48Sdrh         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
23800acb7e48Sdrh         pKeyDup->aSortOrder[i] = 0;
23810acb7e48Sdrh       }
23820acb7e48Sdrh     }
23830acb7e48Sdrh   }
238492b01d53Sdrh 
238592b01d53Sdrh   /* Separate the left and the right query from one another
238692b01d53Sdrh   */
238792b01d53Sdrh   p->pPrior = 0;
23887d10d5a6Sdrh   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
23890acb7e48Sdrh   if( pPrior->pPrior==0 ){
23907d10d5a6Sdrh     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
23910acb7e48Sdrh   }
239292b01d53Sdrh 
239392b01d53Sdrh   /* Compute the limit registers */
239492b01d53Sdrh   computeLimitRegisters(pParse, p, labelEnd);
23950acb7e48Sdrh   if( p->iLimit && op==TK_ALL ){
239692b01d53Sdrh     regLimitA = ++pParse->nMem;
239792b01d53Sdrh     regLimitB = ++pParse->nMem;
239892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
239992b01d53Sdrh                                   regLimitA);
240092b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
240192b01d53Sdrh   }else{
240292b01d53Sdrh     regLimitA = regLimitB = 0;
240392b01d53Sdrh   }
2404633e6d57Sdrh   sqlite3ExprDelete(db, p->pLimit);
24050acb7e48Sdrh   p->pLimit = 0;
2406633e6d57Sdrh   sqlite3ExprDelete(db, p->pOffset);
24070acb7e48Sdrh   p->pOffset = 0;
240892b01d53Sdrh 
2409b21e7c70Sdrh   regAddrA = ++pParse->nMem;
2410b21e7c70Sdrh   regEofA = ++pParse->nMem;
2411b21e7c70Sdrh   regAddrB = ++pParse->nMem;
2412b21e7c70Sdrh   regEofB = ++pParse->nMem;
2413b21e7c70Sdrh   regOutA = ++pParse->nMem;
2414b21e7c70Sdrh   regOutB = ++pParse->nMem;
2415b21e7c70Sdrh   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
2416b21e7c70Sdrh   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
2417b21e7c70Sdrh 
241892b01d53Sdrh   /* Jump past the various subroutines and coroutines to the main
241992b01d53Sdrh   ** merge loop
242092b01d53Sdrh   */
2421b21e7c70Sdrh   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
2422b21e7c70Sdrh   addrSelectA = sqlite3VdbeCurrentAddr(v);
242392b01d53Sdrh 
24240acb7e48Sdrh 
242592b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement to the
24260acb7e48Sdrh   ** left of the compound operator - the "A" select.
24270acb7e48Sdrh   */
2428b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
242992b01d53Sdrh   pPrior->iLimit = regLimitA;
24307f61e92cSdan   explainSetInteger(iSub1, pParse->iNextSelectId);
24317d10d5a6Sdrh   sqlite3Select(pParse, pPrior, &destA);
2432b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
243392b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2434b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for left SELECT"));
2435b21e7c70Sdrh 
243692b01d53Sdrh   /* Generate a coroutine to evaluate the SELECT statement on
243792b01d53Sdrh   ** the right - the "B" select
243892b01d53Sdrh   */
2439b21e7c70Sdrh   addrSelectB = sqlite3VdbeCurrentAddr(v);
2440b21e7c70Sdrh   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
244192b01d53Sdrh   savedLimit = p->iLimit;
244292b01d53Sdrh   savedOffset = p->iOffset;
244392b01d53Sdrh   p->iLimit = regLimitB;
244492b01d53Sdrh   p->iOffset = 0;
24457f61e92cSdan   explainSetInteger(iSub2, pParse->iNextSelectId);
24467d10d5a6Sdrh   sqlite3Select(pParse, p, &destB);
244792b01d53Sdrh   p->iLimit = savedLimit;
244892b01d53Sdrh   p->iOffset = savedOffset;
2449b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
245092b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2451b21e7c70Sdrh   VdbeNoopComment((v, "End coroutine for right SELECT"));
2452b21e7c70Sdrh 
245392b01d53Sdrh   /* Generate a subroutine that outputs the current row of the A
24540acb7e48Sdrh   ** select as the next output row of the compound select.
245592b01d53Sdrh   */
2456b21e7c70Sdrh   VdbeNoopComment((v, "Output routine for A"));
24570acb7e48Sdrh   addrOutA = generateOutputSubroutine(pParse,
24580acb7e48Sdrh                  p, &destA, pDest, regOutA,
24590acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
2460b21e7c70Sdrh 
246192b01d53Sdrh   /* Generate a subroutine that outputs the current row of the B
24620acb7e48Sdrh   ** select as the next output row of the compound select.
246392b01d53Sdrh   */
24640acb7e48Sdrh   if( op==TK_ALL || op==TK_UNION ){
2465b21e7c70Sdrh     VdbeNoopComment((v, "Output routine for B"));
24660acb7e48Sdrh     addrOutB = generateOutputSubroutine(pParse,
24670acb7e48Sdrh                  p, &destB, pDest, regOutB,
24680acb7e48Sdrh                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
24690acb7e48Sdrh   }
2470b21e7c70Sdrh 
247192b01d53Sdrh   /* Generate a subroutine to run when the results from select A
247292b01d53Sdrh   ** are exhausted and only data in select B remains.
247392b01d53Sdrh   */
247492b01d53Sdrh   VdbeNoopComment((v, "eof-A subroutine"));
247592b01d53Sdrh   if( op==TK_EXCEPT || op==TK_INTERSECT ){
24760acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
247792b01d53Sdrh   }else{
24780acb7e48Sdrh     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
2479b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
248092b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
24810acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
248295aa47b1Sdrh     p->nSelectRow += pPrior->nSelectRow;
2483b21e7c70Sdrh   }
2484b21e7c70Sdrh 
248592b01d53Sdrh   /* Generate a subroutine to run when the results from select B
248692b01d53Sdrh   ** are exhausted and only data in select A remains.
248792b01d53Sdrh   */
2488b21e7c70Sdrh   if( op==TK_INTERSECT ){
248992b01d53Sdrh     addrEofB = addrEofA;
249095aa47b1Sdrh     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
2491b21e7c70Sdrh   }else{
249292b01d53Sdrh     VdbeNoopComment((v, "eof-B subroutine"));
24930acb7e48Sdrh     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
2494b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
249592b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
24960acb7e48Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
2497b21e7c70Sdrh   }
2498b21e7c70Sdrh 
249992b01d53Sdrh   /* Generate code to handle the case of A<B
250092b01d53Sdrh   */
2501b21e7c70Sdrh   VdbeNoopComment((v, "A-lt-B subroutine"));
25020acb7e48Sdrh   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
250392b01d53Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
2504b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
250592b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2506b21e7c70Sdrh 
250792b01d53Sdrh   /* Generate code to handle the case of A==B
250892b01d53Sdrh   */
2509b21e7c70Sdrh   if( op==TK_ALL ){
2510b21e7c70Sdrh     addrAeqB = addrAltB;
25110acb7e48Sdrh   }else if( op==TK_INTERSECT ){
25120acb7e48Sdrh     addrAeqB = addrAltB;
25130acb7e48Sdrh     addrAltB++;
251492b01d53Sdrh   }else{
2515b21e7c70Sdrh     VdbeNoopComment((v, "A-eq-B subroutine"));
25160acb7e48Sdrh     addrAeqB =
251792b01d53Sdrh     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
251892b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
251992b01d53Sdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
252092b01d53Sdrh   }
2521b21e7c70Sdrh 
252292b01d53Sdrh   /* Generate code to handle the case of A>B
252392b01d53Sdrh   */
2524b21e7c70Sdrh   VdbeNoopComment((v, "A-gt-B subroutine"));
2525b21e7c70Sdrh   addrAgtB = sqlite3VdbeCurrentAddr(v);
2526b21e7c70Sdrh   if( op==TK_ALL || op==TK_UNION ){
2527b21e7c70Sdrh     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
252892b01d53Sdrh   }
25290acb7e48Sdrh   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
2530b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
253192b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
2532b21e7c70Sdrh 
253392b01d53Sdrh   /* This code runs once to initialize everything.
253492b01d53Sdrh   */
2535b21e7c70Sdrh   sqlite3VdbeJumpHere(v, j1);
2536b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
2537b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
253892b01d53Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
25390acb7e48Sdrh   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
2540b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
2541b21e7c70Sdrh   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
254292b01d53Sdrh 
254392b01d53Sdrh   /* Implement the main merge loop
254492b01d53Sdrh   */
254592b01d53Sdrh   sqlite3VdbeResolveLabel(v, labelCmpr);
25460acb7e48Sdrh   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
25472b596da8Sdrh   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
25480acb7e48Sdrh                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
2549953f7611Sdrh   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
2550b21e7c70Sdrh   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
255192b01d53Sdrh 
255292b01d53Sdrh   /* Jump to the this point in order to terminate the query.
255392b01d53Sdrh   */
2554b21e7c70Sdrh   sqlite3VdbeResolveLabel(v, labelEnd);
2555b21e7c70Sdrh 
255692b01d53Sdrh   /* Set the number of output columns
255792b01d53Sdrh   */
25587d10d5a6Sdrh   if( pDest->eDest==SRT_Output ){
25590acb7e48Sdrh     Select *pFirst = pPrior;
256092b01d53Sdrh     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
256192b01d53Sdrh     generateColumnNames(pParse, 0, pFirst->pEList);
2562b21e7c70Sdrh   }
256392b01d53Sdrh 
25640acb7e48Sdrh   /* Reassembly the compound query so that it will be freed correctly
25650acb7e48Sdrh   ** by the calling function */
25665e7ad508Sdanielk1977   if( p->pPrior ){
2567633e6d57Sdrh     sqlite3SelectDelete(db, p->pPrior);
25685e7ad508Sdanielk1977   }
25690acb7e48Sdrh   p->pPrior = pPrior;
257092b01d53Sdrh 
257192b01d53Sdrh   /*** TBD:  Insert subroutine calls to close cursors on incomplete
257292b01d53Sdrh   **** subqueries ****/
25737f61e92cSdan   explainComposite(pParse, p->op, iSub1, iSub2, 0);
257492b01d53Sdrh   return SQLITE_OK;
257592b01d53Sdrh }
2576de3e41e3Sdanielk1977 #endif
2577b21e7c70Sdrh 
25783514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
257917435752Sdrh /* Forward Declarations */
258017435752Sdrh static void substExprList(sqlite3*, ExprList*, int, ExprList*);
258117435752Sdrh static void substSelect(sqlite3*, Select *, int, ExprList *);
258217435752Sdrh 
25832282792aSdrh /*
2584832508b7Sdrh ** Scan through the expression pExpr.  Replace every reference to
25856a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th
258684e59207Sdrh ** entry in pEList.  (But leave references to the ROWID column
25876a3ea0e6Sdrh ** unchanged.)
2588832508b7Sdrh **
2589832508b7Sdrh ** This routine is part of the flattening procedure.  A subquery
2590832508b7Sdrh ** whose result set is defined by pEList appears as entry in the
2591832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that
2592832508b7Sdrh ** FORM clause entry is iTable.  This routine make the necessary
2593832508b7Sdrh ** changes to pExpr so that it refers directly to the source table
2594832508b7Sdrh ** of the subquery rather the result set of the subquery.
2595832508b7Sdrh */
2596b7916a78Sdrh static Expr *substExpr(
259717435752Sdrh   sqlite3 *db,        /* Report malloc errors to this connection */
259817435752Sdrh   Expr *pExpr,        /* Expr in which substitution occurs */
259917435752Sdrh   int iTable,         /* Table to be substituted */
260017435752Sdrh   ExprList *pEList    /* Substitute expressions */
260117435752Sdrh ){
2602b7916a78Sdrh   if( pExpr==0 ) return 0;
260350350a15Sdrh   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
260450350a15Sdrh     if( pExpr->iColumn<0 ){
260550350a15Sdrh       pExpr->op = TK_NULL;
260650350a15Sdrh     }else{
2607832508b7Sdrh       Expr *pNew;
260884e59207Sdrh       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
26096ab3a2ecSdanielk1977       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
2610b7916a78Sdrh       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
2611b7916a78Sdrh       sqlite3ExprDelete(db, pExpr);
2612b7916a78Sdrh       pExpr = pNew;
261350350a15Sdrh     }
2614832508b7Sdrh   }else{
2615b7916a78Sdrh     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
2616b7916a78Sdrh     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
26176ab3a2ecSdanielk1977     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26186ab3a2ecSdanielk1977       substSelect(db, pExpr->x.pSelect, iTable, pEList);
26196ab3a2ecSdanielk1977     }else{
26206ab3a2ecSdanielk1977       substExprList(db, pExpr->x.pList, iTable, pEList);
26216ab3a2ecSdanielk1977     }
2622832508b7Sdrh   }
2623b7916a78Sdrh   return pExpr;
2624832508b7Sdrh }
262517435752Sdrh static void substExprList(
262617435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
262717435752Sdrh   ExprList *pList,     /* List to scan and in which to make substitutes */
262817435752Sdrh   int iTable,          /* Table to be substituted */
262917435752Sdrh   ExprList *pEList     /* Substitute values */
263017435752Sdrh ){
2631832508b7Sdrh   int i;
2632832508b7Sdrh   if( pList==0 ) return;
2633832508b7Sdrh   for(i=0; i<pList->nExpr; i++){
2634b7916a78Sdrh     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
2635832508b7Sdrh   }
2636832508b7Sdrh }
263717435752Sdrh static void substSelect(
263817435752Sdrh   sqlite3 *db,         /* Report malloc errors here */
263917435752Sdrh   Select *p,           /* SELECT statement in which to make substitutions */
264017435752Sdrh   int iTable,          /* Table to be replaced */
264117435752Sdrh   ExprList *pEList     /* Substitute values */
264217435752Sdrh ){
2643588a9a1aSdrh   SrcList *pSrc;
2644588a9a1aSdrh   struct SrcList_item *pItem;
2645588a9a1aSdrh   int i;
2646b3bce662Sdanielk1977   if( !p ) return;
264717435752Sdrh   substExprList(db, p->pEList, iTable, pEList);
264817435752Sdrh   substExprList(db, p->pGroupBy, iTable, pEList);
264917435752Sdrh   substExprList(db, p->pOrderBy, iTable, pEList);
2650b7916a78Sdrh   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
2651b7916a78Sdrh   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
265217435752Sdrh   substSelect(db, p->pPrior, iTable, pEList);
2653588a9a1aSdrh   pSrc = p->pSrc;
2654e2f02bacSdrh   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
2655e2f02bacSdrh   if( ALWAYS(pSrc) ){
2656588a9a1aSdrh     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
2657588a9a1aSdrh       substSelect(db, pItem->pSelect, iTable, pEList);
2658588a9a1aSdrh     }
2659588a9a1aSdrh   }
2660b3bce662Sdanielk1977 }
26613514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
2662832508b7Sdrh 
26633514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
2664832508b7Sdrh /*
2665630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization.
2666630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
26671350b030Sdrh **
26681350b030Sdrh ** To understand the concept of flattening, consider the following
26691350b030Sdrh ** query:
26701350b030Sdrh **
26711350b030Sdrh **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
26721350b030Sdrh **
26731350b030Sdrh ** The default way of implementing this query is to execute the
26741350b030Sdrh ** subquery first and store the results in a temporary table, then
26751350b030Sdrh ** run the outer query on that temporary table.  This requires two
26761350b030Sdrh ** passes over the data.  Furthermore, because the temporary table
26771350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be
2678832508b7Sdrh ** optimized.
26791350b030Sdrh **
2680832508b7Sdrh ** This routine attempts to rewrite queries such as the above into
26811350b030Sdrh ** a single flat select, like this:
26821350b030Sdrh **
26831350b030Sdrh **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
26841350b030Sdrh **
26851350b030Sdrh ** The code generated for this simpification gives the same result
2686832508b7Sdrh ** but only has to scan the data once.  And because indices might
2687832508b7Sdrh ** exist on the table t1, a complete scan of the data might be
2688832508b7Sdrh ** avoided.
26891350b030Sdrh **
2690832508b7Sdrh ** Flattening is only attempted if all of the following are true:
26911350b030Sdrh **
2692832508b7Sdrh **   (1)  The subquery and the outer query do not both use aggregates.
26931350b030Sdrh **
2694832508b7Sdrh **   (2)  The subquery is not an aggregate or the outer query is not a join.
2695832508b7Sdrh **
26962b300d5dSdrh **   (3)  The subquery is not the right operand of a left outer join
269749ad330dSdan **        (Originally ticket #306.  Strengthened by ticket #3300)
2698832508b7Sdrh **
269949ad330dSdan **   (4)  The subquery is not DISTINCT.
2700832508b7Sdrh **
270149ad330dSdan **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
270249ad330dSdan **        sub-queries that were excluded from this optimization. Restriction
270349ad330dSdan **        (4) has since been expanded to exclude all DISTINCT subqueries.
2704832508b7Sdrh **
2705832508b7Sdrh **   (6)  The subquery does not use aggregates or the outer query is not
2706832508b7Sdrh **        DISTINCT.
2707832508b7Sdrh **
2708630d296cSdrh **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
2709630d296cSdrh **        A FROM clause, consider adding a FROM close with the special
2710630d296cSdrh **        table sqlite_once that consists of a single row containing a
2711630d296cSdrh **        single NULL.
271208192d5fSdrh **
2713df199a25Sdrh **   (8)  The subquery does not use LIMIT or the outer query is not a join.
2714df199a25Sdrh **
2715df199a25Sdrh **   (9)  The subquery does not use LIMIT or the outer query does not use
2716df199a25Sdrh **        aggregates.
2717df199a25Sdrh **
2718df199a25Sdrh **  (10)  The subquery does not use aggregates or the outer query does not
2719df199a25Sdrh **        use LIMIT.
2720df199a25Sdrh **
2721174b6195Sdrh **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
2722174b6195Sdrh **
27237b688edeSdrh **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
27242b300d5dSdrh **        a separate restriction deriving from ticket #350.
27253fc673e6Sdrh **
272649ad330dSdan **  (13)  The subquery and outer query do not both use LIMIT.
2727ac83963aSdrh **
272849ad330dSdan **  (14)  The subquery does not use OFFSET.
2729ac83963aSdrh **
2730ad91c6cdSdrh **  (15)  The outer query is not part of a compound select or the
2731f3913278Sdrh **        subquery does not have a LIMIT clause.
2732f3913278Sdrh **        (See ticket #2339 and ticket [02a8e81d44]).
2733ad91c6cdSdrh **
2734c52e355dSdrh **  (16)  The outer query is not an aggregate or the subquery does
2735c52e355dSdrh **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
2736c52e355dSdrh **        until we introduced the group_concat() function.
2737c52e355dSdrh **
2738f23329a2Sdanielk1977 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
27394914cf92Sdanielk1977 **        compound clause made up entirely of non-aggregate queries, and
2740f23329a2Sdanielk1977 **        the parent query:
2741f23329a2Sdanielk1977 **
2742f23329a2Sdanielk1977 **          * is not itself part of a compound select,
2743f23329a2Sdanielk1977 **          * is not an aggregate or DISTINCT query, and
2744630d296cSdrh **          * is not a join
2745f23329a2Sdanielk1977 **
27464914cf92Sdanielk1977 **        The parent and sub-query may contain WHERE clauses. Subject to
27474914cf92Sdanielk1977 **        rules (11), (13) and (14), they may also contain ORDER BY,
2748630d296cSdrh **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
2749630d296cSdrh **        operator other than UNION ALL because all the other compound
2750630d296cSdrh **        operators have an implied DISTINCT which is disallowed by
2751630d296cSdrh **        restriction (4).
2752f23329a2Sdanielk1977 **
275367c70142Sdan **        Also, each component of the sub-query must return the same number
275467c70142Sdan **        of result columns. This is actually a requirement for any compound
275567c70142Sdan **        SELECT statement, but all the code here does is make sure that no
275667c70142Sdan **        such (illegal) sub-query is flattened. The caller will detect the
275767c70142Sdan **        syntax error and return a detailed message.
275867c70142Sdan **
275949fc1f60Sdanielk1977 **  (18)  If the sub-query is a compound select, then all terms of the
276049fc1f60Sdanielk1977 **        ORDER by clause of the parent must be simple references to
276149fc1f60Sdanielk1977 **        columns of the sub-query.
276249fc1f60Sdanielk1977 **
2763229cf702Sdrh **  (19)  The subquery does not use LIMIT or the outer query does not
2764229cf702Sdrh **        have a WHERE clause.
2765229cf702Sdrh **
2766e8902a70Sdrh **  (20)  If the sub-query is a compound select, then it must not use
2767e8902a70Sdrh **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
2768e8902a70Sdrh **        somewhat by saying that the terms of the ORDER BY clause must
2769630d296cSdrh **        appear as unmodified result columns in the outer query.  But we
2770e8902a70Sdrh **        have other optimizations in mind to deal with that case.
2771e8902a70Sdrh **
2772a91491e5Sshaneh **  (21)  The subquery does not use LIMIT or the outer query is not
2773a91491e5Sshaneh **        DISTINCT.  (See ticket [752e1646fc]).
2774a91491e5Sshaneh **
2775832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query.
2776832508b7Sdrh ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
2777832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
2778832508b7Sdrh **
2779665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0.
2780832508b7Sdrh ** If flattening is attempted this routine returns 1.
2781832508b7Sdrh **
2782832508b7Sdrh ** All of the expression analysis must occur on both the outer query and
2783832508b7Sdrh ** the subquery before this routine runs.
27841350b030Sdrh */
27858c74a8caSdrh static int flattenSubquery(
2786524cc21eSdanielk1977   Parse *pParse,       /* Parsing context */
27878c74a8caSdrh   Select *p,           /* The parent or outer SELECT statement */
27888c74a8caSdrh   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
27898c74a8caSdrh   int isAgg,           /* True if outer SELECT uses aggregate functions */
27908c74a8caSdrh   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
27918c74a8caSdrh ){
2792524cc21eSdanielk1977   const char *zSavedAuthContext = pParse->zAuthContext;
2793f23329a2Sdanielk1977   Select *pParent;
27940bb28106Sdrh   Select *pSub;       /* The inner query or "subquery" */
2795f23329a2Sdanielk1977   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
2796ad3cab52Sdrh   SrcList *pSrc;      /* The FROM clause of the outer query */
2797ad3cab52Sdrh   SrcList *pSubSrc;   /* The FROM clause of the subquery */
27980bb28106Sdrh   ExprList *pList;    /* The result set of the outer query */
27996a3ea0e6Sdrh   int iParent;        /* VDBE cursor number of the pSub result set temp table */
280091bb0eedSdrh   int i;              /* Loop counter */
280191bb0eedSdrh   Expr *pWhere;                    /* The WHERE clause */
280291bb0eedSdrh   struct SrcList_item *pSubitem;   /* The subquery */
2803524cc21eSdanielk1977   sqlite3 *db = pParse->db;
28041350b030Sdrh 
2805832508b7Sdrh   /* Check to see if flattening is permitted.  Return 0 if not.
2806832508b7Sdrh   */
2807a78c22c4Sdrh   assert( p!=0 );
2808a78c22c4Sdrh   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
28097e5418e4Sdrh   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
2810832508b7Sdrh   pSrc = p->pSrc;
2811ad3cab52Sdrh   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
281291bb0eedSdrh   pSubitem = &pSrc->a[iFrom];
281349fc1f60Sdanielk1977   iParent = pSubitem->iCursor;
281491bb0eedSdrh   pSub = pSubitem->pSelect;
2815832508b7Sdrh   assert( pSub!=0 );
2816ac83963aSdrh   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
2817ac83963aSdrh   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
2818832508b7Sdrh   pSubSrc = pSub->pSrc;
2819832508b7Sdrh   assert( pSubSrc );
2820ac83963aSdrh   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
2821ac83963aSdrh   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
2822ac83963aSdrh   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
2823ac83963aSdrh   ** became arbitrary expressions, we were forced to add restrictions (13)
2824ac83963aSdrh   ** and (14). */
2825ac83963aSdrh   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
2826ac83963aSdrh   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
2827f3913278Sdrh   if( p->pRightmost && pSub->pLimit ){
2828ad91c6cdSdrh     return 0;                                            /* Restriction (15) */
2829ad91c6cdSdrh   }
2830ac83963aSdrh   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
283149ad330dSdan   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
283249ad330dSdan   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
283349ad330dSdan      return 0;         /* Restrictions (8)(9) */
2834df199a25Sdrh   }
28357d10d5a6Sdrh   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
28367d10d5a6Sdrh      return 0;         /* Restriction (6)  */
28377d10d5a6Sdrh   }
28387d10d5a6Sdrh   if( p->pOrderBy && pSub->pOrderBy ){
2839ac83963aSdrh      return 0;                                           /* Restriction (11) */
2840ac83963aSdrh   }
2841c52e355dSdrh   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
2842229cf702Sdrh   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
2843a91491e5Sshaneh   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
2844a91491e5Sshaneh      return 0;         /* Restriction (21) */
2845a91491e5Sshaneh   }
2846832508b7Sdrh 
28472b300d5dSdrh   /* OBSOLETE COMMENT 1:
28482b300d5dSdrh   ** Restriction 3:  If the subquery is a join, make sure the subquery is
28498af4d3acSdrh   ** not used as the right operand of an outer join.  Examples of why this
28508af4d3acSdrh   ** is not allowed:
28518af4d3acSdrh   **
28528af4d3acSdrh   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
28538af4d3acSdrh   **
28548af4d3acSdrh   ** If we flatten the above, we would get
28558af4d3acSdrh   **
28568af4d3acSdrh   **         (t1 LEFT OUTER JOIN t2) JOIN t3
28578af4d3acSdrh   **
28588af4d3acSdrh   ** which is not at all the same thing.
28592b300d5dSdrh   **
28602b300d5dSdrh   ** OBSOLETE COMMENT 2:
28612b300d5dSdrh   ** Restriction 12:  If the subquery is the right operand of a left outer
28623fc673e6Sdrh   ** join, make sure the subquery has no WHERE clause.
28633fc673e6Sdrh   ** An examples of why this is not allowed:
28643fc673e6Sdrh   **
28653fc673e6Sdrh   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
28663fc673e6Sdrh   **
28673fc673e6Sdrh   ** If we flatten the above, we would get
28683fc673e6Sdrh   **
28693fc673e6Sdrh   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
28703fc673e6Sdrh   **
28713fc673e6Sdrh   ** But the t2.x>0 test will always fail on a NULL row of t2, which
28723fc673e6Sdrh   ** effectively converts the OUTER JOIN into an INNER JOIN.
28732b300d5dSdrh   **
28742b300d5dSdrh   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
28752b300d5dSdrh   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
28762b300d5dSdrh   ** is fraught with danger.  Best to avoid the whole thing.  If the
28772b300d5dSdrh   ** subquery is the right term of a LEFT JOIN, then do not flatten.
28783fc673e6Sdrh   */
28792b300d5dSdrh   if( (pSubitem->jointype & JT_OUTER)!=0 ){
28803fc673e6Sdrh     return 0;
28813fc673e6Sdrh   }
28823fc673e6Sdrh 
2883f23329a2Sdanielk1977   /* Restriction 17: If the sub-query is a compound SELECT, then it must
2884f23329a2Sdanielk1977   ** use only the UNION ALL operator. And none of the simple select queries
2885f23329a2Sdanielk1977   ** that make up the compound SELECT are allowed to be aggregate or distinct
2886f23329a2Sdanielk1977   ** queries.
2887f23329a2Sdanielk1977   */
2888f23329a2Sdanielk1977   if( pSub->pPrior ){
2889e8902a70Sdrh     if( pSub->pOrderBy ){
2890e8902a70Sdrh       return 0;  /* Restriction 20 */
2891e8902a70Sdrh     }
2892e2f02bacSdrh     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
2893f23329a2Sdanielk1977       return 0;
2894f23329a2Sdanielk1977     }
2895f23329a2Sdanielk1977     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
2896ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2897ccfcbceaSdrh       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
28984b3ac73cSdrh       assert( pSub->pSrc!=0 );
28997d10d5a6Sdrh       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
290080b3c548Sdanielk1977        || (pSub1->pPrior && pSub1->op!=TK_ALL)
29014b3ac73cSdrh        || pSub1->pSrc->nSrc<1
290267c70142Sdan        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
290380b3c548Sdanielk1977       ){
2904f23329a2Sdanielk1977         return 0;
2905f23329a2Sdanielk1977       }
29064b3ac73cSdrh       testcase( pSub1->pSrc->nSrc>1 );
2907f23329a2Sdanielk1977     }
290849fc1f60Sdanielk1977 
290949fc1f60Sdanielk1977     /* Restriction 18. */
291049fc1f60Sdanielk1977     if( p->pOrderBy ){
291149fc1f60Sdanielk1977       int ii;
291249fc1f60Sdanielk1977       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
29134b3ac73cSdrh         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
291449fc1f60Sdanielk1977       }
291549fc1f60Sdanielk1977     }
2916f23329a2Sdanielk1977   }
2917f23329a2Sdanielk1977 
29187d10d5a6Sdrh   /***** If we reach this point, flattening is permitted. *****/
29197d10d5a6Sdrh 
29207d10d5a6Sdrh   /* Authorize the subquery */
2921524cc21eSdanielk1977   pParse->zAuthContext = pSubitem->zName;
2922a2acb0d7Sdrh   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
2923a2acb0d7Sdrh   testcase( i==SQLITE_DENY );
2924524cc21eSdanielk1977   pParse->zAuthContext = zSavedAuthContext;
2925524cc21eSdanielk1977 
29267d10d5a6Sdrh   /* If the sub-query is a compound SELECT statement, then (by restrictions
29277d10d5a6Sdrh   ** 17 and 18 above) it must be a UNION ALL and the parent query must
29287d10d5a6Sdrh   ** be of the form:
2929f23329a2Sdanielk1977   **
2930f23329a2Sdanielk1977   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
2931f23329a2Sdanielk1977   **
2932f23329a2Sdanielk1977   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
2933a78c22c4Sdrh   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
2934f23329a2Sdanielk1977   ** OFFSET clauses and joins them to the left-hand-side of the original
2935f23329a2Sdanielk1977   ** using UNION ALL operators. In this case N is the number of simple
2936f23329a2Sdanielk1977   ** select statements in the compound sub-query.
2937a78c22c4Sdrh   **
2938a78c22c4Sdrh   ** Example:
2939a78c22c4Sdrh   **
2940a78c22c4Sdrh   **     SELECT a+1 FROM (
2941a78c22c4Sdrh   **        SELECT x FROM tab
2942a78c22c4Sdrh   **        UNION ALL
2943a78c22c4Sdrh   **        SELECT y FROM tab
2944a78c22c4Sdrh   **        UNION ALL
2945a78c22c4Sdrh   **        SELECT abs(z*2) FROM tab2
2946a78c22c4Sdrh   **     ) WHERE a!=5 ORDER BY 1
2947a78c22c4Sdrh   **
2948a78c22c4Sdrh   ** Transformed into:
2949a78c22c4Sdrh   **
2950a78c22c4Sdrh   **     SELECT x+1 FROM tab WHERE x+1!=5
2951a78c22c4Sdrh   **     UNION ALL
2952a78c22c4Sdrh   **     SELECT y+1 FROM tab WHERE y+1!=5
2953a78c22c4Sdrh   **     UNION ALL
2954a78c22c4Sdrh   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
2955a78c22c4Sdrh   **     ORDER BY 1
2956a78c22c4Sdrh   **
2957a78c22c4Sdrh   ** We call this the "compound-subquery flattening".
2958f23329a2Sdanielk1977   */
2959f23329a2Sdanielk1977   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
2960f23329a2Sdanielk1977     Select *pNew;
2961f23329a2Sdanielk1977     ExprList *pOrderBy = p->pOrderBy;
29624b86ef1dSdanielk1977     Expr *pLimit = p->pLimit;
2963547180baSdrh     Expr *pOffset = p->pOffset;
2964f23329a2Sdanielk1977     Select *pPrior = p->pPrior;
2965f23329a2Sdanielk1977     p->pOrderBy = 0;
2966f23329a2Sdanielk1977     p->pSrc = 0;
2967f23329a2Sdanielk1977     p->pPrior = 0;
29684b86ef1dSdanielk1977     p->pLimit = 0;
2969547180baSdrh     p->pOffset = 0;
29706ab3a2ecSdanielk1977     pNew = sqlite3SelectDup(db, p, 0);
2971547180baSdrh     p->pOffset = pOffset;
29724b86ef1dSdanielk1977     p->pLimit = pLimit;
2973a78c22c4Sdrh     p->pOrderBy = pOrderBy;
2974a78c22c4Sdrh     p->pSrc = pSrc;
2975a78c22c4Sdrh     p->op = TK_ALL;
2976f23329a2Sdanielk1977     p->pRightmost = 0;
2977a78c22c4Sdrh     if( pNew==0 ){
2978a78c22c4Sdrh       pNew = pPrior;
2979a78c22c4Sdrh     }else{
2980a78c22c4Sdrh       pNew->pPrior = pPrior;
2981f23329a2Sdanielk1977       pNew->pRightmost = 0;
2982f23329a2Sdanielk1977     }
2983a78c22c4Sdrh     p->pPrior = pNew;
2984a78c22c4Sdrh     if( db->mallocFailed ) return 1;
2985a78c22c4Sdrh   }
2986f23329a2Sdanielk1977 
29877d10d5a6Sdrh   /* Begin flattening the iFrom-th entry of the FROM clause
29887d10d5a6Sdrh   ** in the outer query.
2989832508b7Sdrh   */
2990f23329a2Sdanielk1977   pSub = pSub1 = pSubitem->pSelect;
2991c31c2eb8Sdrh 
2992a78c22c4Sdrh   /* Delete the transient table structure associated with the
2993a78c22c4Sdrh   ** subquery
2994a78c22c4Sdrh   */
2995a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zDatabase);
2996a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zName);
2997a78c22c4Sdrh   sqlite3DbFree(db, pSubitem->zAlias);
2998a78c22c4Sdrh   pSubitem->zDatabase = 0;
2999a78c22c4Sdrh   pSubitem->zName = 0;
3000a78c22c4Sdrh   pSubitem->zAlias = 0;
3001a78c22c4Sdrh   pSubitem->pSelect = 0;
3002a78c22c4Sdrh 
3003a78c22c4Sdrh   /* Defer deleting the Table object associated with the
3004a78c22c4Sdrh   ** subquery until code generation is
3005a78c22c4Sdrh   ** complete, since there may still exist Expr.pTab entries that
3006a78c22c4Sdrh   ** refer to the subquery even after flattening.  Ticket #3346.
3007ccfcbceaSdrh   **
3008ccfcbceaSdrh   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
3009a78c22c4Sdrh   */
3010ccfcbceaSdrh   if( ALWAYS(pSubitem->pTab!=0) ){
3011a78c22c4Sdrh     Table *pTabToDel = pSubitem->pTab;
3012a78c22c4Sdrh     if( pTabToDel->nRef==1 ){
301365a7cd16Sdan       Parse *pToplevel = sqlite3ParseToplevel(pParse);
301465a7cd16Sdan       pTabToDel->pNextZombie = pToplevel->pZombieTab;
301565a7cd16Sdan       pToplevel->pZombieTab = pTabToDel;
3016a78c22c4Sdrh     }else{
3017a78c22c4Sdrh       pTabToDel->nRef--;
3018a78c22c4Sdrh     }
3019a78c22c4Sdrh     pSubitem->pTab = 0;
3020a78c22c4Sdrh   }
3021a78c22c4Sdrh 
3022a78c22c4Sdrh   /* The following loop runs once for each term in a compound-subquery
3023a78c22c4Sdrh   ** flattening (as described above).  If we are doing a different kind
3024a78c22c4Sdrh   ** of flattening - a flattening other than a compound-subquery flattening -
3025a78c22c4Sdrh   ** then this loop only runs once.
3026a78c22c4Sdrh   **
3027a78c22c4Sdrh   ** This loop moves all of the FROM elements of the subquery into the
3028c31c2eb8Sdrh   ** the FROM clause of the outer query.  Before doing this, remember
3029c31c2eb8Sdrh   ** the cursor number for the original outer query FROM element in
3030c31c2eb8Sdrh   ** iParent.  The iParent cursor will never be used.  Subsequent code
3031c31c2eb8Sdrh   ** will scan expressions looking for iParent references and replace
3032c31c2eb8Sdrh   ** those references with expressions that resolve to the subquery FROM
3033c31c2eb8Sdrh   ** elements we are now copying in.
3034c31c2eb8Sdrh   */
3035a78c22c4Sdrh   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
3036a78c22c4Sdrh     int nSubSrc;
3037ea678832Sdrh     u8 jointype = 0;
3038a78c22c4Sdrh     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
3039a78c22c4Sdrh     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
3040a78c22c4Sdrh     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
3041588a9a1aSdrh 
3042a78c22c4Sdrh     if( pSrc ){
3043a78c22c4Sdrh       assert( pParent==p );  /* First time through the loop */
3044a78c22c4Sdrh       jointype = pSubitem->jointype;
3045588a9a1aSdrh     }else{
3046a78c22c4Sdrh       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
3047a78c22c4Sdrh       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
3048cfa063b3Sdrh       if( pSrc==0 ){
3049a78c22c4Sdrh         assert( db->mallocFailed );
3050a78c22c4Sdrh         break;
3051cfa063b3Sdrh       }
3052c31c2eb8Sdrh     }
3053a78c22c4Sdrh 
3054a78c22c4Sdrh     /* The subquery uses a single slot of the FROM clause of the outer
3055a78c22c4Sdrh     ** query.  If the subquery has more than one element in its FROM clause,
3056a78c22c4Sdrh     ** then expand the outer query to make space for it to hold all elements
3057a78c22c4Sdrh     ** of the subquery.
3058a78c22c4Sdrh     **
3059a78c22c4Sdrh     ** Example:
3060a78c22c4Sdrh     **
3061a78c22c4Sdrh     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
3062a78c22c4Sdrh     **
3063a78c22c4Sdrh     ** The outer query has 3 slots in its FROM clause.  One slot of the
3064a78c22c4Sdrh     ** outer query (the middle slot) is used by the subquery.  The next
3065a78c22c4Sdrh     ** block of code will expand the out query to 4 slots.  The middle
3066a78c22c4Sdrh     ** slot is expanded to two slots in order to make space for the
3067a78c22c4Sdrh     ** two elements in the FROM clause of the subquery.
3068a78c22c4Sdrh     */
3069a78c22c4Sdrh     if( nSubSrc>1 ){
3070a78c22c4Sdrh       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
3071a78c22c4Sdrh       if( db->mallocFailed ){
3072a78c22c4Sdrh         break;
3073c31c2eb8Sdrh       }
3074c31c2eb8Sdrh     }
3075a78c22c4Sdrh 
3076a78c22c4Sdrh     /* Transfer the FROM clause terms from the subquery into the
3077a78c22c4Sdrh     ** outer query.
3078a78c22c4Sdrh     */
3079c31c2eb8Sdrh     for(i=0; i<nSubSrc; i++){
3080c3a8402aSdrh       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
3081c31c2eb8Sdrh       pSrc->a[i+iFrom] = pSubSrc->a[i];
3082c31c2eb8Sdrh       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
3083c31c2eb8Sdrh     }
308461dfc31dSdrh     pSrc->a[iFrom].jointype = jointype;
3085c31c2eb8Sdrh 
3086c31c2eb8Sdrh     /* Now begin substituting subquery result set expressions for
3087c31c2eb8Sdrh     ** references to the iParent in the outer query.
3088c31c2eb8Sdrh     **
3089c31c2eb8Sdrh     ** Example:
3090c31c2eb8Sdrh     **
3091c31c2eb8Sdrh     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
3092c31c2eb8Sdrh     **   \                     \_____________ subquery __________/          /
3093c31c2eb8Sdrh     **    \_____________________ outer query ______________________________/
3094c31c2eb8Sdrh     **
3095c31c2eb8Sdrh     ** We look at every expression in the outer query and every place we see
3096c31c2eb8Sdrh     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
3097c31c2eb8Sdrh     */
3098f23329a2Sdanielk1977     pList = pParent->pEList;
3099832508b7Sdrh     for(i=0; i<pList->nExpr; i++){
3100ccfcbceaSdrh       if( pList->a[i].zName==0 ){
310142fbf321Sdrh         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
310242fbf321Sdrh         sqlite3Dequote(zName);
310342fbf321Sdrh         pList->a[i].zName = zName;
3104832508b7Sdrh       }
3105ccfcbceaSdrh     }
3106f23329a2Sdanielk1977     substExprList(db, pParent->pEList, iParent, pSub->pEList);
31071b2e0329Sdrh     if( isAgg ){
3108f23329a2Sdanielk1977       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
3109b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
31101b2e0329Sdrh     }
3111174b6195Sdrh     if( pSub->pOrderBy ){
3112f23329a2Sdanielk1977       assert( pParent->pOrderBy==0 );
3113f23329a2Sdanielk1977       pParent->pOrderBy = pSub->pOrderBy;
3114174b6195Sdrh       pSub->pOrderBy = 0;
3115f23329a2Sdanielk1977     }else if( pParent->pOrderBy ){
3116f23329a2Sdanielk1977       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
3117174b6195Sdrh     }
3118832508b7Sdrh     if( pSub->pWhere ){
31196ab3a2ecSdanielk1977       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
3120832508b7Sdrh     }else{
3121832508b7Sdrh       pWhere = 0;
3122832508b7Sdrh     }
3123832508b7Sdrh     if( subqueryIsAgg ){
3124f23329a2Sdanielk1977       assert( pParent->pHaving==0 );
3125f23329a2Sdanielk1977       pParent->pHaving = pParent->pWhere;
3126f23329a2Sdanielk1977       pParent->pWhere = pWhere;
3127b7916a78Sdrh       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
3128f23329a2Sdanielk1977       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
31296ab3a2ecSdanielk1977                                   sqlite3ExprDup(db, pSub->pHaving, 0));
3130f23329a2Sdanielk1977       assert( pParent->pGroupBy==0 );
31316ab3a2ecSdanielk1977       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
3132832508b7Sdrh     }else{
3133b7916a78Sdrh       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
3134f23329a2Sdanielk1977       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
3135832508b7Sdrh     }
3136c31c2eb8Sdrh 
3137c31c2eb8Sdrh     /* The flattened query is distinct if either the inner or the
3138c31c2eb8Sdrh     ** outer query is distinct.
3139c31c2eb8Sdrh     */
31407d10d5a6Sdrh     pParent->selFlags |= pSub->selFlags & SF_Distinct;
31418c74a8caSdrh 
3142a58fdfb1Sdanielk1977     /*
3143a58fdfb1Sdanielk1977     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
3144ac83963aSdrh     **
3145ac83963aSdrh     ** One is tempted to try to add a and b to combine the limits.  But this
3146ac83963aSdrh     ** does not work if either limit is negative.
3147a58fdfb1Sdanielk1977     */
3148a2dc3b1aSdanielk1977     if( pSub->pLimit ){
3149f23329a2Sdanielk1977       pParent->pLimit = pSub->pLimit;
3150a2dc3b1aSdanielk1977       pSub->pLimit = 0;
3151df199a25Sdrh     }
3152f23329a2Sdanielk1977   }
31538c74a8caSdrh 
3154c31c2eb8Sdrh   /* Finially, delete what is left of the subquery and return
3155c31c2eb8Sdrh   ** success.
3156c31c2eb8Sdrh   */
3157633e6d57Sdrh   sqlite3SelectDelete(db, pSub1);
3158f23329a2Sdanielk1977 
3159832508b7Sdrh   return 1;
31601350b030Sdrh }
31613514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
31621350b030Sdrh 
31631350b030Sdrh /*
31644ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first
31654ac391fcSdan ** argument, this function checks if the following are true:
3166a9d1ccb9Sdanielk1977 **
31674ac391fcSdan **    * the query contains just a single aggregate function,
31684ac391fcSdan **    * the aggregate function is either min() or max(), and
31694ac391fcSdan **    * the argument to the aggregate function is a column value.
3170738bdcfbSdanielk1977 **
31714ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
31724ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the
31734ac391fcSdan ** list of arguments passed to the aggregate before returning.
31744ac391fcSdan **
31754ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
31764ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned.
3177a9d1ccb9Sdanielk1977 */
31784ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
31794ac391fcSdan   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
3180a9d1ccb9Sdanielk1977 
31814ac391fcSdan   *ppMinMax = 0;
31824ac391fcSdan   if( pAggInfo->nFunc==1 ){
31834ac391fcSdan     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
31844ac391fcSdan     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
31854ac391fcSdan 
31864ac391fcSdan     assert( pExpr->op==TK_AGG_FUNCTION );
31874ac391fcSdan     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
31884ac391fcSdan       const char *zFunc = pExpr->u.zToken;
31894ac391fcSdan       if( sqlite3StrICmp(zFunc, "min")==0 ){
31904ac391fcSdan         eRet = WHERE_ORDERBY_MIN;
31914ac391fcSdan         *ppMinMax = pEList;
31924ac391fcSdan       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
31934ac391fcSdan         eRet = WHERE_ORDERBY_MAX;
31944ac391fcSdan         *ppMinMax = pEList;
3195a9d1ccb9Sdanielk1977       }
31964ac391fcSdan     }
31974ac391fcSdan   }
31984ac391fcSdan 
31994ac391fcSdan   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
32004ac391fcSdan   return eRet;
3201a9d1ccb9Sdanielk1977 }
3202a9d1ccb9Sdanielk1977 
3203a9d1ccb9Sdanielk1977 /*
3204a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query.
3205a5533162Sdanielk1977 ** The second argment is the associated aggregate-info object. This
3206a5533162Sdanielk1977 ** function tests if the SELECT is of the form:
3207a5533162Sdanielk1977 **
3208a5533162Sdanielk1977 **   SELECT count(*) FROM <tbl>
3209a5533162Sdanielk1977 **
3210a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query
3211a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing
3212a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned.
3213a5533162Sdanielk1977 */
3214a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
3215a5533162Sdanielk1977   Table *pTab;
3216a5533162Sdanielk1977   Expr *pExpr;
3217a5533162Sdanielk1977 
3218a5533162Sdanielk1977   assert( !p->pGroupBy );
3219a5533162Sdanielk1977 
32207a895a80Sdanielk1977   if( p->pWhere || p->pEList->nExpr!=1
3221a5533162Sdanielk1977    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
3222a5533162Sdanielk1977   ){
3223a5533162Sdanielk1977     return 0;
3224a5533162Sdanielk1977   }
3225a5533162Sdanielk1977   pTab = p->pSrc->a[0].pTab;
3226a5533162Sdanielk1977   pExpr = p->pEList->a[0].pExpr;
322702f33725Sdanielk1977   assert( pTab && !pTab->pSelect && pExpr );
322802f33725Sdanielk1977 
322902f33725Sdanielk1977   if( IsVirtual(pTab) ) return 0;
3230a5533162Sdanielk1977   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
3231fb0a6081Sdrh   if( NEVER(pAggInfo->nFunc==0) ) return 0;
3232a5533162Sdanielk1977   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
3233a5533162Sdanielk1977   if( pExpr->flags&EP_Distinct ) return 0;
3234a5533162Sdanielk1977 
3235a5533162Sdanielk1977   return pTab;
3236a5533162Sdanielk1977 }
3237a5533162Sdanielk1977 
3238a5533162Sdanielk1977 /*
3239b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an
3240b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there
3241b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return
3242b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
3243b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK.
3244b1c685b0Sdanielk1977 */
3245b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
3246b1c685b0Sdanielk1977   if( pFrom->pTab && pFrom->zIndex ){
3247b1c685b0Sdanielk1977     Table *pTab = pFrom->pTab;
3248b1c685b0Sdanielk1977     char *zIndex = pFrom->zIndex;
3249b1c685b0Sdanielk1977     Index *pIdx;
3250b1c685b0Sdanielk1977     for(pIdx=pTab->pIndex;
3251b1c685b0Sdanielk1977         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
3252b1c685b0Sdanielk1977         pIdx=pIdx->pNext
3253b1c685b0Sdanielk1977     );
3254b1c685b0Sdanielk1977     if( !pIdx ){
3255b1c685b0Sdanielk1977       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
32561db95106Sdan       pParse->checkSchema = 1;
3257b1c685b0Sdanielk1977       return SQLITE_ERROR;
3258b1c685b0Sdanielk1977     }
3259b1c685b0Sdanielk1977     pFrom->pIndex = pIdx;
3260b1c685b0Sdanielk1977   }
3261b1c685b0Sdanielk1977   return SQLITE_OK;
3262b1c685b0Sdanielk1977 }
3263b1c685b0Sdanielk1977 
3264b1c685b0Sdanielk1977 /*
32657d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement.
32667d10d5a6Sdrh ** "Expanding" means to do the following:
32677d10d5a6Sdrh **
32687d10d5a6Sdrh **    (1)  Make sure VDBE cursor numbers have been assigned to every
32697d10d5a6Sdrh **         element of the FROM clause.
32707d10d5a6Sdrh **
32717d10d5a6Sdrh **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
32727d10d5a6Sdrh **         defines FROM clause.  When views appear in the FROM clause,
32737d10d5a6Sdrh **         fill pTabList->a[].pSelect with a copy of the SELECT statement
32747d10d5a6Sdrh **         that implements the view.  A copy is made of the view's SELECT
32757d10d5a6Sdrh **         statement so that we can freely modify or delete that statement
32767d10d5a6Sdrh **         without worrying about messing up the presistent representation
32777d10d5a6Sdrh **         of the view.
32787d10d5a6Sdrh **
32797d10d5a6Sdrh **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
32807d10d5a6Sdrh **         on joins and the ON and USING clause of joins.
32817d10d5a6Sdrh **
32827d10d5a6Sdrh **    (4)  Scan the list of columns in the result set (pEList) looking
32837d10d5a6Sdrh **         for instances of the "*" operator or the TABLE.* operator.
32847d10d5a6Sdrh **         If found, expand each "*" to be every column in every table
32857d10d5a6Sdrh **         and TABLE.* to be every column in TABLE.
32867d10d5a6Sdrh **
3287b3bce662Sdanielk1977 */
32887d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){
32897d10d5a6Sdrh   Parse *pParse = pWalker->pParse;
32907d10d5a6Sdrh   int i, j, k;
32917d10d5a6Sdrh   SrcList *pTabList;
32927d10d5a6Sdrh   ExprList *pEList;
32937d10d5a6Sdrh   struct SrcList_item *pFrom;
32947d10d5a6Sdrh   sqlite3 *db = pParse->db;
32953e3f1a5bSdrh   Expr *pE, *pRight, *pExpr;
3296785097daSdrh   u16 selFlags = p->selFlags;
32977d10d5a6Sdrh 
3298785097daSdrh   p->selFlags |= SF_Expanded;
32997d10d5a6Sdrh   if( db->mallocFailed  ){
33007d10d5a6Sdrh     return WRC_Abort;
33017d10d5a6Sdrh   }
3302785097daSdrh   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
33037d10d5a6Sdrh     return WRC_Prune;
33047d10d5a6Sdrh   }
33057d10d5a6Sdrh   pTabList = p->pSrc;
33067d10d5a6Sdrh   pEList = p->pEList;
33077d10d5a6Sdrh 
33087d10d5a6Sdrh   /* Make sure cursor numbers have been assigned to all entries in
33097d10d5a6Sdrh   ** the FROM clause of the SELECT statement.
33107d10d5a6Sdrh   */
33117d10d5a6Sdrh   sqlite3SrcListAssignCursors(pParse, pTabList);
33127d10d5a6Sdrh 
33137d10d5a6Sdrh   /* Look up every table named in the FROM clause of the select.  If
33147d10d5a6Sdrh   ** an entry of the FROM clause is a subquery instead of a table or view,
33157d10d5a6Sdrh   ** then create a transient table structure to describe the subquery.
33167d10d5a6Sdrh   */
33177d10d5a6Sdrh   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
33187d10d5a6Sdrh     Table *pTab;
33197d10d5a6Sdrh     if( pFrom->pTab!=0 ){
33207d10d5a6Sdrh       /* This statement has already been prepared.  There is no need
33217d10d5a6Sdrh       ** to go further. */
33227d10d5a6Sdrh       assert( i==0 );
33237d10d5a6Sdrh       return WRC_Prune;
33247d10d5a6Sdrh     }
33257d10d5a6Sdrh     if( pFrom->zName==0 ){
33267d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
33277d10d5a6Sdrh       Select *pSel = pFrom->pSelect;
33287d10d5a6Sdrh       /* A sub-query in the FROM clause of a SELECT */
33297d10d5a6Sdrh       assert( pSel!=0 );
33307d10d5a6Sdrh       assert( pFrom->pTab==0 );
33317d10d5a6Sdrh       sqlite3WalkSelect(pWalker, pSel);
33327d10d5a6Sdrh       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
33337d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
33347d10d5a6Sdrh       pTab->nRef = 1;
33357d10d5a6Sdrh       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
33367d10d5a6Sdrh       while( pSel->pPrior ){ pSel = pSel->pPrior; }
33377d10d5a6Sdrh       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
33387d10d5a6Sdrh       pTab->iPKey = -1;
33391ea87012Sdrh       pTab->nRowEst = 1000000;
33407d10d5a6Sdrh       pTab->tabFlags |= TF_Ephemeral;
33417d10d5a6Sdrh #endif
33427d10d5a6Sdrh     }else{
33437d10d5a6Sdrh       /* An ordinary table or view name in the FROM clause */
33447d10d5a6Sdrh       assert( pFrom->pTab==0 );
334541fb5cd1Sdan       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
33467d10d5a6Sdrh       if( pTab==0 ) return WRC_Abort;
3347d2a56238Sdrh       if( pTab->nRef==0xffff ){
3348d2a56238Sdrh         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
3349d2a56238Sdrh            pTab->zName);
3350d2a56238Sdrh         pFrom->pTab = 0;
3351d2a56238Sdrh         return WRC_Abort;
3352d2a56238Sdrh       }
33537d10d5a6Sdrh       pTab->nRef++;
33547d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
33557d10d5a6Sdrh       if( pTab->pSelect || IsVirtual(pTab) ){
33567d10d5a6Sdrh         /* We reach here if the named table is a really a view */
33577d10d5a6Sdrh         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
335843152cf8Sdrh         assert( pFrom->pSelect==0 );
33596ab3a2ecSdanielk1977         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
33607d10d5a6Sdrh         sqlite3WalkSelect(pWalker, pFrom->pSelect);
33617d10d5a6Sdrh       }
33627d10d5a6Sdrh #endif
33637d10d5a6Sdrh     }
336485574e31Sdanielk1977 
336585574e31Sdanielk1977     /* Locate the index named by the INDEXED BY clause, if any. */
3366b1c685b0Sdanielk1977     if( sqlite3IndexedByLookup(pParse, pFrom) ){
336785574e31Sdanielk1977       return WRC_Abort;
336885574e31Sdanielk1977     }
33697d10d5a6Sdrh   }
33707d10d5a6Sdrh 
33717d10d5a6Sdrh   /* Process NATURAL keywords, and ON and USING clauses of joins.
33727d10d5a6Sdrh   */
33737d10d5a6Sdrh   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
33747d10d5a6Sdrh     return WRC_Abort;
33757d10d5a6Sdrh   }
33767d10d5a6Sdrh 
33777d10d5a6Sdrh   /* For every "*" that occurs in the column list, insert the names of
33787d10d5a6Sdrh   ** all columns in all tables.  And for every TABLE.* insert the names
33797d10d5a6Sdrh   ** of all columns in TABLE.  The parser inserted a special expression
33807d10d5a6Sdrh   ** with the TK_ALL operator for each "*" that it found in the column list.
33817d10d5a6Sdrh   ** The following code just has to locate the TK_ALL expressions and expand
33827d10d5a6Sdrh   ** each one to the list of all columns in all tables.
33837d10d5a6Sdrh   **
33847d10d5a6Sdrh   ** The first loop just checks to see if there are any "*" operators
33857d10d5a6Sdrh   ** that need expanding.
33867d10d5a6Sdrh   */
33877d10d5a6Sdrh   for(k=0; k<pEList->nExpr; k++){
33883e3f1a5bSdrh     pE = pEList->a[k].pExpr;
33897d10d5a6Sdrh     if( pE->op==TK_ALL ) break;
339043152cf8Sdrh     assert( pE->op!=TK_DOT || pE->pRight!=0 );
339143152cf8Sdrh     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
339243152cf8Sdrh     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
33937d10d5a6Sdrh   }
33947d10d5a6Sdrh   if( k<pEList->nExpr ){
33957d10d5a6Sdrh     /*
33967d10d5a6Sdrh     ** If we get here it means the result set contains one or more "*"
33977d10d5a6Sdrh     ** operators that need to be expanded.  Loop through each expression
33987d10d5a6Sdrh     ** in the result set and expand them one by one.
33997d10d5a6Sdrh     */
34007d10d5a6Sdrh     struct ExprList_item *a = pEList->a;
34017d10d5a6Sdrh     ExprList *pNew = 0;
34027d10d5a6Sdrh     int flags = pParse->db->flags;
34037d10d5a6Sdrh     int longNames = (flags & SQLITE_FullColNames)!=0
340438b384a0Sdrh                       && (flags & SQLITE_ShortColNames)==0;
340538b384a0Sdrh 
340638b384a0Sdrh     /* When processing FROM-clause subqueries, it is always the case
340738b384a0Sdrh     ** that full_column_names=OFF and short_column_names=ON.  The
340838b384a0Sdrh     ** sqlite3ResultSetOfSelect() routine makes it so. */
340938b384a0Sdrh     assert( (p->selFlags & SF_NestedFrom)==0
341038b384a0Sdrh           || ((flags & SQLITE_FullColNames)==0 &&
341138b384a0Sdrh               (flags & SQLITE_ShortColNames)!=0) );
34127d10d5a6Sdrh 
34137d10d5a6Sdrh     for(k=0; k<pEList->nExpr; k++){
34143e3f1a5bSdrh       pE = a[k].pExpr;
34153e3f1a5bSdrh       pRight = pE->pRight;
34163e3f1a5bSdrh       assert( pE->op!=TK_DOT || pRight!=0 );
34173e3f1a5bSdrh       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
34187d10d5a6Sdrh         /* This particular expression does not need to be expanded.
34197d10d5a6Sdrh         */
3420b7916a78Sdrh         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
34217d10d5a6Sdrh         if( pNew ){
34227d10d5a6Sdrh           pNew->a[pNew->nExpr-1].zName = a[k].zName;
3423b7916a78Sdrh           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
3424b7916a78Sdrh           a[k].zName = 0;
3425b7916a78Sdrh           a[k].zSpan = 0;
34267d10d5a6Sdrh         }
34277d10d5a6Sdrh         a[k].pExpr = 0;
34287d10d5a6Sdrh       }else{
34297d10d5a6Sdrh         /* This expression is a "*" or a "TABLE.*" and needs to be
34307d10d5a6Sdrh         ** expanded. */
34317d10d5a6Sdrh         int tableSeen = 0;      /* Set to 1 when TABLE matches */
34323e3f1a5bSdrh         char *zTName = 0;       /* text of name of TABLE */
343343152cf8Sdrh         if( pE->op==TK_DOT ){
343443152cf8Sdrh           assert( pE->pLeft!=0 );
343533e619fcSdrh           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
343633e619fcSdrh           zTName = pE->pLeft->u.zToken;
34377d10d5a6Sdrh         }
34387d10d5a6Sdrh         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
34397d10d5a6Sdrh           Table *pTab = pFrom->pTab;
34403e3f1a5bSdrh           Select *pSub = pFrom->pSelect;
34417d10d5a6Sdrh           char *zTabName = pFrom->zAlias;
34423e3f1a5bSdrh           const char *zSchemaName = 0;
3443c75e09c7Sdrh           int iDb;
344443152cf8Sdrh           if( zTabName==0 ){
34457d10d5a6Sdrh             zTabName = pTab->zName;
34467d10d5a6Sdrh           }
34477d10d5a6Sdrh           if( db->mallocFailed ) break;
34483e3f1a5bSdrh           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
34493e3f1a5bSdrh             pSub = 0;
34507d10d5a6Sdrh             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
34517d10d5a6Sdrh               continue;
34527d10d5a6Sdrh             }
34533e3f1a5bSdrh             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3454c75e09c7Sdrh             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
34553e3f1a5bSdrh           }
34567d10d5a6Sdrh           for(j=0; j<pTab->nCol; j++){
34577d10d5a6Sdrh             char *zName = pTab->aCol[j].zName;
3458b7916a78Sdrh             char *zColname;  /* The computed column name */
3459b7916a78Sdrh             char *zToFree;   /* Malloced string that needs to be freed */
3460b7916a78Sdrh             Token sColname;  /* Computed column name as a token */
34617d10d5a6Sdrh 
3462c75e09c7Sdrh             assert( zName );
34633e3f1a5bSdrh             if( zTName && pSub
34643e3f1a5bSdrh              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
34653e3f1a5bSdrh             ){
34663e3f1a5bSdrh               continue;
34673e3f1a5bSdrh             }
34683e3f1a5bSdrh 
34697d10d5a6Sdrh             /* If a column is marked as 'hidden' (currently only possible
34707d10d5a6Sdrh             ** for virtual tables), do not include it in the expanded
34717d10d5a6Sdrh             ** result-set list.
34727d10d5a6Sdrh             */
34737d10d5a6Sdrh             if( IsHiddenColumn(&pTab->aCol[j]) ){
34747d10d5a6Sdrh               assert(IsVirtual(pTab));
34757d10d5a6Sdrh               continue;
34767d10d5a6Sdrh             }
34773e3f1a5bSdrh             tableSeen = 1;
34787d10d5a6Sdrh 
3479da55c48aSdrh             if( i>0 && zTName==0 ){
34802179b434Sdrh               if( (pFrom->jointype & JT_NATURAL)!=0
34812179b434Sdrh                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
34822179b434Sdrh               ){
34837d10d5a6Sdrh                 /* In a NATURAL join, omit the join columns from the
34842179b434Sdrh                 ** table to the right of the join */
34857d10d5a6Sdrh                 continue;
34867d10d5a6Sdrh               }
34872179b434Sdrh               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
34887d10d5a6Sdrh                 /* In a join with a USING clause, omit columns in the
34897d10d5a6Sdrh                 ** using clause from the table on the right. */
34907d10d5a6Sdrh                 continue;
34917d10d5a6Sdrh               }
34927d10d5a6Sdrh             }
3493b7916a78Sdrh             pRight = sqlite3Expr(db, TK_ID, zName);
3494b7916a78Sdrh             zColname = zName;
3495b7916a78Sdrh             zToFree = 0;
34967d10d5a6Sdrh             if( longNames || pTabList->nSrc>1 ){
3497b7916a78Sdrh               Expr *pLeft;
3498b7916a78Sdrh               pLeft = sqlite3Expr(db, TK_ID, zTabName);
34997d10d5a6Sdrh               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
350038b384a0Sdrh               if( zSchemaName ){
3501c75e09c7Sdrh                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
3502c75e09c7Sdrh                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
3503c75e09c7Sdrh               }
3504b7916a78Sdrh               if( longNames ){
3505b7916a78Sdrh                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
3506b7916a78Sdrh                 zToFree = zColname;
3507b7916a78Sdrh               }
35087d10d5a6Sdrh             }else{
35097d10d5a6Sdrh               pExpr = pRight;
35107d10d5a6Sdrh             }
3511b7916a78Sdrh             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
3512b7916a78Sdrh             sColname.z = zColname;
3513b7916a78Sdrh             sColname.n = sqlite3Strlen30(zColname);
3514b7916a78Sdrh             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
35158f25d18bSdrh             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
35163e3f1a5bSdrh               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
35173e3f1a5bSdrh               if( pSub ){
35183e3f1a5bSdrh                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
3519c75e09c7Sdrh                 testcase( pX->zSpan==0 );
35203e3f1a5bSdrh               }else{
35213e3f1a5bSdrh                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
35223e3f1a5bSdrh                                            zSchemaName, zTabName, zColname);
3523c75e09c7Sdrh                 testcase( pX->zSpan==0 );
35243e3f1a5bSdrh               }
35253e3f1a5bSdrh               pX->bSpanIsTab = 1;
35268f25d18bSdrh             }
3527b7916a78Sdrh             sqlite3DbFree(db, zToFree);
35287d10d5a6Sdrh           }
35297d10d5a6Sdrh         }
35307d10d5a6Sdrh         if( !tableSeen ){
35317d10d5a6Sdrh           if( zTName ){
35327d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
35337d10d5a6Sdrh           }else{
35347d10d5a6Sdrh             sqlite3ErrorMsg(pParse, "no tables specified");
35357d10d5a6Sdrh           }
35367d10d5a6Sdrh         }
35377d10d5a6Sdrh       }
35387d10d5a6Sdrh     }
35397d10d5a6Sdrh     sqlite3ExprListDelete(db, pEList);
35407d10d5a6Sdrh     p->pEList = pNew;
35417d10d5a6Sdrh   }
35427d10d5a6Sdrh #if SQLITE_MAX_COLUMN
35437d10d5a6Sdrh   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
35447d10d5a6Sdrh     sqlite3ErrorMsg(pParse, "too many columns in result set");
35457d10d5a6Sdrh   }
35467d10d5a6Sdrh #endif
35477d10d5a6Sdrh   return WRC_Continue;
35487d10d5a6Sdrh }
35497d10d5a6Sdrh 
35507d10d5a6Sdrh /*
35517d10d5a6Sdrh ** No-op routine for the parse-tree walker.
35527d10d5a6Sdrh **
35537d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees
35547d10d5a6Sdrh ** are walked without any actions being taken at each node.  Presumably,
35557d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then
35567d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every
35577d10d5a6Sdrh ** subquery in the parser tree.
35587d10d5a6Sdrh */
355962c14b34Sdanielk1977 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
356062c14b34Sdanielk1977   UNUSED_PARAMETER2(NotUsed, NotUsed2);
35617d10d5a6Sdrh   return WRC_Continue;
35627d10d5a6Sdrh }
35637d10d5a6Sdrh 
35647d10d5a6Sdrh /*
35657d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries.
35667d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT
35677d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above.
35687d10d5a6Sdrh **
35697d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a
35707d10d5a6Sdrh ** SELECT statement.  The SELECT statement must be expanded before
35717d10d5a6Sdrh ** name resolution is performed.
35727d10d5a6Sdrh **
35737d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse.
35747d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr
35757d10d5a6Sdrh ** and/or pParse->db->mallocFailed.
35767d10d5a6Sdrh */
35777d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
35787d10d5a6Sdrh   Walker w;
3579*aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
35807d10d5a6Sdrh   w.xSelectCallback = selectExpander;
35817d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
35827d10d5a6Sdrh   w.pParse = pParse;
35837d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
35847d10d5a6Sdrh }
35857d10d5a6Sdrh 
35867d10d5a6Sdrh 
35877d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
35887d10d5a6Sdrh /*
35897d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
35907d10d5a6Sdrh ** interface.
35917d10d5a6Sdrh **
35927d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl
35937d10d5a6Sdrh ** information to the Table structure that represents the result set
35947d10d5a6Sdrh ** of that subquery.
35957d10d5a6Sdrh **
35967d10d5a6Sdrh ** The Table structure that represents the result set was constructed
35977d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted
35987d10d5a6Sdrh ** at that point because identifiers had not yet been resolved.  This
35997d10d5a6Sdrh ** routine is called after identifier resolution.
36007d10d5a6Sdrh */
36017d10d5a6Sdrh static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
36027d10d5a6Sdrh   Parse *pParse;
36037d10d5a6Sdrh   int i;
36047d10d5a6Sdrh   SrcList *pTabList;
36057d10d5a6Sdrh   struct SrcList_item *pFrom;
36067d10d5a6Sdrh 
36079d8b3072Sdrh   assert( p->selFlags & SF_Resolved );
36085a29d9cbSdrh   if( (p->selFlags & SF_HasTypeInfo)==0 ){
36097d10d5a6Sdrh     p->selFlags |= SF_HasTypeInfo;
36107d10d5a6Sdrh     pParse = pWalker->pParse;
36117d10d5a6Sdrh     pTabList = p->pSrc;
36127d10d5a6Sdrh     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
36137d10d5a6Sdrh       Table *pTab = pFrom->pTab;
361443152cf8Sdrh       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
36157d10d5a6Sdrh         /* A sub-query in the FROM clause of a SELECT */
36167d10d5a6Sdrh         Select *pSel = pFrom->pSelect;
36177d10d5a6Sdrh         assert( pSel );
36187d10d5a6Sdrh         while( pSel->pPrior ) pSel = pSel->pPrior;
36197d10d5a6Sdrh         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
36207d10d5a6Sdrh       }
36217d10d5a6Sdrh     }
36225a29d9cbSdrh   }
36237d10d5a6Sdrh   return WRC_Continue;
36247d10d5a6Sdrh }
36257d10d5a6Sdrh #endif
36267d10d5a6Sdrh 
36277d10d5a6Sdrh 
36287d10d5a6Sdrh /*
36297d10d5a6Sdrh ** This routine adds datatype and collating sequence information to
36307d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a
36317d10d5a6Sdrh ** SELECT statement.
36327d10d5a6Sdrh **
36337d10d5a6Sdrh ** Use this routine after name resolution.
36347d10d5a6Sdrh */
36357d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
36367d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY
36377d10d5a6Sdrh   Walker w;
3638*aa87f9a6Sdrh   memset(&w, 0, sizeof(w));
36397d10d5a6Sdrh   w.xSelectCallback = selectAddSubqueryTypeInfo;
36407d10d5a6Sdrh   w.xExprCallback = exprWalkNoop;
36417d10d5a6Sdrh   w.pParse = pParse;
3642*aa87f9a6Sdrh   w.bSelectDepthFirst = 1;
36437d10d5a6Sdrh   sqlite3WalkSelect(&w, pSelect);
36447d10d5a6Sdrh #endif
36457d10d5a6Sdrh }
36467d10d5a6Sdrh 
36477d10d5a6Sdrh 
36487d10d5a6Sdrh /*
3649030796dfSdrh ** This routine sets up a SELECT statement for processing.  The
36507d10d5a6Sdrh ** following is accomplished:
36517d10d5a6Sdrh **
36527d10d5a6Sdrh **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
36537d10d5a6Sdrh **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
36547d10d5a6Sdrh **     *  ON and USING clauses are shifted into WHERE statements
36557d10d5a6Sdrh **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
36567d10d5a6Sdrh **     *  Identifiers in expression are matched to tables.
36577d10d5a6Sdrh **
36587d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT.
36597d10d5a6Sdrh */
36607d10d5a6Sdrh void sqlite3SelectPrep(
3661b3bce662Sdanielk1977   Parse *pParse,         /* The parser context */
3662b3bce662Sdanielk1977   Select *p,             /* The SELECT statement being coded. */
36637d10d5a6Sdrh   NameContext *pOuterNC  /* Name context for container */
3664b3bce662Sdanielk1977 ){
36657d10d5a6Sdrh   sqlite3 *db;
366643152cf8Sdrh   if( NEVER(p==0) ) return;
36677d10d5a6Sdrh   db = pParse->db;
3668785097daSdrh   if( db->mallocFailed ) return;
36697d10d5a6Sdrh   if( p->selFlags & SF_HasTypeInfo ) return;
36707d10d5a6Sdrh   sqlite3SelectExpand(pParse, p);
36717d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
36727d10d5a6Sdrh   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
36737d10d5a6Sdrh   if( pParse->nErr || db->mallocFailed ) return;
36747d10d5a6Sdrh   sqlite3SelectAddTypeInfo(pParse, p);
3675f6bbe022Sdrh }
3676b3bce662Sdanielk1977 
3677b3bce662Sdanielk1977 /*
367813449892Sdrh ** Reset the aggregate accumulator.
367913449892Sdrh **
368013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold
368113449892Sdrh ** intermediate results while calculating an aggregate.  This
3682030796dfSdrh ** routine generates code that stores NULLs in all of those memory
3683030796dfSdrh ** cells.
3684b3bce662Sdanielk1977 */
368513449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
368613449892Sdrh   Vdbe *v = pParse->pVdbe;
368713449892Sdrh   int i;
3688c99130fdSdrh   struct AggInfo_func *pFunc;
368913449892Sdrh   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
369013449892Sdrh     return;
369113449892Sdrh   }
369213449892Sdrh   for(i=0; i<pAggInfo->nColumn; i++){
36934c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
369413449892Sdrh   }
3695c99130fdSdrh   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
36964c583128Sdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
3697c99130fdSdrh     if( pFunc->iDistinct>=0 ){
3698c99130fdSdrh       Expr *pE = pFunc->pExpr;
36996ab3a2ecSdanielk1977       assert( !ExprHasProperty(pE, EP_xIsSelect) );
37006ab3a2ecSdanielk1977       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
37010daa002cSdrh         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
37020daa002cSdrh            "argument");
3703c99130fdSdrh         pFunc->iDistinct = -1;
3704c99130fdSdrh       }else{
37056ab3a2ecSdanielk1977         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
370666a5167bSdrh         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
370766a5167bSdrh                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
3708c99130fdSdrh       }
3709c99130fdSdrh     }
371013449892Sdrh   }
3711b3bce662Sdanielk1977 }
3712b3bce662Sdanielk1977 
3713b3bce662Sdanielk1977 /*
371413449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function
371513449892Sdrh ** in the AggInfo structure.
3716b3bce662Sdanielk1977 */
371713449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
371813449892Sdrh   Vdbe *v = pParse->pVdbe;
371913449892Sdrh   int i;
372013449892Sdrh   struct AggInfo_func *pF;
372113449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
37226ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
37236ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
372466a5167bSdrh     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
372566a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3726b3bce662Sdanielk1977   }
372713449892Sdrh }
372813449892Sdrh 
372913449892Sdrh /*
373013449892Sdrh ** Update the accumulator memory cells for an aggregate based on
373113449892Sdrh ** the current cursor position.
373213449892Sdrh */
373313449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
373413449892Sdrh   Vdbe *v = pParse->pVdbe;
373513449892Sdrh   int i;
37367a95789cSdrh   int regHit = 0;
37377a95789cSdrh   int addrHitTest = 0;
373813449892Sdrh   struct AggInfo_func *pF;
373913449892Sdrh   struct AggInfo_col *pC;
374013449892Sdrh 
374113449892Sdrh   pAggInfo->directMode = 1;
3742ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
374313449892Sdrh   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
374413449892Sdrh     int nArg;
3745c99130fdSdrh     int addrNext = 0;
374698757157Sdrh     int regAgg;
37476ab3a2ecSdanielk1977     ExprList *pList = pF->pExpr->x.pList;
37486ab3a2ecSdanielk1977     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
374913449892Sdrh     if( pList ){
375013449892Sdrh       nArg = pList->nExpr;
3751892d3179Sdrh       regAgg = sqlite3GetTempRange(pParse, nArg);
37527153d1fbSdrh       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
375313449892Sdrh     }else{
375413449892Sdrh       nArg = 0;
375598757157Sdrh       regAgg = 0;
375613449892Sdrh     }
3757c99130fdSdrh     if( pF->iDistinct>=0 ){
3758c99130fdSdrh       addrNext = sqlite3VdbeMakeLabel(v);
3759c99130fdSdrh       assert( nArg==1 );
37602dcef11bSdrh       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
3761c99130fdSdrh     }
3762e82f5d04Sdrh     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
376313449892Sdrh       CollSeq *pColl = 0;
376413449892Sdrh       struct ExprList_item *pItem;
376513449892Sdrh       int j;
3766e82f5d04Sdrh       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
376743617e9aSdrh       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
376813449892Sdrh         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
376913449892Sdrh       }
377013449892Sdrh       if( !pColl ){
377113449892Sdrh         pColl = pParse->db->pDfltColl;
377213449892Sdrh       }
37737a95789cSdrh       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
37747a95789cSdrh       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
377513449892Sdrh     }
377698757157Sdrh     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
377766a5167bSdrh                       (void*)pF->pFunc, P4_FUNCDEF);
3778ea678832Sdrh     sqlite3VdbeChangeP5(v, (u8)nArg);
3779da250ea5Sdrh     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
3780f49f3523Sdrh     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
3781c99130fdSdrh     if( addrNext ){
3782c99130fdSdrh       sqlite3VdbeResolveLabel(v, addrNext);
3783ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
3784c99130fdSdrh     }
378513449892Sdrh   }
378667a6a40cSdan 
378767a6a40cSdan   /* Before populating the accumulator registers, clear the column cache.
378867a6a40cSdan   ** Otherwise, if any of the required column values are already present
378967a6a40cSdan   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
379067a6a40cSdan   ** to pC->iMem. But by the time the value is used, the original register
379167a6a40cSdan   ** may have been used, invalidating the underlying buffer holding the
379267a6a40cSdan   ** text or blob value. See ticket [883034dcb5].
379367a6a40cSdan   **
379467a6a40cSdan   ** Another solution would be to change the OP_SCopy used to copy cached
379567a6a40cSdan   ** values to an OP_Copy.
379667a6a40cSdan   */
37977a95789cSdrh   if( regHit ){
37987a95789cSdrh     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
37997a95789cSdrh   }
380067a6a40cSdan   sqlite3ExprCacheClear(pParse);
380113449892Sdrh   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
3802389a1adbSdrh     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
380313449892Sdrh   }
380413449892Sdrh   pAggInfo->directMode = 0;
3805ceea3321Sdrh   sqlite3ExprCacheClear(pParse);
38067a95789cSdrh   if( addrHitTest ){
38077a95789cSdrh     sqlite3VdbeJumpHere(v, addrHitTest);
38087a95789cSdrh   }
380913449892Sdrh }
381013449892Sdrh 
3811b3bce662Sdanielk1977 /*
3812ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple
3813ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab").
3814ef7075deSdan */
3815ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN
3816ef7075deSdan static void explainSimpleCount(
3817ef7075deSdan   Parse *pParse,                  /* Parse context */
3818ef7075deSdan   Table *pTab,                    /* Table being queried */
3819ef7075deSdan   Index *pIdx                     /* Index used to optimize scan, or NULL */
3820ef7075deSdan ){
3821ef7075deSdan   if( pParse->explain==2 ){
3822ef7075deSdan     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
3823ef7075deSdan         pTab->zName,
3824ef7075deSdan         pIdx ? "USING COVERING INDEX " : "",
3825ef7075deSdan         pIdx ? pIdx->zName : "",
3826ef7075deSdan         pTab->nRowEst
3827ef7075deSdan     );
3828ef7075deSdan     sqlite3VdbeAddOp4(
3829ef7075deSdan         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
3830ef7075deSdan     );
3831ef7075deSdan   }
3832ef7075deSdan }
3833ef7075deSdan #else
3834ef7075deSdan # define explainSimpleCount(a,b,c)
3835ef7075deSdan #endif
3836ef7075deSdan 
3837ef7075deSdan /*
38387d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument.
38399bb61fe7Sdrh **
3840fef5208cSdrh ** The results are distributed in various ways depending on the
38416c8c8ce0Sdanielk1977 ** contents of the SelectDest structure pointed to by argument pDest
38426c8c8ce0Sdanielk1977 ** as follows:
3843fef5208cSdrh **
38446c8c8ce0Sdanielk1977 **     pDest->eDest    Result
3845fef5208cSdrh **     ------------    -------------------------------------------
38467d10d5a6Sdrh **     SRT_Output      Generate a row of output (using the OP_ResultRow
38477d10d5a6Sdrh **                     opcode) for each row in the result set.
3848fef5208cSdrh **
38497d10d5a6Sdrh **     SRT_Mem         Only valid if the result is a single column.
38507d10d5a6Sdrh **                     Store the first column of the first result row
38512b596da8Sdrh **                     in register pDest->iSDParm then abandon the rest
38527d10d5a6Sdrh **                     of the query.  This destination implies "LIMIT 1".
3853fef5208cSdrh **
38547d10d5a6Sdrh **     SRT_Set         The result must be a single column.  Store each
38552b596da8Sdrh **                     row of result as the key in table pDest->iSDParm.
3856c041c16cSdrh **                     Apply the affinity pDest->affSdst before storing
38577d10d5a6Sdrh **                     results.  Used to implement "IN (SELECT ...)".
3858fef5208cSdrh **
38592b596da8Sdrh **     SRT_Union       Store results as a key in a temporary table
38602b596da8Sdrh **                     identified by pDest->iSDParm.
386182c3d636Sdrh **
38622b596da8Sdrh **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
3863c4a3c779Sdrh **
38642b596da8Sdrh **     SRT_Table       Store results in temporary table pDest->iSDParm.
38657d10d5a6Sdrh **                     This is like SRT_EphemTab except that the table
38667d10d5a6Sdrh **                     is assumed to already be open.
38679bb61fe7Sdrh **
38682b596da8Sdrh **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
38696c8c8ce0Sdanielk1977 **                     the result there. The cursor is left open after
38707d10d5a6Sdrh **                     returning.  This is like SRT_Table except that
38717d10d5a6Sdrh **                     this destination uses OP_OpenEphemeral to create
38727d10d5a6Sdrh **                     the table first.
38736c8c8ce0Sdanielk1977 **
38747d10d5a6Sdrh **     SRT_Coroutine   Generate a co-routine that returns a new row of
38757d10d5a6Sdrh **                     results each time it is invoked.  The entry point
38762b596da8Sdrh **                     of the co-routine is stored in register pDest->iSDParm.
38776c8c8ce0Sdanielk1977 **
38782b596da8Sdrh **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
38796c8c8ce0Sdanielk1977 **                     set is not empty.
38806c8c8ce0Sdanielk1977 **
38817d10d5a6Sdrh **     SRT_Discard     Throw the results away.  This is used by SELECT
38827d10d5a6Sdrh **                     statements within triggers whose only purpose is
38837d10d5a6Sdrh **                     the side-effects of functions.
3884e78e8284Sdrh **
38859bb61fe7Sdrh ** This routine returns the number of errors.  If any errors are
38869bb61fe7Sdrh ** encountered, then an appropriate error message is left in
38879bb61fe7Sdrh ** pParse->zErrMsg.
38889bb61fe7Sdrh **
38899bb61fe7Sdrh ** This routine does NOT free the Select structure passed in.  The
38909bb61fe7Sdrh ** calling function needs to do that.
38919bb61fe7Sdrh */
38924adee20fSdanielk1977 int sqlite3Select(
3893cce7d176Sdrh   Parse *pParse,         /* The parser context */
38949bb61fe7Sdrh   Select *p,             /* The SELECT statement being coded. */
38957d10d5a6Sdrh   SelectDest *pDest      /* What to do with the query results */
3896cce7d176Sdrh ){
389713449892Sdrh   int i, j;              /* Loop counters */
389813449892Sdrh   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
389913449892Sdrh   Vdbe *v;               /* The virtual machine under construction */
3900b3bce662Sdanielk1977   int isAgg;             /* True for select lists like "count(*)" */
3901a2e00042Sdrh   ExprList *pEList;      /* List of columns to extract. */
3902ad3cab52Sdrh   SrcList *pTabList;     /* List of tables to select from */
39039bb61fe7Sdrh   Expr *pWhere;          /* The WHERE clause.  May be NULL */
39049bb61fe7Sdrh   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
39052282792aSdrh   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
39062282792aSdrh   Expr *pHaving;         /* The HAVING clause.  May be NULL */
39071d83f052Sdrh   int rc = 1;            /* Value to return from this function */
3908b9bb7c18Sdrh   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
3909e8e4af76Sdrh   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
391013449892Sdrh   AggInfo sAggInfo;      /* Information used by aggregate queries */
3911ec7429aeSdrh   int iEnd;              /* Address of the end of the query */
391217435752Sdrh   sqlite3 *db;           /* The database connection */
39139bb61fe7Sdrh 
39142ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN
39152ce22453Sdan   int iRestoreSelectId = pParse->iSelectId;
39162ce22453Sdan   pParse->iSelectId = pParse->iNextSelectId++;
39172ce22453Sdan #endif
39182ce22453Sdan 
391917435752Sdrh   db = pParse->db;
392017435752Sdrh   if( p==0 || db->mallocFailed || pParse->nErr ){
39216f7adc8aSdrh     return 1;
39226f7adc8aSdrh   }
39234adee20fSdanielk1977   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
392413449892Sdrh   memset(&sAggInfo, 0, sizeof(sAggInfo));
3925daffd0e5Sdrh 
39266c8c8ce0Sdanielk1977   if( IgnorableOrderby(pDest) ){
39279ed1dfa8Sdanielk1977     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
39289ed1dfa8Sdanielk1977            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
3929ccfcbceaSdrh     /* If ORDER BY makes no difference in the output then neither does
3930ccfcbceaSdrh     ** DISTINCT so it can be removed too. */
3931ccfcbceaSdrh     sqlite3ExprListDelete(db, p->pOrderBy);
3932ccfcbceaSdrh     p->pOrderBy = 0;
39337d10d5a6Sdrh     p->selFlags &= ~SF_Distinct;
39349a99334dSdrh   }
39357d10d5a6Sdrh   sqlite3SelectPrep(pParse, p, 0);
3936ccfcbceaSdrh   pOrderBy = p->pOrderBy;
3937b27b7f5dSdrh   pTabList = p->pSrc;
3938b27b7f5dSdrh   pEList = p->pEList;
3939956f4319Sdanielk1977   if( pParse->nErr || db->mallocFailed ){
39409a99334dSdrh     goto select_end;
39419a99334dSdrh   }
39427d10d5a6Sdrh   isAgg = (p->selFlags & SF_Aggregate)!=0;
394343152cf8Sdrh   assert( pEList!=0 );
3944cce7d176Sdrh 
3945d820cb1bSdrh   /* Begin generating code.
3946d820cb1bSdrh   */
39474adee20fSdanielk1977   v = sqlite3GetVdbe(pParse);
3948d820cb1bSdrh   if( v==0 ) goto select_end;
3949d820cb1bSdrh 
395074b617b2Sdan   /* If writing to memory or generating a set
395174b617b2Sdan   ** only a single column may be output.
395274b617b2Sdan   */
395374b617b2Sdan #ifndef SQLITE_OMIT_SUBQUERY
395474b617b2Sdan   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
395574b617b2Sdan     goto select_end;
395674b617b2Sdan   }
395774b617b2Sdan #endif
395874b617b2Sdan 
3959d820cb1bSdrh   /* Generate code for all sub-queries in the FROM clause
3960d820cb1bSdrh   */
396151522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3962f23329a2Sdanielk1977   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
396313449892Sdrh     struct SrcList_item *pItem = &pTabList->a[i];
39641013c932Sdrh     SelectDest dest;
3965daf79acbSdanielk1977     Select *pSub = pItem->pSelect;
3966f23329a2Sdanielk1977     int isAggSub;
3967c31c2eb8Sdrh 
39685b6a9ed4Sdrh     if( pSub==0 ) continue;
396921172c4cSdrh 
397021172c4cSdrh     /* Sometimes the code for a subquery will be generated more than
397121172c4cSdrh     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
397221172c4cSdrh     ** for example.  In that case, do not regenerate the code to manifest
397321172c4cSdrh     ** a view or the co-routine to implement a view.  The first instance
397421172c4cSdrh     ** is sufficient, though the subroutine to manifest the view does need
397521172c4cSdrh     ** to be invoked again. */
39765b6a9ed4Sdrh     if( pItem->addrFillSub ){
397721172c4cSdrh       if( pItem->viaCoroutine==0 ){
39785b6a9ed4Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
397921172c4cSdrh       }
39805b6a9ed4Sdrh       continue;
39815b6a9ed4Sdrh     }
3982daf79acbSdanielk1977 
3983fc976065Sdanielk1977     /* Increment Parse.nHeight by the height of the largest expression
3984fc976065Sdanielk1977     ** tree refered to by this, the parent select. The child select
3985fc976065Sdanielk1977     ** may contain expression trees of at most
3986fc976065Sdanielk1977     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
3987fc976065Sdanielk1977     ** more conservative than necessary, but much easier than enforcing
3988fc976065Sdanielk1977     ** an exact limit.
3989fc976065Sdanielk1977     */
3990fc976065Sdanielk1977     pParse->nHeight += sqlite3SelectExprHeight(p);
3991daf79acbSdanielk1977 
39927d10d5a6Sdrh     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
3993524cc21eSdanielk1977     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
39945b6a9ed4Sdrh       /* This subquery can be absorbed into its parent. */
3995f23329a2Sdanielk1977       if( isAggSub ){
39967d10d5a6Sdrh         isAgg = 1;
39977d10d5a6Sdrh         p->selFlags |= SF_Aggregate;
3998daf79acbSdanielk1977       }
3999daf79acbSdanielk1977       i = -1;
4000a5759677Sdrh     }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
4001a5759677Sdrh       && OptimizationEnabled(db, SQLITE_SubqCoroutine)
4002a5759677Sdrh     ){
400321172c4cSdrh       /* Implement a co-routine that will return a single row of the result
400421172c4cSdrh       ** set on each invocation.
400521172c4cSdrh       */
400621172c4cSdrh       int addrTop;
400721172c4cSdrh       int addrEof;
400821172c4cSdrh       pItem->regReturn = ++pParse->nMem;
400921172c4cSdrh       addrEof = ++pParse->nMem;
40104b2f3589Sdan       /* Before coding the OP_Goto to jump to the start of the main routine,
40114b2f3589Sdan       ** ensure that the jump to the verify-schema routine has already
40124b2f3589Sdan       ** been coded. Otherwise, the verify-schema would likely be coded as
40134b2f3589Sdan       ** part of the co-routine. If the main routine then accessed the
40144b2f3589Sdan       ** database before invoking the co-routine for the first time (for
40154b2f3589Sdan       ** example to initialize a LIMIT register from a sub-select), it would
40164b2f3589Sdan       ** be doing so without having verified the schema version and obtained
40174b2f3589Sdan       ** the required db locks. See ticket d6b36be38.  */
40184b2f3589Sdan       sqlite3CodeVerifySchema(pParse, -1);
401921172c4cSdrh       sqlite3VdbeAddOp0(v, OP_Goto);
402021172c4cSdrh       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
402121172c4cSdrh       sqlite3VdbeChangeP5(v, 1);
402221172c4cSdrh       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
402321172c4cSdrh       pItem->addrFillSub = addrTop;
402421172c4cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
402521172c4cSdrh       sqlite3VdbeChangeP5(v, 1);
402621172c4cSdrh       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
402721172c4cSdrh       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
402821172c4cSdrh       sqlite3Select(pParse, pSub, &dest);
402921172c4cSdrh       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
403021172c4cSdrh       pItem->viaCoroutine = 1;
403121172c4cSdrh       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
403221172c4cSdrh       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
403321172c4cSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
403421172c4cSdrh       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
403521172c4cSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
403621172c4cSdrh       sqlite3VdbeJumpHere(v, addrTop-1);
403721172c4cSdrh       sqlite3ClearTempRegCache(pParse);
4038daf79acbSdanielk1977     }else{
40395b6a9ed4Sdrh       /* Generate a subroutine that will fill an ephemeral table with
40405b6a9ed4Sdrh       ** the content of this subquery.  pItem->addrFillSub will point
40415b6a9ed4Sdrh       ** to the address of the generated subroutine.  pItem->regReturn
40425b6a9ed4Sdrh       ** is a register allocated to hold the subroutine return address
40435b6a9ed4Sdrh       */
40447157e8eaSdrh       int topAddr;
404548f2d3b1Sdrh       int onceAddr = 0;
40467157e8eaSdrh       int retAddr;
40475b6a9ed4Sdrh       assert( pItem->addrFillSub==0 );
40485b6a9ed4Sdrh       pItem->regReturn = ++pParse->nMem;
40497157e8eaSdrh       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
40507157e8eaSdrh       pItem->addrFillSub = topAddr+1;
40517157e8eaSdrh       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
40521d8cb21fSdan       if( pItem->isCorrelated==0 ){
4053ed17167eSdrh         /* If the subquery is not correlated and if we are not inside of
40545b6a9ed4Sdrh         ** a trigger, then we only need to compute the value of the subquery
40555b6a9ed4Sdrh         ** once. */
40561d8cb21fSdan         onceAddr = sqlite3CodeOnce(pParse);
40575b6a9ed4Sdrh       }
40581013c932Sdrh       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
4059ce7e189dSdan       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
40607d10d5a6Sdrh       sqlite3Select(pParse, pSub, &dest);
406195aa47b1Sdrh       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
406248f2d3b1Sdrh       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
40637157e8eaSdrh       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
40647157e8eaSdrh       VdbeComment((v, "end %s", pItem->pTab->zName));
40657157e8eaSdrh       sqlite3VdbeChangeP1(v, topAddr, retAddr);
4066cdc69557Sdrh       sqlite3ClearTempRegCache(pParse);
4067daf79acbSdanielk1977     }
406843152cf8Sdrh     if( /*pParse->nErr ||*/ db->mallocFailed ){
4069cfa063b3Sdrh       goto select_end;
4070cfa063b3Sdrh     }
4071fc976065Sdanielk1977     pParse->nHeight -= sqlite3SelectExprHeight(p);
4072832508b7Sdrh     pTabList = p->pSrc;
40736c8c8ce0Sdanielk1977     if( !IgnorableOrderby(pDest) ){
4074832508b7Sdrh       pOrderBy = p->pOrderBy;
4075acd4c695Sdrh     }
4076daf79acbSdanielk1977   }
4077daf79acbSdanielk1977   pEList = p->pEList;
4078daf79acbSdanielk1977 #endif
4079daf79acbSdanielk1977   pWhere = p->pWhere;
4080832508b7Sdrh   pGroupBy = p->pGroupBy;
4081832508b7Sdrh   pHaving = p->pHaving;
4082e8e4af76Sdrh   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
4083832508b7Sdrh 
4084f23329a2Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT
4085f23329a2Sdanielk1977   /* If there is are a sequence of queries, do the earlier ones first.
4086f23329a2Sdanielk1977   */
4087f23329a2Sdanielk1977   if( p->pPrior ){
4088f23329a2Sdanielk1977     if( p->pRightmost==0 ){
4089f23329a2Sdanielk1977       Select *pLoop, *pRight = 0;
4090f23329a2Sdanielk1977       int cnt = 0;
4091f23329a2Sdanielk1977       int mxSelect;
4092f23329a2Sdanielk1977       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
4093f23329a2Sdanielk1977         pLoop->pRightmost = p;
4094f23329a2Sdanielk1977         pLoop->pNext = pRight;
4095f23329a2Sdanielk1977         pRight = pLoop;
4096f23329a2Sdanielk1977       }
4097f23329a2Sdanielk1977       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
4098f23329a2Sdanielk1977       if( mxSelect && cnt>mxSelect ){
4099f23329a2Sdanielk1977         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
41002ce22453Sdan         goto select_end;
4101f23329a2Sdanielk1977       }
4102f23329a2Sdanielk1977     }
41037f61e92cSdan     rc = multiSelect(pParse, p, pDest);
410417c0bc0cSdan     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
41057f61e92cSdan     return rc;
4106f23329a2Sdanielk1977   }
4107f23329a2Sdanielk1977 #endif
4108f23329a2Sdanielk1977 
41098c6f666bSdrh   /* If there is both a GROUP BY and an ORDER BY clause and they are
41108c6f666bSdrh   ** identical, then disable the ORDER BY clause since the GROUP BY
41118c6f666bSdrh   ** will cause elements to come out in the correct order.  This is
41128c6f666bSdrh   ** an optimization - the correct answer should result regardless.
41138c6f666bSdrh   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
41148c6f666bSdrh   ** to disable this optimization for testing purposes.
41158c6f666bSdrh   */
41168c6f666bSdrh   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
41177e5418e4Sdrh          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
41188c6f666bSdrh     pOrderBy = 0;
41198c6f666bSdrh   }
41208c6f666bSdrh 
412150118cdfSdan   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
412250118cdfSdan   ** if the select-list is the same as the ORDER BY list, then this query
412350118cdfSdan   ** can be rewritten as a GROUP BY. In other words, this:
412450118cdfSdan   **
412550118cdfSdan   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
412650118cdfSdan   **
412750118cdfSdan   ** is transformed to:
412850118cdfSdan   **
412950118cdfSdan   **     SELECT xyz FROM ... GROUP BY xyz
413050118cdfSdan   **
413150118cdfSdan   ** The second form is preferred as a single index (or temp-table) may be
413250118cdfSdan   ** used for both the ORDER BY and DISTINCT processing. As originally
413350118cdfSdan   ** written the query must use a temp-table for at least one of the ORDER
413450118cdfSdan   ** BY and DISTINCT, and an index or separate temp-table for the other.
413550118cdfSdan   */
413650118cdfSdan   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
413750118cdfSdan    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
413850118cdfSdan   ){
413950118cdfSdan     p->selFlags &= ~SF_Distinct;
414050118cdfSdan     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
414150118cdfSdan     pGroupBy = p->pGroupBy;
414250118cdfSdan     pOrderBy = 0;
4143e8e4af76Sdrh     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
4144e8e4af76Sdrh     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
4145e8e4af76Sdrh     ** original setting of the SF_Distinct flag, not the current setting */
4146e8e4af76Sdrh     assert( sDistinct.isTnct );
414750118cdfSdan   }
414850118cdfSdan 
41498b4c40d8Sdrh   /* If there is an ORDER BY clause, then this sorting
41508b4c40d8Sdrh   ** index might end up being unused if the data can be
41519d2985c7Sdrh   ** extracted in pre-sorted order.  If that is the case, then the
4152b9bb7c18Sdrh   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
41539d2985c7Sdrh   ** we figure out that the sorting index is not needed.  The addrSortIndex
41549d2985c7Sdrh   ** variable is used to facilitate that change.
41557cedc8d4Sdanielk1977   */
41567cedc8d4Sdanielk1977   if( pOrderBy ){
41570342b1f5Sdrh     KeyInfo *pKeyInfo;
41580342b1f5Sdrh     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
41599d2985c7Sdrh     pOrderBy->iECursor = pParse->nTab++;
4160b9bb7c18Sdrh     p->addrOpenEphm[2] = addrSortIndex =
416166a5167bSdrh       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
416266a5167bSdrh                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
416366a5167bSdrh                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
41649d2985c7Sdrh   }else{
41659d2985c7Sdrh     addrSortIndex = -1;
41667cedc8d4Sdanielk1977   }
41677cedc8d4Sdanielk1977 
41682d0794e3Sdrh   /* If the output is destined for a temporary table, open that table.
41692d0794e3Sdrh   */
41706c8c8ce0Sdanielk1977   if( pDest->eDest==SRT_EphemTab ){
41712b596da8Sdrh     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
41722d0794e3Sdrh   }
41732d0794e3Sdrh 
4174f42bacc2Sdrh   /* Set the limiter.
4175f42bacc2Sdrh   */
4176f42bacc2Sdrh   iEnd = sqlite3VdbeMakeLabel(v);
417795aa47b1Sdrh   p->nSelectRow = (double)LARGEST_INT64;
4178f42bacc2Sdrh   computeLimitRegisters(pParse, p, iEnd);
4179c6aff30cSdrh   if( p->iLimit==0 && addrSortIndex>=0 ){
4180c6aff30cSdrh     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
4181c6aff30cSdrh     p->selFlags |= SF_UseSorter;
4182c6aff30cSdrh   }
4183f42bacc2Sdrh 
4184dece1a84Sdrh   /* Open a virtual index to use for the distinct set.
4185cce7d176Sdrh   */
41862ce22453Sdan   if( p->selFlags & SF_Distinct ){
4187e8e4af76Sdrh     sDistinct.tabTnct = pParse->nTab++;
4188e8e4af76Sdrh     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
4189e8e4af76Sdrh                                 sDistinct.tabTnct, 0, 0,
4190e8e4af76Sdrh                                 (char*)keyInfoFromExprList(pParse, p->pEList),
4191e8e4af76Sdrh                                 P4_KEYINFO_HANDOFF);
4192d4187c71Sdrh     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
4193e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
4194832508b7Sdrh   }else{
4195e8e4af76Sdrh     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
4196efb7251dSdrh   }
4197832508b7Sdrh 
419813449892Sdrh   if( !isAgg && pGroupBy==0 ){
4199e8e4af76Sdrh     /* No aggregate functions and no GROUP BY clause */
4200e8e4af76Sdrh     ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
420138cc40c2Sdan 
420238cc40c2Sdan     /* Begin the database scan. */
420346ec5b63Sdrh     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
42041d83f052Sdrh     if( pWInfo==0 ) goto select_end;
420595aa47b1Sdrh     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
4206e8e4af76Sdrh     if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
420746ec5b63Sdrh     if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
4208cce7d176Sdrh 
4209b9bb7c18Sdrh     /* If sorting index that was created by a prior OP_OpenEphemeral
4210b9bb7c18Sdrh     ** instruction ended up not being needed, then change the OP_OpenEphemeral
42119d2985c7Sdrh     ** into an OP_Noop.
42129d2985c7Sdrh     */
42139d2985c7Sdrh     if( addrSortIndex>=0 && pOrderBy==0 ){
421448f2d3b1Sdrh       sqlite3VdbeChangeToNoop(v, addrSortIndex);
4215b9bb7c18Sdrh       p->addrOpenEphm[2] = -1;
42169d2985c7Sdrh     }
42179d2985c7Sdrh 
421838cc40c2Sdan     /* Use the standard inner loop. */
4219e8e4af76Sdrh     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
4220a9671a22Sdrh                     pWInfo->iContinue, pWInfo->iBreak);
42212282792aSdrh 
4222cce7d176Sdrh     /* End the database scan loop.
4223cce7d176Sdrh     */
42244adee20fSdanielk1977     sqlite3WhereEnd(pWInfo);
422513449892Sdrh   }else{
4226e8e4af76Sdrh     /* This case when there exist aggregate functions or a GROUP BY clause
4227e8e4af76Sdrh     ** or both */
422813449892Sdrh     NameContext sNC;    /* Name context for processing aggregate information */
422913449892Sdrh     int iAMem;          /* First Mem address for storing current GROUP BY */
423013449892Sdrh     int iBMem;          /* First Mem address for previous GROUP BY */
423113449892Sdrh     int iUseFlag;       /* Mem address holding flag indicating that at least
423213449892Sdrh                         ** one row of the input to the aggregator has been
423313449892Sdrh                         ** processed */
423413449892Sdrh     int iAbortFlag;     /* Mem address which causes query abort if positive */
423513449892Sdrh     int groupBySort;    /* Rows come from source in GROUP BY order */
4236d176611bSdrh     int addrEnd;        /* End of processing for this SELECT */
42371c9d835dSdrh     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
42381c9d835dSdrh     int sortOut = 0;    /* Output register from the sorter */
4239d176611bSdrh 
4240d176611bSdrh     /* Remove any and all aliases between the result set and the
4241d176611bSdrh     ** GROUP BY clause.
4242d176611bSdrh     */
4243d176611bSdrh     if( pGroupBy ){
4244dc5ea5c7Sdrh       int k;                        /* Loop counter */
4245d176611bSdrh       struct ExprList_item *pItem;  /* For looping over expression in a list */
4246d176611bSdrh 
4247dc5ea5c7Sdrh       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
4248d176611bSdrh         pItem->iAlias = 0;
4249d176611bSdrh       }
4250dc5ea5c7Sdrh       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
4251d176611bSdrh         pItem->iAlias = 0;
4252d176611bSdrh       }
425395aa47b1Sdrh       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
425495aa47b1Sdrh     }else{
425595aa47b1Sdrh       p->nSelectRow = (double)1;
4256d176611bSdrh     }
4257cce7d176Sdrh 
425813449892Sdrh 
4259d176611bSdrh     /* Create a label to jump to when we want to abort the query */
426013449892Sdrh     addrEnd = sqlite3VdbeMakeLabel(v);
426113449892Sdrh 
426213449892Sdrh     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
426313449892Sdrh     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
426413449892Sdrh     ** SELECT statement.
42652282792aSdrh     */
426613449892Sdrh     memset(&sNC, 0, sizeof(sNC));
426713449892Sdrh     sNC.pParse = pParse;
426813449892Sdrh     sNC.pSrcList = pTabList;
426913449892Sdrh     sNC.pAggInfo = &sAggInfo;
427013449892Sdrh     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
42719d2985c7Sdrh     sAggInfo.pGroupBy = pGroupBy;
4272d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pEList);
4273d2b3e23bSdrh     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
4274d2b3e23bSdrh     if( pHaving ){
4275d2b3e23bSdrh       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
427613449892Sdrh     }
427713449892Sdrh     sAggInfo.nAccumulator = sAggInfo.nColumn;
427813449892Sdrh     for(i=0; i<sAggInfo.nFunc; i++){
42796ab3a2ecSdanielk1977       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
42803a8c4be7Sdrh       sNC.ncFlags |= NC_InAggFunc;
42816ab3a2ecSdanielk1977       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
42823a8c4be7Sdrh       sNC.ncFlags &= ~NC_InAggFunc;
428313449892Sdrh     }
428417435752Sdrh     if( db->mallocFailed ) goto select_end;
428513449892Sdrh 
428613449892Sdrh     /* Processing for aggregates with GROUP BY is very different and
42873c4809a2Sdanielk1977     ** much more complex than aggregates without a GROUP BY.
428813449892Sdrh     */
428913449892Sdrh     if( pGroupBy ){
429013449892Sdrh       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
4291d176611bSdrh       int j1;             /* A-vs-B comparision jump */
4292d176611bSdrh       int addrOutputRow;  /* Start of subroutine that outputs a result row */
4293d176611bSdrh       int regOutputRow;   /* Return address register for output subroutine */
4294d176611bSdrh       int addrSetAbort;   /* Set the abort flag and return */
4295d176611bSdrh       int addrTopOfLoop;  /* Top of the input loop */
4296d176611bSdrh       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
4297d176611bSdrh       int addrReset;      /* Subroutine for resetting the accumulator */
4298d176611bSdrh       int regReset;       /* Return address register for reset subroutine */
429913449892Sdrh 
430013449892Sdrh       /* If there is a GROUP BY clause we might need a sorting index to
430113449892Sdrh       ** implement it.  Allocate that sorting index now.  If it turns out
43021c9d835dSdrh       ** that we do not need it after all, the OP_SorterOpen instruction
430313449892Sdrh       ** will be converted into a Noop.
430413449892Sdrh       */
430513449892Sdrh       sAggInfo.sortingIdx = pParse->nTab++;
430613449892Sdrh       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
43071c9d835dSdrh       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
4308cd3e8f7cSdanielk1977           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
4309cd3e8f7cSdanielk1977           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
431013449892Sdrh 
431113449892Sdrh       /* Initialize memory locations used by GROUP BY aggregate processing
431213449892Sdrh       */
43130a07c107Sdrh       iUseFlag = ++pParse->nMem;
43140a07c107Sdrh       iAbortFlag = ++pParse->nMem;
4315d176611bSdrh       regOutputRow = ++pParse->nMem;
4316d176611bSdrh       addrOutputRow = sqlite3VdbeMakeLabel(v);
4317d176611bSdrh       regReset = ++pParse->nMem;
4318d176611bSdrh       addrReset = sqlite3VdbeMakeLabel(v);
43190a07c107Sdrh       iAMem = pParse->nMem + 1;
432013449892Sdrh       pParse->nMem += pGroupBy->nExpr;
43210a07c107Sdrh       iBMem = pParse->nMem + 1;
432213449892Sdrh       pParse->nMem += pGroupBy->nExpr;
43234c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
4324d4e70ebdSdrh       VdbeComment((v, "clear abort flag"));
43254c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
4326d4e70ebdSdrh       VdbeComment((v, "indicate accumulator empty"));
4327b8475df8Sdrh       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
4328e313382eSdrh 
432913449892Sdrh       /* Begin a loop that will extract all source rows in GROUP BY order.
433013449892Sdrh       ** This might involve two separate loops with an OP_Sort in between, or
433113449892Sdrh       ** it might be a single loop that uses an index to extract information
433213449892Sdrh       ** in the right order to begin with.
433313449892Sdrh       */
43342eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
433546ec5b63Sdrh       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
43365360ad34Sdrh       if( pWInfo==0 ) goto select_end;
433746ec5b63Sdrh       if( pWInfo->nOBSat==pGroupBy->nExpr ){
433813449892Sdrh         /* The optimizer is able to deliver rows in group by order so
4339b9bb7c18Sdrh         ** we do not have to sort.  The OP_OpenEphemeral table will be
434013449892Sdrh         ** cancelled later because we still need to use the pKeyInfo
434113449892Sdrh         */
434213449892Sdrh         groupBySort = 0;
434313449892Sdrh       }else{
434413449892Sdrh         /* Rows are coming out in undetermined order.  We have to push
434513449892Sdrh         ** each row into a sorting index, terminate the first loop,
434613449892Sdrh         ** then loop over the sorting index in order to get the output
434713449892Sdrh         ** in sorted order
434813449892Sdrh         */
4349892d3179Sdrh         int regBase;
4350892d3179Sdrh         int regRecord;
4351892d3179Sdrh         int nCol;
4352892d3179Sdrh         int nGroupBy;
4353892d3179Sdrh 
43542ce22453Sdan         explainTempTable(pParse,
4355e8e4af76Sdrh             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
4356e8e4af76Sdrh                     "DISTINCT" : "GROUP BY");
43572ce22453Sdan 
435813449892Sdrh         groupBySort = 1;
4359892d3179Sdrh         nGroupBy = pGroupBy->nExpr;
4360892d3179Sdrh         nCol = nGroupBy + 1;
4361892d3179Sdrh         j = nGroupBy+1;
436213449892Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
4363892d3179Sdrh           if( sAggInfo.aCol[i].iSorterColumn>=j ){
4364892d3179Sdrh             nCol++;
436513449892Sdrh             j++;
436613449892Sdrh           }
4367892d3179Sdrh         }
4368892d3179Sdrh         regBase = sqlite3GetTempRange(pParse, nCol);
4369ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
4370191b54cbSdrh         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
4371892d3179Sdrh         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
4372892d3179Sdrh         j = nGroupBy+1;
4373892d3179Sdrh         for(i=0; i<sAggInfo.nColumn; i++){
4374892d3179Sdrh           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
4375892d3179Sdrh           if( pCol->iSorterColumn>=j ){
4376e55cbd72Sdrh             int r1 = j + regBase;
43776a012f04Sdrh             int r2;
4378701bb3b4Sdrh 
43796a012f04Sdrh             r2 = sqlite3ExprCodeGetColumn(pParse,
4380a748fdccSdrh                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
43816a012f04Sdrh             if( r1!=r2 ){
43826a012f04Sdrh               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
43836a012f04Sdrh             }
43846a012f04Sdrh             j++;
4385892d3179Sdrh           }
4386892d3179Sdrh         }
4387892d3179Sdrh         regRecord = sqlite3GetTempReg(pParse);
43881db639ceSdrh         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
43891c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
4390892d3179Sdrh         sqlite3ReleaseTempReg(pParse, regRecord);
4391892d3179Sdrh         sqlite3ReleaseTempRange(pParse, regBase, nCol);
439213449892Sdrh         sqlite3WhereEnd(pWInfo);
43935134d135Sdan         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
43941c9d835dSdrh         sortOut = sqlite3GetTempReg(pParse);
43951c9d835dSdrh         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
43961c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
4397d4e70ebdSdrh         VdbeComment((v, "GROUP BY sort"));
439813449892Sdrh         sAggInfo.useSortingIdx = 1;
4399ceea3321Sdrh         sqlite3ExprCacheClear(pParse);
440013449892Sdrh       }
440113449892Sdrh 
440213449892Sdrh       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
440313449892Sdrh       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
440413449892Sdrh       ** Then compare the current GROUP BY terms against the GROUP BY terms
440513449892Sdrh       ** from the previous row currently stored in a0, a1, a2...
440613449892Sdrh       */
440713449892Sdrh       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
4408ceea3321Sdrh       sqlite3ExprCacheClear(pParse);
44091c9d835dSdrh       if( groupBySort ){
44101c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
44111c9d835dSdrh       }
441213449892Sdrh       for(j=0; j<pGroupBy->nExpr; j++){
441313449892Sdrh         if( groupBySort ){
44141c9d835dSdrh           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
44151c9d835dSdrh           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
441613449892Sdrh         }else{
441713449892Sdrh           sAggInfo.directMode = 1;
44182dcef11bSdrh           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
441913449892Sdrh         }
442013449892Sdrh       }
442116ee60ffSdrh       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
4422b21e7c70Sdrh                           (char*)pKeyInfo, P4_KEYINFO);
442316ee60ffSdrh       j1 = sqlite3VdbeCurrentAddr(v);
442416ee60ffSdrh       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
442513449892Sdrh 
442613449892Sdrh       /* Generate code that runs whenever the GROUP BY changes.
4427e00ee6ebSdrh       ** Changes in the GROUP BY are detected by the previous code
442813449892Sdrh       ** block.  If there were no changes, this block is skipped.
442913449892Sdrh       **
443013449892Sdrh       ** This code copies current group by terms in b0,b1,b2,...
443113449892Sdrh       ** over to a0,a1,a2.  It then calls the output subroutine
443213449892Sdrh       ** and resets the aggregate accumulator registers in preparation
443313449892Sdrh       ** for the next GROUP BY batch.
443413449892Sdrh       */
4435b21e7c70Sdrh       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
44362eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
4437d4e70ebdSdrh       VdbeComment((v, "output one row"));
44383c84ddffSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
4439d4e70ebdSdrh       VdbeComment((v, "check abort flag"));
44402eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
4441d4e70ebdSdrh       VdbeComment((v, "reset accumulator"));
444213449892Sdrh 
444313449892Sdrh       /* Update the aggregate accumulators based on the content of
444413449892Sdrh       ** the current row
444513449892Sdrh       */
444616ee60ffSdrh       sqlite3VdbeJumpHere(v, j1);
444713449892Sdrh       updateAccumulator(pParse, &sAggInfo);
44484c583128Sdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
4449d4e70ebdSdrh       VdbeComment((v, "indicate data in accumulator"));
445013449892Sdrh 
445113449892Sdrh       /* End of the loop
445213449892Sdrh       */
445313449892Sdrh       if( groupBySort ){
44541c9d835dSdrh         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
445513449892Sdrh       }else{
445613449892Sdrh         sqlite3WhereEnd(pWInfo);
445748f2d3b1Sdrh         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
445813449892Sdrh       }
445913449892Sdrh 
446013449892Sdrh       /* Output the final row of result
446113449892Sdrh       */
44622eb95377Sdrh       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
4463d4e70ebdSdrh       VdbeComment((v, "output final row"));
446413449892Sdrh 
4465d176611bSdrh       /* Jump over the subroutines
4466d176611bSdrh       */
4467d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
4468d176611bSdrh 
4469d176611bSdrh       /* Generate a subroutine that outputs a single row of the result
4470d176611bSdrh       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
4471d176611bSdrh       ** is less than or equal to zero, the subroutine is a no-op.  If
4472d176611bSdrh       ** the processing calls for the query to abort, this subroutine
4473d176611bSdrh       ** increments the iAbortFlag memory location before returning in
4474d176611bSdrh       ** order to signal the caller to abort.
4475d176611bSdrh       */
4476d176611bSdrh       addrSetAbort = sqlite3VdbeCurrentAddr(v);
4477d176611bSdrh       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
4478d176611bSdrh       VdbeComment((v, "set abort flag"));
4479d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
4480d176611bSdrh       sqlite3VdbeResolveLabel(v, addrOutputRow);
4481d176611bSdrh       addrOutputRow = sqlite3VdbeCurrentAddr(v);
4482d176611bSdrh       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
4483d176611bSdrh       VdbeComment((v, "Groupby result generator entry point"));
4484d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
4485d176611bSdrh       finalizeAggFunctions(pParse, &sAggInfo);
4486d176611bSdrh       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
4487d176611bSdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
4488e8e4af76Sdrh                       &sDistinct, pDest,
4489d176611bSdrh                       addrOutputRow+1, addrSetAbort);
4490d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
4491d176611bSdrh       VdbeComment((v, "end groupby result generator"));
4492d176611bSdrh 
4493d176611bSdrh       /* Generate a subroutine that will reset the group-by accumulator
4494d176611bSdrh       */
4495d176611bSdrh       sqlite3VdbeResolveLabel(v, addrReset);
4496d176611bSdrh       resetAccumulator(pParse, &sAggInfo);
4497d176611bSdrh       sqlite3VdbeAddOp1(v, OP_Return, regReset);
4498d176611bSdrh 
449943152cf8Sdrh     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
450013449892Sdrh     else {
4501dba0137eSdanielk1977       ExprList *pDel = 0;
4502a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT
4503a5533162Sdanielk1977       Table *pTab;
4504a5533162Sdanielk1977       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
4505a5533162Sdanielk1977         /* If isSimpleCount() returns a pointer to a Table structure, then
4506a5533162Sdanielk1977         ** the SQL statement is of the form:
4507a5533162Sdanielk1977         **
4508a5533162Sdanielk1977         **   SELECT count(*) FROM <tbl>
4509a5533162Sdanielk1977         **
4510a5533162Sdanielk1977         ** where the Table structure returned represents table <tbl>.
4511a5533162Sdanielk1977         **
4512a5533162Sdanielk1977         ** This statement is so common that it is optimized specially. The
4513a5533162Sdanielk1977         ** OP_Count instruction is executed either on the intkey table that
4514a5533162Sdanielk1977         ** contains the data for table <tbl> or on one of its indexes. It
4515a5533162Sdanielk1977         ** is better to execute the op on an index, as indexes are almost
4516a5533162Sdanielk1977         ** always spread across less pages than their corresponding tables.
4517a5533162Sdanielk1977         */
4518a5533162Sdanielk1977         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4519a5533162Sdanielk1977         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
4520a5533162Sdanielk1977         Index *pIdx;                         /* Iterator variable */
4521a5533162Sdanielk1977         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
4522a5533162Sdanielk1977         Index *pBest = 0;                    /* Best index found so far */
4523a5533162Sdanielk1977         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
4524a9d1ccb9Sdanielk1977 
4525a5533162Sdanielk1977         sqlite3CodeVerifySchema(pParse, iDb);
4526a5533162Sdanielk1977         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
4527a5533162Sdanielk1977 
4528a5533162Sdanielk1977         /* Search for the index that has the least amount of columns. If
4529a5533162Sdanielk1977         ** there is such an index, and it has less columns than the table
4530a5533162Sdanielk1977         ** does, then we can assume that it consumes less space on disk and
4531a5533162Sdanielk1977         ** will therefore be cheaper to scan to determine the query result.
4532a5533162Sdanielk1977         ** In this case set iRoot to the root page number of the index b-tree
4533a5533162Sdanielk1977         ** and pKeyInfo to the KeyInfo structure required to navigate the
4534a5533162Sdanielk1977         ** index.
4535a5533162Sdanielk1977         **
45363e9548b3Sdrh         ** (2011-04-15) Do not do a full scan of an unordered index.
45373e9548b3Sdrh         **
4538a5533162Sdanielk1977         ** In practice the KeyInfo structure will not be used. It is only
4539a5533162Sdanielk1977         ** passed to keep OP_OpenRead happy.
4540a5533162Sdanielk1977         */
4541a5533162Sdanielk1977         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
45423e9548b3Sdrh           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
4543a5533162Sdanielk1977             pBest = pIdx;
4544a5533162Sdanielk1977           }
4545a5533162Sdanielk1977         }
4546a5533162Sdanielk1977         if( pBest && pBest->nColumn<pTab->nCol ){
4547a5533162Sdanielk1977           iRoot = pBest->tnum;
4548a5533162Sdanielk1977           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
4549a5533162Sdanielk1977         }
4550a5533162Sdanielk1977 
4551a5533162Sdanielk1977         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
4552a5533162Sdanielk1977         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
4553a5533162Sdanielk1977         if( pKeyInfo ){
4554a5533162Sdanielk1977           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
4555a5533162Sdanielk1977         }
4556a5533162Sdanielk1977         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
4557a5533162Sdanielk1977         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
4558ef7075deSdan         explainSimpleCount(pParse, pTab, pBest);
4559a5533162Sdanielk1977       }else
4560a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */
4561a5533162Sdanielk1977       {
4562738bdcfbSdanielk1977         /* Check if the query is of one of the following forms:
4563738bdcfbSdanielk1977         **
4564738bdcfbSdanielk1977         **   SELECT min(x) FROM ...
4565738bdcfbSdanielk1977         **   SELECT max(x) FROM ...
4566738bdcfbSdanielk1977         **
4567738bdcfbSdanielk1977         ** If it is, then ask the code in where.c to attempt to sort results
4568738bdcfbSdanielk1977         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
4569738bdcfbSdanielk1977         ** If where.c is able to produce results sorted in this order, then
4570738bdcfbSdanielk1977         ** add vdbe code to break out of the processing loop after the
4571738bdcfbSdanielk1977         ** first iteration (since the first iteration of the loop is
4572738bdcfbSdanielk1977         ** guaranteed to operate on the row with the minimum or maximum
4573738bdcfbSdanielk1977         ** value of x, the only row required).
4574738bdcfbSdanielk1977         **
4575738bdcfbSdanielk1977         ** A special flag must be passed to sqlite3WhereBegin() to slightly
457648864df9Smistachkin         ** modify behavior as follows:
4577738bdcfbSdanielk1977         **
4578738bdcfbSdanielk1977         **   + If the query is a "SELECT min(x)", then the loop coded by
4579738bdcfbSdanielk1977         **     where.c should not iterate over any values with a NULL value
4580738bdcfbSdanielk1977         **     for x.
4581738bdcfbSdanielk1977         **
4582738bdcfbSdanielk1977         **   + The optimizer code in where.c (the thing that decides which
4583738bdcfbSdanielk1977         **     index or indices to use) should place a different priority on
4584738bdcfbSdanielk1977         **     satisfying the 'ORDER BY' clause than it does in other cases.
4585738bdcfbSdanielk1977         **     Refer to code and comments in where.c for details.
4586738bdcfbSdanielk1977         */
4587a5533162Sdanielk1977         ExprList *pMinMax = 0;
45884ac391fcSdan         u8 flag = WHERE_ORDERBY_NORMAL;
45894ac391fcSdan 
45904ac391fcSdan         assert( p->pGroupBy==0 );
45914ac391fcSdan         assert( flag==0 );
45924ac391fcSdan         if( p->pHaving==0 ){
45934ac391fcSdan           flag = minMaxQuery(&sAggInfo, &pMinMax);
45944ac391fcSdan         }
45954ac391fcSdan         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
45964ac391fcSdan 
4597a9d1ccb9Sdanielk1977         if( flag ){
45984ac391fcSdan           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
45996ab3a2ecSdanielk1977           pDel = pMinMax;
46000e359b30Sdrh           if( pMinMax && !db->mallocFailed ){
4601ea678832Sdrh             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
4602a9d1ccb9Sdanielk1977             pMinMax->a[0].pExpr->op = TK_COLUMN;
4603a9d1ccb9Sdanielk1977           }
46041013c932Sdrh         }
4605a9d1ccb9Sdanielk1977 
460613449892Sdrh         /* This case runs if the aggregate has no GROUP BY clause.  The
460713449892Sdrh         ** processing is much simpler since there is only a single row
460813449892Sdrh         ** of output.
460913449892Sdrh         */
461013449892Sdrh         resetAccumulator(pParse, &sAggInfo);
461146ec5b63Sdrh         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
4612dba0137eSdanielk1977         if( pWInfo==0 ){
4613633e6d57Sdrh           sqlite3ExprListDelete(db, pDel);
4614dba0137eSdanielk1977           goto select_end;
4615dba0137eSdanielk1977         }
461613449892Sdrh         updateAccumulator(pParse, &sAggInfo);
461746c35f9bSdrh         assert( pMinMax==0 || pMinMax->nExpr==1 );
461846ec5b63Sdrh         if( pWInfo->nOBSat>0 ){
4619a9d1ccb9Sdanielk1977           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
4620a5533162Sdanielk1977           VdbeComment((v, "%s() by index",
4621a5533162Sdanielk1977                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
4622a9d1ccb9Sdanielk1977         }
462313449892Sdrh         sqlite3WhereEnd(pWInfo);
462413449892Sdrh         finalizeAggFunctions(pParse, &sAggInfo);
46257a895a80Sdanielk1977       }
46267a895a80Sdanielk1977 
462713449892Sdrh       pOrderBy = 0;
462835573356Sdrh       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
4629e8e4af76Sdrh       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
4630a9671a22Sdrh                       pDest, addrEnd, addrEnd);
4631633e6d57Sdrh       sqlite3ExprListDelete(db, pDel);
463213449892Sdrh     }
463313449892Sdrh     sqlite3VdbeResolveLabel(v, addrEnd);
463413449892Sdrh 
463513449892Sdrh   } /* endif aggregate query */
46362282792aSdrh 
4637e8e4af76Sdrh   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
46382ce22453Sdan     explainTempTable(pParse, "DISTINCT");
46392ce22453Sdan   }
46402ce22453Sdan 
4641cce7d176Sdrh   /* If there is an ORDER BY clause, then we need to sort the results
4642cce7d176Sdrh   ** and send them to the callback one by one.
4643cce7d176Sdrh   */
4644cce7d176Sdrh   if( pOrderBy ){
46452ce22453Sdan     explainTempTable(pParse, "ORDER BY");
46466c8c8ce0Sdanielk1977     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
4647cce7d176Sdrh   }
46486a535340Sdrh 
4649ec7429aeSdrh   /* Jump here to skip this query
4650ec7429aeSdrh   */
4651ec7429aeSdrh   sqlite3VdbeResolveLabel(v, iEnd);
4652ec7429aeSdrh 
46531d83f052Sdrh   /* The SELECT was successfully coded.   Set the return code to 0
46541d83f052Sdrh   ** to indicate no errors.
46551d83f052Sdrh   */
46561d83f052Sdrh   rc = 0;
46571d83f052Sdrh 
46581d83f052Sdrh   /* Control jumps to here if an error is encountered above, or upon
46591d83f052Sdrh   ** successful coding of the SELECT.
46601d83f052Sdrh   */
46611d83f052Sdrh select_end:
466217c0bc0cSdan   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
4663955de52cSdanielk1977 
46647d10d5a6Sdrh   /* Identify column names if results of the SELECT are to be output.
4665955de52cSdanielk1977   */
46667d10d5a6Sdrh   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
4667955de52cSdanielk1977     generateColumnNames(pParse, pTabList, pEList);
4668955de52cSdanielk1977   }
4669955de52cSdanielk1977 
4670633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aCol);
4671633e6d57Sdrh   sqlite3DbFree(db, sAggInfo.aFunc);
46721d83f052Sdrh   return rc;
4673cce7d176Sdrh }
4674485f0039Sdrh 
4675678a9aa7Sdrh #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
4676485f0039Sdrh /*
46777e02e5e6Sdrh ** Generate a human-readable description of a the Select object.
4678485f0039Sdrh */
4679a84203a0Sdrh static void explainOneSelect(Vdbe *pVdbe, Select *p){
46807e02e5e6Sdrh   sqlite3ExplainPrintf(pVdbe, "SELECT ");
46814e2a9c32Sdrh   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
46824e2a9c32Sdrh     if( p->selFlags & SF_Distinct ){
46834e2a9c32Sdrh       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
4684485f0039Sdrh     }
46854e2a9c32Sdrh     if( p->selFlags & SF_Aggregate ){
46864e2a9c32Sdrh       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
4687485f0039Sdrh     }
46884e2a9c32Sdrh     sqlite3ExplainNL(pVdbe);
46894e2a9c32Sdrh     sqlite3ExplainPrintf(pVdbe, "   ");
4690485f0039Sdrh   }
46917e02e5e6Sdrh   sqlite3ExplainExprList(pVdbe, p->pEList);
46927e02e5e6Sdrh   sqlite3ExplainNL(pVdbe);
46937e02e5e6Sdrh   if( p->pSrc && p->pSrc->nSrc ){
4694485f0039Sdrh     int i;
46957e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "FROM ");
46967e02e5e6Sdrh     sqlite3ExplainPush(pVdbe);
4697485f0039Sdrh     for(i=0; i<p->pSrc->nSrc; i++){
4698485f0039Sdrh       struct SrcList_item *pItem = &p->pSrc->a[i];
469904b8342bSdrh       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
4700485f0039Sdrh       if( pItem->pSelect ){
47017e02e5e6Sdrh         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
4702485f0039Sdrh         if( pItem->pTab ){
470304b8342bSdrh           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
470404b8342bSdrh         }
4705485f0039Sdrh       }else if( pItem->zName ){
47067e02e5e6Sdrh         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
4707485f0039Sdrh       }
4708485f0039Sdrh       if( pItem->zAlias ){
470904b8342bSdrh         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
4710485f0039Sdrh       }
4711a84203a0Sdrh       if( pItem->jointype & JT_LEFT ){
4712a84203a0Sdrh         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
4713485f0039Sdrh       }
47147e02e5e6Sdrh       sqlite3ExplainNL(pVdbe);
4715485f0039Sdrh     }
47167e02e5e6Sdrh     sqlite3ExplainPop(pVdbe);
4717485f0039Sdrh   }
4718485f0039Sdrh   if( p->pWhere ){
47197e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "WHERE ");
47207e02e5e6Sdrh     sqlite3ExplainExpr(pVdbe, p->pWhere);
47217e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4722485f0039Sdrh   }
4723485f0039Sdrh   if( p->pGroupBy ){
47247e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
47257e02e5e6Sdrh     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
47267e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4727485f0039Sdrh   }
4728485f0039Sdrh   if( p->pHaving ){
47297e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "HAVING ");
47307e02e5e6Sdrh     sqlite3ExplainExpr(pVdbe, p->pHaving);
47317e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4732485f0039Sdrh   }
4733485f0039Sdrh   if( p->pOrderBy ){
47347e02e5e6Sdrh     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
47357e02e5e6Sdrh     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
47367e02e5e6Sdrh     sqlite3ExplainNL(pVdbe);
4737485f0039Sdrh   }
4738a84203a0Sdrh   if( p->pLimit ){
4739a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
4740a84203a0Sdrh     sqlite3ExplainExpr(pVdbe, p->pLimit);
4741a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
4742a84203a0Sdrh   }
4743a84203a0Sdrh   if( p->pOffset ){
4744a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
4745a84203a0Sdrh     sqlite3ExplainExpr(pVdbe, p->pOffset);
4746a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
4747485f0039Sdrh   }
4748485f0039Sdrh }
4749a84203a0Sdrh void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
4750a84203a0Sdrh   if( p==0 ){
4751a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "(null-select)");
4752a84203a0Sdrh     return;
4753a84203a0Sdrh   }
475447f2239fSdrh   while( p->pPrior ){
475547f2239fSdrh     p->pPrior->pNext = p;
475647f2239fSdrh     p = p->pPrior;
475747f2239fSdrh   }
4758a84203a0Sdrh   sqlite3ExplainPush(pVdbe);
4759a84203a0Sdrh   while( p ){
4760a84203a0Sdrh     explainOneSelect(pVdbe, p);
4761a84203a0Sdrh     p = p->pNext;
4762a84203a0Sdrh     if( p==0 ) break;
4763a84203a0Sdrh     sqlite3ExplainNL(pVdbe);
4764a84203a0Sdrh     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
4765a84203a0Sdrh   }
47667e02e5e6Sdrh   sqlite3ExplainPrintf(pVdbe, "END");
4767a84203a0Sdrh   sqlite3ExplainPop(pVdbe);
4768485f0039Sdrh }
47697e02e5e6Sdrh 
4770485f0039Sdrh /* End of the structure debug printing code
4771485f0039Sdrh *****************************************************************************/
477214a55b71Smistachkin #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
4773