select.c

Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains C code routines that are called by the parser
00013 ** to handle SELECT statements in SQLite.
00014 **
00015 ** $Id: select.c,v 1.484 2008/11/12 12:27:31 drh Exp $
00016 */
00017 #include "sqliteInt.h"
00018 
00019 
00020 /*
00021 ** Delete all the content of a Select structure but do not deallocate
00022 ** the select structure itself.
00023 */
00024 static void clearSelect(sqlite3 *db, Select *p){
00025   sqlite3ExprListDelete(db, p->pEList);
00026   sqlite3SrcListDelete(db, p->pSrc);
00027   sqlite3ExprDelete(db, p->pWhere);
00028   sqlite3ExprListDelete(db, p->pGroupBy);
00029   sqlite3ExprDelete(db, p->pHaving);
00030   sqlite3ExprListDelete(db, p->pOrderBy);
00031   sqlite3SelectDelete(db, p->pPrior);
00032   sqlite3ExprDelete(db, p->pLimit);
00033   sqlite3ExprDelete(db, p->pOffset);
00034 }
00035 
00036 /*
00037 ** Initialize a SelectDest structure.
00038 */
00039 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
00040   pDest->eDest = eDest;
00041   pDest->iParm = iParm;
00042   pDest->affinity = 0;
00043   pDest->iMem = 0;
00044   pDest->nMem = 0;
00045 }
00046 
00047 
00048 /*
00049 ** Allocate a new Select structure and return a pointer to that
00050 ** structure.
00051 */
00052 Select *sqlite3SelectNew(
00053   Parse *pParse,        /* Parsing context */
00054   ExprList *pEList,     /* which columns to include in the result */
00055   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
00056   Expr *pWhere,         /* the WHERE clause */
00057   ExprList *pGroupBy,   /* the GROUP BY clause */
00058   Expr *pHaving,        /* the HAVING clause */
00059   ExprList *pOrderBy,   /* the ORDER BY clause */
00060   int isDistinct,       /* true if the DISTINCT keyword is present */
00061   Expr *pLimit,         /* LIMIT value.  NULL means not used */
00062   Expr *pOffset         /* OFFSET value.  NULL means no offset */
00063 ){
00064   Select *pNew;
00065   Select standin;
00066   sqlite3 *db = pParse->db;
00067   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
00068   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
00069   if( pNew==0 ){
00070     pNew = &standin;
00071     memset(pNew, 0, sizeof(*pNew));
00072   }
00073   if( pEList==0 ){
00074     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
00075   }
00076   pNew->pEList = pEList;
00077   pNew->pSrc = pSrc;
00078   pNew->pWhere = pWhere;
00079   pNew->pGroupBy = pGroupBy;
00080   pNew->pHaving = pHaving;
00081   pNew->pOrderBy = pOrderBy;
00082   pNew->selFlags = isDistinct ? SF_Distinct : 0;
00083   pNew->op = TK_SELECT;
00084   pNew->pLimit = pLimit;
00085   pNew->pOffset = pOffset;
00086   pNew->addrOpenEphm[0] = -1;
00087   pNew->addrOpenEphm[1] = -1;
00088   pNew->addrOpenEphm[2] = -1;
00089   if( db->mallocFailed ) {
00090     clearSelect(db, pNew);
00091     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
00092     pNew = 0;
00093   }
00094   return pNew;
00095 }
00096 
00097 /*
00098 ** Delete the given Select structure and all of its substructures.
00099 */
00100 void sqlite3SelectDelete(sqlite3 *db, Select *p){
00101   if( p ){
00102     clearSelect(db, p);
00103     sqlite3DbFree(db, p);
00104   }
00105 }
00106 
00107 /*
00108 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
00109 ** type of join.  Return an integer constant that expresses that type
00110 ** in terms of the following bit values:
00111 **
00112 **     JT_INNER
00113 **     JT_CROSS
00114 **     JT_OUTER
00115 **     JT_NATURAL
00116 **     JT_LEFT
00117 **     JT_RIGHT
00118 **
00119 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
00120 **
00121 ** If an illegal or unsupported join type is seen, then still return
00122 ** a join type, but put an error in the pParse structure.
00123 */
00124 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
00125   int jointype = 0;
00126   Token *apAll[3];
00127   Token *p;
00128   static const struct {
00129     const char zKeyword[8];
00130     u8 nChar;
00131     u8 code;
00132   } keywords[] = {
00133     { "natural", 7, JT_NATURAL },
00134     { "left",    4, JT_LEFT|JT_OUTER },
00135     { "right",   5, JT_RIGHT|JT_OUTER },
00136     { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
00137     { "outer",   5, JT_OUTER },
00138     { "inner",   5, JT_INNER },
00139     { "cross",   5, JT_INNER|JT_CROSS },
00140   };
00141   int i, j;
00142   apAll[0] = pA;
00143   apAll[1] = pB;
00144   apAll[2] = pC;
00145   for(i=0; i<3 && apAll[i]; i++){
00146     p = apAll[i];
00147     for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
00148       if( p->n==keywords[j].nChar 
00149           && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
00150         jointype |= keywords[j].code;
00151         break;
00152       }
00153     }
00154     if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
00155       jointype |= JT_ERROR;
00156       break;
00157     }
00158   }
00159   if(
00160      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
00161      (jointype & JT_ERROR)!=0
00162   ){
00163     const char *zSp = " ";
00164     assert( pB!=0 );
00165     if( pC==0 ){ zSp++; }
00166     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
00167        "%T %T%s%T", pA, pB, zSp, pC);
00168     jointype = JT_INNER;
00169   }else if( jointype & JT_RIGHT ){
00170     sqlite3ErrorMsg(pParse, 
00171       "RIGHT and FULL OUTER JOINs are not currently supported");
00172     jointype = JT_INNER;
00173   }
00174   return jointype;
00175 }
00176 
00177 /*
00178 ** Return the index of a column in a table.  Return -1 if the column
00179 ** is not contained in the table.
00180 */
00181 static int columnIndex(Table *pTab, const char *zCol){
00182   int i;
00183   for(i=0; i<pTab->nCol; i++){
00184     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
00185   }
00186   return -1;
00187 }
00188 
00189 /*
00190 ** Set the value of a token to a '\000'-terminated string.
00191 */
00192 static void setToken(Token *p, const char *z){
00193   p->z = (u8*)z;
00194   p->n = z ? strlen(z) : 0;
00195   p->dyn = 0;
00196 }
00197 
00198 /*
00199 ** Set the token to the double-quoted and escaped version of the string pointed
00200 ** to by z. For example;
00201 **
00202 **    {a"bc}  ->  {"a""bc"}
00203 */
00204 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
00205 
00206   /* Check if the string appears to be quoted using "..." or `...`
00207   ** or [...] or '...' or if the string contains any " characters.  
00208   ** If it does, then record a version of the string with the special
00209   ** characters escaped.
00210   */
00211   const char *z2 = z;
00212   if( *z2!='[' && *z2!='`' && *z2!='\'' ){
00213     while( *z2 ){
00214       if( *z2=='"' ) break;
00215       z2++;
00216     }
00217   }
00218 
00219   if( *z2 ){
00220     /* String contains " characters - copy and quote the string. */
00221     p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
00222     if( p->z ){
00223       p->n = strlen((char *)p->z);
00224       p->dyn = 1;
00225     }
00226   }else{
00227     /* String contains no " characters - copy the pointer. */
00228     p->z = (u8*)z;
00229     p->n = (z2 - z);
00230     p->dyn = 0;
00231   }
00232 }
00233 
00234 /*
00235 ** Create an expression node for an identifier with the name of zName
00236 */
00237 Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
00238   Token dummy;
00239   setToken(&dummy, zName);
00240   return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
00241 }
00242 
00243 /*
00244 ** Add a term to the WHERE expression in *ppExpr that requires the
00245 ** zCol column to be equal in the two tables pTab1 and pTab2.
00246 */
00247 static void addWhereTerm(
00248   Parse *pParse,           /* Parsing context */
00249   const char *zCol,        /* Name of the column */
00250   const Table *pTab1,      /* First table */
00251   const char *zAlias1,     /* Alias for first table.  May be NULL */
00252   const Table *pTab2,      /* Second table */
00253   const char *zAlias2,     /* Alias for second table.  May be NULL */
00254   int iRightJoinTable,     /* VDBE cursor for the right table */
00255   Expr **ppExpr,           /* Add the equality term to this expression */
00256   int isOuterJoin          /* True if dealing with an OUTER join */
00257 ){
00258   Expr *pE1a, *pE1b, *pE1c;
00259   Expr *pE2a, *pE2b, *pE2c;
00260   Expr *pE;
00261 
00262   pE1a = sqlite3CreateIdExpr(pParse, zCol);
00263   pE2a = sqlite3CreateIdExpr(pParse, zCol);
00264   if( zAlias1==0 ){
00265     zAlias1 = pTab1->zName;
00266   }
00267   pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
00268   if( zAlias2==0 ){
00269     zAlias2 = pTab2->zName;
00270   }
00271   pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
00272   pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
00273   pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
00274   pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
00275   if( pE && isOuterJoin ){
00276     ExprSetProperty(pE, EP_FromJoin);
00277     pE->iRightJoinTable = iRightJoinTable;
00278   }
00279   *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
00280 }
00281 
00282 /*
00283 ** Set the EP_FromJoin property on all terms of the given expression.
00284 ** And set the Expr.iRightJoinTable to iTable for every term in the
00285 ** expression.
00286 **
00287 ** The EP_FromJoin property is used on terms of an expression to tell
00288 ** the LEFT OUTER JOIN processing logic that this term is part of the
00289 ** join restriction specified in the ON or USING clause and not a part
00290 ** of the more general WHERE clause.  These terms are moved over to the
00291 ** WHERE clause during join processing but we need to remember that they
00292 ** originated in the ON or USING clause.
00293 **
00294 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
00295 ** expression depends on table iRightJoinTable even if that table is not
00296 ** explicitly mentioned in the expression.  That information is needed
00297 ** for cases like this:
00298 **
00299 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
00300 **
00301 ** The where clause needs to defer the handling of the t1.x=5
00302 ** term until after the t2 loop of the join.  In that way, a
00303 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
00304 ** defer the handling of t1.x=5, it will be processed immediately
00305 ** after the t1 loop and rows with t1.x!=5 will never appear in
00306 ** the output, which is incorrect.
00307 */
00308 static void setJoinExpr(Expr *p, int iTable){
00309   while( p ){
00310     ExprSetProperty(p, EP_FromJoin);
00311     p->iRightJoinTable = iTable;
00312     setJoinExpr(p->pLeft, iTable);
00313     p = p->pRight;
00314   } 
00315 }
00316 
00317 /*
00318 ** This routine processes the join information for a SELECT statement.
00319 ** ON and USING clauses are converted into extra terms of the WHERE clause.
00320 ** NATURAL joins also create extra WHERE clause terms.
00321 **
00322 ** The terms of a FROM clause are contained in the Select.pSrc structure.
00323 ** The left most table is the first entry in Select.pSrc.  The right-most
00324 ** table is the last entry.  The join operator is held in the entry to
00325 ** the left.  Thus entry 0 contains the join operator for the join between
00326 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
00327 ** also attached to the left entry.
00328 **
00329 ** This routine returns the number of errors encountered.
00330 */
00331 static int sqliteProcessJoin(Parse *pParse, Select *p){
00332   SrcList *pSrc;                  /* All tables in the FROM clause */
00333   int i, j;                       /* Loop counters */
00334   struct SrcList_item *pLeft;     /* Left table being joined */
00335   struct SrcList_item *pRight;    /* Right table being joined */
00336 
00337   pSrc = p->pSrc;
00338   pLeft = &pSrc->a[0];
00339   pRight = &pLeft[1];
00340   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
00341     Table *pLeftTab = pLeft->pTab;
00342     Table *pRightTab = pRight->pTab;
00343     int isOuter;
00344 
00345     if( pLeftTab==0 || pRightTab==0 ) continue;
00346     isOuter = (pRight->jointype & JT_OUTER)!=0;
00347 
00348     /* When the NATURAL keyword is present, add WHERE clause terms for
00349     ** every column that the two tables have in common.
00350     */
00351     if( pRight->jointype & JT_NATURAL ){
00352       if( pRight->pOn || pRight->pUsing ){
00353         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
00354            "an ON or USING clause", 0);
00355         return 1;
00356       }
00357       for(j=0; j<pLeftTab->nCol; j++){
00358         char *zName = pLeftTab->aCol[j].zName;
00359         if( columnIndex(pRightTab, zName)>=0 ){
00360           addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
00361                               pRightTab, pRight->zAlias,
00362                               pRight->iCursor, &p->pWhere, isOuter);
00363           
00364         }
00365       }
00366     }
00367 
00368     /* Disallow both ON and USING clauses in the same join
00369     */
00370     if( pRight->pOn && pRight->pUsing ){
00371       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
00372         "clauses in the same join");
00373       return 1;
00374     }
00375 
00376     /* Add the ON clause to the end of the WHERE clause, connected by
00377     ** an AND operator.
00378     */
00379     if( pRight->pOn ){
00380       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
00381       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
00382       pRight->pOn = 0;
00383     }
00384 
00385     /* Create extra terms on the WHERE clause for each column named
00386     ** in the USING clause.  Example: If the two tables to be joined are 
00387     ** A and B and the USING clause names X, Y, and Z, then add this
00388     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
00389     ** Report an error if any column mentioned in the USING clause is
00390     ** not contained in both tables to be joined.
00391     */
00392     if( pRight->pUsing ){
00393       IdList *pList = pRight->pUsing;
00394       for(j=0; j<pList->nId; j++){
00395         char *zName = pList->a[j].zName;
00396         if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
00397           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
00398             "not present in both tables", zName);
00399           return 1;
00400         }
00401         addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
00402                             pRightTab, pRight->zAlias,
00403                             pRight->iCursor, &p->pWhere, isOuter);
00404       }
00405     }
00406   }
00407   return 0;
00408 }
00409 
00410 /*
00411 ** Insert code into "v" that will push the record on the top of the
00412 ** stack into the sorter.
00413 */
00414 static void pushOntoSorter(
00415   Parse *pParse,         /* Parser context */
00416   ExprList *pOrderBy,    /* The ORDER BY clause */
00417   Select *pSelect,       /* The whole SELECT statement */
00418   int regData            /* Register holding data to be sorted */
00419 ){
00420   Vdbe *v = pParse->pVdbe;
00421   int nExpr = pOrderBy->nExpr;
00422   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
00423   int regRecord = sqlite3GetTempReg(pParse);
00424   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
00425   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
00426   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
00427   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
00428   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
00429   sqlite3ReleaseTempReg(pParse, regRecord);
00430   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
00431   if( pSelect->iLimit ){
00432     int addr1, addr2;
00433     int iLimit;
00434     if( pSelect->iOffset ){
00435       iLimit = pSelect->iOffset+1;
00436     }else{
00437       iLimit = pSelect->iLimit;
00438     }
00439     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
00440     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
00441     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
00442     sqlite3VdbeJumpHere(v, addr1);
00443     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
00444     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
00445     sqlite3VdbeJumpHere(v, addr2);
00446     pSelect->iLimit = 0;
00447   }
00448 }
00449 
00450 /*
00451 ** Add code to implement the OFFSET
00452 */
00453 static void codeOffset(
00454   Vdbe *v,          /* Generate code into this VM */
00455   Select *p,        /* The SELECT statement being coded */
00456   int iContinue     /* Jump here to skip the current record */
00457 ){
00458   if( p->iOffset && iContinue!=0 ){
00459     int addr;
00460     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
00461     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
00462     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
00463     VdbeComment((v, "skip OFFSET records"));
00464     sqlite3VdbeJumpHere(v, addr);
00465   }
00466 }
00467 
00468 /*
00469 ** Add code that will check to make sure the N registers starting at iMem
00470 ** form a distinct entry.  iTab is a sorting index that holds previously
00471 ** seen combinations of the N values.  A new entry is made in iTab
00472 ** if the current N values are new.
00473 **
00474 ** A jump to addrRepeat is made and the N+1 values are popped from the
00475 ** stack if the top N elements are not distinct.
00476 */
00477 static void codeDistinct(
00478   Parse *pParse,     /* Parsing and code generating context */
00479   int iTab,          /* A sorting index used to test for distinctness */
00480   int addrRepeat,    /* Jump to here if not distinct */
00481   int N,             /* Number of elements */
00482   int iMem           /* First element */
00483 ){
00484   Vdbe *v;
00485   int r1;
00486 
00487   v = pParse->pVdbe;
00488   r1 = sqlite3GetTempReg(pParse);
00489   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
00490   sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
00491   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
00492   sqlite3ReleaseTempReg(pParse, r1);
00493 }
00494 
00495 /*
00496 ** Generate an error message when a SELECT is used within a subexpression
00497 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
00498 ** column.  We do this in a subroutine because the error occurs in multiple
00499 ** places.
00500 */
00501 static int checkForMultiColumnSelectError(
00502   Parse *pParse,       /* Parse context. */
00503   SelectDest *pDest,   /* Destination of SELECT results */
00504   int nExpr            /* Number of result columns returned by SELECT */
00505 ){
00506   int eDest = pDest->eDest;
00507   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
00508     sqlite3ErrorMsg(pParse, "only a single result allowed for "
00509        "a SELECT that is part of an expression");
00510     return 1;
00511   }else{
00512     return 0;
00513   }
00514 }
00515 
00516 /*
00517 ** This routine generates the code for the inside of the inner loop
00518 ** of a SELECT.
00519 **
00520 ** If srcTab and nColumn are both zero, then the pEList expressions
00521 ** are evaluated in order to get the data for this row.  If nColumn>0
00522 ** then data is pulled from srcTab and pEList is used only to get the
00523 ** datatypes for each column.
00524 */
00525 static void selectInnerLoop(
00526   Parse *pParse,          /* The parser context */
00527   Select *p,              /* The complete select statement being coded */
00528   ExprList *pEList,       /* List of values being extracted */
00529   int srcTab,             /* Pull data from this table */
00530   int nColumn,            /* Number of columns in the source table */
00531   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
00532   int distinct,           /* If >=0, make sure results are distinct */
00533   SelectDest *pDest,      /* How to dispose of the results */
00534   int iContinue,          /* Jump here to continue with next row */
00535   int iBreak              /* Jump here to break out of the inner loop */
00536 ){
00537   Vdbe *v = pParse->pVdbe;
00538   int i;
00539   int hasDistinct;        /* True if the DISTINCT keyword is present */
00540   int regResult;              /* Start of memory holding result set */
00541   int eDest = pDest->eDest;   /* How to dispose of results */
00542   int iParm = pDest->iParm;   /* First argument to disposal method */
00543   int nResultCol;             /* Number of result columns */
00544 
00545   if( v==0 ) return;
00546   assert( pEList!=0 );
00547   hasDistinct = distinct>=0;
00548   if( pOrderBy==0 && !hasDistinct ){
00549     codeOffset(v, p, iContinue);
00550   }
00551 
00552   /* Pull the requested columns.
00553   */
00554   if( nColumn>0 ){
00555     nResultCol = nColumn;
00556   }else{
00557     nResultCol = pEList->nExpr;
00558   }
00559   if( pDest->iMem==0 ){
00560     pDest->iMem = pParse->nMem+1;
00561     pDest->nMem = nResultCol;
00562     pParse->nMem += nResultCol;
00563   }else if( pDest->nMem!=nResultCol ){
00564     /* This happens when two SELECTs of a compound SELECT have differing
00565     ** numbers of result columns.  The error message will be generated by
00566     ** a higher-level routine. */
00567     return;
00568   }
00569   regResult = pDest->iMem;
00570   if( nColumn>0 ){
00571     for(i=0; i<nColumn; i++){
00572       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
00573     }
00574   }else if( eDest!=SRT_Exists ){
00575     /* If the destination is an EXISTS(...) expression, the actual
00576     ** values returned by the SELECT are not required.
00577     */
00578     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
00579   }
00580   nColumn = nResultCol;
00581 
00582   /* If the DISTINCT keyword was present on the SELECT statement
00583   ** and this row has been seen before, then do not make this row
00584   ** part of the result.
00585   */
00586   if( hasDistinct ){
00587     assert( pEList!=0 );
00588     assert( pEList->nExpr==nColumn );
00589     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
00590     if( pOrderBy==0 ){
00591       codeOffset(v, p, iContinue);
00592     }
00593   }
00594 
00595   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
00596     return;
00597   }
00598 
00599   switch( eDest ){
00600     /* In this mode, write each query result to the key of the temporary
00601     ** table iParm.
00602     */
00603 #ifndef SQLITE_OMIT_COMPOUND_SELECT
00604     case SRT_Union: {
00605       int r1;
00606       r1 = sqlite3GetTempReg(pParse);
00607       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
00608       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
00609       sqlite3ReleaseTempReg(pParse, r1);
00610       break;
00611     }
00612 
00613     /* Construct a record from the query result, but instead of
00614     ** saving that record, use it as a key to delete elements from
00615     ** the temporary table iParm.
00616     */
00617     case SRT_Except: {
00618       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
00619       break;
00620     }
00621 #endif
00622 
00623     /* Store the result as data using a unique key.
00624     */
00625     case SRT_Table:
00626     case SRT_EphemTab: {
00627       int r1 = sqlite3GetTempReg(pParse);
00628       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
00629       if( pOrderBy ){
00630         pushOntoSorter(pParse, pOrderBy, p, r1);
00631       }else{
00632         int r2 = sqlite3GetTempReg(pParse);
00633         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
00634         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
00635         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
00636         sqlite3ReleaseTempReg(pParse, r2);
00637       }
00638       sqlite3ReleaseTempReg(pParse, r1);
00639       break;
00640     }
00641 
00642 #ifndef SQLITE_OMIT_SUBQUERY
00643     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
00644     ** then there should be a single item on the stack.  Write this
00645     ** item into the set table with bogus data.
00646     */
00647     case SRT_Set: {
00648       assert( nColumn==1 );
00649       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
00650       if( pOrderBy ){
00651         /* At first glance you would think we could optimize out the
00652         ** ORDER BY in this case since the order of entries in the set
00653         ** does not matter.  But there might be a LIMIT clause, in which
00654         ** case the order does matter */
00655         pushOntoSorter(pParse, pOrderBy, p, regResult);
00656       }else{
00657         int r1 = sqlite3GetTempReg(pParse);
00658         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
00659         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
00660         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
00661         sqlite3ReleaseTempReg(pParse, r1);
00662       }
00663       break;
00664     }
00665 
00666     /* If any row exist in the result set, record that fact and abort.
00667     */
00668     case SRT_Exists: {
00669       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
00670       /* The LIMIT clause will terminate the loop for us */
00671       break;
00672     }
00673 
00674     /* If this is a scalar select that is part of an expression, then
00675     ** store the results in the appropriate memory cell and break out
00676     ** of the scan loop.
00677     */
00678     case SRT_Mem: {
00679       assert( nColumn==1 );
00680       if( pOrderBy ){
00681         pushOntoSorter(pParse, pOrderBy, p, regResult);
00682       }else{
00683         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
00684         /* The LIMIT clause will jump out of the loop for us */
00685       }
00686       break;
00687     }
00688 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
00689 
00690     /* Send the data to the callback function or to a subroutine.  In the
00691     ** case of a subroutine, the subroutine itself is responsible for
00692     ** popping the data from the stack.
00693     */
00694     case SRT_Coroutine:
00695     case SRT_Output: {
00696       if( pOrderBy ){
00697         int r1 = sqlite3GetTempReg(pParse);
00698         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
00699         pushOntoSorter(pParse, pOrderBy, p, r1);
00700         sqlite3ReleaseTempReg(pParse, r1);
00701       }else if( eDest==SRT_Coroutine ){
00702         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
00703       }else{
00704         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
00705         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
00706       }
00707       break;
00708     }
00709 
00710 #if !defined(SQLITE_OMIT_TRIGGER)
00711     /* Discard the results.  This is used for SELECT statements inside
00712     ** the body of a TRIGGER.  The purpose of such selects is to call
00713     ** user-defined functions that have side effects.  We do not care
00714     ** about the actual results of the select.
00715     */
00716     default: {
00717       assert( eDest==SRT_Discard );
00718       break;
00719     }
00720 #endif
00721   }
00722 
00723   /* Jump to the end of the loop if the LIMIT is reached.
00724   */
00725   if( p->iLimit ){
00726     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
00727                             ** pushOntoSorter() would have cleared p->iLimit */
00728     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
00729     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
00730   }
00731 }
00732 
00733 /*
00734 ** Given an expression list, generate a KeyInfo structure that records
00735 ** the collating sequence for each expression in that expression list.
00736 **
00737 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
00738 ** KeyInfo structure is appropriate for initializing a virtual index to
00739 ** implement that clause.  If the ExprList is the result set of a SELECT
00740 ** then the KeyInfo structure is appropriate for initializing a virtual
00741 ** index to implement a DISTINCT test.
00742 **
00743 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
00744 ** function is responsible for seeing that this structure is eventually
00745 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
00746 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
00747 */
00748 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
00749   sqlite3 *db = pParse->db;
00750   int nExpr;
00751   KeyInfo *pInfo;
00752   struct ExprList_item *pItem;
00753   int i;
00754 
00755   nExpr = pList->nExpr;
00756   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
00757   if( pInfo ){
00758     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
00759     pInfo->nField = nExpr;
00760     pInfo->enc = ENC(db);
00761     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
00762       CollSeq *pColl;
00763       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
00764       if( !pColl ){
00765         pColl = db->pDfltColl;
00766       }
00767       pInfo->aColl[i] = pColl;
00768       pInfo->aSortOrder[i] = pItem->sortOrder;
00769     }
00770   }
00771   return pInfo;
00772 }
00773 
00774 
00775 /*
00776 ** If the inner loop was generated using a non-null pOrderBy argument,
00777 ** then the results were placed in a sorter.  After the loop is terminated
00778 ** we need to run the sorter and output the results.  The following
00779 ** routine generates the code needed to do that.
00780 */
00781 static void generateSortTail(
00782   Parse *pParse,    /* Parsing context */
00783   Select *p,        /* The SELECT statement */
00784   Vdbe *v,          /* Generate code into this VDBE */
00785   int nColumn,      /* Number of columns of data */
00786   SelectDest *pDest /* Write the sorted results here */
00787 ){
00788   int brk = sqlite3VdbeMakeLabel(v);
00789   int cont = sqlite3VdbeMakeLabel(v);
00790   int addr;
00791   int iTab;
00792   int pseudoTab = 0;
00793   ExprList *pOrderBy = p->pOrderBy;
00794 
00795   int eDest = pDest->eDest;
00796   int iParm = pDest->iParm;
00797 
00798   int regRow;
00799   int regRowid;
00800 
00801   iTab = pOrderBy->iECursor;
00802   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
00803     pseudoTab = pParse->nTab++;
00804     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
00805     sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
00806   }
00807   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
00808   codeOffset(v, p, cont);
00809   regRow = sqlite3GetTempReg(pParse);
00810   regRowid = sqlite3GetTempReg(pParse);
00811   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
00812   switch( eDest ){
00813     case SRT_Table:
00814     case SRT_EphemTab: {
00815       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
00816       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
00817       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
00818       break;
00819     }
00820 #ifndef SQLITE_OMIT_SUBQUERY
00821     case SRT_Set: {
00822       assert( nColumn==1 );
00823       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
00824       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
00825       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
00826       break;
00827     }
00828     case SRT_Mem: {
00829       assert( nColumn==1 );
00830       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
00831       /* The LIMIT clause will terminate the loop for us */
00832       break;
00833     }
00834 #endif
00835     case SRT_Output:
00836     case SRT_Coroutine: {
00837       int i;
00838       sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
00839       sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
00840       for(i=0; i<nColumn; i++){
00841         assert( regRow!=pDest->iMem+i );
00842         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
00843       }
00844       if( eDest==SRT_Output ){
00845         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
00846         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
00847       }else{
00848         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
00849       }
00850       break;
00851     }
00852     default: {
00853       /* Do nothing */
00854       break;
00855     }
00856   }
00857   sqlite3ReleaseTempReg(pParse, regRow);
00858   sqlite3ReleaseTempReg(pParse, regRowid);
00859 
00860   /* LIMIT has been implemented by the pushOntoSorter() routine.
00861   */
00862   assert( p->iLimit==0 );
00863 
00864   /* The bottom of the loop
00865   */
00866   sqlite3VdbeResolveLabel(v, cont);
00867   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
00868   sqlite3VdbeResolveLabel(v, brk);
00869   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
00870     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
00871   }
00872 
00873 }
00874 
00875 /*
00876 ** Return a pointer to a string containing the 'declaration type' of the
00877 ** expression pExpr. The string may be treated as static by the caller.
00878 **
00879 ** The declaration type is the exact datatype definition extracted from the
00880 ** original CREATE TABLE statement if the expression is a column. The
00881 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
00882 ** is considered a column can be complex in the presence of subqueries. The
00883 ** result-set expression in all of the following SELECT statements is 
00884 ** considered a column by this function.
00885 **
00886 **   SELECT col FROM tbl;
00887 **   SELECT (SELECT col FROM tbl;
00888 **   SELECT (SELECT col FROM tbl);
00889 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
00890 ** 
00891 ** The declaration type for any expression other than a column is NULL.
00892 */
00893 static const char *columnType(
00894   NameContext *pNC, 
00895   Expr *pExpr,
00896   const char **pzOriginDb,
00897   const char **pzOriginTab,
00898   const char **pzOriginCol
00899 ){
00900   char const *zType = 0;
00901   char const *zOriginDb = 0;
00902   char const *zOriginTab = 0;
00903   char const *zOriginCol = 0;
00904   int j;
00905   if( pExpr==0 || pNC->pSrcList==0 ) return 0;
00906 
00907   switch( pExpr->op ){
00908     case TK_AGG_COLUMN:
00909     case TK_COLUMN: {
00910       /* The expression is a column. Locate the table the column is being
00911       ** extracted from in NameContext.pSrcList. This table may be real
00912       ** database table or a subquery.
00913       */
00914       Table *pTab = 0;            /* Table structure column is extracted from */
00915       Select *pS = 0;             /* Select the column is extracted from */
00916       int iCol = pExpr->iColumn;  /* Index of column in pTab */
00917       while( pNC && !pTab ){
00918         SrcList *pTabList = pNC->pSrcList;
00919         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
00920         if( j<pTabList->nSrc ){
00921           pTab = pTabList->a[j].pTab;
00922           pS = pTabList->a[j].pSelect;
00923         }else{
00924           pNC = pNC->pNext;
00925         }
00926       }
00927 
00928       if( pTab==0 ){
00929         /* FIX ME:
00930         ** This can occurs if you have something like "SELECT new.x;" inside
00931         ** a trigger.  In other words, if you reference the special "new"
00932         ** table in the result set of a select.  We do not have a good way
00933         ** to find the actual table type, so call it "TEXT".  This is really
00934         ** something of a bug, but I do not know how to fix it.
00935         **
00936         ** This code does not produce the correct answer - it just prevents
00937         ** a segfault.  See ticket #1229.
00938         */
00939         zType = "TEXT";
00940         break;
00941       }
00942 
00943       assert( pTab );
00944       if( pS ){
00945         /* The "table" is actually a sub-select or a view in the FROM clause
00946         ** of the SELECT statement. Return the declaration type and origin
00947         ** data for the result-set column of the sub-select.
00948         */
00949         if( iCol>=0 && iCol<pS->pEList->nExpr ){
00950           /* If iCol is less than zero, then the expression requests the
00951           ** rowid of the sub-select or view. This expression is legal (see 
00952           ** test case misc2.2.2) - it always evaluates to NULL.
00953           */
00954           NameContext sNC;
00955           Expr *p = pS->pEList->a[iCol].pExpr;
00956           sNC.pSrcList = pS->pSrc;
00957           sNC.pNext = 0;
00958           sNC.pParse = pNC->pParse;
00959           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
00960         }
00961       }else if( pTab->pSchema ){
00962         /* A real table */
00963         assert( !pS );
00964         if( iCol<0 ) iCol = pTab->iPKey;
00965         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
00966         if( iCol<0 ){
00967           zType = "INTEGER";
00968           zOriginCol = "rowid";
00969         }else{
00970           zType = pTab->aCol[iCol].zType;
00971           zOriginCol = pTab->aCol[iCol].zName;
00972         }
00973         zOriginTab = pTab->zName;
00974         if( pNC->pParse ){
00975           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
00976           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
00977         }
00978       }
00979       break;
00980     }
00981 #ifndef SQLITE_OMIT_SUBQUERY
00982     case TK_SELECT: {
00983       /* The expression is a sub-select. Return the declaration type and
00984       ** origin info for the single column in the result set of the SELECT
00985       ** statement.
00986       */
00987       NameContext sNC;
00988       Select *pS = pExpr->pSelect;
00989       Expr *p = pS->pEList->a[0].pExpr;
00990       sNC.pSrcList = pS->pSrc;
00991       sNC.pNext = pNC;
00992       sNC.pParse = pNC->pParse;
00993       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
00994       break;
00995     }
00996 #endif
00997   }
00998   
00999   if( pzOriginDb ){
01000     assert( pzOriginTab && pzOriginCol );
01001     *pzOriginDb = zOriginDb;
01002     *pzOriginTab = zOriginTab;
01003     *pzOriginCol = zOriginCol;
01004   }
01005   return zType;
01006 }
01007 
01008 /*
01009 ** Generate code that will tell the VDBE the declaration types of columns
01010 ** in the result set.
01011 */
01012 static void generateColumnTypes(
01013   Parse *pParse,      /* Parser context */
01014   SrcList *pTabList,  /* List of tables */
01015   ExprList *pEList    /* Expressions defining the result set */
01016 ){
01017 #ifndef SQLITE_OMIT_DECLTYPE
01018   Vdbe *v = pParse->pVdbe;
01019   int i;
01020   NameContext sNC;
01021   sNC.pSrcList = pTabList;
01022   sNC.pParse = pParse;
01023   for(i=0; i<pEList->nExpr; i++){
01024     Expr *p = pEList->a[i].pExpr;
01025     const char *zType;
01026 #ifdef SQLITE_ENABLE_COLUMN_METADATA
01027     const char *zOrigDb = 0;
01028     const char *zOrigTab = 0;
01029     const char *zOrigCol = 0;
01030     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
01031 
01032     /* The vdbe must make its own copy of the column-type and other 
01033     ** column specific strings, in case the schema is reset before this
01034     ** virtual machine is deleted.
01035     */
01036     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
01037     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
01038     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
01039 #else
01040     zType = columnType(&sNC, p, 0, 0, 0);
01041 #endif
01042     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
01043   }
01044 #endif /* SQLITE_OMIT_DECLTYPE */
01045 }
01046 
01047 /*
01048 ** Generate code that will tell the VDBE the names of columns
01049 ** in the result set.  This information is used to provide the
01050 ** azCol[] values in the callback.
01051 */
01052 static void generateColumnNames(
01053   Parse *pParse,      /* Parser context */
01054   SrcList *pTabList,  /* List of tables */
01055   ExprList *pEList    /* Expressions defining the result set */
01056 ){
01057   Vdbe *v = pParse->pVdbe;
01058   int i, j;
01059   sqlite3 *db = pParse->db;
01060   int fullNames, shortNames;
01061 
01062 #ifndef SQLITE_OMIT_EXPLAIN
01063   /* If this is an EXPLAIN, skip this step */
01064   if( pParse->explain ){
01065     return;
01066   }
01067 #endif
01068 
01069   assert( v!=0 );
01070   if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
01071   pParse->colNamesSet = 1;
01072   fullNames = (db->flags & SQLITE_FullColNames)!=0;
01073   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
01074   sqlite3VdbeSetNumCols(v, pEList->nExpr);
01075   for(i=0; i<pEList->nExpr; i++){
01076     Expr *p;
01077     p = pEList->a[i].pExpr;
01078     if( p==0 ) continue;
01079     if( pEList->a[i].zName ){
01080       char *zName = pEList->a[i].zName;
01081       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
01082     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
01083       Table *pTab;
01084       char *zCol;
01085       int iCol = p->iColumn;
01086       for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
01087       assert( j<pTabList->nSrc );
01088       pTab = pTabList->a[j].pTab;
01089       if( iCol<0 ) iCol = pTab->iPKey;
01090       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
01091       if( iCol<0 ){
01092         zCol = "rowid";
01093       }else{
01094         zCol = pTab->aCol[iCol].zName;
01095       }
01096       if( !shortNames && !fullNames ){
01097         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
01098             sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
01099       }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
01100         char *zName = 0;
01101         char *zTab;
01102  
01103         zTab = pTabList->a[j].zAlias;
01104         if( fullNames || zTab==0 ) zTab = pTab->zName;
01105         zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
01106         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
01107       }else{
01108         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
01109       }
01110     }else{
01111       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
01112           sqlite3DbStrNDup(db, (char*)p->span.z, p->span.n), SQLITE_DYNAMIC);
01113     }
01114   }
01115   generateColumnTypes(pParse, pTabList, pEList);
01116 }
01117 
01118 #ifndef SQLITE_OMIT_COMPOUND_SELECT
01119 /*
01120 ** Name of the connection operator, used for error messages.
01121 */
01122 static const char *selectOpName(int id){
01123   char *z;
01124   switch( id ){
01125     case TK_ALL:       z = "UNION ALL";   break;
01126     case TK_INTERSECT: z = "INTERSECT";   break;
01127     case TK_EXCEPT:    z = "EXCEPT";      break;
01128     default:           z = "UNION";       break;
01129   }
01130   return z;
01131 }
01132 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
01133 
01134 /*
01135 ** Given a an expression list (which is really the list of expressions
01136 ** that form the result set of a SELECT statement) compute appropriate
01137 ** column names for a table that would hold the expression list.
01138 **
01139 ** All column names will be unique.
01140 **
01141 ** Only the column names are computed.  Column.zType, Column.zColl,
01142 ** and other fields of Column are zeroed.
01143 **
01144 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
01145 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
01146 */
01147 static int selectColumnsFromExprList(
01148   Parse *pParse,          /* Parsing context */
01149   ExprList *pEList,       /* Expr list from which to derive column names */
01150   int *pnCol,             /* Write the number of columns here */
01151   Column **paCol          /* Write the new column list here */
01152 ){
01153   sqlite3 *db = pParse->db;
01154   int i, j, cnt;
01155   Column *aCol, *pCol;
01156   int nCol;
01157   Expr *p;
01158   char *zName;
01159   int nName;
01160 
01161   *pnCol = nCol = pEList->nExpr;
01162   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
01163   if( aCol==0 ) return SQLITE_NOMEM;
01164   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
01165     /* Get an appropriate name for the column
01166     */
01167     p = pEList->a[i].pExpr;
01168     assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
01169     if( (zName = pEList->a[i].zName)!=0 ){
01170       /* If the column contains an "AS <name>" phrase, use <name> as the name */
01171       zName = sqlite3DbStrDup(db, zName);
01172     }else{
01173       Expr *pCol = p;
01174       Table *pTab;
01175       while( pCol->op==TK_DOT ) pCol = pCol->pRight;
01176       if( pCol->op==TK_COLUMN && (pTab = pCol->pTab)!=0 ){
01177         /* For columns use the column name name */
01178         int iCol = pCol->iColumn;
01179         if( iCol<0 ) iCol = pTab->iPKey;
01180         zName = sqlite3MPrintf(db, "%s",
01181                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
01182       }else{
01183         /* Use the original text of the column expression as its name */
01184         zName = sqlite3MPrintf(db, "%T", &pCol->span);
01185       }
01186     }
01187     if( db->mallocFailed ){
01188       sqlite3DbFree(db, zName);
01189       break;
01190     }
01191     sqlite3Dequote(zName);
01192 
01193     /* Make sure the column name is unique.  If the name is not unique,
01194     ** append a integer to the name so that it becomes unique.
01195     */
01196     nName = strlen(zName);
01197     for(j=cnt=0; j<i; j++){
01198       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
01199         char *zNewName;
01200         zName[nName] = 0;
01201         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
01202         sqlite3DbFree(db, zName);
01203         zName = zNewName;
01204         j = -1;
01205         if( zName==0 ) break;
01206       }
01207     }
01208     pCol->zName = zName;
01209   }
01210   if( db->mallocFailed ){
01211     int j;
01212     for(j=0; j<i; j++){
01213       sqlite3DbFree(db, aCol[j].zName);
01214     }
01215     sqlite3DbFree(db, aCol);
01216     *paCol = 0;
01217     *pnCol = 0;
01218     return SQLITE_NOMEM;
01219   }
01220   return SQLITE_OK;
01221 }
01222 
01223 /*
01224 ** Add type and collation information to a column list based on
01225 ** a SELECT statement.
01226 ** 
01227 ** The column list presumably came from selectColumnNamesFromExprList().
01228 ** The column list has only names, not types or collations.  This
01229 ** routine goes through and adds the types and collations.
01230 **
01231 ** This routine requires that all indentifiers in the SELECT
01232 ** statement be resolved.
01233 */
01234 static void selectAddColumnTypeAndCollation(
01235   Parse *pParse,        /* Parsing contexts */
01236   int nCol,             /* Number of columns */
01237   Column *aCol,         /* List of columns */
01238   Select *pSelect       /* SELECT used to determine types and collations */
01239 ){
01240   sqlite3 *db = pParse->db;
01241   NameContext sNC;
01242   Column *pCol;
01243   CollSeq *pColl;
01244   int i;
01245   Expr *p;
01246   struct ExprList_item *a;
01247 
01248   assert( pSelect!=0 );
01249   assert( (pSelect->selFlags & SF_Resolved)!=0 );
01250   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
01251   if( db->mallocFailed ) return;
01252   memset(&sNC, 0, sizeof(sNC));
01253   sNC.pSrcList = pSelect->pSrc;
01254   a = pSelect->pEList->a;
01255   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
01256     p = a[i].pExpr;
01257     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
01258     pCol->affinity = sqlite3ExprAffinity(p);
01259     pColl = sqlite3ExprCollSeq(pParse, p);
01260     if( pColl ){
01261       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
01262     }
01263   }
01264 }
01265 
01266 /*
01267 ** Given a SELECT statement, generate a Table structure that describes
01268 ** the result set of that SELECT.
01269 */
01270 Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
01271   Table *pTab;
01272   sqlite3 *db = pParse->db;
01273   int savedFlags;
01274 
01275   savedFlags = db->flags;
01276   db->flags &= ~SQLITE_FullColNames;
01277   db->flags |= SQLITE_ShortColNames;
01278   sqlite3SelectPrep(pParse, pSelect, 0);
01279   if( pParse->nErr ) return 0;
01280   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
01281   db->flags = savedFlags;
01282   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
01283   if( pTab==0 ){
01284     return 0;
01285   }
01286   pTab->db = db;
01287   pTab->nRef = 1;
01288   pTab->zName = 0;
01289   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
01290   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
01291   pTab->iPKey = -1;
01292   if( db->mallocFailed ){
01293     sqlite3DeleteTable(pTab);
01294     return 0;
01295   }
01296   return pTab;
01297 }
01298 
01299 /*
01300 ** Get a VDBE for the given parser context.  Create a new one if necessary.
01301 ** If an error occurs, return NULL and leave a message in pParse.
01302 */
01303 Vdbe *sqlite3GetVdbe(Parse *pParse){
01304   Vdbe *v = pParse->pVdbe;
01305   if( v==0 ){
01306     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
01307 #ifndef SQLITE_OMIT_TRACE
01308     if( v ){
01309       sqlite3VdbeAddOp0(v, OP_Trace);
01310     }
01311 #endif
01312   }
01313   return v;
01314 }
01315 
01316 
01317 /*
01318 ** Compute the iLimit and iOffset fields of the SELECT based on the
01319 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
01320 ** that appear in the original SQL statement after the LIMIT and OFFSET
01321 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
01322 ** are the integer memory register numbers for counters used to compute 
01323 ** the limit and offset.  If there is no limit and/or offset, then 
01324 ** iLimit and iOffset are negative.
01325 **
01326 ** This routine changes the values of iLimit and iOffset only if
01327 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
01328 ** iOffset should have been preset to appropriate default values
01329 ** (usually but not always -1) prior to calling this routine.
01330 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
01331 ** redefined.  The UNION ALL operator uses this property to force
01332 ** the reuse of the same limit and offset registers across multiple
01333 ** SELECT statements.
01334 */
01335 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
01336   Vdbe *v = 0;
01337   int iLimit = 0;
01338   int iOffset;
01339   int addr1;
01340   if( p->iLimit ) return;
01341 
01342   /* 
01343   ** "LIMIT -1" always shows all rows.  There is some
01344   ** contraversy about what the correct behavior should be.
01345   ** The current implementation interprets "LIMIT 0" to mean
01346   ** no rows.
01347   */
01348   if( p->pLimit ){
01349     p->iLimit = iLimit = ++pParse->nMem;
01350     v = sqlite3GetVdbe(pParse);
01351     if( v==0 ) return;
01352     sqlite3ExprCode(pParse, p->pLimit, iLimit);
01353     sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
01354     VdbeComment((v, "LIMIT counter"));
01355     sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
01356   }
01357   if( p->pOffset ){
01358     p->iOffset = iOffset = ++pParse->nMem;
01359     if( p->pLimit ){
01360       pParse->nMem++;   /* Allocate an extra register for limit+offset */
01361     }
01362     v = sqlite3GetVdbe(pParse);
01363     if( v==0 ) return;
01364     sqlite3ExprCode(pParse, p->pOffset, iOffset);
01365     sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
01366     VdbeComment((v, "OFFSET counter"));
01367     addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
01368     sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
01369     sqlite3VdbeJumpHere(v, addr1);
01370     if( p->pLimit ){
01371       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
01372       VdbeComment((v, "LIMIT+OFFSET"));
01373       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
01374       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
01375       sqlite3VdbeJumpHere(v, addr1);
01376     }
01377   }
01378 }
01379 
01380 #ifndef SQLITE_OMIT_COMPOUND_SELECT
01381 /*
01382 ** Return the appropriate collating sequence for the iCol-th column of
01383 ** the result set for the compound-select statement "p".  Return NULL if
01384 ** the column has no default collating sequence.
01385 **
01386 ** The collating sequence for the compound select is taken from the
01387 ** left-most term of the select that has a collating sequence.
01388 */
01389 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
01390   CollSeq *pRet;
01391   if( p->pPrior ){
01392     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
01393   }else{
01394     pRet = 0;
01395   }
01396   if( pRet==0 ){
01397     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
01398   }
01399   return pRet;
01400 }
01401 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
01402 
01403 /* Forward reference */
01404 static int multiSelectOrderBy(
01405   Parse *pParse,        /* Parsing context */
01406   Select *p,            /* The right-most of SELECTs to be coded */
01407   SelectDest *pDest     /* What to do with query results */
01408 );
01409 
01410 
01411 #ifndef SQLITE_OMIT_COMPOUND_SELECT
01412 /*
01413 ** This routine is called to process a compound query form from
01414 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
01415 ** INTERSECT
01416 **
01417 ** "p" points to the right-most of the two queries.  the query on the
01418 ** left is p->pPrior.  The left query could also be a compound query
01419 ** in which case this routine will be called recursively. 
01420 **
01421 ** The results of the total query are to be written into a destination
01422 ** of type eDest with parameter iParm.
01423 **
01424 ** Example 1:  Consider a three-way compound SQL statement.
01425 **
01426 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
01427 **
01428 ** This statement is parsed up as follows:
01429 **
01430 **     SELECT c FROM t3
01431 **      |
01432 **      `----->  SELECT b FROM t2
01433 **                |
01434 **                `------>  SELECT a FROM t1
01435 **
01436 ** The arrows in the diagram above represent the Select.pPrior pointer.
01437 ** So if this routine is called with p equal to the t3 query, then
01438 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
01439 **
01440 ** Notice that because of the way SQLite parses compound SELECTs, the
01441 ** individual selects always group from left to right.
01442 */
01443 static int multiSelect(
01444   Parse *pParse,        /* Parsing context */
01445   Select *p,            /* The right-most of SELECTs to be coded */
01446   SelectDest *pDest     /* What to do with query results */
01447 ){
01448   int rc = SQLITE_OK;   /* Success code from a subroutine */
01449   Select *pPrior;       /* Another SELECT immediately to our left */
01450   Vdbe *v;              /* Generate code to this VDBE */
01451   SelectDest dest;      /* Alternative data destination */
01452   Select *pDelete = 0;  /* Chain of simple selects to delete */
01453   sqlite3 *db;          /* Database connection */
01454 
01455   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
01456   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
01457   */
01458   assert( p && p->pPrior );  /* Calling function guarantees this much */
01459   db = pParse->db;
01460   pPrior = p->pPrior;
01461   assert( pPrior->pRightmost!=pPrior );
01462   assert( pPrior->pRightmost==p->pRightmost );
01463   dest = *pDest;
01464   if( pPrior->pOrderBy ){
01465     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
01466       selectOpName(p->op));
01467     rc = 1;
01468     goto multi_select_end;
01469   }
01470   if( pPrior->pLimit ){
01471     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
01472       selectOpName(p->op));
01473     rc = 1;
01474     goto multi_select_end;
01475   }
01476 
01477   v = sqlite3GetVdbe(pParse);
01478   assert( v!=0 );  /* The VDBE already created by calling function */
01479 
01480   /* Create the destination temporary table if necessary
01481   */
01482   if( dest.eDest==SRT_EphemTab ){
01483     assert( p->pEList );
01484     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
01485     dest.eDest = SRT_Table;
01486   }
01487 
01488   /* Make sure all SELECTs in the statement have the same number of elements
01489   ** in their result sets.
01490   */
01491   assert( p->pEList && pPrior->pEList );
01492   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
01493     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
01494       " do not have the same number of result columns", selectOpName(p->op));
01495     rc = 1;
01496     goto multi_select_end;
01497   }
01498 
01499   /* Compound SELECTs that have an ORDER BY clause are handled separately.
01500   */
01501   if( p->pOrderBy ){
01502     return multiSelectOrderBy(pParse, p, pDest);
01503   }
01504 
01505   /* Generate code for the left and right SELECT statements.
01506   */
01507   switch( p->op ){
01508     case TK_ALL: {
01509       int addr = 0;
01510       assert( !pPrior->pLimit );
01511       pPrior->pLimit = p->pLimit;
01512       pPrior->pOffset = p->pOffset;
01513       rc = sqlite3Select(pParse, pPrior, &dest);
01514       p->pLimit = 0;
01515       p->pOffset = 0;
01516       if( rc ){
01517         goto multi_select_end;
01518       }
01519       p->pPrior = 0;
01520       p->iLimit = pPrior->iLimit;
01521       p->iOffset = pPrior->iOffset;
01522       if( p->iLimit ){
01523         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
01524         VdbeComment((v, "Jump ahead if LIMIT reached"));
01525       }
01526       rc = sqlite3Select(pParse, p, &dest);
01527       pDelete = p->pPrior;
01528       p->pPrior = pPrior;
01529       if( rc ){
01530         goto multi_select_end;
01531       }
01532       if( addr ){
01533         sqlite3VdbeJumpHere(v, addr);
01534       }
01535       break;
01536     }
01537     case TK_EXCEPT:
01538     case TK_UNION: {
01539       int unionTab;    /* Cursor number of the temporary table holding result */
01540       int op = 0;      /* One of the SRT_ operations to apply to self */
01541       int priorOp;     /* The SRT_ operation to apply to prior selects */
01542       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
01543       int addr;
01544       SelectDest uniondest;
01545 
01546       priorOp = SRT_Union;
01547       if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
01548         /* We can reuse a temporary table generated by a SELECT to our
01549         ** right.
01550         */
01551         unionTab = dest.iParm;
01552       }else{
01553         /* We will need to create our own temporary table to hold the
01554         ** intermediate results.
01555         */
01556         unionTab = pParse->nTab++;
01557         assert( p->pOrderBy==0 );
01558         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
01559         assert( p->addrOpenEphm[0] == -1 );
01560         p->addrOpenEphm[0] = addr;
01561         p->pRightmost->selFlags |= SF_UsesEphemeral;
01562         assert( p->pEList );
01563       }
01564 
01565       /* Code the SELECT statements to our left
01566       */
01567       assert( !pPrior->pOrderBy );
01568       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
01569       rc = sqlite3Select(pParse, pPrior, &uniondest);
01570       if( rc ){
01571         goto multi_select_end;
01572       }
01573 
01574       /* Code the current SELECT statement
01575       */
01576       if( p->op==TK_EXCEPT ){
01577         op = SRT_Except;
01578       }else{
01579         assert( p->op==TK_UNION );
01580         op = SRT_Union;
01581       }
01582       p->pPrior = 0;
01583       pLimit = p->pLimit;
01584       p->pLimit = 0;
01585       pOffset = p->pOffset;
01586       p->pOffset = 0;
01587       uniondest.eDest = op;
01588       rc = sqlite3Select(pParse, p, &uniondest);
01589       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
01590       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
01591       sqlite3ExprListDelete(db, p->pOrderBy);
01592       pDelete = p->pPrior;
01593       p->pPrior = pPrior;
01594       p->pOrderBy = 0;
01595       sqlite3ExprDelete(db, p->pLimit);
01596       p->pLimit = pLimit;
01597       p->pOffset = pOffset;
01598       p->iLimit = 0;
01599       p->iOffset = 0;
01600       if( rc ){
01601         goto multi_select_end;
01602       }
01603 
01604 
01605       /* Convert the data in the temporary table into whatever form
01606       ** it is that we currently need.
01607       */      
01608       if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
01609         int iCont, iBreak, iStart;
01610         assert( p->pEList );
01611         if( dest.eDest==SRT_Output ){
01612           Select *pFirst = p;
01613           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
01614           generateColumnNames(pParse, 0, pFirst->pEList);
01615         }
01616         iBreak = sqlite3VdbeMakeLabel(v);
01617         iCont = sqlite3VdbeMakeLabel(v);
01618         computeLimitRegisters(pParse, p, iBreak);
01619         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
01620         iStart = sqlite3VdbeCurrentAddr(v);
01621         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
01622                         0, -1, &dest, iCont, iBreak);
01623         sqlite3VdbeResolveLabel(v, iCont);
01624         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
01625         sqlite3VdbeResolveLabel(v, iBreak);
01626         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
01627       }
01628       break;
01629     }
01630     case TK_INTERSECT: {
01631       int tab1, tab2;
01632       int iCont, iBreak, iStart;
01633       Expr *pLimit, *pOffset;
01634       int addr;
01635       SelectDest intersectdest;
01636       int r1;
01637 
01638       /* INTERSECT is different from the others since it requires
01639       ** two temporary tables.  Hence it has its own case.  Begin
01640       ** by allocating the tables we will need.
01641       */
01642       tab1 = pParse->nTab++;
01643       tab2 = pParse->nTab++;
01644       assert( p->pOrderBy==0 );
01645 
01646       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
01647       assert( p->addrOpenEphm[0] == -1 );
01648       p->addrOpenEphm[0] = addr;
01649       p->pRightmost->selFlags |= SF_UsesEphemeral;
01650       assert( p->pEList );
01651 
01652       /* Code the SELECTs to our left into temporary table "tab1".
01653       */
01654       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
01655       rc = sqlite3Select(pParse, pPrior, &intersectdest);
01656       if( rc ){
01657         goto multi_select_end;
01658       }
01659 
01660       /* Code the current SELECT into temporary table "tab2"
01661       */
01662       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
01663       assert( p->addrOpenEphm[1] == -1 );
01664       p->addrOpenEphm[1] = addr;
01665       p->pPrior = 0;
01666       pLimit = p->pLimit;
01667       p->pLimit = 0;
01668       pOffset = p->pOffset;
01669       p->pOffset = 0;
01670       intersectdest.iParm = tab2;
01671       rc = sqlite3Select(pParse, p, &intersectdest);
01672       pDelete = p->pPrior;
01673       p->pPrior = pPrior;
01674       sqlite3ExprDelete(db, p->pLimit);
01675       p->pLimit = pLimit;
01676       p->pOffset = pOffset;
01677       if( rc ){
01678         goto multi_select_end;
01679       }
01680 
01681       /* Generate code to take the intersection of the two temporary
01682       ** tables.
01683       */
01684       assert( p->pEList );
01685       if( dest.eDest==SRT_Output ){
01686         Select *pFirst = p;
01687         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
01688         generateColumnNames(pParse, 0, pFirst->pEList);
01689       }
01690       iBreak = sqlite3VdbeMakeLabel(v);
01691       iCont = sqlite3VdbeMakeLabel(v);
01692       computeLimitRegisters(pParse, p, iBreak);
01693       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
01694       r1 = sqlite3GetTempReg(pParse);
01695       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
01696       sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
01697       sqlite3ReleaseTempReg(pParse, r1);
01698       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
01699                       0, -1, &dest, iCont, iBreak);
01700       sqlite3VdbeResolveLabel(v, iCont);
01701       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
01702       sqlite3VdbeResolveLabel(v, iBreak);
01703       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
01704       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
01705       break;
01706     }
01707   }
01708 
01709   /* Compute collating sequences used by 
01710   ** temporary tables needed to implement the compound select.
01711   ** Attach the KeyInfo structure to all temporary tables.
01712   **
01713   ** This section is run by the right-most SELECT statement only.
01714   ** SELECT statements to the left always skip this part.  The right-most
01715   ** SELECT might also skip this part if it has no ORDER BY clause and
01716   ** no temp tables are required.
01717   */
01718   if( p->selFlags & SF_UsesEphemeral ){
01719     int i;                        /* Loop counter */
01720     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
01721     Select *pLoop;                /* For looping through SELECT statements */
01722     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
01723     int nCol;                     /* Number of columns in result set */
01724 
01725     assert( p->pRightmost==p );
01726     nCol = p->pEList->nExpr;
01727     pKeyInfo = sqlite3DbMallocZero(db,
01728                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
01729     if( !pKeyInfo ){
01730       rc = SQLITE_NOMEM;
01731       goto multi_select_end;
01732     }
01733 
01734     pKeyInfo->enc = ENC(db);
01735     pKeyInfo->nField = nCol;
01736 
01737     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
01738       *apColl = multiSelectCollSeq(pParse, p, i);
01739       if( 0==*apColl ){
01740         *apColl = db->pDfltColl;
01741       }
01742     }
01743 
01744     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
01745       for(i=0; i<2; i++){
01746         int addr = pLoop->addrOpenEphm[i];
01747         if( addr<0 ){
01748           /* If [0] is unused then [1] is also unused.  So we can
01749           ** always safely abort as soon as the first unused slot is found */
01750           assert( pLoop->addrOpenEphm[1]<0 );
01751           break;
01752         }
01753         sqlite3VdbeChangeP2(v, addr, nCol);
01754         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
01755         pLoop->addrOpenEphm[i] = -1;
01756       }
01757     }
01758     sqlite3DbFree(db, pKeyInfo);
01759   }
01760 
01761 multi_select_end:
01762   pDest->iMem = dest.iMem;
01763   pDest->nMem = dest.nMem;
01764   sqlite3SelectDelete(db, pDelete);
01765   return rc;
01766 }
01767 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
01768 
01769 /*
01770 ** Code an output subroutine for a coroutine implementation of a
01771 ** SELECT statment.
01772 **
01773 ** The data to be output is contained in pIn->iMem.  There are
01774 ** pIn->nMem columns to be output.  pDest is where the output should
01775 ** be sent.
01776 **
01777 ** regReturn is the number of the register holding the subroutine
01778 ** return address.
01779 **
01780 ** If regPrev>0 then it is a the first register in a vector that
01781 ** records the previous output.  mem[regPrev] is a flag that is false
01782 ** if there has been no previous output.  If regPrev>0 then code is
01783 ** generated to suppress duplicates.  pKeyInfo is used for comparing
01784 ** keys.
01785 **
01786 ** If the LIMIT found in p->iLimit is reached, jump immediately to
01787 ** iBreak.
01788 */
01789 static int generateOutputSubroutine(
01790   Parse *pParse,          /* Parsing context */
01791   Select *p,              /* The SELECT statement */
01792   SelectDest *pIn,        /* Coroutine supplying data */
01793   SelectDest *pDest,      /* Where to send the data */
01794   int regReturn,          /* The return address register */
01795   int regPrev,            /* Previous result register.  No uniqueness if 0 */
01796   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
01797   int p4type,             /* The p4 type for pKeyInfo */
01798   int iBreak              /* Jump here if we hit the LIMIT */
01799 ){
01800   Vdbe *v = pParse->pVdbe;
01801   int iContinue;
01802   int addr;
01803 
01804   addr = sqlite3VdbeCurrentAddr(v);
01805   iContinue = sqlite3VdbeMakeLabel(v);
01806 
01807   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
01808   */
01809   if( regPrev ){
01810     int j1, j2;
01811     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
01812     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
01813                               (char*)pKeyInfo, p4type);
01814     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
01815     sqlite3VdbeJumpHere(v, j1);
01816     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
01817     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
01818   }
01819   if( pParse->db->mallocFailed ) return 0;
01820 
01821   /* Suppress the the first OFFSET entries if there is an OFFSET clause
01822   */
01823   codeOffset(v, p, iContinue);
01824 
01825   switch( pDest->eDest ){
01826     /* Store the result as data using a unique key.
01827     */
01828     case SRT_Table:
01829     case SRT_EphemTab: {
01830       int r1 = sqlite3GetTempReg(pParse);
01831       int r2 = sqlite3GetTempReg(pParse);
01832       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
01833       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
01834       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
01835       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
01836       sqlite3ReleaseTempReg(pParse, r2);
01837       sqlite3ReleaseTempReg(pParse, r1);
01838       break;
01839     }
01840 
01841 #ifndef SQLITE_OMIT_SUBQUERY
01842     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
01843     ** then there should be a single item on the stack.  Write this
01844     ** item into the set table with bogus data.
01845     */
01846     case SRT_Set: {
01847       int r1;
01848       assert( pIn->nMem==1 );
01849       p->affinity = 
01850          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
01851       r1 = sqlite3GetTempReg(pParse);
01852       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
01853       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
01854       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
01855       sqlite3ReleaseTempReg(pParse, r1);
01856       break;
01857     }
01858 
01859 #if 0  /* Never occurs on an ORDER BY query */
01860     /* If any row exist in the result set, record that fact and abort.
01861     */
01862     case SRT_Exists: {
01863       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
01864       /* The LIMIT clause will terminate the loop for us */
01865       break;
01866     }
01867 #endif
01868 
01869     /* If this is a scalar select that is part of an expression, then
01870     ** store the results in the appropriate memory cell and break out
01871     ** of the scan loop.
01872     */
01873     case SRT_Mem: {
01874       assert( pIn->nMem==1 );
01875       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
01876       /* The LIMIT clause will jump out of the loop for us */
01877       break;
01878     }
01879 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
01880 
01881     /* The results are stored in a sequence of registers
01882     ** starting at pDest->iMem.  Then the co-routine yields.
01883     */
01884     case SRT_Coroutine: {
01885       if( pDest->iMem==0 ){
01886         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
01887         pDest->nMem = pIn->nMem;
01888       }
01889       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
01890       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
01891       break;
01892     }
01893 
01894     /* Results are stored in a sequence of registers.  Then the
01895     ** OP_ResultRow opcode is used to cause sqlite3_step() to return
01896     ** the next row of result.
01897     */
01898     case SRT_Output: {
01899       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
01900       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
01901       break;
01902     }
01903 
01904 #if !defined(SQLITE_OMIT_TRIGGER)
01905     /* Discard the results.  This is used for SELECT statements inside
01906     ** the body of a TRIGGER.  The purpose of such selects is to call
01907     ** user-defined functions that have side effects.  We do not care
01908     ** about the actual results of the select.
01909     */
01910     default: {
01911       break;
01912     }
01913 #endif
01914   }
01915 
01916   /* Jump to the end of the loop if the LIMIT is reached.
01917   */
01918   if( p->iLimit ){
01919     sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
01920     sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
01921   }
01922 
01923   /* Generate the subroutine return
01924   */
01925   sqlite3VdbeResolveLabel(v, iContinue);
01926   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
01927 
01928   return addr;
01929 }
01930 
01931 /*
01932 ** Alternative compound select code generator for cases when there
01933 ** is an ORDER BY clause.
01934 **
01935 ** We assume a query of the following form:
01936 **
01937 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
01938 **
01939 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
01940 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
01941 ** co-routines.  Then run the co-routines in parallel and merge the results
01942 ** into the output.  In addition to the two coroutines (called selectA and
01943 ** selectB) there are 7 subroutines:
01944 **
01945 **    outA:    Move the output of the selectA coroutine into the output
01946 **             of the compound query.
01947 **
01948 **    outB:    Move the output of the selectB coroutine into the output
01949 **             of the compound query.  (Only generated for UNION and
01950 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
01951 **             appears only in B.)
01952 **
01953 **    AltB:    Called when there is data from both coroutines and A<B.
01954 **
01955 **    AeqB:    Called when there is data from both coroutines and A==B.
01956 **
01957 **    AgtB:    Called when there is data from both coroutines and A>B.
01958 **
01959 **    EofA:    Called when data is exhausted from selectA.
01960 **
01961 **    EofB:    Called when data is exhausted from selectB.
01962 **
01963 ** The implementation of the latter five subroutines depend on which 
01964 ** <operator> is used:
01965 **
01966 **
01967 **             UNION ALL         UNION            EXCEPT          INTERSECT
01968 **          -------------  -----------------  --------------  -----------------
01969 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
01970 **
01971 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
01972 **
01973 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
01974 **
01975 **   EofA:   outB, nextB      outB, nextB          halt             halt
01976 **
01977 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
01978 **
01979 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
01980 ** causes an immediate jump to EofA and an EOF on B following nextB causes
01981 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
01982 ** following nextX causes a jump to the end of the select processing.
01983 **
01984 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
01985 ** within the output subroutine.  The regPrev register set holds the previously
01986 ** output value.  A comparison is made against this value and the output
01987 ** is skipped if the next results would be the same as the previous.
01988 **
01989 ** The implementation plan is to implement the two coroutines and seven
01990 ** subroutines first, then put the control logic at the bottom.  Like this:
01991 **
01992 **          goto Init
01993 **     coA: coroutine for left query (A)
01994 **     coB: coroutine for right query (B)
01995 **    outA: output one row of A
01996 **    outB: output one row of B (UNION and UNION ALL only)
01997 **    EofA: ...
01998 **    EofB: ...
01999 **    AltB: ...
02000 **    AeqB: ...
02001 **    AgtB: ...
02002 **    Init: initialize coroutine registers
02003 **          yield coA
02004 **          if eof(A) goto EofA
02005 **          yield coB
02006 **          if eof(B) goto EofB
02007 **    Cmpr: Compare A, B
02008 **          Jump AltB, AeqB, AgtB
02009 **     End: ...
02010 **
02011 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
02012 ** actually called using Gosub and they do not Return.  EofA and EofB loop
02013 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
02014 ** and AgtB jump to either L2 or to one of EofA or EofB.
02015 */
02016 #ifndef SQLITE_OMIT_COMPOUND_SELECT
02017 static int multiSelectOrderBy(
02018   Parse *pParse,        /* Parsing context */
02019   Select *p,            /* The right-most of SELECTs to be coded */
02020   SelectDest *pDest     /* What to do with query results */
02021 ){
02022   int i, j;             /* Loop counters */
02023   Select *pPrior;       /* Another SELECT immediately to our left */
02024   Vdbe *v;              /* Generate code to this VDBE */
02025   SelectDest destA;     /* Destination for coroutine A */
02026   SelectDest destB;     /* Destination for coroutine B */
02027   int regAddrA;         /* Address register for select-A coroutine */
02028   int regEofA;          /* Flag to indicate when select-A is complete */
02029   int regAddrB;         /* Address register for select-B coroutine */
02030   int regEofB;          /* Flag to indicate when select-B is complete */
02031   int addrSelectA;      /* Address of the select-A coroutine */
02032   int addrSelectB;      /* Address of the select-B coroutine */
02033   int regOutA;          /* Address register for the output-A subroutine */
02034   int regOutB;          /* Address register for the output-B subroutine */
02035   int addrOutA;         /* Address of the output-A subroutine */
02036   int addrOutB;         /* Address of the output-B subroutine */
02037   int addrEofA;         /* Address of the select-A-exhausted subroutine */
02038   int addrEofB;         /* Address of the select-B-exhausted subroutine */
02039   int addrAltB;         /* Address of the A<B subroutine */
02040   int addrAeqB;         /* Address of the A==B subroutine */
02041   int addrAgtB;         /* Address of the A>B subroutine */
02042   int regLimitA;        /* Limit register for select-A */
02043   int regLimitB;        /* Limit register for select-A */
02044   int regPrev;          /* A range of registers to hold previous output */
02045   int savedLimit;       /* Saved value of p->iLimit */
02046   int savedOffset;      /* Saved value of p->iOffset */
02047   int labelCmpr;        /* Label for the start of the merge algorithm */
02048   int labelEnd;         /* Label for the end of the overall SELECT stmt */
02049   int j1;               /* Jump instructions that get retargetted */
02050   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
02051   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
02052   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
02053   sqlite3 *db;          /* Database connection */
02054   ExprList *pOrderBy;   /* The ORDER BY clause */
02055   int nOrderBy;         /* Number of terms in the ORDER BY clause */
02056   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
02057 
02058   assert( p->pOrderBy!=0 );
02059   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
02060   db = pParse->db;
02061   v = pParse->pVdbe;
02062   if( v==0 ) return SQLITE_NOMEM;
02063   labelEnd = sqlite3VdbeMakeLabel(v);
02064   labelCmpr = sqlite3VdbeMakeLabel(v);
02065 
02066 
02067   /* Patch up the ORDER BY clause
02068   */
02069   op = p->op;  
02070   pPrior = p->pPrior;
02071   assert( pPrior->pOrderBy==0 );
02072   pOrderBy = p->pOrderBy;
02073   assert( pOrderBy );
02074   nOrderBy = pOrderBy->nExpr;
02075 
02076   /* For operators other than UNION ALL we have to make sure that
02077   ** the ORDER BY clause covers every term of the result set.  Add
02078   ** terms to the ORDER BY clause as necessary.
02079   */
02080   if( op!=TK_ALL ){
02081     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
02082       struct ExprList_item *pItem;
02083       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
02084         assert( pItem->iCol>0 );
02085         if( pItem->iCol==i ) break;
02086       }
02087       if( j==nOrderBy ){
02088         Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
02089         if( pNew==0 ) return SQLITE_NOMEM;
02090         pNew->flags |= EP_IntValue;
02091         pNew->iTable = i;
02092         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
02093         pOrderBy->a[nOrderBy++].iCol = i;
02094       }
02095     }
02096   }
02097 
02098   /* Compute the comparison permutation and keyinfo that is used with
02099   ** the permutation in order to comparisons to determine if the next
02100   ** row of results comes from selectA or selectB.  Also add explicit
02101   ** collations to the ORDER BY clause terms so that when the subqueries
02102   ** to the right and the left are evaluated, they use the correct
02103   ** collation.
02104   */
02105   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
02106   if( aPermute ){
02107     struct ExprList_item *pItem;
02108     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
02109       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
02110       aPermute[i] = pItem->iCol - 1;
02111     }
02112     pKeyMerge =
02113       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
02114     if( pKeyMerge ){
02115       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
02116       pKeyMerge->nField = nOrderBy;
02117       pKeyMerge->enc = ENC(db);
02118       for(i=0; i<nOrderBy; i++){
02119         CollSeq *pColl;
02120         Expr *pTerm = pOrderBy->a[i].pExpr;
02121         if( pTerm->flags & EP_ExpCollate ){
02122           pColl = pTerm->pColl;
02123         }else{
02124           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
02125           pTerm->flags |= EP_ExpCollate;
02126           pTerm->pColl = pColl;
02127         }
02128         pKeyMerge->aColl[i] = pColl;
02129         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
02130       }
02131     }
02132   }else{
02133     pKeyMerge = 0;
02134   }
02135 
02136   /* Reattach the ORDER BY clause to the query.
02137   */
02138   p->pOrderBy = pOrderBy;
02139   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
02140 
02141   /* Allocate a range of temporary registers and the KeyInfo needed
02142   ** for the logic that removes duplicate result rows when the
02143   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
02144   */
02145   if( op==TK_ALL ){
02146     regPrev = 0;
02147   }else{
02148     int nExpr = p->pEList->nExpr;
02149     assert( nOrderBy>=nExpr || db->mallocFailed );
02150     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
02151     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
02152     pKeyDup = sqlite3DbMallocZero(db,
02153                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
02154     if( pKeyDup ){
02155       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
02156       pKeyDup->nField = nExpr;
02157       pKeyDup->enc = ENC(db);
02158       for(i=0; i<nExpr; i++){
02159         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
02160         pKeyDup->aSortOrder[i] = 0;
02161       }
02162     }
02163   }
02164  
02165   /* Separate the left and the right query from one another
02166   */
02167   p->pPrior = 0;
02168   pPrior->pRightmost = 0;
02169   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
02170   if( pPrior->pPrior==0 ){
02171     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
02172   }
02173 
02174   /* Compute the limit registers */
02175   computeLimitRegisters(pParse, p, labelEnd);
02176   if( p->iLimit && op==TK_ALL ){
02177     regLimitA = ++pParse->nMem;
02178     regLimitB = ++pParse->nMem;
02179     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
02180                                   regLimitA);
02181     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
02182   }else{
02183     regLimitA = regLimitB = 0;
02184   }
02185   sqlite3ExprDelete(db, p->pLimit);
02186   p->pLimit = 0;
02187   sqlite3ExprDelete(db, p->pOffset);
02188   p->pOffset = 0;
02189 
02190   regAddrA = ++pParse->nMem;
02191   regEofA = ++pParse->nMem;
02192   regAddrB = ++pParse->nMem;
02193   regEofB = ++pParse->nMem;
02194   regOutA = ++pParse->nMem;
02195   regOutB = ++pParse->nMem;
02196   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
02197   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
02198 
02199   /* Jump past the various subroutines and coroutines to the main
02200   ** merge loop
02201   */
02202   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
02203   addrSelectA = sqlite3VdbeCurrentAddr(v);
02204 
02205 
02206   /* Generate a coroutine to evaluate the SELECT statement to the
02207   ** left of the compound operator - the "A" select.
02208   */
02209   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
02210   pPrior->iLimit = regLimitA;
02211   sqlite3Select(pParse, pPrior, &destA);
02212   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
02213   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
02214   VdbeNoopComment((v, "End coroutine for left SELECT"));
02215 
02216   /* Generate a coroutine to evaluate the SELECT statement on 
02217   ** the right - the "B" select
02218   */
02219   addrSelectB = sqlite3VdbeCurrentAddr(v);
02220   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
02221   savedLimit = p->iLimit;
02222   savedOffset = p->iOffset;
02223   p->iLimit = regLimitB;
02224   p->iOffset = 0;  
02225   sqlite3Select(pParse, p, &destB);
02226   p->iLimit = savedLimit;
02227   p->iOffset = savedOffset;
02228   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
02229   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
02230   VdbeNoopComment((v, "End coroutine for right SELECT"));
02231 
02232   /* Generate a subroutine that outputs the current row of the A
02233   ** select as the next output row of the compound select.
02234   */
02235   VdbeNoopComment((v, "Output routine for A"));
02236   addrOutA = generateOutputSubroutine(pParse,
02237                  p, &destA, pDest, regOutA,
02238                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
02239   
02240   /* Generate a subroutine that outputs the current row of the B
02241   ** select as the next output row of the compound select.
02242   */
02243   if( op==TK_ALL || op==TK_UNION ){
02244     VdbeNoopComment((v, "Output routine for B"));
02245     addrOutB = generateOutputSubroutine(pParse,
02246                  p, &destB, pDest, regOutB,
02247                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
02248   }
02249 
02250   /* Generate a subroutine to run when the results from select A
02251   ** are exhausted and only data in select B remains.
02252   */
02253   VdbeNoopComment((v, "eof-A subroutine"));
02254   if( op==TK_EXCEPT || op==TK_INTERSECT ){
02255     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
02256   }else{  
02257     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
02258     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
02259     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
02260     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
02261   }
02262 
02263   /* Generate a subroutine to run when the results from select B
02264   ** are exhausted and only data in select A remains.
02265   */
02266   if( op==TK_INTERSECT ){
02267     addrEofB = addrEofA;
02268   }else{  
02269     VdbeNoopComment((v, "eof-B subroutine"));
02270     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
02271     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
02272     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
02273     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
02274   }
02275 
02276   /* Generate code to handle the case of A<B
02277   */
02278   VdbeNoopComment((v, "A-lt-B subroutine"));
02279   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
02280   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
02281   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
02282   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
02283 
02284   /* Generate code to handle the case of A==B
02285   */
02286   if( op==TK_ALL ){
02287     addrAeqB = addrAltB;
02288   }else if( op==TK_INTERSECT ){
02289     addrAeqB = addrAltB;
02290     addrAltB++;
02291   }else{
02292     VdbeNoopComment((v, "A-eq-B subroutine"));
02293     addrAeqB =
02294     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
02295     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
02296     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
02297   }
02298 
02299   /* Generate code to handle the case of A>B
02300   */
02301   VdbeNoopComment((v, "A-gt-B subroutine"));
02302   addrAgtB = sqlite3VdbeCurrentAddr(v);
02303   if( op==TK_ALL || op==TK_UNION ){
02304     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
02305   }
02306   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
02307   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
02308   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
02309 
02310   /* This code runs once to initialize everything.
02311   */
02312   sqlite3VdbeJumpHere(v, j1);
02313   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
02314   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
02315   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
02316   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
02317   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
02318   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
02319 
02320   /* Implement the main merge loop
02321   */
02322   sqlite3VdbeResolveLabel(v, labelCmpr);
02323   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
02324   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
02325                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
02326   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
02327 
02328   /* Release temporary registers
02329   */
02330   if( regPrev ){
02331     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
02332   }
02333 
02334   /* Jump to the this point in order to terminate the query.
02335   */
02336   sqlite3VdbeResolveLabel(v, labelEnd);
02337 
02338   /* Set the number of output columns
02339   */
02340   if( pDest->eDest==SRT_Output ){
02341     Select *pFirst = pPrior;
02342     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
02343     generateColumnNames(pParse, 0, pFirst->pEList);
02344   }
02345 
02346   /* Reassembly the compound query so that it will be freed correctly
02347   ** by the calling function */
02348   if( p->pPrior ){
02349     sqlite3SelectDelete(db, p->pPrior);
02350   }
02351   p->pPrior = pPrior;
02352 
02353   /*** TBD:  Insert subroutine calls to close cursors on incomplete
02354   **** subqueries ****/
02355   return SQLITE_OK;
02356 }
02357 #endif
02358 
02359 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
02360 /* Forward Declarations */
02361 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
02362 static void substSelect(sqlite3*, Select *, int, ExprList *);
02363 
02364 /*
02365 ** Scan through the expression pExpr.  Replace every reference to
02366 ** a column in table number iTable with a copy of the iColumn-th
02367 ** entry in pEList.  (But leave references to the ROWID column 
02368 ** unchanged.)
02369 **
02370 ** This routine is part of the flattening procedure.  A subquery
02371 ** whose result set is defined by pEList appears as entry in the
02372 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
02373 ** FORM clause entry is iTable.  This routine make the necessary 
02374 ** changes to pExpr so that it refers directly to the source table
02375 ** of the subquery rather the result set of the subquery.
02376 */
02377 static void substExpr(
02378   sqlite3 *db,        /* Report malloc errors to this connection */
02379   Expr *pExpr,        /* Expr in which substitution occurs */
02380   int iTable,         /* Table to be substituted */
02381   ExprList *pEList    /* Substitute expressions */
02382 ){
02383   if( pExpr==0 ) return;
02384   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
02385     if( pExpr->iColumn<0 ){
02386       pExpr->op = TK_NULL;
02387     }else{
02388       Expr *pNew;
02389       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
02390       assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
02391       pNew = pEList->a[pExpr->iColumn].pExpr;
02392       assert( pNew!=0 );
02393       pExpr->op = pNew->op;
02394       assert( pExpr->pLeft==0 );
02395       pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
02396       assert( pExpr->pRight==0 );
02397       pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
02398       assert( pExpr->pList==0 );
02399       pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
02400       pExpr->iTable = pNew->iTable;
02401       pExpr->pTab = pNew->pTab;
02402       pExpr->iColumn = pNew->iColumn;
02403       pExpr->iAgg = pNew->iAgg;
02404       sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
02405       sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
02406       pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
02407       pExpr->flags = pNew->flags;
02408     }
02409   }else{
02410     substExpr(db, pExpr->pLeft, iTable, pEList);
02411     substExpr(db, pExpr->pRight, iTable, pEList);
02412     substSelect(db, pExpr->pSelect, iTable, pEList);
02413     substExprList(db, pExpr->pList, iTable, pEList);
02414   }
02415 }
02416 static void substExprList(
02417   sqlite3 *db,         /* Report malloc errors here */
02418   ExprList *pList,     /* List to scan and in which to make substitutes */
02419   int iTable,          /* Table to be substituted */
02420   ExprList *pEList     /* Substitute values */
02421 ){
02422   int i;
02423   if( pList==0 ) return;
02424   for(i=0; i<pList->nExpr; i++){
02425     substExpr(db, pList->a[i].pExpr, iTable, pEList);
02426   }
02427 }
02428 static void substSelect(
02429   sqlite3 *db,         /* Report malloc errors here */
02430   Select *p,           /* SELECT statement in which to make substitutions */
02431   int iTable,          /* Table to be replaced */
02432   ExprList *pEList     /* Substitute values */
02433 ){
02434   SrcList *pSrc;
02435   struct SrcList_item *pItem;
02436   int i;
02437   if( !p ) return;
02438   substExprList(db, p->pEList, iTable, pEList);
02439   substExprList(db, p->pGroupBy, iTable, pEList);
02440   substExprList(db, p->pOrderBy, iTable, pEList);
02441   substExpr(db, p->pHaving, iTable, pEList);
02442   substExpr(db, p->pWhere, iTable, pEList);
02443   substSelect(db, p->pPrior, iTable, pEList);
02444   pSrc = p->pSrc;
02445   if( pSrc ){
02446     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
02447       substSelect(db, pItem->pSelect, iTable, pEList);
02448     }
02449   }
02450 }
02451 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
02452 
02453 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
02454 /*
02455 ** This routine attempts to flatten subqueries in order to speed
02456 ** execution.  It returns 1 if it makes changes and 0 if no flattening
02457 ** occurs.
02458 **
02459 ** To understand the concept of flattening, consider the following
02460 ** query:
02461 **
02462 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
02463 **
02464 ** The default way of implementing this query is to execute the
02465 ** subquery first and store the results in a temporary table, then
02466 ** run the outer query on that temporary table.  This requires two
02467 ** passes over the data.  Furthermore, because the temporary table
02468 ** has no indices, the WHERE clause on the outer query cannot be
02469 ** optimized.
02470 **
02471 ** This routine attempts to rewrite queries such as the above into
02472 ** a single flat select, like this:
02473 **
02474 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
02475 **
02476 ** The code generated for this simpification gives the same result
02477 ** but only has to scan the data once.  And because indices might 
02478 ** exist on the table t1, a complete scan of the data might be
02479 ** avoided.
02480 **
02481 ** Flattening is only attempted if all of the following are true:
02482 **
02483 **   (1)  The subquery and the outer query do not both use aggregates.
02484 **
02485 **   (2)  The subquery is not an aggregate or the outer query is not a join.
02486 **
02487 **   (3)  The subquery is not the right operand of a left outer join
02488 **        (Originally ticket #306.  Strenghtened by ticket #3300)
02489 **
02490 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
02491 **
02492 **   (5)  The subquery is not DISTINCT or the outer query does not use
02493 **        aggregates.
02494 **
02495 **   (6)  The subquery does not use aggregates or the outer query is not
02496 **        DISTINCT.
02497 **
02498 **   (7)  The subquery has a FROM clause.
02499 **
02500 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
02501 **
02502 **   (9)  The subquery does not use LIMIT or the outer query does not use
02503 **        aggregates.
02504 **
02505 **  (10)  The subquery does not use aggregates or the outer query does not
02506 **        use LIMIT.
02507 **
02508 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
02509 **
02510 **  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
02511 **        a separate restriction deriving from ticket #350.
02512 **
02513 **  (13)  The subquery and outer query do not both use LIMIT
02514 **
02515 **  (14)  The subquery does not use OFFSET
02516 **
02517 **  (15)  The outer query is not part of a compound select or the
02518 **        subquery does not have both an ORDER BY and a LIMIT clause.
02519 **        (See ticket #2339)
02520 **
02521 **  (16)  The outer query is not an aggregate or the subquery does
02522 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
02523 **        until we introduced the group_concat() function.  
02524 **
02525 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
02526 **        compound clause made up entirely of non-aggregate queries, and 
02527 **        the parent query:
02528 **
02529 **          * is not itself part of a compound select,
02530 **          * is not an aggregate or DISTINCT query, and
02531 **          * has no other tables or sub-selects in the FROM clause.
02532 **
02533 **        The parent and sub-query may contain WHERE clauses. Subject to
02534 **        rules (11), (13) and (14), they may also contain ORDER BY,
02535 **        LIMIT and OFFSET clauses.
02536 **
02537 **  (18)  If the sub-query is a compound select, then all terms of the
02538 **        ORDER by clause of the parent must be simple references to 
02539 **        columns of the sub-query.
02540 **
02541 **  (19)  The subquery does not use LIMIT or the outer query does not
02542 **        have a WHERE clause.
02543 **
02544 ** In this routine, the "p" parameter is a pointer to the outer query.
02545 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
02546 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
02547 **
02548 ** If flattening is not attempted, this routine is a no-op and returns 0.
02549 ** If flattening is attempted this routine returns 1.
02550 **
02551 ** All of the expression analysis must occur on both the outer query and
02552 ** the subquery before this routine runs.
02553 */
02554 static int flattenSubquery(
02555   Parse *pParse,       /* Parsing context */
02556   Select *p,           /* The parent or outer SELECT statement */
02557   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
02558   int isAgg,           /* True if outer SELECT uses aggregate functions */
02559   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
02560 ){
02561   const char *zSavedAuthContext = pParse->zAuthContext;
02562   Select *pParent;
02563   Select *pSub;       /* The inner query or "subquery" */
02564   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
02565   SrcList *pSrc;      /* The FROM clause of the outer query */
02566   SrcList *pSubSrc;   /* The FROM clause of the subquery */
02567   ExprList *pList;    /* The result set of the outer query */
02568   int iParent;        /* VDBE cursor number of the pSub result set temp table */
02569   int i;              /* Loop counter */
02570   Expr *pWhere;                    /* The WHERE clause */
02571   struct SrcList_item *pSubitem;   /* The subquery */
02572   sqlite3 *db = pParse->db;
02573 
02574   /* Check to see if flattening is permitted.  Return 0 if not.
02575   */
02576   assert( p!=0 );
02577   if( p==0 ) return 0;
02578   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
02579   pSrc = p->pSrc;
02580   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
02581   pSubitem = &pSrc->a[iFrom];
02582   iParent = pSubitem->iCursor;
02583   pSub = pSubitem->pSelect;
02584   assert( pSub!=0 );
02585   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
02586   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
02587   pSubSrc = pSub->pSrc;
02588   assert( pSubSrc );
02589   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
02590   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
02591   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
02592   ** became arbitrary expressions, we were forced to add restrictions (13)
02593   ** and (14). */
02594   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
02595   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
02596   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
02597     return 0;                                            /* Restriction (15) */
02598   }
02599   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
02600   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
02601          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
02602      return 0;       
02603   }
02604   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
02605      return 0;         /* Restriction (6)  */
02606   }
02607   if( p->pOrderBy && pSub->pOrderBy ){
02608      return 0;                                           /* Restriction (11) */
02609   }
02610   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
02611   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
02612 
02613   /* OBSOLETE COMMENT 1:
02614   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
02615   ** not used as the right operand of an outer join.  Examples of why this
02616   ** is not allowed:
02617   **
02618   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
02619   **
02620   ** If we flatten the above, we would get
02621   **
02622   **         (t1 LEFT OUTER JOIN t2) JOIN t3
02623   **
02624   ** which is not at all the same thing.
02625   **
02626   ** OBSOLETE COMMENT 2:
02627   ** Restriction 12:  If the subquery is the right operand of a left outer
02628   ** join, make sure the subquery has no WHERE clause.
02629   ** An examples of why this is not allowed:
02630   **
02631   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
02632   **
02633   ** If we flatten the above, we would get
02634   **
02635   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
02636   **
02637   ** But the t2.x>0 test will always fail on a NULL row of t2, which
02638   ** effectively converts the OUTER JOIN into an INNER JOIN.
02639   **
02640   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
02641   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
02642   ** is fraught with danger.  Best to avoid the whole thing.  If the
02643   ** subquery is the right term of a LEFT JOIN, then do not flatten.
02644   */
02645   if( (pSubitem->jointype & JT_OUTER)!=0 ){
02646     return 0;
02647   }
02648 
02649   /* Restriction 17: If the sub-query is a compound SELECT, then it must
02650   ** use only the UNION ALL operator. And none of the simple select queries
02651   ** that make up the compound SELECT are allowed to be aggregate or distinct
02652   ** queries.
02653   */
02654   if( pSub->pPrior ){
02655     if( p->pPrior || isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
02656       return 0;
02657     }
02658     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
02659       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
02660        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
02661        || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
02662       ){
02663         return 0;
02664       }
02665     }
02666 
02667     /* Restriction 18. */
02668     if( p->pOrderBy ){
02669       int ii;
02670       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
02671         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
02672       }
02673     }
02674   }
02675 
02676   /***** If we reach this point, flattening is permitted. *****/
02677 
02678   /* Authorize the subquery */
02679   pParse->zAuthContext = pSubitem->zName;
02680   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
02681   pParse->zAuthContext = zSavedAuthContext;
02682 
02683   /* If the sub-query is a compound SELECT statement, then (by restrictions
02684   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
02685   ** be of the form:
02686   **
02687   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
02688   **
02689   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
02690   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
02691   ** OFFSET clauses and joins them to the left-hand-side of the original
02692   ** using UNION ALL operators. In this case N is the number of simple
02693   ** select statements in the compound sub-query.
02694   **
02695   ** Example:
02696   **
02697   **     SELECT a+1 FROM (
02698   **        SELECT x FROM tab
02699   **        UNION ALL
02700   **        SELECT y FROM tab
02701   **        UNION ALL
02702   **        SELECT abs(z*2) FROM tab2
02703   **     ) WHERE a!=5 ORDER BY 1
02704   **
02705   ** Transformed into:
02706   **
02707   **     SELECT x+1 FROM tab WHERE x+1!=5
02708   **     UNION ALL
02709   **     SELECT y+1 FROM tab WHERE y+1!=5
02710   **     UNION ALL
02711   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
02712   **     ORDER BY 1
02713   **
02714   ** We call this the "compound-subquery flattening".
02715   */
02716   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
02717     Select *pNew;
02718     ExprList *pOrderBy = p->pOrderBy;
02719     Expr *pLimit = p->pLimit;
02720     Select *pPrior = p->pPrior;
02721     p->pOrderBy = 0;
02722     p->pSrc = 0;
02723     p->pPrior = 0;
02724     p->pLimit = 0;
02725     pNew = sqlite3SelectDup(db, p);
02726     p->pLimit = pLimit;
02727     p->pOrderBy = pOrderBy;
02728     p->pSrc = pSrc;
02729     p->op = TK_ALL;
02730     p->pRightmost = 0;
02731     if( pNew==0 ){
02732       pNew = pPrior;
02733     }else{
02734       pNew->pPrior = pPrior;
02735       pNew->pRightmost = 0;
02736     }
02737     p->pPrior = pNew;
02738     if( db->mallocFailed ) return 1;
02739   }
02740 
02741   /* Begin flattening the iFrom-th entry of the FROM clause 
02742   ** in the outer query.
02743   */
02744   pSub = pSub1 = pSubitem->pSelect;
02745 
02746   /* Delete the transient table structure associated with the
02747   ** subquery
02748   */
02749   sqlite3DbFree(db, pSubitem->zDatabase);
02750   sqlite3DbFree(db, pSubitem->zName);
02751   sqlite3DbFree(db, pSubitem->zAlias);
02752   pSubitem->zDatabase = 0;
02753   pSubitem->zName = 0;
02754   pSubitem->zAlias = 0;
02755   pSubitem->pSelect = 0;
02756 
02757   /* Defer deleting the Table object associated with the
02758   ** subquery until code generation is
02759   ** complete, since there may still exist Expr.pTab entries that
02760   ** refer to the subquery even after flattening.  Ticket #3346.
02761   */
02762   if( pSubitem->pTab!=0 ){
02763     Table *pTabToDel = pSubitem->pTab;
02764     if( pTabToDel->nRef==1 ){
02765       pTabToDel->pNextZombie = pParse->pZombieTab;
02766       pParse->pZombieTab = pTabToDel;
02767     }else{
02768       pTabToDel->nRef--;
02769     }
02770     pSubitem->pTab = 0;
02771   }
02772 
02773   /* The following loop runs once for each term in a compound-subquery
02774   ** flattening (as described above).  If we are doing a different kind
02775   ** of flattening - a flattening other than a compound-subquery flattening -
02776   ** then this loop only runs once.
02777   **
02778   ** This loop moves all of the FROM elements of the subquery into the
02779   ** the FROM clause of the outer query.  Before doing this, remember
02780   ** the cursor number for the original outer query FROM element in
02781   ** iParent.  The iParent cursor will never be used.  Subsequent code
02782   ** will scan expressions looking for iParent references and replace
02783   ** those references with expressions that resolve to the subquery FROM
02784   ** elements we are now copying in.
02785   */
02786   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
02787     int nSubSrc;
02788     int jointype = 0;
02789     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
02790     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
02791     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
02792 
02793     if( pSrc ){
02794       assert( pParent==p );  /* First time through the loop */
02795       jointype = pSubitem->jointype;
02796     }else{
02797       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
02798       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
02799       if( pSrc==0 ){
02800         assert( db->mallocFailed );
02801         break;
02802       }
02803     }
02804 
02805     /* The subquery uses a single slot of the FROM clause of the outer
02806     ** query.  If the subquery has more than one element in its FROM clause,
02807     ** then expand the outer query to make space for it to hold all elements
02808     ** of the subquery.
02809     **
02810     ** Example:
02811     **
02812     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
02813     **
02814     ** The outer query has 3 slots in its FROM clause.  One slot of the
02815     ** outer query (the middle slot) is used by the subquery.  The next
02816     ** block of code will expand the out query to 4 slots.  The middle
02817     ** slot is expanded to two slots in order to make space for the
02818     ** two elements in the FROM clause of the subquery.
02819     */
02820     if( nSubSrc>1 ){
02821       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
02822       if( db->mallocFailed ){
02823         break;
02824       }
02825     }
02826 
02827     /* Transfer the FROM clause terms from the subquery into the
02828     ** outer query.
02829     */
02830     for(i=0; i<nSubSrc; i++){
02831       pSrc->a[i+iFrom] = pSubSrc->a[i];
02832       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
02833     }
02834     pSrc->a[iFrom].jointype = jointype;
02835   
02836     /* Now begin substituting subquery result set expressions for 
02837     ** references to the iParent in the outer query.
02838     ** 
02839     ** Example:
02840     **
02841     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
02842     **   \                     \_____________ subquery __________/          /
02843     **    \_____________________ outer query ______________________________/
02844     **
02845     ** We look at every expression in the outer query and every place we see
02846     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
02847     */
02848     pList = pParent->pEList;
02849     for(i=0; i<pList->nExpr; i++){
02850       Expr *pExpr;
02851       if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
02852         pList->a[i].zName = 
02853                sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
02854       }
02855     }
02856     substExprList(db, pParent->pEList, iParent, pSub->pEList);
02857     if( isAgg ){
02858       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
02859       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
02860     }
02861     if( pSub->pOrderBy ){
02862       assert( pParent->pOrderBy==0 );
02863       pParent->pOrderBy = pSub->pOrderBy;
02864       pSub->pOrderBy = 0;
02865     }else if( pParent->pOrderBy ){
02866       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
02867     }
02868     if( pSub->pWhere ){
02869       pWhere = sqlite3ExprDup(db, pSub->pWhere);
02870     }else{
02871       pWhere = 0;
02872     }
02873     if( subqueryIsAgg ){
02874       assert( pParent->pHaving==0 );
02875       pParent->pHaving = pParent->pWhere;
02876       pParent->pWhere = pWhere;
02877       substExpr(db, pParent->pHaving, iParent, pSub->pEList);
02878       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
02879                                   sqlite3ExprDup(db, pSub->pHaving));
02880       assert( pParent->pGroupBy==0 );
02881       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
02882     }else{
02883       substExpr(db, pParent->pWhere, iParent, pSub->pEList);
02884       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
02885     }
02886   
02887     /* The flattened query is distinct if either the inner or the
02888     ** outer query is distinct. 
02889     */
02890     pParent->selFlags |= pSub->selFlags & SF_Distinct;
02891   
02892     /*
02893     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
02894     **
02895     ** One is tempted to try to add a and b to combine the limits.  But this
02896     ** does not work if either limit is negative.
02897     */
02898     if( pSub->pLimit ){
02899       pParent->pLimit = pSub->pLimit;
02900       pSub->pLimit = 0;
02901     }
02902   }
02903 
02904   /* Finially, delete what is left of the subquery and return
02905   ** success.
02906   */
02907   sqlite3SelectDelete(db, pSub1);
02908 
02909   return 1;
02910 }
02911 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
02912 
02913 /*
02914 ** Analyze the SELECT statement passed as an argument to see if it
02915 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
02916 ** it is, or 0 otherwise. At present, a query is considered to be
02917 ** a min()/max() query if:
02918 **
02919 **   1. There is a single object in the FROM clause.
02920 **
02921 **   2. There is a single expression in the result set, and it is
02922 **      either min(x) or max(x), where x is a column reference.
02923 */
02924 static int minMaxQuery(Parse *pParse, Select *p){
02925   Expr *pExpr;
02926   ExprList *pEList = p->pEList;
02927 
02928   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
02929   pExpr = pEList->a[0].pExpr;
02930   pEList = pExpr->pList;
02931   if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
02932   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
02933   if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
02934   if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
02935     return WHERE_ORDERBY_MIN;
02936   }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
02937     return WHERE_ORDERBY_MAX;
02938   }
02939   return WHERE_ORDERBY_NORMAL;
02940 }
02941 
02942 /*
02943 ** If the source-list item passed as an argument was augmented with an
02944 ** INDEXED BY clause, then try to locate the specified index. If there
02945 ** was such a clause and the named index cannot be found, return 
02946 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
02947 ** pFrom->pIndex and return SQLITE_OK.
02948 */
02949 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
02950   if( pFrom->pTab && pFrom->zIndex ){
02951     Table *pTab = pFrom->pTab;
02952     char *zIndex = pFrom->zIndex;
02953     Index *pIdx;
02954     for(pIdx=pTab->pIndex; 
02955         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
02956         pIdx=pIdx->pNext
02957     );
02958     if( !pIdx ){
02959       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
02960       return SQLITE_ERROR;
02961     }
02962     pFrom->pIndex = pIdx;
02963   }
02964   return SQLITE_OK;
02965 }
02966 
02967 /*
02968 ** This routine is a Walker callback for "expanding" a SELECT statement.
02969 ** "Expanding" means to do the following:
02970 **
02971 **    (1)  Make sure VDBE cursor numbers have been assigned to every
02972 **         element of the FROM clause.
02973 **
02974 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
02975 **         defines FROM clause.  When views appear in the FROM clause,
02976 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
02977 **         that implements the view.  A copy is made of the view's SELECT
02978 **         statement so that we can freely modify or delete that statement
02979 **         without worrying about messing up the presistent representation
02980 **         of the view.
02981 **
02982 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
02983 **         on joins and the ON and USING clause of joins.
02984 **
02985 **    (4)  Scan the list of columns in the result set (pEList) looking
02986 **         for instances of the "*" operator or the TABLE.* operator.
02987 **         If found, expand each "*" to be every column in every table
02988 **         and TABLE.* to be every column in TABLE.
02989 **
02990 */
02991 static int selectExpander(Walker *pWalker, Select *p){
02992   Parse *pParse = pWalker->pParse;
02993   int i, j, k;
02994   SrcList *pTabList;
02995   ExprList *pEList;
02996   struct SrcList_item *pFrom;
02997   sqlite3 *db = pParse->db;
02998 
02999   if( db->mallocFailed  ){
03000     return WRC_Abort;
03001   }
03002   if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
03003     return WRC_Prune;
03004   }
03005   p->selFlags |= SF_Expanded;
03006   pTabList = p->pSrc;
03007   pEList = p->pEList;
03008 
03009   /* Make sure cursor numbers have been assigned to all entries in
03010   ** the FROM clause of the SELECT statement.
03011   */
03012   sqlite3SrcListAssignCursors(pParse, pTabList);
03013 
03014   /* Look up every table named in the FROM clause of the select.  If
03015   ** an entry of the FROM clause is a subquery instead of a table or view,
03016   ** then create a transient table structure to describe the subquery.
03017   */
03018   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
03019     Table *pTab;
03020     if( pFrom->pTab!=0 ){
03021       /* This statement has already been prepared.  There is no need
03022       ** to go further. */
03023       assert( i==0 );
03024       return WRC_Prune;
03025     }
03026     if( pFrom->zName==0 ){
03027 #ifndef SQLITE_OMIT_SUBQUERY
03028       Select *pSel = pFrom->pSelect;
03029       /* A sub-query in the FROM clause of a SELECT */
03030       assert( pSel!=0 );
03031       assert( pFrom->pTab==0 );
03032       sqlite3WalkSelect(pWalker, pSel);
03033       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
03034       if( pTab==0 ) return WRC_Abort;
03035       pTab->db = db;
03036       pTab->nRef = 1;
03037       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
03038       while( pSel->pPrior ){ pSel = pSel->pPrior; }
03039       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
03040       pTab->iPKey = -1;
03041       pTab->tabFlags |= TF_Ephemeral;
03042 #endif
03043     }else{
03044       /* An ordinary table or view name in the FROM clause */
03045       assert( pFrom->pTab==0 );
03046       pFrom->pTab = pTab = 
03047         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
03048       if( pTab==0 ) return WRC_Abort;
03049       pTab->nRef++;
03050 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
03051       if( pTab->pSelect || IsVirtual(pTab) ){
03052         /* We reach here if the named table is a really a view */
03053         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
03054 
03055         /* If pFrom->pSelect!=0 it means we are dealing with a
03056         ** view within a view.  The SELECT structure has already been
03057         ** copied by the outer view so we can skip the copy step here
03058         ** in the inner view.
03059         */
03060         if( pFrom->pSelect==0 ){
03061           pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
03062           sqlite3WalkSelect(pWalker, pFrom->pSelect);
03063         }
03064       }
03065 #endif
03066     }
03067 
03068     /* Locate the index named by the INDEXED BY clause, if any. */
03069     if( sqlite3IndexedByLookup(pParse, pFrom) ){
03070       return WRC_Abort;
03071     }
03072   }
03073 
03074   /* Process NATURAL keywords, and ON and USING clauses of joins.
03075   */
03076   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
03077     return WRC_Abort;
03078   }
03079 
03080   /* For every "*" that occurs in the column list, insert the names of
03081   ** all columns in all tables.  And for every TABLE.* insert the names
03082   ** of all columns in TABLE.  The parser inserted a special expression
03083   ** with the TK_ALL operator for each "*" that it found in the column list.
03084   ** The following code just has to locate the TK_ALL expressions and expand
03085   ** each one to the list of all columns in all tables.
03086   **
03087   ** The first loop just checks to see if there are any "*" operators
03088   ** that need expanding.
03089   */
03090   for(k=0; k<pEList->nExpr; k++){
03091     Expr *pE = pEList->a[k].pExpr;
03092     if( pE->op==TK_ALL ) break;
03093     if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
03094          && pE->pLeft && pE->pLeft->op==TK_ID ) break;
03095   }
03096   if( k<pEList->nExpr ){
03097     /*
03098     ** If we get here it means the result set contains one or more "*"
03099     ** operators that need to be expanded.  Loop through each expression
03100     ** in the result set and expand them one by one.
03101     */
03102     struct ExprList_item *a = pEList->a;
03103     ExprList *pNew = 0;
03104     int flags = pParse->db->flags;
03105     int longNames = (flags & SQLITE_FullColNames)!=0
03106                       && (flags & SQLITE_ShortColNames)==0;
03107 
03108     for(k=0; k<pEList->nExpr; k++){
03109       Expr *pE = a[k].pExpr;
03110       if( pE->op!=TK_ALL &&
03111            (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
03112         /* This particular expression does not need to be expanded.
03113         */
03114         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
03115         if( pNew ){
03116           pNew->a[pNew->nExpr-1].zName = a[k].zName;
03117         }
03118         a[k].pExpr = 0;
03119         a[k].zName = 0;
03120       }else{
03121         /* This expression is a "*" or a "TABLE.*" and needs to be
03122         ** expanded. */
03123         int tableSeen = 0;      /* Set to 1 when TABLE matches */
03124         char *zTName;            /* text of name of TABLE */
03125         if( pE->op==TK_DOT && pE->pLeft ){
03126           zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
03127         }else{
03128           zTName = 0;
03129         }
03130         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
03131           Table *pTab = pFrom->pTab;
03132           char *zTabName = pFrom->zAlias;
03133           if( zTabName==0 || zTabName[0]==0 ){ 
03134             zTabName = pTab->zName;
03135           }
03136           if( db->mallocFailed ) break;
03137           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
03138             continue;
03139           }
03140           tableSeen = 1;
03141           for(j=0; j<pTab->nCol; j++){
03142             Expr *pExpr, *pRight;
03143             char *zName = pTab->aCol[j].zName;
03144 
03145             /* If a column is marked as 'hidden' (currently only possible
03146             ** for virtual tables), do not include it in the expanded
03147             ** result-set list.
03148             */
03149             if( IsHiddenColumn(&pTab->aCol[j]) ){
03150               assert(IsVirtual(pTab));
03151               continue;
03152             }
03153 
03154             if( i>0 ){
03155               struct SrcList_item *pLeft = &pTabList->a[i-1];
03156               if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
03157                         columnIndex(pLeft->pTab, zName)>=0 ){
03158                 /* In a NATURAL join, omit the join columns from the 
03159                 ** table on the right */
03160                 continue;
03161               }
03162               if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
03163                 /* In a join with a USING clause, omit columns in the
03164                 ** using clause from the table on the right. */
03165                 continue;
03166               }
03167             }
03168             pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
03169             if( pRight==0 ) break;
03170             setQuotedToken(pParse, &pRight->token, zName);
03171             if( longNames || pTabList->nSrc>1 ){
03172               Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
03173               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
03174               if( pExpr==0 ) break;
03175               setQuotedToken(pParse, &pLeft->token, zTabName);
03176               setToken(&pExpr->span, 
03177                   sqlite3MPrintf(db, "%s.%s", zTabName, zName));
03178               pExpr->span.dyn = 1;
03179               pExpr->token.z = 0;
03180               pExpr->token.n = 0;
03181               pExpr->token.dyn = 0;
03182             }else{
03183               pExpr = pRight;
03184               pExpr->span = pExpr->token;
03185               pExpr->span.dyn = 0;
03186             }
03187             if( longNames ){
03188               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
03189             }else{
03190               pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
03191             }
03192           }
03193         }
03194         if( !tableSeen ){
03195           if( zTName ){
03196             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
03197           }else{
03198             sqlite3ErrorMsg(pParse, "no tables specified");
03199           }
03200         }
03201         sqlite3DbFree(db, zTName);
03202       }
03203     }
03204     sqlite3ExprListDelete(db, pEList);
03205     p->pEList = pNew;
03206   }
03207 #if SQLITE_MAX_COLUMN
03208   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
03209     sqlite3ErrorMsg(pParse, "too many columns in result set");
03210   }
03211 #endif
03212   return WRC_Continue;
03213 }
03214 
03215 /*
03216 ** No-op routine for the parse-tree walker.
03217 **
03218 ** When this routine is the Walker.xExprCallback then expression trees
03219 ** are walked without any actions being taken at each node.  Presumably,
03220 ** when this routine is used for Walker.xExprCallback then 
03221 ** Walker.xSelectCallback is set to do something useful for every 
03222 ** subquery in the parser tree.
03223 */
03224 static int exprWalkNoop(Walker *pWalker, Expr *pExpr){
03225   return WRC_Continue;
03226 }
03227 
03228 /*
03229 ** This routine "expands" a SELECT statement and all of its subqueries.
03230 ** For additional information on what it means to "expand" a SELECT
03231 ** statement, see the comment on the selectExpand worker callback above.
03232 **
03233 ** Expanding a SELECT statement is the first step in processing a
03234 ** SELECT statement.  The SELECT statement must be expanded before
03235 ** name resolution is performed.
03236 **
03237 ** If anything goes wrong, an error message is written into pParse.
03238 ** The calling function can detect the problem by looking at pParse->nErr
03239 ** and/or pParse->db->mallocFailed.
03240 */
03241 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
03242   Walker w;
03243   w.xSelectCallback = selectExpander;
03244   w.xExprCallback = exprWalkNoop;
03245   w.pParse = pParse;
03246   sqlite3WalkSelect(&w, pSelect);
03247 }
03248 
03249 
03250 #ifndef SQLITE_OMIT_SUBQUERY
03251 /*
03252 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
03253 ** interface.
03254 **
03255 ** For each FROM-clause subquery, add Column.zType and Column.zColl
03256 ** information to the Table structure that represents the result set
03257 ** of that subquery.
03258 **
03259 ** The Table structure that represents the result set was constructed
03260 ** by selectExpander() but the type and collation information was omitted
03261 ** at that point because identifiers had not yet been resolved.  This
03262 ** routine is called after identifier resolution.
03263 */
03264 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
03265   Parse *pParse;
03266   int i;
03267   SrcList *pTabList;
03268   struct SrcList_item *pFrom;
03269 
03270   assert( p->selFlags & SF_Resolved );
03271   if( (p->selFlags & SF_HasTypeInfo)==0 ){
03272     p->selFlags |= SF_HasTypeInfo;
03273     pParse = pWalker->pParse;
03274     pTabList = p->pSrc;
03275     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
03276       Table *pTab = pFrom->pTab;
03277       if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
03278         /* A sub-query in the FROM clause of a SELECT */
03279         Select *pSel = pFrom->pSelect;
03280         assert( pSel );
03281         while( pSel->pPrior ) pSel = pSel->pPrior;
03282         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
03283       }
03284     }
03285   }
03286   return WRC_Continue;
03287 }
03288 #endif
03289 
03290 
03291 /*
03292 ** This routine adds datatype and collating sequence information to
03293 ** the Table structures of all FROM-clause subqueries in a
03294 ** SELECT statement.
03295 **
03296 ** Use this routine after name resolution.
03297 */
03298 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
03299 #ifndef SQLITE_OMIT_SUBQUERY
03300   Walker w;
03301   w.xSelectCallback = selectAddSubqueryTypeInfo;
03302   w.xExprCallback = exprWalkNoop;
03303   w.pParse = pParse;
03304   sqlite3WalkSelect(&w, pSelect);
03305 #endif
03306 }
03307 
03308 
03309 /*
03310 ** This routine sets of a SELECT statement for processing.  The
03311 ** following is accomplished:
03312 **
03313 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
03314 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
03315 **     *  ON and USING clauses are shifted into WHERE statements
03316 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
03317 **     *  Identifiers in expression are matched to tables.
03318 **
03319 ** This routine acts recursively on all subqueries within the SELECT.
03320 */
03321 void sqlite3SelectPrep(
03322   Parse *pParse,         /* The parser context */
03323   Select *p,             /* The SELECT statement being coded. */
03324   NameContext *pOuterNC  /* Name context for container */
03325 ){
03326   sqlite3 *db;
03327   if( p==0 ) return;
03328   db = pParse->db;
03329   if( p->selFlags & SF_HasTypeInfo ) return;
03330   if( pParse->nErr || db->mallocFailed ) return;
03331   sqlite3SelectExpand(pParse, p);
03332   if( pParse->nErr || db->mallocFailed ) return;
03333   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
03334   if( pParse->nErr || db->mallocFailed ) return;
03335   sqlite3SelectAddTypeInfo(pParse, p);
03336 }
03337 
03338 /*
03339 ** Reset the aggregate accumulator.
03340 **
03341 ** The aggregate accumulator is a set of memory cells that hold
03342 ** intermediate results while calculating an aggregate.  This
03343 ** routine simply stores NULLs in all of those memory cells.
03344 */
03345 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
03346   Vdbe *v = pParse->pVdbe;
03347   int i;
03348   struct AggInfo_func *pFunc;
03349   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
03350     return;
03351   }
03352   for(i=0; i<pAggInfo->nColumn; i++){
03353     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
03354   }
03355   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
03356     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
03357     if( pFunc->iDistinct>=0 ){
03358       Expr *pE = pFunc->pExpr;
03359       if( pE->pList==0 || pE->pList->nExpr!=1 ){
03360         sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
03361            "by an expression");
03362         pFunc->iDistinct = -1;
03363       }else{
03364         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
03365         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
03366                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
03367       }
03368     }
03369   }
03370 }
03371 
03372 /*
03373 ** Invoke the OP_AggFinalize opcode for every aggregate function
03374 ** in the AggInfo structure.
03375 */
03376 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
03377   Vdbe *v = pParse->pVdbe;
03378   int i;
03379   struct AggInfo_func *pF;
03380   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
03381     ExprList *pList = pF->pExpr->pList;
03382     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
03383                       (void*)pF->pFunc, P4_FUNCDEF);
03384   }
03385 }
03386 
03387 /*
03388 ** Update the accumulator memory cells for an aggregate based on
03389 ** the current cursor position.
03390 */
03391 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
03392   Vdbe *v = pParse->pVdbe;
03393   int i;
03394   struct AggInfo_func *pF;
03395   struct AggInfo_col *pC;
03396 
03397   pAggInfo->directMode = 1;
03398   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
03399     int nArg;
03400     int addrNext = 0;
03401     int regAgg;
03402     ExprList *pList = pF->pExpr->pList;
03403     if( pList ){
03404       nArg = pList->nExpr;
03405       regAgg = sqlite3GetTempRange(pParse, nArg);
03406       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
03407     }else{
03408       nArg = 0;
03409       regAgg = 0;
03410     }
03411     if( pF->iDistinct>=0 ){
03412       addrNext = sqlite3VdbeMakeLabel(v);
03413       assert( nArg==1 );
03414       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
03415     }
03416     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
03417       CollSeq *pColl = 0;
03418       struct ExprList_item *pItem;
03419       int j;
03420       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
03421       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
03422         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
03423       }
03424       if( !pColl ){
03425         pColl = pParse->db->pDfltColl;
03426       }
03427       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
03428     }
03429     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
03430                       (void*)pF->pFunc, P4_FUNCDEF);
03431     sqlite3VdbeChangeP5(v, nArg);
03432     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
03433     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
03434     if( addrNext ){
03435       sqlite3VdbeResolveLabel(v, addrNext);
03436     }
03437   }
03438   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
03439     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
03440   }
03441   pAggInfo->directMode = 0;
03442 }
03443 
03444 /*
03445 ** Generate code for the SELECT statement given in the p argument.  
03446 **
03447 ** The results are distributed in various ways depending on the
03448 ** contents of the SelectDest structure pointed to by argument pDest
03449 ** as follows:
03450 **
03451 **     pDest->eDest    Result
03452 **     ------------    -------------------------------------------
03453 **     SRT_Output      Generate a row of output (using the OP_ResultRow
03454 **                     opcode) for each row in the result set.
03455 **
03456 **     SRT_Mem         Only valid if the result is a single column.
03457 **                     Store the first column of the first result row
03458 **                     in register pDest->iParm then abandon the rest
03459 **                     of the query.  This destination implies "LIMIT 1".
03460 **
03461 **     SRT_Set         The result must be a single column.  Store each
03462 **                     row of result as the key in table pDest->iParm. 
03463 **                     Apply the affinity pDest->affinity before storing
03464 **                     results.  Used to implement "IN (SELECT ...)".
03465 **
03466 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
03467 **
03468 **     SRT_Except      Remove results from the temporary table pDest->iParm.
03469 **
03470 **     SRT_Table       Store results in temporary table pDest->iParm.
03471 **                     This is like SRT_EphemTab except that the table
03472 **                     is assumed to already be open.
03473 **
03474 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
03475 **                     the result there. The cursor is left open after
03476 **                     returning.  This is like SRT_Table except that
03477 **                     this destination uses OP_OpenEphemeral to create
03478 **                     the table first.
03479 **
03480 **     SRT_Coroutine   Generate a co-routine that returns a new row of
03481 **                     results each time it is invoked.  The entry point
03482 **                     of the co-routine is stored in register pDest->iParm.
03483 **
03484 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
03485 **                     set is not empty.
03486 **
03487 **     SRT_Discard     Throw the results away.  This is used by SELECT
03488 **                     statements within triggers whose only purpose is
03489 **                     the side-effects of functions.
03490 **
03491 ** This routine returns the number of errors.  If any errors are
03492 ** encountered, then an appropriate error message is left in
03493 ** pParse->zErrMsg.
03494 **
03495 ** This routine does NOT free the Select structure passed in.  The
03496 ** calling function needs to do that.
03497 */
03498 int sqlite3Select(
03499   Parse *pParse,         /* The parser context */
03500   Select *p,             /* The SELECT statement being coded. */
03501   SelectDest *pDest      /* What to do with the query results */
03502 ){
03503   int i, j;              /* Loop counters */
03504   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
03505   Vdbe *v;               /* The virtual machine under construction */
03506   int isAgg;             /* True for select lists like "count(*)" */
03507   ExprList *pEList;      /* List of columns to extract. */
03508   SrcList *pTabList;     /* List of tables to select from */
03509   Expr *pWhere;          /* The WHERE clause.  May be NULL */
03510   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
03511   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
03512   Expr *pHaving;         /* The HAVING clause.  May be NULL */
03513   int isDistinct;        /* True if the DISTINCT keyword is present */
03514   int distinct;          /* Table to use for the distinct set */
03515   int rc = 1;            /* Value to return from this function */
03516   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
03517   AggInfo sAggInfo;      /* Information used by aggregate queries */
03518   int iEnd;              /* Address of the end of the query */
03519   sqlite3 *db;           /* The database connection */
03520 
03521   db = pParse->db;
03522   if( p==0 || db->mallocFailed || pParse->nErr ){
03523     return 1;
03524   }
03525   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
03526   memset(&sAggInfo, 0, sizeof(sAggInfo));
03527 
03528   pOrderBy = p->pOrderBy;
03529   if( IgnorableOrderby(pDest) ){
03530     p->pOrderBy = 0;
03531 
03532     /* In these cases the DISTINCT operator makes no difference to the
03533     ** results, so remove it if it were specified.
03534     */
03535     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
03536            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
03537     p->selFlags &= ~SF_Distinct;
03538   }
03539   sqlite3SelectPrep(pParse, p, 0);
03540   if( pParse->nErr ){
03541     goto select_end;
03542   }
03543   p->pOrderBy = pOrderBy;
03544 
03545 
03546   /* Make local copies of the parameters for this query.
03547   */
03548   pTabList = p->pSrc;
03549   isAgg = (p->selFlags & SF_Aggregate)!=0;
03550   pEList = p->pEList;
03551   if( pEList==0 ) goto select_end;
03552 
03553   /* 
03554   ** Do not even attempt to generate any code if we have already seen
03555   ** errors before this routine starts.
03556   */
03557   if( pParse->nErr>0 ) goto select_end;
03558 
03559   /* ORDER BY is ignored for some destinations.
03560   */
03561   if( IgnorableOrderby(pDest) ){
03562     pOrderBy = 0;
03563   }
03564 
03565   /* Begin generating code.
03566   */
03567   v = sqlite3GetVdbe(pParse);
03568   if( v==0 ) goto select_end;
03569 
03570   /* Generate code for all sub-queries in the FROM clause
03571   */
03572 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
03573   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
03574     struct SrcList_item *pItem = &pTabList->a[i];
03575     SelectDest dest;
03576     Select *pSub = pItem->pSelect;
03577     int isAggSub;
03578 
03579     if( pSub==0 || pItem->isPopulated ) continue;
03580 
03581     /* Increment Parse.nHeight by the height of the largest expression
03582     ** tree refered to by this, the parent select. The child select
03583     ** may contain expression trees of at most
03584     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
03585     ** more conservative than necessary, but much easier than enforcing
03586     ** an exact limit.
03587     */
03588     pParse->nHeight += sqlite3SelectExprHeight(p);
03589 
03590     /* Check to see if the subquery can be absorbed into the parent. */
03591     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
03592     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
03593       if( isAggSub ){
03594         isAgg = 1;
03595         p->selFlags |= SF_Aggregate;
03596       }
03597       i = -1;
03598     }else{
03599       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
03600       assert( pItem->isPopulated==0 );
03601       sqlite3Select(pParse, pSub, &dest);
03602       pItem->isPopulated = 1;
03603     }
03604     if( pParse->nErr || db->mallocFailed ){
03605       goto select_end;
03606     }
03607     pParse->nHeight -= sqlite3SelectExprHeight(p);
03608     pTabList = p->pSrc;
03609     if( !IgnorableOrderby(pDest) ){
03610       pOrderBy = p->pOrderBy;
03611     }
03612   }
03613   pEList = p->pEList;
03614 #endif
03615   pWhere = p->pWhere;
03616   pGroupBy = p->pGroupBy;
03617   pHaving = p->pHaving;
03618   isDistinct = (p->selFlags & SF_Distinct)!=0;
03619 
03620 #ifndef SQLITE_OMIT_COMPOUND_SELECT
03621   /* If there is are a sequence of queries, do the earlier ones first.
03622   */
03623   if( p->pPrior ){
03624     if( p->pRightmost==0 ){
03625       Select *pLoop, *pRight = 0;
03626       int cnt = 0;
03627       int mxSelect;
03628       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
03629         pLoop->pRightmost = p;
03630         pLoop->pNext = pRight;
03631         pRight = pLoop;
03632       }
03633       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
03634       if( mxSelect && cnt>mxSelect ){
03635         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
03636         return 1;
03637       }
03638     }
03639     return multiSelect(pParse, p, pDest);
03640   }
03641 #endif
03642 
03643   /* If writing to memory or generating a set
03644   ** only a single column may be output.
03645   */
03646 #ifndef SQLITE_OMIT_SUBQUERY
03647   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
03648     goto select_end;
03649   }
03650 #endif
03651 
03652   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
03653   ** GROUP BY might use an index, DISTINCT never does.
03654   */
03655   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
03656     p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
03657     pGroupBy = p->pGroupBy;
03658     p->selFlags &= ~SF_Distinct;
03659     isDistinct = 0;
03660   }
03661 
03662   /* If there is an ORDER BY clause, then this sorting
03663   ** index might end up being unused if the data can be 
03664   ** extracted in pre-sorted order.  If that is the case, then the
03665   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
03666   ** we figure out that the sorting index is not needed.  The addrSortIndex
03667   ** variable is used to facilitate that change.
03668   */
03669   if( pOrderBy ){
03670     KeyInfo *pKeyInfo;
03671     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
03672     pOrderBy->iECursor = pParse->nTab++;
03673     p->addrOpenEphm[2] = addrSortIndex =
03674       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
03675                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
03676                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
03677   }else{
03678     addrSortIndex = -1;
03679   }
03680 
03681   /* If the output is destined for a temporary table, open that table.
03682   */
03683   if( pDest->eDest==SRT_EphemTab ){
03684     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
03685   }
03686 
03687   /* Set the limiter.
03688   */
03689   iEnd = sqlite3VdbeMakeLabel(v);
03690   computeLimitRegisters(pParse, p, iEnd);
03691 
03692   /* Open a virtual index to use for the distinct set.
03693   */
03694   if( isDistinct ){
03695     KeyInfo *pKeyInfo;
03696     assert( isAgg || pGroupBy );
03697     distinct = pParse->nTab++;
03698     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
03699     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
03700                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
03701   }else{
03702     distinct = -1;
03703   }
03704 
03705   /* Aggregate and non-aggregate queries are handled differently */
03706   if( !isAgg && pGroupBy==0 ){
03707     /* This case is for non-aggregate queries
03708     ** Begin the database scan
03709     */
03710     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
03711     if( pWInfo==0 ) goto select_end;
03712 
03713     /* If sorting index that was created by a prior OP_OpenEphemeral 
03714     ** instruction ended up not being needed, then change the OP_OpenEphemeral
03715     ** into an OP_Noop.
03716     */
03717     if( addrSortIndex>=0 && pOrderBy==0 ){
03718       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
03719       p->addrOpenEphm[2] = -1;
03720     }
03721 
03722     /* Use the standard inner loop
03723     */
03724     assert(!isDistinct);
03725     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
03726                     pWInfo->iContinue, pWInfo->iBreak);
03727 
03728     /* End the database scan loop.
03729     */
03730     sqlite3WhereEnd(pWInfo);
03731   }else{
03732     /* This is the processing for aggregate queries */
03733     NameContext sNC;    /* Name context for processing aggregate information */
03734     int iAMem;          /* First Mem address for storing current GROUP BY */
03735     int iBMem;          /* First Mem address for previous GROUP BY */
03736     int iUseFlag;       /* Mem address holding flag indicating that at least
03737                         ** one row of the input to the aggregator has been
03738                         ** processed */
03739     int iAbortFlag;     /* Mem address which causes query abort if positive */
03740     int groupBySort;    /* Rows come from source in GROUP BY order */
03741     int addrEnd;        /* End of processing for this SELECT */
03742 
03743     /* Remove any and all aliases between the result set and the
03744     ** GROUP BY clause.
03745     */
03746     if( pGroupBy ){
03747       int i;                        /* Loop counter */
03748       struct ExprList_item *pItem;  /* For looping over expression in a list */
03749 
03750       for(i=p->pEList->nExpr, pItem=p->pEList->a; i>0; i--, pItem++){
03751         pItem->iAlias = 0;
03752       }
03753       for(i=pGroupBy->nExpr, pItem=pGroupBy->a; i>0; i--, pItem++){
03754         pItem->iAlias = 0;
03755       }
03756     }
03757 
03758  
03759     /* Create a label to jump to when we want to abort the query */
03760     addrEnd = sqlite3VdbeMakeLabel(v);
03761 
03762     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
03763     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
03764     ** SELECT statement.
03765     */
03766     memset(&sNC, 0, sizeof(sNC));
03767     sNC.pParse = pParse;
03768     sNC.pSrcList = pTabList;
03769     sNC.pAggInfo = &sAggInfo;
03770     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
03771     sAggInfo.pGroupBy = pGroupBy;
03772     sqlite3ExprAnalyzeAggList(&sNC, pEList);
03773     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
03774     if( pHaving ){
03775       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
03776     }
03777     sAggInfo.nAccumulator = sAggInfo.nColumn;
03778     for(i=0; i<sAggInfo.nFunc; i++){
03779       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
03780     }
03781     if( db->mallocFailed ) goto select_end;
03782 
03783     /* Processing for aggregates with GROUP BY is very different and
03784     ** much more complex than aggregates without a GROUP BY.
03785     */
03786     if( pGroupBy ){
03787       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
03788       int j1;             /* A-vs-B comparision jump */
03789       int addrOutputRow;  /* Start of subroutine that outputs a result row */
03790       int regOutputRow;   /* Return address register for output subroutine */
03791       int addrSetAbort;   /* Set the abort flag and return */
03792       int addrTopOfLoop;  /* Top of the input loop */
03793       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
03794       int addrReset;      /* Subroutine for resetting the accumulator */
03795       int regReset;       /* Return address register for reset subroutine */
03796 
03797       /* If there is a GROUP BY clause we might need a sorting index to
03798       ** implement it.  Allocate that sorting index now.  If it turns out
03799       ** that we do not need it after all, the OpenEphemeral instruction
03800       ** will be converted into a Noop.  
03801       */
03802       sAggInfo.sortingIdx = pParse->nTab++;
03803       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
03804       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
03805           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
03806           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
03807 
03808       /* Initialize memory locations used by GROUP BY aggregate processing
03809       */
03810       iUseFlag = ++pParse->nMem;
03811       iAbortFlag = ++pParse->nMem;
03812       regOutputRow = ++pParse->nMem;
03813       addrOutputRow = sqlite3VdbeMakeLabel(v);
03814       regReset = ++pParse->nMem;
03815       addrReset = sqlite3VdbeMakeLabel(v);
03816       iAMem = pParse->nMem + 1;
03817       pParse->nMem += pGroupBy->nExpr;
03818       iBMem = pParse->nMem + 1;
03819       pParse->nMem += pGroupBy->nExpr;
03820       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
03821       VdbeComment((v, "clear abort flag"));
03822       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
03823       VdbeComment((v, "indicate accumulator empty"));
03824 
03825       /* Begin a loop that will extract all source rows in GROUP BY order.
03826       ** This might involve two separate loops with an OP_Sort in between, or
03827       ** it might be a single loop that uses an index to extract information
03828       ** in the right order to begin with.
03829       */
03830       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
03831       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
03832       if( pWInfo==0 ) goto select_end;
03833       if( pGroupBy==0 ){
03834         /* The optimizer is able to deliver rows in group by order so
03835         ** we do not have to sort.  The OP_OpenEphemeral table will be
03836         ** cancelled later because we still need to use the pKeyInfo
03837         */
03838         pGroupBy = p->pGroupBy;
03839         groupBySort = 0;
03840       }else{
03841         /* Rows are coming out in undetermined order.  We have to push
03842         ** each row into a sorting index, terminate the first loop,
03843         ** then loop over the sorting index in order to get the output
03844         ** in sorted order
03845         */
03846         int regBase;
03847         int regRecord;
03848         int nCol;
03849         int nGroupBy;
03850 
03851         groupBySort = 1;
03852         nGroupBy = pGroupBy->nExpr;
03853         nCol = nGroupBy + 1;
03854         j = nGroupBy+1;
03855         for(i=0; i<sAggInfo.nColumn; i++){
03856           if( sAggInfo.aCol[i].iSorterColumn>=j ){
03857             nCol++;
03858             j++;
03859           }
03860         }
03861         regBase = sqlite3GetTempRange(pParse, nCol);
03862         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
03863         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
03864         j = nGroupBy+1;
03865         for(i=0; i<sAggInfo.nColumn; i++){
03866           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
03867           if( pCol->iSorterColumn>=j ){
03868             int r1 = j + regBase;
03869             int r2;
03870 
03871             r2 = sqlite3ExprCodeGetColumn(pParse, 
03872                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
03873             if( r1!=r2 ){
03874               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
03875             }
03876             j++;
03877           }
03878         }
03879         regRecord = sqlite3GetTempReg(pParse);
03880         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
03881         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
03882         sqlite3ReleaseTempReg(pParse, regRecord);
03883         sqlite3ReleaseTempRange(pParse, regBase, nCol);
03884         sqlite3WhereEnd(pWInfo);
03885         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
03886         VdbeComment((v, "GROUP BY sort"));
03887         sAggInfo.useSortingIdx = 1;
03888       }
03889 
03890       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
03891       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
03892       ** Then compare the current GROUP BY terms against the GROUP BY terms
03893       ** from the previous row currently stored in a0, a1, a2...
03894       */
03895       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
03896       for(j=0; j<pGroupBy->nExpr; j++){
03897         if( groupBySort ){
03898           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
03899         }else{
03900           sAggInfo.directMode = 1;
03901           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
03902         }
03903       }
03904       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
03905                           (char*)pKeyInfo, P4_KEYINFO);
03906       j1 = sqlite3VdbeCurrentAddr(v);
03907       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
03908 
03909       /* Generate code that runs whenever the GROUP BY changes.
03910       ** Changes in the GROUP BY are detected by the previous code
03911       ** block.  If there were no changes, this block is skipped.
03912       **
03913       ** This code copies current group by terms in b0,b1,b2,...
03914       ** over to a0,a1,a2.  It then calls the output subroutine
03915       ** and resets the aggregate accumulator registers in preparation
03916       ** for the next GROUP BY batch.
03917       */
03918       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
03919       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
03920       VdbeComment((v, "output one row"));
03921       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
03922       VdbeComment((v, "check abort flag"));
03923       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
03924       VdbeComment((v, "reset accumulator"));
03925 
03926       /* Update the aggregate accumulators based on the content of
03927       ** the current row
03928       */
03929       sqlite3VdbeJumpHere(v, j1);
03930       updateAccumulator(pParse, &sAggInfo);
03931       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
03932       VdbeComment((v, "indicate data in accumulator"));
03933 
03934       /* End of the loop
03935       */
03936       if( groupBySort ){
03937         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
03938       }else{
03939         sqlite3WhereEnd(pWInfo);
03940         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
03941       }
03942 
03943       /* Output the final row of result
03944       */
03945       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
03946       VdbeComment((v, "output final row"));
03947 
03948       /* Jump over the subroutines
03949       */
03950       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
03951 
03952       /* Generate a subroutine that outputs a single row of the result
03953       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
03954       ** is less than or equal to zero, the subroutine is a no-op.  If
03955       ** the processing calls for the query to abort, this subroutine
03956       ** increments the iAbortFlag memory location before returning in
03957       ** order to signal the caller to abort.
03958       */
03959       addrSetAbort = sqlite3VdbeCurrentAddr(v);
03960       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
03961       VdbeComment((v, "set abort flag"));
03962       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
03963       sqlite3VdbeResolveLabel(v, addrOutputRow);
03964       addrOutputRow = sqlite3VdbeCurrentAddr(v);
03965       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
03966       VdbeComment((v, "Groupby result generator entry point"));
03967       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
03968       finalizeAggFunctions(pParse, &sAggInfo);
03969       if( pHaving ){
03970         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
03971       }
03972       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
03973                       distinct, pDest,
03974                       addrOutputRow+1, addrSetAbort);
03975       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
03976       VdbeComment((v, "end groupby result generator"));
03977 
03978       /* Generate a subroutine that will reset the group-by accumulator
03979       */
03980       sqlite3VdbeResolveLabel(v, addrReset);
03981       resetAccumulator(pParse, &sAggInfo);
03982       sqlite3VdbeAddOp1(v, OP_Return, regReset);
03983      
03984     } /* endif pGroupBy */
03985     else {
03986       ExprList *pMinMax = 0;
03987       ExprList *pDel = 0;
03988       u8 flag;
03989 
03990       /* Check if the query is of one of the following forms:
03991       **
03992       **   SELECT min(x) FROM ...
03993       **   SELECT max(x) FROM ...
03994       **
03995       ** If it is, then ask the code in where.c to attempt to sort results
03996       ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
03997       ** If where.c is able to produce results sorted in this order, then
03998       ** add vdbe code to break out of the processing loop after the 
03999       ** first iteration (since the first iteration of the loop is 
04000       ** guaranteed to operate on the row with the minimum or maximum 
04001       ** value of x, the only row required).
04002       **
04003       ** A special flag must be passed to sqlite3WhereBegin() to slightly
04004       ** modify behaviour as follows:
04005       **
04006       **   + If the query is a "SELECT min(x)", then the loop coded by
04007       **     where.c should not iterate over any values with a NULL value
04008       **     for x.
04009       **
04010       **   + The optimizer code in where.c (the thing that decides which
04011       **     index or indices to use) should place a different priority on 
04012       **     satisfying the 'ORDER BY' clause than it does in other cases.
04013       **     Refer to code and comments in where.c for details.
04014       */
04015       flag = minMaxQuery(pParse, p);
04016       if( flag ){
04017         pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
04018         if( pMinMax && !db->mallocFailed ){
04019           pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
04020           pMinMax->a[0].pExpr->op = TK_COLUMN;
04021         }
04022       }
04023 
04024       /* This case runs if the aggregate has no GROUP BY clause.  The
04025       ** processing is much simpler since there is only a single row
04026       ** of output.
04027       */
04028       resetAccumulator(pParse, &sAggInfo);
04029       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
04030       if( pWInfo==0 ){
04031         sqlite3ExprListDelete(db, pDel);
04032         goto select_end;
04033       }
04034       updateAccumulator(pParse, &sAggInfo);
04035       if( !pMinMax && flag ){
04036         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
04037         VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
04038       }
04039       sqlite3WhereEnd(pWInfo);
04040       finalizeAggFunctions(pParse, &sAggInfo);
04041       pOrderBy = 0;
04042       if( pHaving ){
04043         sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
04044       }
04045       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
04046                       pDest, addrEnd, addrEnd);
04047 
04048       sqlite3ExprListDelete(db, pDel);
04049     }
04050     sqlite3VdbeResolveLabel(v, addrEnd);
04051     
04052   } /* endif aggregate query */
04053 
04054   /* If there is an ORDER BY clause, then we need to sort the results
04055   ** and send them to the callback one by one.
04056   */
04057   if( pOrderBy ){
04058     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
04059   }
04060 
04061   /* Jump here to skip this query
04062   */
04063   sqlite3VdbeResolveLabel(v, iEnd);
04064 
04065   /* The SELECT was successfully coded.   Set the return code to 0
04066   ** to indicate no errors.
04067   */
04068   rc = 0;
04069 
04070   /* Control jumps to here if an error is encountered above, or upon
04071   ** successful coding of the SELECT.
04072   */
04073 select_end:
04074 
04075   /* Identify column names if results of the SELECT are to be output.
04076   */
04077   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
04078     generateColumnNames(pParse, pTabList, pEList);
04079   }
04080 
04081   sqlite3DbFree(db, sAggInfo.aCol);
04082   sqlite3DbFree(db, sAggInfo.aFunc);
04083   return rc;
04084 }
04085 
04086 #if defined(SQLITE_DEBUG)
04087 /*
04088 *******************************************************************************
04089 ** The following code is used for testing and debugging only.  The code
04090 ** that follows does not appear in normal builds.
04091 **
04092 ** These routines are used to print out the content of all or part of a 
04093 ** parse structures such as Select or Expr.  Such printouts are useful
04094 ** for helping to understand what is happening inside the code generator
04095 ** during the execution of complex SELECT statements.
04096 **
04097 ** These routine are not called anywhere from within the normal
04098 ** code base.  Then are intended to be called from within the debugger
04099 ** or from temporary "printf" statements inserted for debugging.
04100 */
04101 void sqlite3PrintExpr(Expr *p){
04102   if( p->token.z && p->token.n>0 ){
04103     sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
04104   }else{
04105     sqlite3DebugPrintf("(%d", p->op);
04106   }
04107   if( p->pLeft ){
04108     sqlite3DebugPrintf(" ");
04109     sqlite3PrintExpr(p->pLeft);
04110   }
04111   if( p->pRight ){
04112     sqlite3DebugPrintf(" ");
04113     sqlite3PrintExpr(p->pRight);
04114   }
04115   sqlite3DebugPrintf(")");
04116 }
04117 void sqlite3PrintExprList(ExprList *pList){
04118   int i;
04119   for(i=0; i<pList->nExpr; i++){
04120     sqlite3PrintExpr(pList->a[i].pExpr);
04121     if( i<pList->nExpr-1 ){
04122       sqlite3DebugPrintf(", ");
04123     }
04124   }
04125 }
04126 void sqlite3PrintSelect(Select *p, int indent){
04127   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
04128   sqlite3PrintExprList(p->pEList);
04129   sqlite3DebugPrintf("\n");
04130   if( p->pSrc ){
04131     char *zPrefix;
04132     int i;
04133     zPrefix = "FROM";
04134     for(i=0; i<p->pSrc->nSrc; i++){
04135       struct SrcList_item *pItem = &p->pSrc->a[i];
04136       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
04137       zPrefix = "";
04138       if( pItem->pSelect ){
04139         sqlite3DebugPrintf("(\n");
04140         sqlite3PrintSelect(pItem->pSelect, indent+10);
04141         sqlite3DebugPrintf("%*s)", indent+8, "");
04142       }else if( pItem->zName ){
04143         sqlite3DebugPrintf("%s", pItem->zName);
04144       }
04145       if( pItem->pTab ){
04146         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
04147       }
04148       if( pItem->zAlias ){
04149         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
04150       }
04151       if( i<p->pSrc->nSrc-1 ){
04152         sqlite3DebugPrintf(",");
04153       }
04154       sqlite3DebugPrintf("\n");
04155     }
04156   }
04157   if( p->pWhere ){
04158     sqlite3DebugPrintf("%*s WHERE ", indent, "");
04159     sqlite3PrintExpr(p->pWhere);
04160     sqlite3DebugPrintf("\n");
04161   }
04162   if( p->pGroupBy ){
04163     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
04164     sqlite3PrintExprList(p->pGroupBy);
04165     sqlite3DebugPrintf("\n");
04166   }
04167   if( p->pHaving ){
04168     sqlite3DebugPrintf("%*s HAVING ", indent, "");
04169     sqlite3PrintExpr(p->pHaving);
04170     sqlite3DebugPrintf("\n");
04171   }
04172   if( p->pOrderBy ){
04173     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
04174     sqlite3PrintExprList(p->pOrderBy);
04175     sqlite3DebugPrintf("\n");
04176   }
04177 }
04178 /* End of the structure debug printing code
04179 *****************************************************************************/
04180 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:56 2011 by Doxygen 1.6.1