1cce7d176Sdrh /* 2b19a2bc6Sdrh ** 2001 September 15 3cce7d176Sdrh ** 4b19a2bc6Sdrh ** The author disclaims copyright to this source code. In place of 5b19a2bc6Sdrh ** a legal notice, here is a blessing: 6cce7d176Sdrh ** 7b19a2bc6Sdrh ** May you do good and not evil. 8b19a2bc6Sdrh ** May you find forgiveness for yourself and forgive others. 9b19a2bc6Sdrh ** May you share freely, never taking more than you give. 10cce7d176Sdrh ** 11cce7d176Sdrh ************************************************************************* 12cce7d176Sdrh ** This file contains C code routines that are called by the parser 13b19a2bc6Sdrh ** to handle SELECT statements in SQLite. 14cce7d176Sdrh ** 15*142bdf40Sdanielk1977 ** $Id: select.c,v 1.236 2005/01/30 11:11:44 danielk1977 Exp $ 16cce7d176Sdrh */ 17cce7d176Sdrh #include "sqliteInt.h" 18cce7d176Sdrh 19315555caSdrh 20cce7d176Sdrh /* 219bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 229bb61fe7Sdrh ** structure. 23cce7d176Sdrh */ 244adee20fSdanielk1977 Select *sqlite3SelectNew( 25daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 26ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 27daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 28daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 29daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 30daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 319bbca4c1Sdrh int isDistinct, /* true if the DISTINCT keyword is present */ 329bbca4c1Sdrh int nLimit, /* LIMIT value. -1 means not used */ 33ef0cae50Sdrh int nOffset /* OFFSET value. 0 means no offset */ 349bb61fe7Sdrh ){ 359bb61fe7Sdrh Select *pNew; 369bb61fe7Sdrh pNew = sqliteMalloc( sizeof(*pNew) ); 37daffd0e5Sdrh if( pNew==0 ){ 384adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 394adee20fSdanielk1977 sqlite3SrcListDelete(pSrc); 404adee20fSdanielk1977 sqlite3ExprDelete(pWhere); 414adee20fSdanielk1977 sqlite3ExprListDelete(pGroupBy); 424adee20fSdanielk1977 sqlite3ExprDelete(pHaving); 434adee20fSdanielk1977 sqlite3ExprListDelete(pOrderBy); 44daffd0e5Sdrh }else{ 45b733d037Sdrh if( pEList==0 ){ 464adee20fSdanielk1977 pEList = sqlite3ExprListAppend(0, sqlite3Expr(TK_ALL,0,0,0), 0); 47b733d037Sdrh } 489bb61fe7Sdrh pNew->pEList = pEList; 499bb61fe7Sdrh pNew->pSrc = pSrc; 509bb61fe7Sdrh pNew->pWhere = pWhere; 519bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 529bb61fe7Sdrh pNew->pHaving = pHaving; 539bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 549bb61fe7Sdrh pNew->isDistinct = isDistinct; 5582c3d636Sdrh pNew->op = TK_SELECT; 569bbca4c1Sdrh pNew->nLimit = nLimit; 579bbca4c1Sdrh pNew->nOffset = nOffset; 587b58daeaSdrh pNew->iLimit = -1; 597b58daeaSdrh pNew->iOffset = -1; 60daffd0e5Sdrh } 619bb61fe7Sdrh return pNew; 629bb61fe7Sdrh } 639bb61fe7Sdrh 649bb61fe7Sdrh /* 6501f3f253Sdrh ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the 6601f3f253Sdrh ** type of join. Return an integer constant that expresses that type 6701f3f253Sdrh ** in terms of the following bit values: 6801f3f253Sdrh ** 6901f3f253Sdrh ** JT_INNER 7001f3f253Sdrh ** JT_OUTER 7101f3f253Sdrh ** JT_NATURAL 7201f3f253Sdrh ** JT_LEFT 7301f3f253Sdrh ** JT_RIGHT 7401f3f253Sdrh ** 7501f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 7601f3f253Sdrh ** 7701f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 7801f3f253Sdrh ** a join type, but put an error in the pParse structure. 7901f3f253Sdrh */ 804adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 8101f3f253Sdrh int jointype = 0; 8201f3f253Sdrh Token *apAll[3]; 8301f3f253Sdrh Token *p; 845719628aSdrh static const struct { 8501f3f253Sdrh const char *zKeyword; 86290c1948Sdrh u8 nChar; 87290c1948Sdrh u8 code; 8801f3f253Sdrh } keywords[] = { 8901f3f253Sdrh { "natural", 7, JT_NATURAL }, 90195e6967Sdrh { "left", 4, JT_LEFT|JT_OUTER }, 91195e6967Sdrh { "right", 5, JT_RIGHT|JT_OUTER }, 92195e6967Sdrh { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 9301f3f253Sdrh { "outer", 5, JT_OUTER }, 9401f3f253Sdrh { "inner", 5, JT_INNER }, 9501f3f253Sdrh { "cross", 5, JT_INNER }, 9601f3f253Sdrh }; 9701f3f253Sdrh int i, j; 9801f3f253Sdrh apAll[0] = pA; 9901f3f253Sdrh apAll[1] = pB; 10001f3f253Sdrh apAll[2] = pC; 101195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 10201f3f253Sdrh p = apAll[i]; 10301f3f253Sdrh for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){ 10401f3f253Sdrh if( p->n==keywords[j].nChar 1054adee20fSdanielk1977 && sqlite3StrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){ 10601f3f253Sdrh jointype |= keywords[j].code; 10701f3f253Sdrh break; 10801f3f253Sdrh } 10901f3f253Sdrh } 11001f3f253Sdrh if( j>=sizeof(keywords)/sizeof(keywords[0]) ){ 11101f3f253Sdrh jointype |= JT_ERROR; 11201f3f253Sdrh break; 11301f3f253Sdrh } 11401f3f253Sdrh } 115ad2d8307Sdrh if( 116ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 117195e6967Sdrh (jointype & JT_ERROR)!=0 118ad2d8307Sdrh ){ 119ae29ffbeSdrh const char *zSp1 = " "; 120ae29ffbeSdrh const char *zSp2 = " "; 121ae29ffbeSdrh if( pB==0 ){ zSp1++; } 122ae29ffbeSdrh if( pC==0 ){ zSp2++; } 123ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 124ae29ffbeSdrh "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); 12501f3f253Sdrh jointype = JT_INNER; 126195e6967Sdrh }else if( jointype & JT_RIGHT ){ 1274adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 128da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 129195e6967Sdrh jointype = JT_INNER; 13001f3f253Sdrh } 13101f3f253Sdrh return jointype; 13201f3f253Sdrh } 13301f3f253Sdrh 13401f3f253Sdrh /* 135ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 136ad2d8307Sdrh ** is not contained in the table. 137ad2d8307Sdrh */ 138ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 139ad2d8307Sdrh int i; 140ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1414adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 142ad2d8307Sdrh } 143ad2d8307Sdrh return -1; 144ad2d8307Sdrh } 145ad2d8307Sdrh 146ad2d8307Sdrh /* 14791bb0eedSdrh ** Set the value of a token to a '\000'-terminated string. 14891bb0eedSdrh */ 14991bb0eedSdrh static void setToken(Token *p, const char *z){ 15091bb0eedSdrh p->z = z; 15191bb0eedSdrh p->n = strlen(z); 15291bb0eedSdrh p->dyn = 0; 15391bb0eedSdrh } 15491bb0eedSdrh 15591bb0eedSdrh 15691bb0eedSdrh /* 157ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the 158ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2. 159ad2d8307Sdrh */ 160ad2d8307Sdrh static void addWhereTerm( 161ad2d8307Sdrh const char *zCol, /* Name of the column */ 162ad2d8307Sdrh const Table *pTab1, /* First table */ 163030530deSdrh const char *zAlias1, /* Alias for first table. May be NULL */ 164ad2d8307Sdrh const Table *pTab2, /* Second table */ 165030530deSdrh const char *zAlias2, /* Alias for second table. May be NULL */ 166ad2d8307Sdrh Expr **ppExpr /* Add the equality term to this expression */ 167ad2d8307Sdrh ){ 168ad2d8307Sdrh Token dummy; 169ad2d8307Sdrh Expr *pE1a, *pE1b, *pE1c; 170ad2d8307Sdrh Expr *pE2a, *pE2b, *pE2c; 171ad2d8307Sdrh Expr *pE; 172ad2d8307Sdrh 17391bb0eedSdrh setToken(&dummy, zCol); 1744adee20fSdanielk1977 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy); 1754adee20fSdanielk1977 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy); 176030530deSdrh if( zAlias1==0 ){ 177030530deSdrh zAlias1 = pTab1->zName; 178030530deSdrh } 179030530deSdrh setToken(&dummy, zAlias1); 1804adee20fSdanielk1977 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy); 181030530deSdrh if( zAlias2==0 ){ 182030530deSdrh zAlias2 = pTab2->zName; 183030530deSdrh } 184030530deSdrh setToken(&dummy, zAlias2); 1854adee20fSdanielk1977 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy); 1864adee20fSdanielk1977 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0); 1874adee20fSdanielk1977 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0); 1884adee20fSdanielk1977 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0); 1891f16230bSdrh ExprSetProperty(pE, EP_FromJoin); 19091bb0eedSdrh *ppExpr = sqlite3ExprAnd(*ppExpr, pE); 191ad2d8307Sdrh } 192ad2d8307Sdrh 193ad2d8307Sdrh /* 1941f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 1951cc093c2Sdrh ** 196e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 1971cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 1981f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 1991f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 2001f16230bSdrh ** WHERE clause during join processing but we need to remember that they 2011f16230bSdrh ** originated in the ON or USING clause. 2021cc093c2Sdrh */ 2031cc093c2Sdrh static void setJoinExpr(Expr *p){ 2041cc093c2Sdrh while( p ){ 2051f16230bSdrh ExprSetProperty(p, EP_FromJoin); 2061cc093c2Sdrh setJoinExpr(p->pLeft); 2071cc093c2Sdrh p = p->pRight; 2081cc093c2Sdrh } 2091cc093c2Sdrh } 2101cc093c2Sdrh 2111cc093c2Sdrh /* 212ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 213ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 214ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 215ad2d8307Sdrh ** 21691bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 21791bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 21891bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 21991bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 22091bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 22191bb0eedSdrh ** also attached to the left entry. 22291bb0eedSdrh ** 223ad2d8307Sdrh ** This routine returns the number of errors encountered. 224ad2d8307Sdrh */ 225ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 22691bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 22791bb0eedSdrh int i, j; /* Loop counters */ 22891bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 22991bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 230ad2d8307Sdrh 23191bb0eedSdrh pSrc = p->pSrc; 23291bb0eedSdrh pLeft = &pSrc->a[0]; 23391bb0eedSdrh pRight = &pLeft[1]; 23491bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 23591bb0eedSdrh Table *pLeftTab = pLeft->pTab; 23691bb0eedSdrh Table *pRightTab = pRight->pTab; 23791bb0eedSdrh 23891bb0eedSdrh if( pLeftTab==0 || pRightTab==0 ) continue; 239ad2d8307Sdrh 240ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 241ad2d8307Sdrh ** every column that the two tables have in common. 242ad2d8307Sdrh */ 24391bb0eedSdrh if( pLeft->jointype & JT_NATURAL ){ 24491bb0eedSdrh if( pLeft->pOn || pLeft->pUsing ){ 2454adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 246ad2d8307Sdrh "an ON or USING clause", 0); 247ad2d8307Sdrh return 1; 248ad2d8307Sdrh } 24991bb0eedSdrh for(j=0; j<pLeftTab->nCol; j++){ 25091bb0eedSdrh char *zName = pLeftTab->aCol[j].zName; 25191bb0eedSdrh if( columnIndex(pRightTab, zName)>=0 ){ 252030530deSdrh addWhereTerm(zName, pLeftTab, pLeft->zAlias, 253030530deSdrh pRightTab, pRight->zAlias, &p->pWhere); 254ad2d8307Sdrh } 255ad2d8307Sdrh } 256ad2d8307Sdrh } 257ad2d8307Sdrh 258ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 259ad2d8307Sdrh */ 26091bb0eedSdrh if( pLeft->pOn && pLeft->pUsing ){ 2614adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 262da93d238Sdrh "clauses in the same join"); 263ad2d8307Sdrh return 1; 264ad2d8307Sdrh } 265ad2d8307Sdrh 266ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 26791bb0eedSdrh ** an AND operator. 268ad2d8307Sdrh */ 26991bb0eedSdrh if( pLeft->pOn ){ 27091bb0eedSdrh setJoinExpr(pLeft->pOn); 27191bb0eedSdrh p->pWhere = sqlite3ExprAnd(p->pWhere, pLeft->pOn); 27291bb0eedSdrh pLeft->pOn = 0; 273ad2d8307Sdrh } 274ad2d8307Sdrh 275ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 276ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 277ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 278ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 279ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 280ad2d8307Sdrh ** not contained in both tables to be joined. 281ad2d8307Sdrh */ 28291bb0eedSdrh if( pLeft->pUsing ){ 28391bb0eedSdrh IdList *pList = pLeft->pUsing; 284ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 28591bb0eedSdrh char *zName = pList->a[j].zName; 28691bb0eedSdrh if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){ 2874adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 28891bb0eedSdrh "not present in both tables", zName); 289ad2d8307Sdrh return 1; 290ad2d8307Sdrh } 291030530deSdrh addWhereTerm(zName, pLeftTab, pLeft->zAlias, 292030530deSdrh pRightTab, pRight->zAlias, &p->pWhere); 293ad2d8307Sdrh } 294ad2d8307Sdrh } 295ad2d8307Sdrh } 296ad2d8307Sdrh return 0; 297ad2d8307Sdrh } 298ad2d8307Sdrh 299ad2d8307Sdrh /* 3009bb61fe7Sdrh ** Delete the given Select structure and all of its substructures. 3019bb61fe7Sdrh */ 3024adee20fSdanielk1977 void sqlite3SelectDelete(Select *p){ 30382c3d636Sdrh if( p==0 ) return; 3044adee20fSdanielk1977 sqlite3ExprListDelete(p->pEList); 3054adee20fSdanielk1977 sqlite3SrcListDelete(p->pSrc); 3064adee20fSdanielk1977 sqlite3ExprDelete(p->pWhere); 3074adee20fSdanielk1977 sqlite3ExprListDelete(p->pGroupBy); 3084adee20fSdanielk1977 sqlite3ExprDelete(p->pHaving); 3094adee20fSdanielk1977 sqlite3ExprListDelete(p->pOrderBy); 3104adee20fSdanielk1977 sqlite3SelectDelete(p->pPrior); 3119bb61fe7Sdrh sqliteFree(p); 3129bb61fe7Sdrh } 3139bb61fe7Sdrh 3149bb61fe7Sdrh /* 3152282792aSdrh ** Delete the aggregate information from the parse structure. 3162282792aSdrh */ 317b3bce662Sdanielk1977 #if 0 3181d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){ 3192282792aSdrh sqliteFree(pParse->aAgg); 3202282792aSdrh pParse->aAgg = 0; 3212282792aSdrh pParse->nAgg = 0; 3222282792aSdrh pParse->useAgg = 0; 3232282792aSdrh } 324b3bce662Sdanielk1977 #endif 3252282792aSdrh 3262282792aSdrh /* 327c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 328c926afbcSdrh ** stack into the sorter. 329c926afbcSdrh */ 330c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){ 331c926afbcSdrh int i; 332c926afbcSdrh for(i=0; i<pOrderBy->nExpr; i++){ 3334adee20fSdanielk1977 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr); 334c926afbcSdrh } 335ededfd5eSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr, 0); 3364adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0); 337c926afbcSdrh } 338c926afbcSdrh 339c926afbcSdrh /* 340ea48eb2eSdrh ** Add code to implement the OFFSET and LIMIT 341ea48eb2eSdrh */ 342ea48eb2eSdrh static void codeLimiter( 343bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 344ea48eb2eSdrh Select *p, /* The SELECT statement being coded */ 345ea48eb2eSdrh int iContinue, /* Jump here to skip the current record */ 346ea48eb2eSdrh int iBreak, /* Jump here to end the loop */ 347ea48eb2eSdrh int nPop /* Number of times to pop stack when jumping */ 348ea48eb2eSdrh ){ 349ea48eb2eSdrh if( p->iOffset>=0 ){ 350ea48eb2eSdrh int addr = sqlite3VdbeCurrentAddr(v) + 2; 351ea48eb2eSdrh if( nPop>0 ) addr++; 352ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr); 353ea48eb2eSdrh if( nPop>0 ){ 354ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Pop, nPop, 0); 355ea48eb2eSdrh } 356ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); 357ad6d9460Sdrh VdbeComment((v, "# skip OFFSET records")); 358ea48eb2eSdrh } 359ea48eb2eSdrh if( p->iLimit>=0 ){ 360ea48eb2eSdrh sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak); 361ad6d9460Sdrh VdbeComment((v, "# exit when LIMIT reached")); 362ea48eb2eSdrh } 363ea48eb2eSdrh } 364ea48eb2eSdrh 365ea48eb2eSdrh /* 3662282792aSdrh ** This routine generates the code for the inside of the inner loop 3672282792aSdrh ** of a SELECT. 36882c3d636Sdrh ** 36938640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 37038640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 37138640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 37238640e15Sdrh ** datatypes for each column. 3732282792aSdrh */ 3742282792aSdrh static int selectInnerLoop( 3752282792aSdrh Parse *pParse, /* The parser context */ 376df199a25Sdrh Select *p, /* The complete select statement being coded */ 3772282792aSdrh ExprList *pEList, /* List of values being extracted */ 37882c3d636Sdrh int srcTab, /* Pull data from this table */ 379967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 3802282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 3812282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 3822282792aSdrh int eDest, /* How to dispose of the results */ 3832282792aSdrh int iParm, /* An argument to the disposal method */ 3842282792aSdrh int iContinue, /* Jump here to continue with next row */ 38584ac9d02Sdanielk1977 int iBreak, /* Jump here to break out of the inner loop */ 38684ac9d02Sdanielk1977 char *aff /* affinity string if eDest is SRT_Union */ 3872282792aSdrh ){ 3882282792aSdrh Vdbe *v = pParse->pVdbe; 3892282792aSdrh int i; 390ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 39138640e15Sdrh 392daffd0e5Sdrh if( v==0 ) return 0; 39338640e15Sdrh assert( pEList!=0 ); 3942282792aSdrh 395df199a25Sdrh /* If there was a LIMIT clause on the SELECT statement, then do the check 396df199a25Sdrh ** to see if this row should be output. 397df199a25Sdrh */ 398ea48eb2eSdrh hasDistinct = distinct>=0 && pEList && pEList->nExpr>0; 399ea48eb2eSdrh if( pOrderBy==0 && !hasDistinct ){ 400bab39e13Sdrh codeLimiter(v, p, iContinue, iBreak, 0); 401df199a25Sdrh } 402df199a25Sdrh 403967e8b73Sdrh /* Pull the requested columns. 4042282792aSdrh */ 40538640e15Sdrh if( nColumn>0 ){ 406967e8b73Sdrh for(i=0; i<nColumn; i++){ 4074adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, srcTab, i); 40882c3d636Sdrh } 40938640e15Sdrh }else{ 41038640e15Sdrh nColumn = pEList->nExpr; 41138640e15Sdrh for(i=0; i<pEList->nExpr; i++){ 4124adee20fSdanielk1977 sqlite3ExprCode(pParse, pEList->a[i].pExpr); 41338640e15Sdrh } 41482c3d636Sdrh } 4152282792aSdrh 416daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 417daffd0e5Sdrh ** and this row has been seen before, then do not make this row 418daffd0e5Sdrh ** part of the result. 4192282792aSdrh */ 420ea48eb2eSdrh if( hasDistinct ){ 4210bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT 4224adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7); 4230bd1f4eaSdrh #endif 424ededfd5eSdanielk1977 /* Deliberately leave the affinity string off of the following 425ededfd5eSdanielk1977 ** OP_MakeRecord */ 426ededfd5eSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, pEList->nExpr * -1, 0); 4274adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3); 4284adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0); 4294adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); 430ad6d9460Sdrh VdbeComment((v, "# skip indistinct records")); 4310f69c1e3Sdanielk1977 sqlite3VdbeAddOp(v, OP_String8, 0, 0); 4324adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0); 433ea48eb2eSdrh if( pOrderBy==0 ){ 434bab39e13Sdrh codeLimiter(v, p, iContinue, iBreak, nColumn); 435ea48eb2eSdrh } 4362282792aSdrh } 43782c3d636Sdrh 438c926afbcSdrh switch( eDest ){ 4395338a5f7Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 44082c3d636Sdrh /* In this mode, write each query result to the key of the temporary 44182c3d636Sdrh ** table iParm. 4422282792aSdrh */ 443c926afbcSdrh case SRT_Union: { 4444adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 44584ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 4460f69c1e3Sdanielk1977 sqlite3VdbeAddOp(v, OP_String8, 0, 0); 4474adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0); 448c926afbcSdrh break; 449c926afbcSdrh } 45082c3d636Sdrh 45182c3d636Sdrh /* Construct a record from the query result, but instead of 45282c3d636Sdrh ** saving that record, use it as a key to delete elements from 45382c3d636Sdrh ** the temporary table iParm. 45482c3d636Sdrh */ 455c926afbcSdrh case SRT_Except: { 4560bd1f4eaSdrh int addr; 4574adee20fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 45884ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 4594adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3); 4604adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0); 461c926afbcSdrh break; 462c926afbcSdrh } 4635338a5f7Sdanielk1977 #endif 4645338a5f7Sdanielk1977 4655338a5f7Sdanielk1977 /* Store the result as data using a unique key. 4665338a5f7Sdanielk1977 */ 4675338a5f7Sdanielk1977 case SRT_Table: 4685338a5f7Sdanielk1977 case SRT_TempTable: { 4695338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 4705338a5f7Sdanielk1977 if( pOrderBy ){ 4715338a5f7Sdanielk1977 pushOntoSorter(pParse, v, pOrderBy); 4725338a5f7Sdanielk1977 }else{ 4735338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0); 4745338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 4755338a5f7Sdanielk1977 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0); 4765338a5f7Sdanielk1977 } 4775338a5f7Sdanielk1977 break; 4785338a5f7Sdanielk1977 } 4792282792aSdrh 48093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 4812282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 4822282792aSdrh ** then there should be a single item on the stack. Write this 4832282792aSdrh ** item into the set table with bogus data. 4842282792aSdrh */ 485c926afbcSdrh case SRT_Set: { 4864adee20fSdanielk1977 int addr1 = sqlite3VdbeCurrentAddr(v); 48752b36cabSdrh int addr2; 488e014a838Sdanielk1977 489967e8b73Sdrh assert( nColumn==1 ); 4904adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3); 4914adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 4924adee20fSdanielk1977 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 493c926afbcSdrh if( pOrderBy ){ 494c926afbcSdrh pushOntoSorter(pParse, v, pOrderBy); 495c926afbcSdrh }else{ 496e014a838Sdanielk1977 char aff = (iParm>>16)&0xFF; 497e014a838Sdanielk1977 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff); 49894a11211Sdrh sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &aff, 1); 4990f69c1e3Sdanielk1977 sqlite3VdbeAddOp(v, OP_String8, 0, 0); 500e014a838Sdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0); 501c926afbcSdrh } 5024adee20fSdanielk1977 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v)); 503c926afbcSdrh break; 504c926afbcSdrh } 50582c3d636Sdrh 5062282792aSdrh /* If this is a scalar select that is part of an expression, then 5072282792aSdrh ** store the results in the appropriate memory cell and break out 5082282792aSdrh ** of the scan loop. 5092282792aSdrh */ 51051522cd3Sdrh case SRT_Exists: 511c926afbcSdrh case SRT_Mem: { 512967e8b73Sdrh assert( nColumn==1 ); 513c926afbcSdrh if( pOrderBy ){ 514c926afbcSdrh pushOntoSorter(pParse, v, pOrderBy); 515c926afbcSdrh }else{ 5164adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 5174adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak); 518c926afbcSdrh } 519c926afbcSdrh break; 520c926afbcSdrh } 52193758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 5222282792aSdrh 523f46f905aSdrh /* Send the data to the callback function. 524f46f905aSdrh */ 525f46f905aSdrh case SRT_Callback: 526f46f905aSdrh case SRT_Sorter: { 527f46f905aSdrh if( pOrderBy ){ 528ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 529f46f905aSdrh pushOntoSorter(pParse, v, pOrderBy); 530f46f905aSdrh }else{ 531f46f905aSdrh assert( eDest==SRT_Callback ); 5324adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 533f46f905aSdrh } 534f46f905aSdrh break; 535f46f905aSdrh } 536f46f905aSdrh 537142e30dfSdrh /* Invoke a subroutine to handle the results. The subroutine itself 538142e30dfSdrh ** is responsible for popping the results off of the stack. 539142e30dfSdrh */ 540142e30dfSdrh case SRT_Subroutine: { 541ac82fcf5Sdrh if( pOrderBy ){ 5424adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 543ac82fcf5Sdrh pushOntoSorter(pParse, v, pOrderBy); 544ac82fcf5Sdrh }else{ 5454adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 546ac82fcf5Sdrh } 547142e30dfSdrh break; 548142e30dfSdrh } 549142e30dfSdrh 55093758c8dSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_CURSOR) 551d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 552d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 553d7489c39Sdrh ** user-defined functions that have side effects. We do not care 554d7489c39Sdrh ** about the actual results of the select. 555d7489c39Sdrh */ 556c926afbcSdrh default: { 557f46f905aSdrh assert( eDest==SRT_Discard ); 5584adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 559c926afbcSdrh break; 560c926afbcSdrh } 56193758c8dSdanielk1977 #endif 562c926afbcSdrh } 56382c3d636Sdrh return 0; 56482c3d636Sdrh } 56582c3d636Sdrh 56682c3d636Sdrh /* 567d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 568d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 569d8bc7086Sdrh ** we need to run the sorter and output the results. The following 570d8bc7086Sdrh ** routine generates the code needed to do that. 571d8bc7086Sdrh */ 572c926afbcSdrh static void generateSortTail( 573ffbc3088Sdrh Parse *pParse, /* The parsing context */ 574c926afbcSdrh Select *p, /* The SELECT statement */ 575c926afbcSdrh Vdbe *v, /* Generate code into this VDBE */ 576c926afbcSdrh int nColumn, /* Number of columns of data */ 577c926afbcSdrh int eDest, /* Write the sorted results here */ 578c926afbcSdrh int iParm /* Optional parameter associated with eDest */ 579c926afbcSdrh ){ 5804adee20fSdanielk1977 int end1 = sqlite3VdbeMakeLabel(v); 5814adee20fSdanielk1977 int end2 = sqlite3VdbeMakeLabel(v); 582d8bc7086Sdrh int addr; 583ffbc3088Sdrh KeyInfo *pInfo; 584ffbc3088Sdrh ExprList *pOrderBy; 585ffbc3088Sdrh int nCol, i; 5869bb575fdSdrh sqlite3 *db = pParse->db; 587ffbc3088Sdrh 588f46f905aSdrh if( eDest==SRT_Sorter ) return; 589ffbc3088Sdrh pOrderBy = p->pOrderBy; 590ffbc3088Sdrh nCol = pOrderBy->nExpr; 591ffbc3088Sdrh pInfo = sqliteMalloc( sizeof(*pInfo) + nCol*(sizeof(CollSeq*)+1) ); 592ffbc3088Sdrh if( pInfo==0 ) return; 593ffbc3088Sdrh pInfo->aSortOrder = (char*)&pInfo->aColl[nCol]; 594ffbc3088Sdrh pInfo->nField = nCol; 595ffbc3088Sdrh for(i=0; i<nCol; i++){ 5960202b29eSdanielk1977 /* If a collation sequence was specified explicity, then it 5970202b29eSdanielk1977 ** is stored in pOrderBy->a[i].zName. Otherwise, use the default 5980202b29eSdanielk1977 ** collation type for the expression. 5990202b29eSdanielk1977 */ 6007cedc8d4Sdanielk1977 pInfo->aColl[i] = sqlite3ExprCollSeq(pParse, pOrderBy->a[i].pExpr); 6010202b29eSdanielk1977 if( !pInfo->aColl[i] ){ 602ffbc3088Sdrh pInfo->aColl[i] = db->pDfltColl; 6030202b29eSdanielk1977 } 604ffbc3088Sdrh pInfo->aSortOrder[i] = pOrderBy->a[i].sortOrder; 605ffbc3088Sdrh } 606ffbc3088Sdrh sqlite3VdbeOp3(v, OP_Sort, 0, 0, (char*)pInfo, P3_KEYINFO_HANDOFF); 6074adee20fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1); 608bab39e13Sdrh codeLimiter(v, p, addr, end2, 1); 609c926afbcSdrh switch( eDest ){ 610c926afbcSdrh case SRT_Table: 611c926afbcSdrh case SRT_TempTable: { 6124adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0); 6134adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 6144adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0); 615c926afbcSdrh break; 616c926afbcSdrh } 61793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 618c926afbcSdrh case SRT_Set: { 619c926afbcSdrh assert( nColumn==1 ); 6204adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); 6214adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 6224adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); 623ededfd5eSdanielk1977 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, "n", P3_STATIC); 6240f69c1e3Sdanielk1977 sqlite3VdbeAddOp(v, OP_String8, 0, 0); 625e014a838Sdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0); 626c926afbcSdrh break; 627c926afbcSdrh } 62851522cd3Sdrh case SRT_Exists: 629c926afbcSdrh case SRT_Mem: { 630c926afbcSdrh assert( nColumn==1 ); 6314adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 6324adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, end1); 633c926afbcSdrh break; 634c926afbcSdrh } 63593758c8dSdanielk1977 #endif 636ce665cf6Sdrh case SRT_Callback: 637ac82fcf5Sdrh case SRT_Subroutine: { 638ac82fcf5Sdrh int i; 63984ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0); 64084ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 641ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 6424adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, -1-i, i); 643ac82fcf5Sdrh } 644ce665cf6Sdrh if( eDest==SRT_Callback ){ 645ce665cf6Sdrh sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 646ce665cf6Sdrh }else{ 6474adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 648ce665cf6Sdrh } 64984ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 2, 0); 650ac82fcf5Sdrh break; 651ac82fcf5Sdrh } 652c926afbcSdrh default: { 653f46f905aSdrh /* Do nothing */ 654c926afbcSdrh break; 655c926afbcSdrh } 656c926afbcSdrh } 6574adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, addr); 6584adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, end2); 6594adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 6604adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, end1); 6614adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0); 662d8bc7086Sdrh } 663d8bc7086Sdrh 664d8bc7086Sdrh /* 665517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 666517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 667e78e8284Sdrh ** 668517eb646Sdanielk1977 ** If the declaration type is the exact datatype definition extracted from 669517eb646Sdanielk1977 ** the original CREATE TABLE statement if the expression is a column. 670e78e8284Sdrh ** 671517eb646Sdanielk1977 ** The declaration type for an expression is either TEXT, NUMERIC or ANY. 672517eb646Sdanielk1977 ** The declaration type for a ROWID field is INTEGER. 673fcb78a49Sdrh */ 674b3bce662Sdanielk1977 static const char *columnType(NameContext *pNC, Expr *pExpr){ 67500e279d9Sdanielk1977 char const *zType; 676517eb646Sdanielk1977 int j; 677b3bce662Sdanielk1977 if( pExpr==0 || pNC->pSrcList==0 ) return 0; 6785338a5f7Sdanielk1977 6795338a5f7Sdanielk1977 /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING, 6805338a5f7Sdanielk1977 ** and LIMIT clauses. But pExpr originates in the result set of a 6815338a5f7Sdanielk1977 ** SELECT. So pExpr can never contain an AS operator. 6825338a5f7Sdanielk1977 */ 6835338a5f7Sdanielk1977 assert( pExpr->op!=TK_AS ); 6845338a5f7Sdanielk1977 68500e279d9Sdanielk1977 switch( pExpr->op ){ 68600e279d9Sdanielk1977 case TK_COLUMN: { 687b3bce662Sdanielk1977 Table *pTab = 0; 688517eb646Sdanielk1977 int iCol = pExpr->iColumn; 689b3bce662Sdanielk1977 while( pNC && !pTab ){ 690b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 691b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 692b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 6936a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 694b3bce662Sdanielk1977 }else{ 695b3bce662Sdanielk1977 pNC = pNC->pNext; 696b3bce662Sdanielk1977 } 697b3bce662Sdanielk1977 } 698b3bce662Sdanielk1977 assert( pTab ); 699fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 700fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 701fcb78a49Sdrh if( iCol<0 ){ 702fcb78a49Sdrh zType = "INTEGER"; 703fcb78a49Sdrh }else{ 704fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 705fcb78a49Sdrh } 70600e279d9Sdanielk1977 break; 707736c22b8Sdrh } 70893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 70900e279d9Sdanielk1977 case TK_SELECT: { 710b3bce662Sdanielk1977 NameContext sNC; 71100e279d9Sdanielk1977 Select *pS = pExpr->pSelect; 712b3bce662Sdanielk1977 sNC.pSrcList = pExpr->pSelect->pSrc; 713b3bce662Sdanielk1977 sNC.pNext = pNC; 714b3bce662Sdanielk1977 zType = columnType(&sNC, pS->pEList->a[0].pExpr); 71500e279d9Sdanielk1977 break; 716fcb78a49Sdrh } 71793758c8dSdanielk1977 #endif 71800e279d9Sdanielk1977 default: 71900e279d9Sdanielk1977 zType = 0; 72000e279d9Sdanielk1977 } 72100e279d9Sdanielk1977 722517eb646Sdanielk1977 return zType; 723517eb646Sdanielk1977 } 724517eb646Sdanielk1977 725517eb646Sdanielk1977 /* 726517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 727517eb646Sdanielk1977 ** in the result set. 728517eb646Sdanielk1977 */ 729517eb646Sdanielk1977 static void generateColumnTypes( 730517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 731517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 732517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 733517eb646Sdanielk1977 ){ 734517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 735517eb646Sdanielk1977 int i; 736b3bce662Sdanielk1977 NameContext sNC; 737b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 738517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 739517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 740b3bce662Sdanielk1977 const char *zType = columnType(&sNC, p); 74100e279d9Sdanielk1977 if( zType==0 ) continue; 742fbcd585fSdanielk1977 /* The vdbe must make it's own copy of the column-type, in case the 743fbcd585fSdanielk1977 ** schema is reset before this virtual machine is deleted. 744fbcd585fSdanielk1977 */ 745fbcd585fSdanielk1977 sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType)); 746fcb78a49Sdrh } 747fcb78a49Sdrh } 748fcb78a49Sdrh 749fcb78a49Sdrh /* 750fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 751fcb78a49Sdrh ** in the result set. This information is used to provide the 752fcabd464Sdrh ** azCol[] values in the callback. 75382c3d636Sdrh */ 754832508b7Sdrh static void generateColumnNames( 755832508b7Sdrh Parse *pParse, /* Parser context */ 756ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 757832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 758832508b7Sdrh ){ 759d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 7606a3ea0e6Sdrh int i, j; 7619bb575fdSdrh sqlite3 *db = pParse->db; 762fcabd464Sdrh int fullNames, shortNames; 763fcabd464Sdrh 764fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 7653cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 7663cf86063Sdanielk1977 if( pParse->explain ){ 76761de0d1bSdanielk1977 return; 7683cf86063Sdanielk1977 } 7695338a5f7Sdanielk1977 #endif 7703cf86063Sdanielk1977 771d6502758Sdrh assert( v!=0 ); 7726f8a503dSdanielk1977 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return; 773d8bc7086Sdrh pParse->colNamesSet = 1; 774fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 775fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 77622322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 77782c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 77882c3d636Sdrh Expr *p; 7795a38705eSdrh p = pEList->a[i].pExpr; 7805a38705eSdrh if( p==0 ) continue; 78182c3d636Sdrh if( pEList->a[i].zName ){ 78282c3d636Sdrh char *zName = pEList->a[i].zName; 783d8123366Sdanielk1977 sqlite3VdbeSetColName(v, i, zName, strlen(zName)); 78482c3d636Sdrh continue; 78582c3d636Sdrh } 786fa173a76Sdrh if( p->op==TK_COLUMN && pTabList ){ 7876a3ea0e6Sdrh Table *pTab; 78897665873Sdrh char *zCol; 7898aff1015Sdrh int iCol = p->iColumn; 7906a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 7916a3ea0e6Sdrh assert( j<pTabList->nSrc ); 7926a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 7938aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 79497665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 795b1363206Sdrh if( iCol<0 ){ 79647a6db2bSdrh zCol = "rowid"; 797b1363206Sdrh }else{ 798b1363206Sdrh zCol = pTab->aCol[iCol].zName; 799b1363206Sdrh } 800fcabd464Sdrh if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 8013cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n); 802fcabd464Sdrh }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 80382c3d636Sdrh char *zName = 0; 80482c3d636Sdrh char *zTab; 80582c3d636Sdrh 8066a3ea0e6Sdrh zTab = pTabList->a[j].zAlias; 807fcabd464Sdrh if( fullNames || zTab==0 ) zTab = pTab->zName; 8084adee20fSdanielk1977 sqlite3SetString(&zName, zTab, ".", zCol, 0); 8093cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, zName, P3_DYNAMIC); 81082c3d636Sdrh }else{ 81147a6db2bSdrh sqlite3VdbeSetColName(v, i, zCol, strlen(zCol)); 81282c3d636Sdrh } 8136977fea8Sdrh }else if( p->span.z && p->span.z[0] ){ 8143cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, p->span.z, p->span.n); 8153cf86063Sdanielk1977 /* sqlite3VdbeCompressSpace(v, addr); */ 8161bee3d7bSdrh }else{ 8171bee3d7bSdrh char zName[30]; 8181bee3d7bSdrh assert( p->op!=TK_COLUMN || pTabList==0 ); 8191bee3d7bSdrh sprintf(zName, "column%d", i+1); 8203cf86063Sdanielk1977 sqlite3VdbeSetColName(v, i, zName, 0); 82182c3d636Sdrh } 82282c3d636Sdrh } 82376d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 8245080aaa7Sdrh } 82582c3d636Sdrh 82693758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 82782c3d636Sdrh /* 828d8bc7086Sdrh ** Name of the connection operator, used for error messages. 829d8bc7086Sdrh */ 830d8bc7086Sdrh static const char *selectOpName(int id){ 831d8bc7086Sdrh char *z; 832d8bc7086Sdrh switch( id ){ 833d8bc7086Sdrh case TK_ALL: z = "UNION ALL"; break; 834d8bc7086Sdrh case TK_INTERSECT: z = "INTERSECT"; break; 835d8bc7086Sdrh case TK_EXCEPT: z = "EXCEPT"; break; 836d8bc7086Sdrh default: z = "UNION"; break; 837d8bc7086Sdrh } 838d8bc7086Sdrh return z; 839d8bc7086Sdrh } 84093758c8dSdanielk1977 #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 841d8bc7086Sdrh 842d8bc7086Sdrh /* 843315555caSdrh ** Forward declaration 844315555caSdrh */ 8459b3187e1Sdrh static int prepSelectStmt(Parse*, Select*); 846315555caSdrh 847315555caSdrh /* 84822f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes 84922f70c32Sdrh ** the result set of that SELECT. 85022f70c32Sdrh */ 8514adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 85222f70c32Sdrh Table *pTab; 853b733d037Sdrh int i, j; 85422f70c32Sdrh ExprList *pEList; 855290c1948Sdrh Column *aCol, *pCol; 85622f70c32Sdrh 8579b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 85822f70c32Sdrh return 0; 85922f70c32Sdrh } 860*142bdf40Sdanielk1977 if( sqlite3SelectResolve(pParse, pSelect, 0) ){ 861*142bdf40Sdanielk1977 return 0; 862*142bdf40Sdanielk1977 } 86322f70c32Sdrh pTab = sqliteMalloc( sizeof(Table) ); 86422f70c32Sdrh if( pTab==0 ){ 86522f70c32Sdrh return 0; 86622f70c32Sdrh } 86722f70c32Sdrh pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0; 86822f70c32Sdrh pEList = pSelect->pEList; 86922f70c32Sdrh pTab->nCol = pEList->nExpr; 870417be79cSdrh assert( pTab->nCol>0 ); 871b733d037Sdrh pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol ); 872290c1948Sdrh for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){ 87379d5f63fSdrh Expr *p, *pR; 874517eb646Sdanielk1977 char *zType; 87591bb0eedSdrh char *zName; 87679d5f63fSdrh char *zBasename; 87779d5f63fSdrh int cnt; 878b3bce662Sdanielk1977 NameContext sNC; 87979d5f63fSdrh 88079d5f63fSdrh /* Get an appropriate name for the column 88179d5f63fSdrh */ 88279d5f63fSdrh p = pEList->a[i].pExpr; 883290c1948Sdrh assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 ); 88491bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 88579d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 88691bb0eedSdrh zName = sqliteStrDup(zName); 887517eb646Sdanielk1977 }else if( p->op==TK_DOT 888b733d037Sdrh && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 88979d5f63fSdrh /* For columns of the from A.B use B as the name */ 89091bb0eedSdrh zName = sqlite3MPrintf("%T", &pR->token); 891b733d037Sdrh }else if( p->span.z && p->span.z[0] ){ 89279d5f63fSdrh /* Use the original text of the column expression as its name */ 89391bb0eedSdrh zName = sqlite3MPrintf("%T", &p->span); 89422f70c32Sdrh }else{ 89579d5f63fSdrh /* If all else fails, make up a name */ 89691bb0eedSdrh zName = sqlite3MPrintf("column%d", i+1); 89722f70c32Sdrh } 89891bb0eedSdrh sqlite3Dequote(zName); 89979d5f63fSdrh 90079d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 90179d5f63fSdrh ** append a integer to the name so that it becomes unique. 90279d5f63fSdrh */ 90379d5f63fSdrh zBasename = zName; 90479d5f63fSdrh for(j=cnt=0; j<i; j++){ 90579d5f63fSdrh if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){ 90679d5f63fSdrh zName = sqlite3MPrintf("%s:%d", zBasename, ++cnt); 90779d5f63fSdrh j = -1; 90879d5f63fSdrh } 90979d5f63fSdrh } 91079d5f63fSdrh if( zBasename!=zName ){ 91179d5f63fSdrh sqliteFree(zBasename); 91279d5f63fSdrh } 91391bb0eedSdrh pCol->zName = zName; 914e014a838Sdanielk1977 91579d5f63fSdrh /* Get the typename, type affinity, and collating sequence for the 91679d5f63fSdrh ** column. 91779d5f63fSdrh */ 918b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 919b3bce662Sdanielk1977 zType = sqliteStrDup(columnType(&sNC, p)); 920290c1948Sdrh pCol->zType = zType; 921290c1948Sdrh pCol->affinity = SQLITE_AFF_NUMERIC; 922517eb646Sdanielk1977 if( zType ){ 923290c1948Sdrh pCol->affinity = sqlite3AffinityType(zType, strlen(zType)); 924517eb646Sdanielk1977 } 925290c1948Sdrh pCol->pColl = sqlite3ExprCollSeq(pParse, p); 926290c1948Sdrh if( !pCol->pColl ){ 927290c1948Sdrh pCol->pColl = pParse->db->pDfltColl; 9280202b29eSdanielk1977 } 92922f70c32Sdrh } 93022f70c32Sdrh pTab->iPKey = -1; 93122f70c32Sdrh return pTab; 93222f70c32Sdrh } 93322f70c32Sdrh 93422f70c32Sdrh /* 9359b3187e1Sdrh ** Prepare a SELECT statement for processing by doing the following 9369b3187e1Sdrh ** things: 937d8bc7086Sdrh ** 9389b3187e1Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 9399b3187e1Sdrh ** element of the FROM clause. 9409b3187e1Sdrh ** 9419b3187e1Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 9429b3187e1Sdrh ** defines FROM clause. When views appear in the FROM clause, 94363eb5f29Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 94463eb5f29Sdrh ** that implements the view. A copy is made of the view's SELECT 94563eb5f29Sdrh ** statement so that we can freely modify or delete that statement 94663eb5f29Sdrh ** without worrying about messing up the presistent representation 94763eb5f29Sdrh ** of the view. 948d8bc7086Sdrh ** 9499b3187e1Sdrh ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword 950ad2d8307Sdrh ** on joins and the ON and USING clause of joins. 951ad2d8307Sdrh ** 9529b3187e1Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 95354473229Sdrh ** for instances of the "*" operator or the TABLE.* operator. 95454473229Sdrh ** If found, expand each "*" to be every column in every table 95554473229Sdrh ** and TABLE.* to be every column in TABLE. 956d8bc7086Sdrh ** 957d8bc7086Sdrh ** Return 0 on success. If there are problems, leave an error message 958d8bc7086Sdrh ** in pParse and return non-zero. 959d8bc7086Sdrh */ 9609b3187e1Sdrh static int prepSelectStmt(Parse *pParse, Select *p){ 96154473229Sdrh int i, j, k, rc; 962ad3cab52Sdrh SrcList *pTabList; 963daffd0e5Sdrh ExprList *pEList; 964a76b5dfcSdrh Table *pTab; 965290c1948Sdrh struct SrcList_item *pFrom; 966daffd0e5Sdrh 967daffd0e5Sdrh if( p==0 || p->pSrc==0 ) return 1; 968daffd0e5Sdrh pTabList = p->pSrc; 969daffd0e5Sdrh pEList = p->pEList; 970d8bc7086Sdrh 9719b3187e1Sdrh /* Make sure cursor numbers have been assigned to all entries in 9729b3187e1Sdrh ** the FROM clause of the SELECT statement. 9739b3187e1Sdrh */ 9749b3187e1Sdrh sqlite3SrcListAssignCursors(pParse, p->pSrc); 9759b3187e1Sdrh 9769b3187e1Sdrh /* Look up every table named in the FROM clause of the select. If 9779b3187e1Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 9789b3187e1Sdrh ** then create a transient table structure to describe the subquery. 979d8bc7086Sdrh */ 980290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 9819b3187e1Sdrh if( pFrom->pTab!=0 ){ 9829b3187e1Sdrh /* This statement has already been prepared. There is no need 9839b3187e1Sdrh ** to go further. */ 9849b3187e1Sdrh assert( i==0 ); 985d8bc7086Sdrh return 0; 986d8bc7086Sdrh } 987290c1948Sdrh if( pFrom->zName==0 ){ 98893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 98922f70c32Sdrh /* A sub-query in the FROM clause of a SELECT */ 990290c1948Sdrh assert( pFrom->pSelect!=0 ); 991290c1948Sdrh if( pFrom->zAlias==0 ){ 99291bb0eedSdrh pFrom->zAlias = 99391bb0eedSdrh sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect); 994ad2d8307Sdrh } 995290c1948Sdrh pFrom->pTab = pTab = 996290c1948Sdrh sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect); 99722f70c32Sdrh if( pTab==0 ){ 998daffd0e5Sdrh return 1; 999daffd0e5Sdrh } 10005cf590c1Sdrh /* The isTransient flag indicates that the Table structure has been 10015cf590c1Sdrh ** dynamically allocated and may be freed at any time. In other words, 10025cf590c1Sdrh ** pTab is not pointing to a persistent table structure that defines 10035cf590c1Sdrh ** part of the schema. */ 100422f70c32Sdrh pTab->isTransient = 1; 100593758c8dSdanielk1977 #endif 100622f70c32Sdrh }else{ 1007a76b5dfcSdrh /* An ordinary table or view name in the FROM clause */ 1008290c1948Sdrh pFrom->pTab = pTab = 1009290c1948Sdrh sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); 1010a76b5dfcSdrh if( pTab==0 ){ 1011d8bc7086Sdrh return 1; 1012d8bc7086Sdrh } 101393758c8dSdanielk1977 #ifndef SQLITE_OMIT_VIEW 1014a76b5dfcSdrh if( pTab->pSelect ){ 101563eb5f29Sdrh /* We reach here if the named table is a really a view */ 10164adee20fSdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 1017417be79cSdrh return 1; 1018417be79cSdrh } 1019290c1948Sdrh /* If pFrom->pSelect!=0 it means we are dealing with a 102063eb5f29Sdrh ** view within a view. The SELECT structure has already been 102163eb5f29Sdrh ** copied by the outer view so we can skip the copy step here 102263eb5f29Sdrh ** in the inner view. 102363eb5f29Sdrh */ 1024290c1948Sdrh if( pFrom->pSelect==0 ){ 1025290c1948Sdrh pFrom->pSelect = sqlite3SelectDup(pTab->pSelect); 1026a76b5dfcSdrh } 1027d8bc7086Sdrh } 102893758c8dSdanielk1977 #endif 102922f70c32Sdrh } 103063eb5f29Sdrh } 1031d8bc7086Sdrh 1032ad2d8307Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 1033ad2d8307Sdrh */ 1034ad2d8307Sdrh if( sqliteProcessJoin(pParse, p) ) return 1; 1035ad2d8307Sdrh 10367c917d19Sdrh /* For every "*" that occurs in the column list, insert the names of 103754473229Sdrh ** all columns in all tables. And for every TABLE.* insert the names 103854473229Sdrh ** of all columns in TABLE. The parser inserted a special expression 10397c917d19Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 10407c917d19Sdrh ** The following code just has to locate the TK_ALL expressions and expand 10417c917d19Sdrh ** each one to the list of all columns in all tables. 104254473229Sdrh ** 104354473229Sdrh ** The first loop just checks to see if there are any "*" operators 104454473229Sdrh ** that need expanding. 1045d8bc7086Sdrh */ 10467c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 104754473229Sdrh Expr *pE = pEList->a[k].pExpr; 104854473229Sdrh if( pE->op==TK_ALL ) break; 104954473229Sdrh if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 105054473229Sdrh && pE->pLeft && pE->pLeft->op==TK_ID ) break; 10517c917d19Sdrh } 105254473229Sdrh rc = 0; 10537c917d19Sdrh if( k<pEList->nExpr ){ 105454473229Sdrh /* 105554473229Sdrh ** If we get here it means the result set contains one or more "*" 105654473229Sdrh ** operators that need to be expanded. Loop through each expression 105754473229Sdrh ** in the result set and expand them one by one. 105854473229Sdrh */ 10597c917d19Sdrh struct ExprList_item *a = pEList->a; 10607c917d19Sdrh ExprList *pNew = 0; 10617c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 106254473229Sdrh Expr *pE = a[k].pExpr; 106354473229Sdrh if( pE->op!=TK_ALL && 106454473229Sdrh (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 106554473229Sdrh /* This particular expression does not need to be expanded. 106654473229Sdrh */ 10674adee20fSdanielk1977 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0); 10687c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 10697c917d19Sdrh a[k].pExpr = 0; 10707c917d19Sdrh a[k].zName = 0; 10717c917d19Sdrh }else{ 107254473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 107354473229Sdrh ** expanded. */ 107454473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 1075cf55b7aeSdrh char *zTName; /* text of name of TABLE */ 107654473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 1077cf55b7aeSdrh zTName = sqlite3NameFromToken(&pE->pLeft->token); 107854473229Sdrh }else{ 1079cf55b7aeSdrh zTName = 0; 108054473229Sdrh } 1081290c1948Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 1082290c1948Sdrh Table *pTab = pFrom->pTab; 1083290c1948Sdrh char *zTabName = pFrom->zAlias; 108454473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 108554473229Sdrh zTabName = pTab->zName; 108654473229Sdrh } 1087cf55b7aeSdrh if( zTName && (zTabName==0 || zTabName[0]==0 || 1088cf55b7aeSdrh sqlite3StrICmp(zTName, zTabName)!=0) ){ 108954473229Sdrh continue; 109054473229Sdrh } 109154473229Sdrh tableSeen = 1; 1092d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 109322f70c32Sdrh Expr *pExpr, *pLeft, *pRight; 1094ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 1095ad2d8307Sdrh 109691bb0eedSdrh if( i>0 ){ 109791bb0eedSdrh struct SrcList_item *pLeft = &pTabList->a[i-1]; 109891bb0eedSdrh if( (pLeft->jointype & JT_NATURAL)!=0 && 109991bb0eedSdrh columnIndex(pLeft->pTab, zName)>=0 ){ 1100ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 1101ad2d8307Sdrh ** table on the right */ 1102ad2d8307Sdrh continue; 1103ad2d8307Sdrh } 110491bb0eedSdrh if( sqlite3IdListIndex(pLeft->pUsing, zName)>=0 ){ 1105ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 1106ad2d8307Sdrh ** using clause from the table on the right. */ 1107ad2d8307Sdrh continue; 1108ad2d8307Sdrh } 110991bb0eedSdrh } 11104adee20fSdanielk1977 pRight = sqlite3Expr(TK_ID, 0, 0, 0); 111122f70c32Sdrh if( pRight==0 ) break; 111291bb0eedSdrh setToken(&pRight->token, zName); 11134b59ab5eSdrh if( zTabName && pTabList->nSrc>1 ){ 11144adee20fSdanielk1977 pLeft = sqlite3Expr(TK_ID, 0, 0, 0); 11154adee20fSdanielk1977 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0); 111622f70c32Sdrh if( pExpr==0 ) break; 111791bb0eedSdrh setToken(&pLeft->token, zTabName); 111891bb0eedSdrh setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName)); 11196977fea8Sdrh pExpr->span.dyn = 1; 11206977fea8Sdrh pExpr->token.z = 0; 11216977fea8Sdrh pExpr->token.n = 0; 11226977fea8Sdrh pExpr->token.dyn = 0; 112322f70c32Sdrh }else{ 112422f70c32Sdrh pExpr = pRight; 11256977fea8Sdrh pExpr->span = pExpr->token; 112622f70c32Sdrh } 112779d5f63fSdrh pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token); 1128d8bc7086Sdrh } 1129d8bc7086Sdrh } 113054473229Sdrh if( !tableSeen ){ 1131cf55b7aeSdrh if( zTName ){ 1132cf55b7aeSdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 1133f5db2d3eSdrh }else{ 11344adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1135f5db2d3eSdrh } 113654473229Sdrh rc = 1; 113754473229Sdrh } 1138cf55b7aeSdrh sqliteFree(zTName); 11397c917d19Sdrh } 11407c917d19Sdrh } 11414adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 11427c917d19Sdrh p->pEList = pNew; 1143d8bc7086Sdrh } 114454473229Sdrh return rc; 1145d8bc7086Sdrh } 1146d8bc7086Sdrh 1147d8bc7086Sdrh /* 1148ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers 1149ff78bd2fSdrh ** in a select structure. It just sets the pointers to NULL. This 1150ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect 1151ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer. 1152ff78bd2fSdrh ** 1153ff78bd2fSdrh ** This routine is called on the Select structure that defines a 1154ff78bd2fSdrh ** VIEW in order to undo any bindings to tables. This is necessary 1155ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command. 11565cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field 11575cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the 11585cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used. 1159ff78bd2fSdrh */ 11605338a5f7Sdanielk1977 #if 0 11614adee20fSdanielk1977 void sqlite3SelectUnbind(Select *p){ 1162ff78bd2fSdrh int i; 1163ad3cab52Sdrh SrcList *pSrc = p->pSrc; 116491bb0eedSdrh struct SrcList_item *pItem; 1165ff78bd2fSdrh Table *pTab; 1166ff78bd2fSdrh if( p==0 ) return; 116791bb0eedSdrh for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){ 116891bb0eedSdrh if( (pTab = pItem->pTab)!=0 ){ 1169ff78bd2fSdrh if( pTab->isTransient ){ 11704adee20fSdanielk1977 sqlite3DeleteTable(0, pTab); 1171ff78bd2fSdrh } 117291bb0eedSdrh pItem->pTab = 0; 117391bb0eedSdrh if( pItem->pSelect ){ 117491bb0eedSdrh sqlite3SelectUnbind(pItem->pSelect); 1175ff78bd2fSdrh } 1176ff78bd2fSdrh } 1177ff78bd2fSdrh } 1178ff78bd2fSdrh } 11795338a5f7Sdanielk1977 #endif 1180ff78bd2fSdrh 118193758c8dSdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 1182ff78bd2fSdrh /* 1183d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with 1184d8bc7086Sdrh ** columns in a result. For each ORDER BY expression, the opcode of 1185967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of 1186d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable 1187d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter. 1188d8bc7086Sdrh ** 1189d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first. A match 1190d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT. 1191d8bc7086Sdrh ** 1192d8bc7086Sdrh ** Any entry that does not match is flagged as an error. The number 1193d8bc7086Sdrh ** of errors is returned. 1194d8bc7086Sdrh */ 1195d8bc7086Sdrh static int matchOrderbyToColumn( 1196d8bc7086Sdrh Parse *pParse, /* A place to leave error messages */ 1197d8bc7086Sdrh Select *pSelect, /* Match to result columns of this SELECT */ 1198d8bc7086Sdrh ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 1199e4de1febSdrh int iTable, /* Insert this value in iTable */ 1200d8bc7086Sdrh int mustComplete /* If TRUE all ORDER BYs must match */ 1201d8bc7086Sdrh ){ 1202d8bc7086Sdrh int nErr = 0; 1203d8bc7086Sdrh int i, j; 1204d8bc7086Sdrh ExprList *pEList; 1205d8bc7086Sdrh 1206daffd0e5Sdrh if( pSelect==0 || pOrderBy==0 ) return 1; 1207d8bc7086Sdrh if( mustComplete ){ 1208d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 1209d8bc7086Sdrh } 12109b3187e1Sdrh if( prepSelectStmt(pParse, pSelect) ){ 1211d8bc7086Sdrh return 1; 1212d8bc7086Sdrh } 1213d8bc7086Sdrh if( pSelect->pPrior ){ 121492cd52f5Sdrh if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 121592cd52f5Sdrh return 1; 121692cd52f5Sdrh } 1217d8bc7086Sdrh } 1218d8bc7086Sdrh pEList = pSelect->pEList; 1219d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 1220d8bc7086Sdrh Expr *pE = pOrderBy->a[i].pExpr; 1221e4de1febSdrh int iCol = -1; 1222d8bc7086Sdrh if( pOrderBy->a[i].done ) continue; 12234adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 1224e4de1febSdrh if( iCol<=0 || iCol>pEList->nExpr ){ 12254adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1226da93d238Sdrh "ORDER BY position %d should be between 1 and %d", 1227e4de1febSdrh iCol, pEList->nExpr); 1228e4de1febSdrh nErr++; 1229e4de1febSdrh break; 1230e4de1febSdrh } 1231fcb78a49Sdrh if( !mustComplete ) continue; 1232e4de1febSdrh iCol--; 1233e4de1febSdrh } 1234e4de1febSdrh for(j=0; iCol<0 && j<pEList->nExpr; j++){ 12354cfa7934Sdrh if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){ 1236a76b5dfcSdrh char *zName, *zLabel; 1237a76b5dfcSdrh zName = pEList->a[j].zName; 1238a99db3b6Sdrh zLabel = sqlite3NameFromToken(&pE->token); 1239a99db3b6Sdrh assert( zLabel!=0 ); 12404adee20fSdanielk1977 if( sqlite3StrICmp(zName, zLabel)==0 ){ 1241e4de1febSdrh iCol = j; 1242d8bc7086Sdrh } 12436e142f54Sdrh sqliteFree(zLabel); 1244d8bc7086Sdrh } 12454adee20fSdanielk1977 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){ 1246e4de1febSdrh iCol = j; 1247d8bc7086Sdrh } 1248e4de1febSdrh } 1249e4de1febSdrh if( iCol>=0 ){ 1250967e8b73Sdrh pE->op = TK_COLUMN; 1251e4de1febSdrh pE->iColumn = iCol; 1252d8bc7086Sdrh pE->iTable = iTable; 1253d8bc7086Sdrh pOrderBy->a[i].done = 1; 1254d8bc7086Sdrh } 1255e4de1febSdrh if( iCol<0 && mustComplete ){ 12564adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1257da93d238Sdrh "ORDER BY term number %d does not match any result column", i+1); 1258d8bc7086Sdrh nErr++; 1259d8bc7086Sdrh break; 1260d8bc7086Sdrh } 1261d8bc7086Sdrh } 1262d8bc7086Sdrh return nErr; 1263d8bc7086Sdrh } 126493758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */ 1265d8bc7086Sdrh 1266d8bc7086Sdrh /* 1267d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1268d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1269d8bc7086Sdrh */ 12704adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1271d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1272d8bc7086Sdrh if( v==0 ){ 12734adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1274d8bc7086Sdrh } 1275d8bc7086Sdrh return v; 1276d8bc7086Sdrh } 1277d8bc7086Sdrh 1278d8bc7086Sdrh /* 12797b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 12807b58daeaSdrh ** nLimit and nOffset fields. nLimit and nOffset hold the integers 12817b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 12827b58daeaSdrh ** keywords. Or that hold -1 and 0 if those keywords are omitted. 12837b58daeaSdrh ** iLimit and iOffset are the integer memory register numbers for 12847b58daeaSdrh ** counters used to compute the limit and offset. If there is no 12857b58daeaSdrh ** limit and/or offset, then iLimit and iOffset are negative. 12867b58daeaSdrh ** 12877b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if 12887b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset. iLimit and 12897b58daeaSdrh ** iOffset should have been preset to appropriate default values 12907b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 12917b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get 12927b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 12937b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 12947b58daeaSdrh ** SELECT statements. 12957b58daeaSdrh */ 12967b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){ 12977b58daeaSdrh /* 12987b58daeaSdrh ** If the comparison is p->nLimit>0 then "LIMIT 0" shows 12997b58daeaSdrh ** all rows. It is the same as no limit. If the comparision is 13007b58daeaSdrh ** p->nLimit>=0 then "LIMIT 0" show no rows at all. 13017b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 13027b58daeaSdrh ** contraversy about what the correct behavior should be. 13037b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 13047b58daeaSdrh ** no rows. 13057b58daeaSdrh */ 13067b58daeaSdrh if( p->nLimit>=0 ){ 13077b58daeaSdrh int iMem = pParse->nMem++; 13084adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 13097b58daeaSdrh if( v==0 ) return; 13104adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0); 13114adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 1312ad6d9460Sdrh VdbeComment((v, "# LIMIT counter")); 13137b58daeaSdrh p->iLimit = iMem; 13147b58daeaSdrh } 13157b58daeaSdrh if( p->nOffset>0 ){ 13167b58daeaSdrh int iMem = pParse->nMem++; 13174adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 13187b58daeaSdrh if( v==0 ) return; 13194adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0); 13204adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 1321ad6d9460Sdrh VdbeComment((v, "# OFFSET counter")); 13227b58daeaSdrh p->iOffset = iMem; 13237b58daeaSdrh } 13247b58daeaSdrh } 13257b58daeaSdrh 13267b58daeaSdrh /* 1327d3d39e93Sdrh ** Generate VDBE instructions that will open a transient table that 1328d3d39e93Sdrh ** will be used for an index or to store keyed results for a compound 1329d3d39e93Sdrh ** select. In other words, open a transient table that needs a 1330d3d39e93Sdrh ** KeyInfo structure. The number of columns in the KeyInfo is determined 1331d3d39e93Sdrh ** by the result set of the SELECT statement in the second argument. 1332d3d39e93Sdrh ** 1333dc1bdc4fSdanielk1977 ** Specifically, this routine is called to open an index table for 1334dc1bdc4fSdanielk1977 ** DISTINCT, UNION, INTERSECT and EXCEPT select statements (but not 1335dc1bdc4fSdanielk1977 ** UNION ALL). 1336dc1bdc4fSdanielk1977 ** 1337d3d39e93Sdrh ** Make the new table a KeyAsData table if keyAsData is true. 1338dc1bdc4fSdanielk1977 ** 1339dc1bdc4fSdanielk1977 ** The value returned is the address of the OP_OpenTemp instruction. 1340d3d39e93Sdrh */ 1341dc1bdc4fSdanielk1977 static int openTempIndex(Parse *pParse, Select *p, int iTab, int keyAsData){ 1342d3d39e93Sdrh KeyInfo *pKeyInfo; 1343736c22b8Sdrh int nColumn; 13449bb575fdSdrh sqlite3 *db = pParse->db; 1345d3d39e93Sdrh int i; 1346d3d39e93Sdrh Vdbe *v = pParse->pVdbe; 1347dc1bdc4fSdanielk1977 int addr; 1348d3d39e93Sdrh 13499b3187e1Sdrh if( prepSelectStmt(pParse, p) ){ 1350dc1bdc4fSdanielk1977 return 0; 1351736c22b8Sdrh } 1352736c22b8Sdrh nColumn = p->pEList->nExpr; 1353d3d39e93Sdrh pKeyInfo = sqliteMalloc( sizeof(*pKeyInfo)+nColumn*sizeof(CollSeq*) ); 1354dc1bdc4fSdanielk1977 if( pKeyInfo==0 ) return 0; 135591bb0eedSdrh pKeyInfo->enc = db->enc; 1356d3d39e93Sdrh pKeyInfo->nField = nColumn; 1357d3d39e93Sdrh for(i=0; i<nColumn; i++){ 1358dc1bdc4fSdanielk1977 pKeyInfo->aColl[i] = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr); 1359dc1bdc4fSdanielk1977 if( !pKeyInfo->aColl[i] ){ 1360d3d39e93Sdrh pKeyInfo->aColl[i] = db->pDfltColl; 1361d3d39e93Sdrh } 1362dc1bdc4fSdanielk1977 } 1363dc1bdc4fSdanielk1977 addr = sqlite3VdbeOp3(v, OP_OpenTemp, iTab, 0, 1364dc1bdc4fSdanielk1977 (char*)pKeyInfo, P3_KEYINFO_HANDOFF); 1365d3d39e93Sdrh if( keyAsData ){ 1366d3d39e93Sdrh sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1); 1367d3d39e93Sdrh } 1368dc1bdc4fSdanielk1977 return addr; 1369dc1bdc4fSdanielk1977 } 1370dc1bdc4fSdanielk1977 1371b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1372fbc4ee7bSdrh /* 13738cdbf836Sdrh ** Add the address "addr" to the set of all OpenTemp opcode addresses 13748cdbf836Sdrh ** that are being accumulated in p->ppOpenTemp. 1375fbc4ee7bSdrh */ 13768cdbf836Sdrh static int multiSelectOpenTempAddr(Select *p, int addr){ 13778cdbf836Sdrh IdList *pList = *p->ppOpenTemp = sqlite3IdListAppend(*p->ppOpenTemp, 0); 1378fbc4ee7bSdrh if( pList==0 ){ 1379dc1bdc4fSdanielk1977 return SQLITE_NOMEM; 1380dc1bdc4fSdanielk1977 } 1381fbc4ee7bSdrh pList->a[pList->nId-1].idx = addr; 1382dc1bdc4fSdanielk1977 return SQLITE_OK; 1383dc1bdc4fSdanielk1977 } 1384b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1385dc1bdc4fSdanielk1977 1386b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1387fbc4ee7bSdrh /* 1388fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1389fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1390fbc4ee7bSdrh ** the column has no default collating sequence. 1391fbc4ee7bSdrh ** 1392fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1393fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1394fbc4ee7bSdrh */ 1395dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1396fbc4ee7bSdrh CollSeq *pRet; 1397dc1bdc4fSdanielk1977 if( p->pPrior ){ 1398dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1399fbc4ee7bSdrh }else{ 1400fbc4ee7bSdrh pRet = 0; 1401dc1bdc4fSdanielk1977 } 1402fbc4ee7bSdrh if( pRet==0 ){ 1403dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1404dc1bdc4fSdanielk1977 } 1405dc1bdc4fSdanielk1977 return pRet; 1406d3d39e93Sdrh } 1407b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 1408d3d39e93Sdrh 1409b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1410d3d39e93Sdrh /* 141182c3d636Sdrh ** This routine is called to process a query that is really the union 141282c3d636Sdrh ** or intersection of two or more separate queries. 1413c926afbcSdrh ** 1414e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1415e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1416e78e8284Sdrh ** in which case this routine will be called recursively. 1417e78e8284Sdrh ** 1418e78e8284Sdrh ** The results of the total query are to be written into a destination 1419e78e8284Sdrh ** of type eDest with parameter iParm. 1420e78e8284Sdrh ** 1421e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1422e78e8284Sdrh ** 1423e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1424e78e8284Sdrh ** 1425e78e8284Sdrh ** This statement is parsed up as follows: 1426e78e8284Sdrh ** 1427e78e8284Sdrh ** SELECT c FROM t3 1428e78e8284Sdrh ** | 1429e78e8284Sdrh ** `-----> SELECT b FROM t2 1430e78e8284Sdrh ** | 14314b11c6d3Sjplyon ** `------> SELECT a FROM t1 1432e78e8284Sdrh ** 1433e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1434e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1435e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1436e78e8284Sdrh ** 1437e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1438e78e8284Sdrh ** individual selects always group from left to right. 143982c3d636Sdrh */ 144084ac9d02Sdanielk1977 static int multiSelect( 1441fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 1442fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 1443fbc4ee7bSdrh int eDest, /* \___ Store query results as specified */ 1444fbc4ee7bSdrh int iParm, /* / by these two parameters. */ 144584ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 144684ac9d02Sdanielk1977 ){ 144784ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 144810e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 144910e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 1450fbc4ee7bSdrh IdList *pOpenTemp = 0;/* OP_OpenTemp opcodes that need a KeyInfo */ 14518cdbf836Sdrh int aAddr[5]; /* Addresses of SetNumColumns operators */ 14528cdbf836Sdrh int nAddr = 0; /* Number used */ 14538cdbf836Sdrh int nCol; /* Number of columns in the result set */ 145482c3d636Sdrh 14557b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 1456fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 145782c3d636Sdrh */ 145884ac9d02Sdanielk1977 if( p==0 || p->pPrior==0 ){ 145984ac9d02Sdanielk1977 rc = 1; 146084ac9d02Sdanielk1977 goto multi_select_end; 146184ac9d02Sdanielk1977 } 1462d8bc7086Sdrh pPrior = p->pPrior; 1463d8bc7086Sdrh if( pPrior->pOrderBy ){ 14644adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1465da93d238Sdrh selectOpName(p->op)); 146684ac9d02Sdanielk1977 rc = 1; 146784ac9d02Sdanielk1977 goto multi_select_end; 146882c3d636Sdrh } 14697b58daeaSdrh if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){ 14704adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 14717b58daeaSdrh selectOpName(p->op)); 147284ac9d02Sdanielk1977 rc = 1; 147384ac9d02Sdanielk1977 goto multi_select_end; 14747b58daeaSdrh } 147582c3d636Sdrh 1476d8bc7086Sdrh /* Make sure we have a valid query engine. If not, create a new one. 1477d8bc7086Sdrh */ 14784adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 147984ac9d02Sdanielk1977 if( v==0 ){ 148084ac9d02Sdanielk1977 rc = 1; 148184ac9d02Sdanielk1977 goto multi_select_end; 148284ac9d02Sdanielk1977 } 1483d8bc7086Sdrh 14848cdbf836Sdrh /* If *p this is the right-most select statement, then initialize 14858cdbf836Sdrh ** p->ppOpenTemp to point to pOpenTemp. If *p is not the right most 14868cdbf836Sdrh ** statement then p->ppOpenTemp will have already been initialized 14878cdbf836Sdrh ** by a prior call to this same procedure. Pass along the pOpenTemp 14888cdbf836Sdrh ** pointer to pPrior, the next statement to our left. 1489fbc4ee7bSdrh */ 1490fbc4ee7bSdrh if( p->ppOpenTemp==0 ){ 1491fbc4ee7bSdrh p->ppOpenTemp = &pOpenTemp; 1492fbc4ee7bSdrh } 1493fbc4ee7bSdrh pPrior->ppOpenTemp = p->ppOpenTemp; 1494fbc4ee7bSdrh 14951cc3d75fSdrh /* Create the destination temporary table if necessary 14961cc3d75fSdrh */ 14971cc3d75fSdrh if( eDest==SRT_TempTable ){ 1498b4964b72Sdanielk1977 assert( p->pEList ); 14994adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0); 15008cdbf836Sdrh assert( nAddr==0 ); 15018cdbf836Sdrh aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 0); 15021cc3d75fSdrh eDest = SRT_Table; 15031cc3d75fSdrh } 15041cc3d75fSdrh 1505f46f905aSdrh /* Generate code for the left and right SELECT statements. 1506d8bc7086Sdrh */ 150782c3d636Sdrh switch( p->op ){ 1508f46f905aSdrh case TK_ALL: { 1509f46f905aSdrh if( p->pOrderBy==0 ){ 15107b58daeaSdrh pPrior->nLimit = p->nLimit; 15117b58daeaSdrh pPrior->nOffset = p->nOffset; 1512b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); 151384ac9d02Sdanielk1977 if( rc ){ 151484ac9d02Sdanielk1977 goto multi_select_end; 151584ac9d02Sdanielk1977 } 1516f46f905aSdrh p->pPrior = 0; 15177b58daeaSdrh p->iLimit = pPrior->iLimit; 15187b58daeaSdrh p->iOffset = pPrior->iOffset; 15197b58daeaSdrh p->nLimit = -1; 15207b58daeaSdrh p->nOffset = 0; 1521b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); 1522f46f905aSdrh p->pPrior = pPrior; 152384ac9d02Sdanielk1977 if( rc ){ 152484ac9d02Sdanielk1977 goto multi_select_end; 152584ac9d02Sdanielk1977 } 1526f46f905aSdrh break; 1527f46f905aSdrh } 1528f46f905aSdrh /* For UNION ALL ... ORDER BY fall through to the next case */ 1529f46f905aSdrh } 153082c3d636Sdrh case TK_EXCEPT: 153182c3d636Sdrh case TK_UNION: { 1532d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1533742f947bSdanielk1977 int op = 0; /* One of the SRT_ operations to apply to self */ 1534d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 15357b58daeaSdrh int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */ 1536c926afbcSdrh ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */ 1537dc1bdc4fSdanielk1977 int addr; 153882c3d636Sdrh 1539d8bc7086Sdrh priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 15407b58daeaSdrh if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){ 1541d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1542c926afbcSdrh ** right. 1543d8bc7086Sdrh */ 154482c3d636Sdrh unionTab = iParm; 154582c3d636Sdrh }else{ 1546d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1547d8bc7086Sdrh ** intermediate results. 1548d8bc7086Sdrh */ 154982c3d636Sdrh unionTab = pParse->nTab++; 1550d8bc7086Sdrh if( p->pOrderBy 1551d8bc7086Sdrh && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){ 155284ac9d02Sdanielk1977 rc = 1; 155384ac9d02Sdanielk1977 goto multi_select_end; 1554d8bc7086Sdrh } 1555dc1bdc4fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0); 1556d8bc7086Sdrh if( p->op!=TK_ALL ){ 15578cdbf836Sdrh rc = multiSelectOpenTempAddr(p, addr); 1558dc1bdc4fSdanielk1977 if( rc!=SQLITE_OK ){ 1559dc1bdc4fSdanielk1977 goto multi_select_end; 1560dc1bdc4fSdanielk1977 } 1561dc1bdc4fSdanielk1977 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1); 156282c3d636Sdrh } 15638cdbf836Sdrh assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) ); 15648cdbf836Sdrh aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0); 156584ac9d02Sdanielk1977 assert( p->pEList ); 1566d8bc7086Sdrh } 1567d8bc7086Sdrh 1568d8bc7086Sdrh /* Code the SELECT statements to our left 1569d8bc7086Sdrh */ 1570b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 1571b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); 157284ac9d02Sdanielk1977 if( rc ){ 157384ac9d02Sdanielk1977 goto multi_select_end; 157484ac9d02Sdanielk1977 } 1575d8bc7086Sdrh 1576d8bc7086Sdrh /* Code the current SELECT statement 1577d8bc7086Sdrh */ 1578d8bc7086Sdrh switch( p->op ){ 1579d8bc7086Sdrh case TK_EXCEPT: op = SRT_Except; break; 1580d8bc7086Sdrh case TK_UNION: op = SRT_Union; break; 1581d8bc7086Sdrh case TK_ALL: op = SRT_Table; break; 1582d8bc7086Sdrh } 158382c3d636Sdrh p->pPrior = 0; 1584c926afbcSdrh pOrderBy = p->pOrderBy; 1585c926afbcSdrh p->pOrderBy = 0; 15867b58daeaSdrh nLimit = p->nLimit; 15877b58daeaSdrh p->nLimit = -1; 15887b58daeaSdrh nOffset = p->nOffset; 15897b58daeaSdrh p->nOffset = 0; 1590b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); 159182c3d636Sdrh p->pPrior = pPrior; 1592c926afbcSdrh p->pOrderBy = pOrderBy; 15937b58daeaSdrh p->nLimit = nLimit; 15947b58daeaSdrh p->nOffset = nOffset; 1595be5fd490Sdrh p->iLimit = -1; 1596be5fd490Sdrh p->iOffset = -1; 159784ac9d02Sdanielk1977 if( rc ){ 159884ac9d02Sdanielk1977 goto multi_select_end; 159984ac9d02Sdanielk1977 } 160084ac9d02Sdanielk1977 1601d8bc7086Sdrh 1602d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1603d8bc7086Sdrh ** it is that we currently need. 1604d8bc7086Sdrh */ 1605c926afbcSdrh if( eDest!=priorOp || unionTab!=iParm ){ 16066b56344dSdrh int iCont, iBreak, iStart; 160782c3d636Sdrh assert( p->pEList ); 160841202ccaSdrh if( eDest==SRT_Callback ){ 16096a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 161041202ccaSdrh } 16114adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 16124adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 16134adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); 16147b58daeaSdrh computeLimitRegisters(pParse, p); 16154adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 161638640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 1617d8bc7086Sdrh p->pOrderBy, -1, eDest, iParm, 161884ac9d02Sdanielk1977 iCont, iBreak, 0); 161984ac9d02Sdanielk1977 if( rc ){ 162084ac9d02Sdanielk1977 rc = 1; 162184ac9d02Sdanielk1977 goto multi_select_end; 162284ac9d02Sdanielk1977 } 16234adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 16244adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); 16254adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 16264adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); 162782c3d636Sdrh } 162882c3d636Sdrh break; 162982c3d636Sdrh } 163082c3d636Sdrh case TK_INTERSECT: { 163182c3d636Sdrh int tab1, tab2; 16326b56344dSdrh int iCont, iBreak, iStart; 16337b58daeaSdrh int nLimit, nOffset; 1634dc1bdc4fSdanielk1977 int addr; 163582c3d636Sdrh 1636d8bc7086Sdrh /* INTERSECT is different from the others since it requires 16376206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1638d8bc7086Sdrh ** by allocating the tables we will need. 1639d8bc7086Sdrh */ 164082c3d636Sdrh tab1 = pParse->nTab++; 164182c3d636Sdrh tab2 = pParse->nTab++; 1642d8bc7086Sdrh if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){ 164384ac9d02Sdanielk1977 rc = 1; 164484ac9d02Sdanielk1977 goto multi_select_end; 1645d8bc7086Sdrh } 1646dc1bdc4fSdanielk1977 1647dc1bdc4fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 0); 16488cdbf836Sdrh rc = multiSelectOpenTempAddr(p, addr); 1649dc1bdc4fSdanielk1977 if( rc!=SQLITE_OK ){ 1650dc1bdc4fSdanielk1977 goto multi_select_end; 1651dc1bdc4fSdanielk1977 } 1652dc1bdc4fSdanielk1977 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1); 16538cdbf836Sdrh assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) ); 16548cdbf836Sdrh aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0); 165584ac9d02Sdanielk1977 assert( p->pEList ); 1656d8bc7086Sdrh 1657d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1658d8bc7086Sdrh */ 1659b3bce662Sdanielk1977 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); 166084ac9d02Sdanielk1977 if( rc ){ 166184ac9d02Sdanielk1977 goto multi_select_end; 166284ac9d02Sdanielk1977 } 1663d8bc7086Sdrh 1664d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1665d8bc7086Sdrh */ 1666dc1bdc4fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0); 16678cdbf836Sdrh rc = multiSelectOpenTempAddr(p, addr); 1668dc1bdc4fSdanielk1977 if( rc!=SQLITE_OK ){ 1669dc1bdc4fSdanielk1977 goto multi_select_end; 1670dc1bdc4fSdanielk1977 } 1671dc1bdc4fSdanielk1977 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1); 16728cdbf836Sdrh assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) ); 16738cdbf836Sdrh aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0); 167482c3d636Sdrh p->pPrior = 0; 16757b58daeaSdrh nLimit = p->nLimit; 16767b58daeaSdrh p->nLimit = -1; 16777b58daeaSdrh nOffset = p->nOffset; 16787b58daeaSdrh p->nOffset = 0; 1679b3bce662Sdanielk1977 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); 168082c3d636Sdrh p->pPrior = pPrior; 16817b58daeaSdrh p->nLimit = nLimit; 16827b58daeaSdrh p->nOffset = nOffset; 168384ac9d02Sdanielk1977 if( rc ){ 168484ac9d02Sdanielk1977 goto multi_select_end; 168584ac9d02Sdanielk1977 } 1686d8bc7086Sdrh 1687d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1688d8bc7086Sdrh ** tables. 1689d8bc7086Sdrh */ 169082c3d636Sdrh assert( p->pEList ); 169141202ccaSdrh if( eDest==SRT_Callback ){ 16926a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 169341202ccaSdrh } 16944adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 16954adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 16964adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); 16977b58daeaSdrh computeLimitRegisters(pParse, p); 16984adee20fSdanielk1977 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0); 16994adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); 170038640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 1701d8bc7086Sdrh p->pOrderBy, -1, eDest, iParm, 170284ac9d02Sdanielk1977 iCont, iBreak, 0); 170384ac9d02Sdanielk1977 if( rc ){ 170484ac9d02Sdanielk1977 rc = 1; 170584ac9d02Sdanielk1977 goto multi_select_end; 170684ac9d02Sdanielk1977 } 17074adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 17084adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); 17094adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 17104adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab2, 0); 17114adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab1, 0); 171282c3d636Sdrh break; 171382c3d636Sdrh } 171482c3d636Sdrh } 17158cdbf836Sdrh 17168cdbf836Sdrh /* Make sure all SELECTs in the statement have the same number of elements 17178cdbf836Sdrh ** in their result sets. 17188cdbf836Sdrh */ 171982c3d636Sdrh assert( p->pEList && pPrior->pEList ); 172082c3d636Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 17214adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1722da93d238Sdrh " do not have the same number of result columns", selectOpName(p->op)); 172384ac9d02Sdanielk1977 rc = 1; 172484ac9d02Sdanielk1977 goto multi_select_end; 17252282792aSdrh } 172684ac9d02Sdanielk1977 17278cdbf836Sdrh /* Set the number of columns in temporary tables 17288cdbf836Sdrh */ 17298cdbf836Sdrh nCol = p->pEList->nExpr; 17308cdbf836Sdrh while( nAddr>0 ){ 17318cdbf836Sdrh nAddr--; 17328cdbf836Sdrh sqlite3VdbeChangeP2(v, aAddr[nAddr], nCol); 17338cdbf836Sdrh } 17348cdbf836Sdrh 1735fbc4ee7bSdrh /* Compute collating sequences used by either the ORDER BY clause or 1736fbc4ee7bSdrh ** by any temporary tables needed to implement the compound select. 1737fbc4ee7bSdrh ** Attach the KeyInfo structure to all temporary tables. Invoke the 1738fbc4ee7bSdrh ** ORDER BY processing if there is an ORDER BY clause. 17398cdbf836Sdrh ** 17408cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 17418cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 17428cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 17438cdbf836Sdrh ** no temp tables are required. 1744fbc4ee7bSdrh */ 1745dc1bdc4fSdanielk1977 if( p->pOrderBy || (pOpenTemp && pOpenTemp->nId>0) ){ 1746fbc4ee7bSdrh int i; /* Loop counter */ 1747fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 1748fbc4ee7bSdrh 17498cdbf836Sdrh assert( p->ppOpenTemp == &pOpenTemp ); 1750fbc4ee7bSdrh pKeyInfo = sqliteMalloc(sizeof(*pKeyInfo)+nCol*sizeof(CollSeq*)); 1751dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 1752dc1bdc4fSdanielk1977 rc = SQLITE_NOMEM; 1753dc1bdc4fSdanielk1977 goto multi_select_end; 1754dc1bdc4fSdanielk1977 } 1755dc1bdc4fSdanielk1977 1756dc1bdc4fSdanielk1977 pKeyInfo->enc = pParse->db->enc; 1757dc1bdc4fSdanielk1977 pKeyInfo->nField = nCol; 1758dc1bdc4fSdanielk1977 1759dc1bdc4fSdanielk1977 for(i=0; i<nCol; i++){ 1760dc1bdc4fSdanielk1977 pKeyInfo->aColl[i] = multiSelectCollSeq(pParse, p, i); 1761dc1bdc4fSdanielk1977 if( !pKeyInfo->aColl[i] ){ 1762dc1bdc4fSdanielk1977 pKeyInfo->aColl[i] = pParse->db->pDfltColl; 1763dc1bdc4fSdanielk1977 } 1764dc1bdc4fSdanielk1977 } 1765dc1bdc4fSdanielk1977 1766dc1bdc4fSdanielk1977 for(i=0; pOpenTemp && i<pOpenTemp->nId; i++){ 1767dc1bdc4fSdanielk1977 int p3type = (i==0?P3_KEYINFO_HANDOFF:P3_KEYINFO); 1768dc1bdc4fSdanielk1977 int addr = pOpenTemp->a[i].idx; 1769dc1bdc4fSdanielk1977 sqlite3VdbeChangeP3(v, addr, (char *)pKeyInfo, p3type); 1770dc1bdc4fSdanielk1977 } 1771dc1bdc4fSdanielk1977 1772dc1bdc4fSdanielk1977 if( p->pOrderBy ){ 1773fbc4ee7bSdrh struct ExprList_item *pOrderByTerm = p->pOrderBy->a; 1774fbc4ee7bSdrh for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){ 1775fbc4ee7bSdrh Expr *pExpr = pOrderByTerm->pExpr; 1776fbc4ee7bSdrh char *zName = pOrderByTerm->zName; 1777dc1bdc4fSdanielk1977 assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol ); 1778b3bce662Sdanielk1977 /* assert( !pExpr->pColl ); */ 1779dc1bdc4fSdanielk1977 if( zName ){ 1780dc1bdc4fSdanielk1977 pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1); 178184ac9d02Sdanielk1977 }else{ 1782dc1bdc4fSdanielk1977 pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn]; 178384ac9d02Sdanielk1977 } 178484ac9d02Sdanielk1977 } 1785dc1bdc4fSdanielk1977 generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); 1786dc1bdc4fSdanielk1977 } 1787dc1bdc4fSdanielk1977 1788dc1bdc4fSdanielk1977 if( !pOpenTemp ){ 1789dc1bdc4fSdanielk1977 /* This happens for UNION ALL ... ORDER BY */ 1790dc1bdc4fSdanielk1977 sqliteFree(pKeyInfo); 1791dc1bdc4fSdanielk1977 } 1792dc1bdc4fSdanielk1977 } 1793dc1bdc4fSdanielk1977 1794dc1bdc4fSdanielk1977 multi_select_end: 1795dc1bdc4fSdanielk1977 if( pOpenTemp ){ 1796dc1bdc4fSdanielk1977 sqlite3IdListDelete(pOpenTemp); 1797dc1bdc4fSdanielk1977 } 1798dc1bdc4fSdanielk1977 p->ppOpenTemp = 0; 179984ac9d02Sdanielk1977 return rc; 18002282792aSdrh } 1801b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 18022282792aSdrh 1803b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 18042282792aSdrh /* 1805832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 18066a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 180784e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 18086a3ea0e6Sdrh ** unchanged.) 1809832508b7Sdrh ** 1810832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 1811832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 1812832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 1813832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 1814832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 1815832508b7Sdrh ** of the subquery rather the result set of the subquery. 1816832508b7Sdrh */ 18176a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */ 1818b3bce662Sdanielk1977 static void substSelect(Select *, int, ExprList *); /* Forward Decl */ 18196a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){ 1820832508b7Sdrh if( pExpr==0 ) return; 182150350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 182250350a15Sdrh if( pExpr->iColumn<0 ){ 182350350a15Sdrh pExpr->op = TK_NULL; 182450350a15Sdrh }else{ 1825832508b7Sdrh Expr *pNew; 182684e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 1827832508b7Sdrh assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 1828832508b7Sdrh pNew = pEList->a[pExpr->iColumn].pExpr; 1829832508b7Sdrh assert( pNew!=0 ); 1830832508b7Sdrh pExpr->op = pNew->op; 1831d94a6698Sdrh assert( pExpr->pLeft==0 ); 18324adee20fSdanielk1977 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft); 1833d94a6698Sdrh assert( pExpr->pRight==0 ); 18344adee20fSdanielk1977 pExpr->pRight = sqlite3ExprDup(pNew->pRight); 1835d94a6698Sdrh assert( pExpr->pList==0 ); 18364adee20fSdanielk1977 pExpr->pList = sqlite3ExprListDup(pNew->pList); 1837832508b7Sdrh pExpr->iTable = pNew->iTable; 1838832508b7Sdrh pExpr->iColumn = pNew->iColumn; 1839832508b7Sdrh pExpr->iAgg = pNew->iAgg; 18404adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->token, &pNew->token); 18414adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->span, &pNew->span); 184250350a15Sdrh } 1843832508b7Sdrh }else{ 18446a3ea0e6Sdrh substExpr(pExpr->pLeft, iTable, pEList); 18456a3ea0e6Sdrh substExpr(pExpr->pRight, iTable, pEList); 1846b3bce662Sdanielk1977 substSelect(pExpr->pSelect, iTable, pEList); 18476a3ea0e6Sdrh substExprList(pExpr->pList, iTable, pEList); 1848832508b7Sdrh } 1849832508b7Sdrh } 1850b3bce662Sdanielk1977 static void substExprList(ExprList *pList, int iTable, ExprList *pEList){ 1851832508b7Sdrh int i; 1852832508b7Sdrh if( pList==0 ) return; 1853832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 18546a3ea0e6Sdrh substExpr(pList->a[i].pExpr, iTable, pEList); 1855832508b7Sdrh } 1856832508b7Sdrh } 1857b3bce662Sdanielk1977 static void substSelect(Select *p, int iTable, ExprList *pEList){ 1858b3bce662Sdanielk1977 if( !p ) return; 1859b3bce662Sdanielk1977 substExprList(p->pEList, iTable, pEList); 1860b3bce662Sdanielk1977 substExprList(p->pGroupBy, iTable, pEList); 1861b3bce662Sdanielk1977 substExprList(p->pOrderBy, iTable, pEList); 1862b3bce662Sdanielk1977 substExpr(p->pHaving, iTable, pEList); 1863b3bce662Sdanielk1977 substExpr(p->pWhere, iTable, pEList); 1864b3bce662Sdanielk1977 } 1865b7f9164eSdrh #endif /* !defined(SQLITE_OMIT_VIEW) */ 1866832508b7Sdrh 1867b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 1868832508b7Sdrh /* 18691350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 18701350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 18711350b030Sdrh ** occurs. 18721350b030Sdrh ** 18731350b030Sdrh ** To understand the concept of flattening, consider the following 18741350b030Sdrh ** query: 18751350b030Sdrh ** 18761350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 18771350b030Sdrh ** 18781350b030Sdrh ** The default way of implementing this query is to execute the 18791350b030Sdrh ** subquery first and store the results in a temporary table, then 18801350b030Sdrh ** run the outer query on that temporary table. This requires two 18811350b030Sdrh ** passes over the data. Furthermore, because the temporary table 18821350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 1883832508b7Sdrh ** optimized. 18841350b030Sdrh ** 1885832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 18861350b030Sdrh ** a single flat select, like this: 18871350b030Sdrh ** 18881350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 18891350b030Sdrh ** 18901350b030Sdrh ** The code generated for this simpification gives the same result 1891832508b7Sdrh ** but only has to scan the data once. And because indices might 1892832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 1893832508b7Sdrh ** avoided. 18941350b030Sdrh ** 1895832508b7Sdrh ** Flattening is only attempted if all of the following are true: 18961350b030Sdrh ** 1897832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 18981350b030Sdrh ** 1899832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 1900832508b7Sdrh ** 19018af4d3acSdrh ** (3) The subquery is not the right operand of a left outer join, or 19028af4d3acSdrh ** the subquery is not itself a join. (Ticket #306) 1903832508b7Sdrh ** 1904832508b7Sdrh ** (4) The subquery is not DISTINCT or the outer query is not a join. 1905832508b7Sdrh ** 1906832508b7Sdrh ** (5) The subquery is not DISTINCT or the outer query does not use 1907832508b7Sdrh ** aggregates. 1908832508b7Sdrh ** 1909832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 1910832508b7Sdrh ** DISTINCT. 1911832508b7Sdrh ** 191208192d5fSdrh ** (7) The subquery has a FROM clause. 191308192d5fSdrh ** 1914df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 1915df199a25Sdrh ** 1916df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 1917df199a25Sdrh ** aggregates. 1918df199a25Sdrh ** 1919df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 1920df199a25Sdrh ** use LIMIT. 1921df199a25Sdrh ** 1922174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 1923174b6195Sdrh ** 19243fc673e6Sdrh ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 19253fc673e6Sdrh ** subquery has no WHERE clause. (added by ticket #350) 19263fc673e6Sdrh ** 1927832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 1928832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 1929832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 1930832508b7Sdrh ** 1931665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 1932832508b7Sdrh ** If flattening is attempted this routine returns 1. 1933832508b7Sdrh ** 1934832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 1935832508b7Sdrh ** the subquery before this routine runs. 19361350b030Sdrh */ 19378c74a8caSdrh static int flattenSubquery( 19388c74a8caSdrh Parse *pParse, /* The parsing context */ 19398c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 19408c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 19418c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 19428c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 19438c74a8caSdrh ){ 19440bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 1945ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 1946ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 19470bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 19486a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 194991bb0eedSdrh int i; /* Loop counter */ 195091bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 195191bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 19521350b030Sdrh 1953832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 1954832508b7Sdrh */ 1955832508b7Sdrh if( p==0 ) return 0; 1956832508b7Sdrh pSrc = p->pSrc; 1957ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 195891bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 195991bb0eedSdrh pSub = pSubitem->pSelect; 1960832508b7Sdrh assert( pSub!=0 ); 1961832508b7Sdrh if( isAgg && subqueryIsAgg ) return 0; 1962ad3cab52Sdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; 1963832508b7Sdrh pSubSrc = pSub->pSrc; 1964832508b7Sdrh assert( pSubSrc ); 1965c31c2eb8Sdrh if( pSubSrc->nSrc==0 ) return 0; 1966df199a25Sdrh if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){ 1967df199a25Sdrh return 0; 1968df199a25Sdrh } 1969d11d382cSdrh if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0; 1970174b6195Sdrh if( p->pOrderBy && pSub->pOrderBy ) return 0; 1971832508b7Sdrh 19728af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 19738af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 19748af4d3acSdrh ** is not allowed: 19758af4d3acSdrh ** 19768af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 19778af4d3acSdrh ** 19788af4d3acSdrh ** If we flatten the above, we would get 19798af4d3acSdrh ** 19808af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 19818af4d3acSdrh ** 19828af4d3acSdrh ** which is not at all the same thing. 19838af4d3acSdrh */ 19848af4d3acSdrh if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){ 19858af4d3acSdrh return 0; 19868af4d3acSdrh } 19878af4d3acSdrh 19883fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 19893fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 19903fc673e6Sdrh ** An examples of why this is not allowed: 19913fc673e6Sdrh ** 19923fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 19933fc673e6Sdrh ** 19943fc673e6Sdrh ** If we flatten the above, we would get 19953fc673e6Sdrh ** 19963fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 19973fc673e6Sdrh ** 19983fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 19993fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 20003fc673e6Sdrh */ 20013fc673e6Sdrh if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 20023fc673e6Sdrh && pSub->pWhere!=0 ){ 20033fc673e6Sdrh return 0; 20043fc673e6Sdrh } 20053fc673e6Sdrh 20060bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 200763eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 2008832508b7Sdrh */ 2009c31c2eb8Sdrh 2010c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 2011c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 2012c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 2013c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 2014c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 2015c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 2016c31c2eb8Sdrh ** elements we are now copying in. 2017c31c2eb8Sdrh */ 201891bb0eedSdrh iParent = pSubitem->iCursor; 2019c31c2eb8Sdrh { 2020c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 202191bb0eedSdrh int jointype = pSubitem->jointype; 202291bb0eedSdrh Table *pTab = pSubitem->pTab; 2023c31c2eb8Sdrh 202491bb0eedSdrh if( pTab && pTab->isTransient ){ 202591bb0eedSdrh sqlite3DeleteTable(0, pSubitem->pTab); 2026c31c2eb8Sdrh } 202791bb0eedSdrh sqliteFree(pSubitem->zDatabase); 202891bb0eedSdrh sqliteFree(pSubitem->zName); 202991bb0eedSdrh sqliteFree(pSubitem->zAlias); 2030c31c2eb8Sdrh if( nSubSrc>1 ){ 2031c31c2eb8Sdrh int extra = nSubSrc - 1; 2032c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 20334adee20fSdanielk1977 pSrc = sqlite3SrcListAppend(pSrc, 0, 0); 2034c31c2eb8Sdrh } 2035c31c2eb8Sdrh p->pSrc = pSrc; 2036c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 2037c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 2038c31c2eb8Sdrh } 2039c31c2eb8Sdrh } 2040c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 2041c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 2042c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 2043c31c2eb8Sdrh } 20448af4d3acSdrh pSrc->a[iFrom+nSubSrc-1].jointype = jointype; 2045c31c2eb8Sdrh } 2046c31c2eb8Sdrh 2047c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 2048c31c2eb8Sdrh ** references to the iParent in the outer query. 2049c31c2eb8Sdrh ** 2050c31c2eb8Sdrh ** Example: 2051c31c2eb8Sdrh ** 2052c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 2053c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 2054c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 2055c31c2eb8Sdrh ** 2056c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 2057c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 2058c31c2eb8Sdrh */ 20596a3ea0e6Sdrh substExprList(p->pEList, iParent, pSub->pEList); 2060832508b7Sdrh pList = p->pEList; 2061832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 20626977fea8Sdrh Expr *pExpr; 20636977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 20646977fea8Sdrh pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n); 2065832508b7Sdrh } 2066832508b7Sdrh } 20671b2e0329Sdrh if( isAgg ){ 20686a3ea0e6Sdrh substExprList(p->pGroupBy, iParent, pSub->pEList); 20696a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 20701b2e0329Sdrh } 2071174b6195Sdrh if( pSub->pOrderBy ){ 2072174b6195Sdrh assert( p->pOrderBy==0 ); 2073174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 2074174b6195Sdrh pSub->pOrderBy = 0; 2075174b6195Sdrh }else if( p->pOrderBy ){ 20766a3ea0e6Sdrh substExprList(p->pOrderBy, iParent, pSub->pEList); 2077174b6195Sdrh } 2078832508b7Sdrh if( pSub->pWhere ){ 20794adee20fSdanielk1977 pWhere = sqlite3ExprDup(pSub->pWhere); 2080832508b7Sdrh }else{ 2081832508b7Sdrh pWhere = 0; 2082832508b7Sdrh } 2083832508b7Sdrh if( subqueryIsAgg ){ 2084832508b7Sdrh assert( p->pHaving==0 ); 20851b2e0329Sdrh p->pHaving = p->pWhere; 20861b2e0329Sdrh p->pWhere = pWhere; 20876a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 208891bb0eedSdrh p->pHaving = sqlite3ExprAnd(p->pHaving, sqlite3ExprDup(pSub->pHaving)); 20891b2e0329Sdrh assert( p->pGroupBy==0 ); 20904adee20fSdanielk1977 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy); 2091832508b7Sdrh }else{ 20926a3ea0e6Sdrh substExpr(p->pWhere, iParent, pSub->pEList); 209391bb0eedSdrh p->pWhere = sqlite3ExprAnd(p->pWhere, pWhere); 2094832508b7Sdrh } 2095c31c2eb8Sdrh 2096c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 2097c31c2eb8Sdrh ** outer query is distinct. 2098c31c2eb8Sdrh */ 2099832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 21008c74a8caSdrh 2101c31c2eb8Sdrh /* Transfer the limit expression from the subquery to the outer 2102c31c2eb8Sdrh ** query. 2103c31c2eb8Sdrh */ 2104df199a25Sdrh if( pSub->nLimit>=0 ){ 2105df199a25Sdrh if( p->nLimit<0 ){ 2106df199a25Sdrh p->nLimit = pSub->nLimit; 2107df199a25Sdrh }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){ 2108df199a25Sdrh p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset; 2109df199a25Sdrh } 2110df199a25Sdrh } 2111df199a25Sdrh p->nOffset += pSub->nOffset; 21128c74a8caSdrh 2113c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 2114c31c2eb8Sdrh ** success. 2115c31c2eb8Sdrh */ 21164adee20fSdanielk1977 sqlite3SelectDelete(pSub); 2117832508b7Sdrh return 1; 21181350b030Sdrh } 2119b7f9164eSdrh #endif /* SQLITE_OMIT_VIEW */ 21201350b030Sdrh 21211350b030Sdrh /* 21229562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it 21239562b551Sdrh ** is a simple min() or max() query. If it is and this query can be 21249562b551Sdrh ** satisfied using a single seek to the beginning or end of an index, 2125e78e8284Sdrh ** then generate the code for this SELECT and return 1. If this is not a 21269562b551Sdrh ** simple min() or max() query, then return 0; 21279562b551Sdrh ** 21289562b551Sdrh ** A simply min() or max() query looks like this: 21299562b551Sdrh ** 21309562b551Sdrh ** SELECT min(a) FROM table; 21319562b551Sdrh ** SELECT max(a) FROM table; 21329562b551Sdrh ** 21339562b551Sdrh ** The query may have only a single table in its FROM argument. There 21349562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses. The result set must 21359562b551Sdrh ** be the min() or max() of a single column of the table. The column 21369562b551Sdrh ** in the min() or max() function must be indexed. 21379562b551Sdrh ** 21384adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select(). 21399562b551Sdrh ** See the header comment on that routine for additional information. 21409562b551Sdrh */ 21419562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ 21429562b551Sdrh Expr *pExpr; 21439562b551Sdrh int iCol; 21449562b551Sdrh Table *pTab; 21459562b551Sdrh Index *pIdx; 21469562b551Sdrh int base; 21479562b551Sdrh Vdbe *v; 21489562b551Sdrh int seekOp; 21499562b551Sdrh int cont; 21506e17529eSdrh ExprList *pEList, *pList, eList; 21519562b551Sdrh struct ExprList_item eListItem; 21526e17529eSdrh SrcList *pSrc; 21536e17529eSdrh 21549562b551Sdrh /* Check to see if this query is a simple min() or max() query. Return 21559562b551Sdrh ** zero if it is not. 21569562b551Sdrh */ 21579562b551Sdrh if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; 21586e17529eSdrh pSrc = p->pSrc; 21596e17529eSdrh if( pSrc->nSrc!=1 ) return 0; 21606e17529eSdrh pEList = p->pEList; 21616e17529eSdrh if( pEList->nExpr!=1 ) return 0; 21626e17529eSdrh pExpr = pEList->a[0].pExpr; 21639562b551Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 21646e17529eSdrh pList = pExpr->pList; 21656e17529eSdrh if( pList==0 || pList->nExpr!=1 ) return 0; 21666977fea8Sdrh if( pExpr->token.n!=3 ) return 0; 21674adee20fSdanielk1977 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){ 21680bce8354Sdrh seekOp = OP_Rewind; 21694adee20fSdanielk1977 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){ 21700bce8354Sdrh seekOp = OP_Last; 21710bce8354Sdrh }else{ 21720bce8354Sdrh return 0; 21730bce8354Sdrh } 21746e17529eSdrh pExpr = pList->a[0].pExpr; 21759562b551Sdrh if( pExpr->op!=TK_COLUMN ) return 0; 21769562b551Sdrh iCol = pExpr->iColumn; 21776e17529eSdrh pTab = pSrc->a[0].pTab; 21789562b551Sdrh 21799562b551Sdrh /* If we get to here, it means the query is of the correct form. 218017f71934Sdrh ** Check to make sure we have an index and make pIdx point to the 218117f71934Sdrh ** appropriate index. If the min() or max() is on an INTEGER PRIMARY 218217f71934Sdrh ** key column, no index is necessary so set pIdx to NULL. If no 218317f71934Sdrh ** usable index is found, return 0. 21849562b551Sdrh */ 21859562b551Sdrh if( iCol<0 ){ 21869562b551Sdrh pIdx = 0; 21879562b551Sdrh }else{ 2188dc1bdc4fSdanielk1977 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr); 21899562b551Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 21909562b551Sdrh assert( pIdx->nColumn>=1 ); 2191dc1bdc4fSdanielk1977 if( pIdx->aiColumn[0]==iCol && pIdx->keyInfo.aColl[0]==pColl ) break; 21929562b551Sdrh } 21939562b551Sdrh if( pIdx==0 ) return 0; 21949562b551Sdrh } 21959562b551Sdrh 2196e5f50722Sdrh /* Identify column types if we will be using the callback. This 21979562b551Sdrh ** step is skipped if the output is going to a table or a memory cell. 2198e5f50722Sdrh ** The column names have already been generated in the calling function. 21999562b551Sdrh */ 22004adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 22019562b551Sdrh if( v==0 ) return 0; 22029562b551Sdrh 22030c37e630Sdrh /* If the output is destined for a temporary table, open that table. 22040c37e630Sdrh */ 22050c37e630Sdrh if( eDest==SRT_TempTable ){ 22064adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0); 2207b4964b72Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1); 22080c37e630Sdrh } 22090c37e630Sdrh 221017f71934Sdrh /* Generating code to find the min or the max. Basically all we have 221117f71934Sdrh ** to do is find the first or the last entry in the chosen index. If 221217f71934Sdrh ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first 221317f71934Sdrh ** or last entry in the main table. 22149562b551Sdrh */ 22154adee20fSdanielk1977 sqlite3CodeVerifySchema(pParse, pTab->iDb); 22166e17529eSdrh base = pSrc->a[0].iCursor; 22177b58daeaSdrh computeLimitRegisters(pParse, p); 22186e17529eSdrh if( pSrc->a[0].pSelect==0 ){ 2219ad6d9460Sdrh sqlite3OpenTableForReading(v, base, pTab); 22206e17529eSdrh } 22214adee20fSdanielk1977 cont = sqlite3VdbeMakeLabel(v); 22229562b551Sdrh if( pIdx==0 ){ 22234adee20fSdanielk1977 sqlite3VdbeAddOp(v, seekOp, base, 0); 22249562b551Sdrh }else{ 22253719d7f9Sdanielk1977 /* Even though the cursor used to open the index here is closed 22263719d7f9Sdanielk1977 ** as soon as a single value has been read from it, allocate it 22273719d7f9Sdanielk1977 ** using (pParse->nTab++) to prevent the cursor id from being 22283719d7f9Sdanielk1977 ** reused. This is important for statements of the form 22293719d7f9Sdanielk1977 ** "INSERT INTO x SELECT max() FROM x". 22303719d7f9Sdanielk1977 */ 22313719d7f9Sdanielk1977 int iIdx; 22323719d7f9Sdanielk1977 iIdx = pParse->nTab++; 22334adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0); 22343719d7f9Sdanielk1977 sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 2235d3d39e93Sdrh (char*)&pIdx->keyInfo, P3_KEYINFO); 22369eb516c0Sdrh if( seekOp==OP_Rewind ){ 22371af3fdb4Sdrh sqlite3VdbeAddOp(v, OP_String, 0, 0); 22381af3fdb4Sdrh sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0); 22391af3fdb4Sdrh seekOp = OP_MoveGt; 22409eb516c0Sdrh } 22413719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, seekOp, iIdx, 0); 22423719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, OP_IdxRecno, iIdx, 0); 22433719d7f9Sdanielk1977 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); 22447cf6e4deSdrh sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 22459562b551Sdrh } 22465cf8e8c7Sdrh eList.nExpr = 1; 22475cf8e8c7Sdrh memset(&eListItem, 0, sizeof(eListItem)); 22485cf8e8c7Sdrh eList.a = &eListItem; 22495cf8e8c7Sdrh eList.a[0].pExpr = pExpr; 225084ac9d02Sdanielk1977 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0); 22514adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, cont); 22524adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, base, 0); 22536e17529eSdrh 22549562b551Sdrh return 1; 22559562b551Sdrh } 22569562b551Sdrh 22579562b551Sdrh /* 2258290c1948Sdrh ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return 2259290c1948Sdrh ** the number of errors seen. 2260290c1948Sdrh ** 2261290c1948Sdrh ** An ORDER BY or GROUP BY is a list of expressions. If any expression 2262290c1948Sdrh ** is an integer constant, then that expression is replaced by the 2263290c1948Sdrh ** corresponding entry in the result set. 2264290c1948Sdrh */ 2265290c1948Sdrh static int processOrderGroupBy( 2266b3bce662Sdanielk1977 NameContext *pNC, /* Name context of the SELECT statement. */ 2267290c1948Sdrh ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 2268290c1948Sdrh const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 2269290c1948Sdrh ){ 2270290c1948Sdrh int i; 2271b3bce662Sdanielk1977 ExprList *pEList = pNC->pEList; /* The result set of the SELECT */ 2272b3bce662Sdanielk1977 Parse *pParse = pNC->pParse; /* The result set of the SELECT */ 2273b3bce662Sdanielk1977 assert( pEList ); 2274b3bce662Sdanielk1977 2275290c1948Sdrh if( pOrderBy==0 ) return 0; 2276290c1948Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 2277290c1948Sdrh int iCol; 2278290c1948Sdrh Expr *pE = pOrderBy->a[i].pExpr; 2279b3bce662Sdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 2280b3bce662Sdanielk1977 if( iCol>0 && iCol<=pEList->nExpr ){ 2281290c1948Sdrh sqlite3ExprDelete(pE); 2282290c1948Sdrh pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr); 2283b3bce662Sdanielk1977 }else{ 2284290c1948Sdrh sqlite3ErrorMsg(pParse, 2285290c1948Sdrh "%s BY column number %d out of range - should be " 2286290c1948Sdrh "between 1 and %d", zType, iCol, pEList->nExpr); 2287290c1948Sdrh return 1; 2288290c1948Sdrh } 2289290c1948Sdrh } 2290b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(pNC, pE) ){ 2291b3bce662Sdanielk1977 return 1; 2292b3bce662Sdanielk1977 } 2293b3bce662Sdanielk1977 if( sqlite3ExprIsConstant(pE) ){ 2294b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, 2295b3bce662Sdanielk1977 "%s BY terms must not be non-integer constants", zType); 2296b3bce662Sdanielk1977 return 1; 2297b3bce662Sdanielk1977 } 2298290c1948Sdrh } 2299290c1948Sdrh return 0; 2300290c1948Sdrh } 2301290c1948Sdrh 2302290c1948Sdrh /* 2303b3bce662Sdanielk1977 ** This routine resolves any names used in the result set of the 2304b3bce662Sdanielk1977 ** supplied SELECT statement. If the SELECT statement being resolved 2305b3bce662Sdanielk1977 ** is a sub-select, then pOuterNC is a pointer to the NameContext 2306b3bce662Sdanielk1977 ** of the parent SELECT. 2307b3bce662Sdanielk1977 */ 2308b3bce662Sdanielk1977 int sqlite3SelectResolve( 2309b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 2310b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 2311b3bce662Sdanielk1977 NameContext *pOuterNC /* The outer name context. May be NULL. */ 2312b3bce662Sdanielk1977 ){ 2313b3bce662Sdanielk1977 ExprList *pEList; /* Result set. */ 2314b3bce662Sdanielk1977 int i; /* For-loop variable used in multiple places */ 2315b3bce662Sdanielk1977 NameContext sNC; /* Local name-context */ 2316b3bce662Sdanielk1977 2317b3bce662Sdanielk1977 /* If this routine has run before, return immediately. */ 2318b3bce662Sdanielk1977 if( p->isResolved ){ 2319b3bce662Sdanielk1977 assert( !pOuterNC ); 2320b3bce662Sdanielk1977 return SQLITE_OK; 2321b3bce662Sdanielk1977 } 2322b3bce662Sdanielk1977 p->isResolved = 1; 2323b3bce662Sdanielk1977 2324b3bce662Sdanielk1977 /* If there have already been errors, do nothing. */ 2325b3bce662Sdanielk1977 if( pParse->nErr>0 ){ 2326b3bce662Sdanielk1977 return SQLITE_ERROR; 2327b3bce662Sdanielk1977 } 2328b3bce662Sdanielk1977 2329b3bce662Sdanielk1977 /* Prepare the select statement. This call will allocate all cursors 2330b3bce662Sdanielk1977 ** required to handle the tables and subqueries in the FROM clause. 2331b3bce662Sdanielk1977 */ 2332b3bce662Sdanielk1977 if( prepSelectStmt(pParse, p) ){ 2333b3bce662Sdanielk1977 return SQLITE_ERROR; 2334b3bce662Sdanielk1977 } 2335b3bce662Sdanielk1977 2336b3bce662Sdanielk1977 /* Set up the local name-context to pass to ExprResolveNames(). */ 2337b3bce662Sdanielk1977 sNC.pNext = pOuterNC; 2338b3bce662Sdanielk1977 sNC.pParse = pParse; 2339b3bce662Sdanielk1977 sNC.pSrcList = p->pSrc; 2340b3bce662Sdanielk1977 sNC.allowAgg = 1; 2341b3bce662Sdanielk1977 sNC.hasAgg = 0; 2342b3bce662Sdanielk1977 sNC.nErr = 0; 2343b3bce662Sdanielk1977 sNC.nRef = 0; 2344b3bce662Sdanielk1977 sNC.pEList = 0; 2345b3bce662Sdanielk1977 2346b3bce662Sdanielk1977 /* NameContext.nDepth stores the depth of recursion for this query. For 2347b3bce662Sdanielk1977 ** an outer query (e.g. SELECT * FROM sqlite_master) this is 1. For 2348b3bce662Sdanielk1977 ** a subquery it is 2. For a subquery of a subquery, 3. And so on. 2349b3bce662Sdanielk1977 ** Parse.nMaxDepth is the maximum depth for any subquery resolved so 2350b3bce662Sdanielk1977 ** far. This is used to determine the number of aggregate contexts 2351b3bce662Sdanielk1977 ** required at runtime. 2352b3bce662Sdanielk1977 */ 2353b3bce662Sdanielk1977 sNC.nDepth = (pOuterNC?pOuterNC->nDepth+1:1); 2354b3bce662Sdanielk1977 if( sNC.nDepth>pParse->nMaxDepth ){ 2355b3bce662Sdanielk1977 pParse->nMaxDepth = sNC.nDepth; 2356b3bce662Sdanielk1977 } 2357b3bce662Sdanielk1977 2358b3bce662Sdanielk1977 /* Resolve names in the result set. */ 2359b3bce662Sdanielk1977 pEList = p->pEList; 2360b3bce662Sdanielk1977 if( !pEList ) return SQLITE_ERROR; 2361b3bce662Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 2362b3bce662Sdanielk1977 Expr *pX = pEList->a[i].pExpr; 2363b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, pX) ){ 2364b3bce662Sdanielk1977 return SQLITE_ERROR; 2365b3bce662Sdanielk1977 } 2366b3bce662Sdanielk1977 } 2367b3bce662Sdanielk1977 2368b3bce662Sdanielk1977 /* If there are no aggregate functions in the result-set, and no GROUP BY 2369b3bce662Sdanielk1977 ** expression, do not allow aggregates in any of the other expressions. 2370b3bce662Sdanielk1977 */ 2371b3bce662Sdanielk1977 assert( !p->isAgg ); 2372b3bce662Sdanielk1977 if( p->pGroupBy || sNC.hasAgg ){ 2373b3bce662Sdanielk1977 p->isAgg = 1; 2374b3bce662Sdanielk1977 }else{ 2375b3bce662Sdanielk1977 sNC.allowAgg = 0; 2376b3bce662Sdanielk1977 } 2377b3bce662Sdanielk1977 2378b3bce662Sdanielk1977 /* If a HAVING clause is present, then there must be a GROUP BY clause. 2379b3bce662Sdanielk1977 */ 2380b3bce662Sdanielk1977 if( p->pHaving && !p->pGroupBy ){ 2381b3bce662Sdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2382b3bce662Sdanielk1977 return SQLITE_ERROR; 2383b3bce662Sdanielk1977 } 2384b3bce662Sdanielk1977 2385b3bce662Sdanielk1977 /* Add the expression list to the name-context before parsing the 2386b3bce662Sdanielk1977 ** other expressions in the SELECT statement. This is so that 2387b3bce662Sdanielk1977 ** expressions in the WHERE clause (etc.) can refer to expressions by 2388b3bce662Sdanielk1977 ** aliases in the result set. 2389b3bce662Sdanielk1977 ** 2390b3bce662Sdanielk1977 ** Minor point: If this is the case, then the expression will be 2391b3bce662Sdanielk1977 ** re-evaluated for each reference to it. 2392b3bce662Sdanielk1977 */ 2393b3bce662Sdanielk1977 sNC.pEList = p->pEList; 2394b3bce662Sdanielk1977 if( sqlite3ExprResolveNames(&sNC, p->pWhere) || 2395b3bce662Sdanielk1977 sqlite3ExprResolveNames(&sNC, p->pHaving) || 2396b3bce662Sdanielk1977 processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") || 2397b3bce662Sdanielk1977 processOrderGroupBy(&sNC, p->pGroupBy, "GROUP") 2398b3bce662Sdanielk1977 ){ 2399b3bce662Sdanielk1977 return SQLITE_ERROR; 2400b3bce662Sdanielk1977 } 2401b3bce662Sdanielk1977 2402b3bce662Sdanielk1977 return SQLITE_OK; 2403b3bce662Sdanielk1977 } 2404b3bce662Sdanielk1977 2405b3bce662Sdanielk1977 /* 2406b3bce662Sdanielk1977 ** An instance of the following struct is used by sqlite3Select() 2407b3bce662Sdanielk1977 ** to save aggregate related information from the Parse object 2408b3bce662Sdanielk1977 ** at the start of each call and to restore it at the end. See 2409b3bce662Sdanielk1977 ** saveAggregateInfo() and restoreAggregateInfo(). 2410b3bce662Sdanielk1977 */ 2411b3bce662Sdanielk1977 struct AggregateInfo { 2412b3bce662Sdanielk1977 u8 useAgg; 2413b3bce662Sdanielk1977 int nAgg; 2414b3bce662Sdanielk1977 AggExpr *aAgg; 2415b3bce662Sdanielk1977 }; 2416b3bce662Sdanielk1977 typedef struct AggregateInfo AggregateInfo; 2417b3bce662Sdanielk1977 2418b3bce662Sdanielk1977 /* 2419b3bce662Sdanielk1977 ** Copy aggregate related information from the Parse structure 2420b3bce662Sdanielk1977 ** into the AggregateInfo structure. Zero the aggregate related 2421b3bce662Sdanielk1977 ** values in the Parse struct. 2422b3bce662Sdanielk1977 */ 2423b3bce662Sdanielk1977 static void saveAggregateInfo(Parse *pParse, AggregateInfo *pInfo){ 2424b3bce662Sdanielk1977 pInfo->aAgg = pParse->aAgg; 2425b3bce662Sdanielk1977 pInfo->nAgg = pParse->nAgg; 2426b3bce662Sdanielk1977 pInfo->useAgg = pParse->useAgg; 2427b3bce662Sdanielk1977 pParse->aAgg = 0; 2428b3bce662Sdanielk1977 pParse->nAgg = 0; 2429b3bce662Sdanielk1977 pParse->useAgg = 0; 2430b3bce662Sdanielk1977 } 2431b3bce662Sdanielk1977 2432b3bce662Sdanielk1977 /* 2433b3bce662Sdanielk1977 ** Copy aggregate related information from the AggregateInfo struct 2434b3bce662Sdanielk1977 ** back into the Parse structure. The aggregate related information 2435b3bce662Sdanielk1977 ** currently stored in the Parse structure is deleted. 2436b3bce662Sdanielk1977 */ 2437b3bce662Sdanielk1977 static void restoreAggregateInfo(Parse *pParse, AggregateInfo *pInfo){ 2438b3bce662Sdanielk1977 sqliteFree(pParse->aAgg); 2439b3bce662Sdanielk1977 pParse->aAgg = pInfo->aAgg; 2440b3bce662Sdanielk1977 pParse->nAgg = pInfo->nAgg; 2441b3bce662Sdanielk1977 pParse->useAgg = pInfo->useAgg; 2442b3bce662Sdanielk1977 } 2443b3bce662Sdanielk1977 2444b3bce662Sdanielk1977 /* 24459bb61fe7Sdrh ** Generate code for the given SELECT statement. 24469bb61fe7Sdrh ** 2447fef5208cSdrh ** The results are distributed in various ways depending on the 2448fef5208cSdrh ** value of eDest and iParm. 2449fef5208cSdrh ** 2450fef5208cSdrh ** eDest Value Result 2451fef5208cSdrh ** ------------ ------------------------------------------- 2452fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2453fef5208cSdrh ** 2454fef5208cSdrh ** SRT_Mem Store first result in memory cell iParm 2455fef5208cSdrh ** 2456e014a838Sdanielk1977 ** SRT_Set Store results as keys of table iParm. 2457fef5208cSdrh ** 245882c3d636Sdrh ** SRT_Union Store results as a key in a temporary table iParm 245982c3d636Sdrh ** 24604b11c6d3Sjplyon ** SRT_Except Remove results from the temporary table iParm. 2461c4a3c779Sdrh ** 2462c4a3c779Sdrh ** SRT_Table Store results in temporary table iParm 24639bb61fe7Sdrh ** 2464e78e8284Sdrh ** The table above is incomplete. Additional eDist value have be added 2465e78e8284Sdrh ** since this comment was written. See the selectInnerLoop() function for 2466e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings. 2467e78e8284Sdrh ** 24689bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 24699bb61fe7Sdrh ** encountered, then an appropriate error message is left in 24709bb61fe7Sdrh ** pParse->zErrMsg. 24719bb61fe7Sdrh ** 24729bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 24739bb61fe7Sdrh ** calling function needs to do that. 24741b2e0329Sdrh ** 24751b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 24761b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 24771b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 24781b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 24791b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 24801b2e0329Sdrh ** can be changed. 2481e78e8284Sdrh ** 2482e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2483e78e8284Sdrh ** 2484e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2485e78e8284Sdrh ** \ \_______ subquery _______/ / 2486e78e8284Sdrh ** \ / 2487e78e8284Sdrh ** \____________________ outer query ___________________/ 2488e78e8284Sdrh ** 2489e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2490e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2491e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2492e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2493e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2494e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 24959bb61fe7Sdrh */ 24964adee20fSdanielk1977 int sqlite3Select( 2497cce7d176Sdrh Parse *pParse, /* The parser context */ 24989bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 2499e78e8284Sdrh int eDest, /* How to dispose of the results */ 2500e78e8284Sdrh int iParm, /* A parameter used by the eDest disposal method */ 2501832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 2502832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 250384ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 2504b3bce662Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 2505cce7d176Sdrh ){ 2506d8bc7086Sdrh int i; 2507cce7d176Sdrh WhereInfo *pWInfo; 2508cce7d176Sdrh Vdbe *v; 2509b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 2510a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 2511ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 25129bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 25139bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 25142282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 25152282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 251619a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 251719a775c2Sdrh int distinct; /* Table to use for the distinct set */ 25181d83f052Sdrh int rc = 1; /* Value to return from this function */ 2519b3bce662Sdanielk1977 AggregateInfo sAggInfo; 25209bb61fe7Sdrh 25216f8a503dSdanielk1977 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1; 25224adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 2523daffd0e5Sdrh 2524b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 252582c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 252682c3d636Sdrh */ 252782c3d636Sdrh if( p->pPrior ){ 2528b6c29897Sdrh #ifndef SQLITE_OMIT_CURSOR 2529b6c29897Sdrh if( p->pFetch ){ 2530b6c29897Sdrh sqlite3ErrorMsg(pParse, "cursors cannot be used on compound queries"); 2531b6c29897Sdrh goto select_end; 2532b6c29897Sdrh } 2533b6c29897Sdrh #endif 253484ac9d02Sdanielk1977 return multiSelect(pParse, p, eDest, iParm, aff); 253582c3d636Sdrh } 2536b7f9164eSdrh #endif 253782c3d636Sdrh 2538b3bce662Sdanielk1977 saveAggregateInfo(pParse, &sAggInfo); 2539b3bce662Sdanielk1977 pOrderBy = p->pOrderBy; 2540b3bce662Sdanielk1977 if( eDest==SRT_Union || eDest==SRT_Except || eDest==SRT_Discard ){ 2541b3bce662Sdanielk1977 p->pOrderBy = 0; 2542b3bce662Sdanielk1977 } 2543b3bce662Sdanielk1977 if( sqlite3SelectResolve(pParse, p, 0) ){ 2544b3bce662Sdanielk1977 goto select_end; 2545b3bce662Sdanielk1977 } 2546b3bce662Sdanielk1977 p->pOrderBy = pOrderBy; 2547b3bce662Sdanielk1977 254882c3d636Sdrh /* Make local copies of the parameters for this query. 254982c3d636Sdrh */ 25509bb61fe7Sdrh pTabList = p->pSrc; 25519bb61fe7Sdrh pWhere = p->pWhere; 25522282792aSdrh pGroupBy = p->pGroupBy; 25532282792aSdrh pHaving = p->pHaving; 2554b3bce662Sdanielk1977 isAgg = p->isAgg; 255519a775c2Sdrh isDistinct = p->isDistinct; 2556b3bce662Sdanielk1977 pEList = p->pEList; 2557b3bce662Sdanielk1977 if( pEList==0 ) goto select_end; 25589bb61fe7Sdrh 25599bb61fe7Sdrh /* 25609bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 25619bb61fe7Sdrh ** errors before this routine starts. 25629bb61fe7Sdrh */ 25631d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 2564cce7d176Sdrh 25652282792aSdrh /* If writing to memory or generating a set 25662282792aSdrh ** only a single column may be output. 256719a775c2Sdrh */ 256851522cd3Sdrh assert( eDest!=SRT_Exists || pEList->nExpr==1 ); 256993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 2570fef5208cSdrh if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){ 25714adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "only a single result allowed for " 2572da93d238Sdrh "a SELECT that is part of an expression"); 25731d83f052Sdrh goto select_end; 257419a775c2Sdrh } 257593758c8dSdanielk1977 #endif 257619a775c2Sdrh 2577c926afbcSdrh /* ORDER BY is ignored for some destinations. 25782282792aSdrh */ 2579c926afbcSdrh switch( eDest ){ 2580c926afbcSdrh case SRT_Union: 2581c926afbcSdrh case SRT_Except: 2582c926afbcSdrh case SRT_Discard: 2583acd4c695Sdrh pOrderBy = 0; 2584c926afbcSdrh break; 2585c926afbcSdrh default: 2586c926afbcSdrh break; 25872282792aSdrh } 25882282792aSdrh 2589b6c29897Sdrh /* We cannot use a SQL cursor on a join or on a DISTINCT query 2590b6c29897Sdrh */ 2591b6c29897Sdrh #ifndef SQLITE_OMIT_CURSOR 2592b6c29897Sdrh if( p->pFetch ){ 2593b6c29897Sdrh if( p->isDistinct ){ 2594b6c29897Sdrh sqlite3ErrorMsg(pParse, "cursors cannot be used on DISTINCT queries"); 2595b6c29897Sdrh goto select_end; 2596b6c29897Sdrh } 2597b6c29897Sdrh if( pTabList->nSrc>0 ){ 2598b6c29897Sdrh sqlite3ErrorMsg(pParse, "cursors cannot be used on joins"); 2599b6c29897Sdrh goto select_end; 2600b6c29897Sdrh } 2601b6c29897Sdrh if( pTabList->a[0].pSelect ){ 2602b6c29897Sdrh sqlite3ErrorMsg(pParse, "cursor cannot be used with nested queries " 2603b6c29897Sdrh "or views"); 2604b6c29897Sdrh goto select_end; 2605b6c29897Sdrh } 2606b6c29897Sdrh } 2607b6c29897Sdrh #endif 2608b6c29897Sdrh 2609d820cb1bSdrh /* Begin generating code. 2610d820cb1bSdrh */ 26114adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2612d820cb1bSdrh if( v==0 ) goto select_end; 2613d820cb1bSdrh 2614e78e8284Sdrh /* Identify column names if we will be using them in a callback. This 2615e78e8284Sdrh ** step is skipped if the output is going to some other destination. 26160bb28106Sdrh */ 26170bb28106Sdrh if( eDest==SRT_Callback ){ 26186a3ea0e6Sdrh generateColumnNames(pParse, pTabList, pEList); 26190bb28106Sdrh } 26200bb28106Sdrh 2621d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 2622d820cb1bSdrh */ 262351522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 2624ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 2625742f947bSdanielk1977 const char *zSavedAuthContext = 0; 2626c31c2eb8Sdrh int needRestoreContext; 2627c31c2eb8Sdrh 2628a76b5dfcSdrh if( pTabList->a[i].pSelect==0 ) continue; 26295cf590c1Sdrh if( pTabList->a[i].zName!=0 ){ 26305cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 26315cf590c1Sdrh pParse->zAuthContext = pTabList->a[i].zName; 2632c31c2eb8Sdrh needRestoreContext = 1; 2633c31c2eb8Sdrh }else{ 2634c31c2eb8Sdrh needRestoreContext = 0; 26355cf590c1Sdrh } 26364adee20fSdanielk1977 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable, 2637b3bce662Sdanielk1977 pTabList->a[i].iCursor, p, i, &isAgg, 0); 2638c31c2eb8Sdrh if( needRestoreContext ){ 26395cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 26405cf590c1Sdrh } 2641832508b7Sdrh pTabList = p->pSrc; 2642832508b7Sdrh pWhere = p->pWhere; 2643c31c2eb8Sdrh if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){ 2644832508b7Sdrh pOrderBy = p->pOrderBy; 2645acd4c695Sdrh } 2646832508b7Sdrh pGroupBy = p->pGroupBy; 2647832508b7Sdrh pHaving = p->pHaving; 2648832508b7Sdrh isDistinct = p->isDistinct; 26491b2e0329Sdrh } 265051522cd3Sdrh #endif 26511b2e0329Sdrh 26526e17529eSdrh /* Check for the special case of a min() or max() function by itself 26536e17529eSdrh ** in the result set. 26546e17529eSdrh */ 26556e17529eSdrh if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ 26566e17529eSdrh rc = 0; 26576e17529eSdrh goto select_end; 26586e17529eSdrh } 26596e17529eSdrh 26601b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 26611b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 26621b2e0329Sdrh */ 2663b7f9164eSdrh #ifndef SQLITE_OMIT_VIEW 26641b2e0329Sdrh if( pParent && pParentAgg && 26658c74a8caSdrh flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){ 26661b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 2667b3bce662Sdanielk1977 goto select_end; 26681b2e0329Sdrh } 2669b7f9164eSdrh #endif 2670832508b7Sdrh 26717cedc8d4Sdanielk1977 /* If there is an ORDER BY clause, resolve any collation sequences 26727cedc8d4Sdanielk1977 ** names that have been explicitly specified. 26737cedc8d4Sdanielk1977 */ 26747cedc8d4Sdanielk1977 if( pOrderBy ){ 26757cedc8d4Sdanielk1977 for(i=0; i<pOrderBy->nExpr; i++){ 26767cedc8d4Sdanielk1977 if( pOrderBy->a[i].zName ){ 26777cedc8d4Sdanielk1977 pOrderBy->a[i].pExpr->pColl = 26787cedc8d4Sdanielk1977 sqlite3LocateCollSeq(pParse, pOrderBy->a[i].zName, -1); 26797cedc8d4Sdanielk1977 } 26807cedc8d4Sdanielk1977 } 26817cedc8d4Sdanielk1977 if( pParse->nErr ){ 26827cedc8d4Sdanielk1977 goto select_end; 26837cedc8d4Sdanielk1977 } 26847cedc8d4Sdanielk1977 } 26857cedc8d4Sdanielk1977 26867b58daeaSdrh /* Set the limiter. 26877b58daeaSdrh */ 26887b58daeaSdrh computeLimitRegisters(pParse, p); 26897b58daeaSdrh 26902d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 26912d0794e3Sdrh */ 26922d0794e3Sdrh if( eDest==SRT_TempTable ){ 26934adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0); 2694b4964b72Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr); 26952d0794e3Sdrh } 26962d0794e3Sdrh 26972282792aSdrh /* Do an analysis of aggregate expressions. 2698efb7251dSdrh */ 2699bb999ef6Sdrh if( isAgg || pGroupBy ){ 27000bce8354Sdrh assert( pParse->nAgg==0 ); 2701bb999ef6Sdrh isAgg = 1; 27022282792aSdrh for(i=0; i<pEList->nExpr; i++){ 27034adee20fSdanielk1977 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){ 27041d83f052Sdrh goto select_end; 27052282792aSdrh } 27062282792aSdrh } 27072282792aSdrh if( pGroupBy ){ 27082282792aSdrh for(i=0; i<pGroupBy->nExpr; i++){ 27094adee20fSdanielk1977 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){ 27101d83f052Sdrh goto select_end; 27112282792aSdrh } 27122282792aSdrh } 27132282792aSdrh } 27144adee20fSdanielk1977 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){ 27151d83f052Sdrh goto select_end; 27162282792aSdrh } 2717191b690eSdrh if( pOrderBy ){ 2718191b690eSdrh for(i=0; i<pOrderBy->nExpr; i++){ 27194adee20fSdanielk1977 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){ 27201d83f052Sdrh goto select_end; 2721191b690eSdrh } 2722191b690eSdrh } 2723191b690eSdrh } 2724efb7251dSdrh } 2725efb7251dSdrh 27262282792aSdrh /* Reset the aggregator 2727cce7d176Sdrh */ 2728cce7d176Sdrh if( isAgg ){ 2729e159fdf2Sdanielk1977 int addr = sqlite3VdbeAddOp(v, OP_AggReset, (pGroupBy?0:1), pParse->nAgg); 2730e5095355Sdrh for(i=0; i<pParse->nAgg; i++){ 27310bce8354Sdrh FuncDef *pFunc; 27320bce8354Sdrh if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){ 2733f9b596ebSdrh sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_FUNCDEF); 2734e5095355Sdrh } 2735e5095355Sdrh } 2736e159fdf2Sdanielk1977 if( pGroupBy ){ 2737ce2663ccSdanielk1977 int sz = sizeof(KeyInfo) + pGroupBy->nExpr*sizeof(CollSeq*); 2738ce2663ccSdanielk1977 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(sz); 2739ce2663ccSdanielk1977 if( 0==pKey ){ 2740ce2663ccSdanielk1977 goto select_end; 2741ce2663ccSdanielk1977 } 2742ce2663ccSdanielk1977 pKey->enc = pParse->db->enc; 2743ce2663ccSdanielk1977 pKey->nField = pGroupBy->nExpr; 2744ce2663ccSdanielk1977 for(i=0; i<pGroupBy->nExpr; i++){ 2745ce2663ccSdanielk1977 pKey->aColl[i] = sqlite3ExprCollSeq(pParse, pGroupBy->a[i].pExpr); 2746ce2663ccSdanielk1977 if( !pKey->aColl[i] ){ 2747ce2663ccSdanielk1977 pKey->aColl[i] = pParse->db->pDfltColl; 2748ce2663ccSdanielk1977 } 2749ce2663ccSdanielk1977 } 2750ce2663ccSdanielk1977 sqlite3VdbeChangeP3(v, addr, (char *)pKey, P3_KEYINFO_HANDOFF); 27511bee3d7bSdrh } 2752cce7d176Sdrh } 2753cce7d176Sdrh 275451522cd3Sdrh /* Initialize the memory cell to NULL for SRT_Mem or 0 for SRT_Exists 275519a775c2Sdrh */ 275651522cd3Sdrh if( eDest==SRT_Mem || eDest==SRT_Exists ){ 275751522cd3Sdrh sqlite3VdbeAddOp(v, eDest==SRT_Mem ? OP_String8 : OP_Integer, 0, 0); 27584adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 275919a775c2Sdrh } 276019a775c2Sdrh 2761832508b7Sdrh /* Open a temporary table to use for the distinct set. 2762cce7d176Sdrh */ 276319a775c2Sdrh if( isDistinct ){ 2764832508b7Sdrh distinct = pParse->nTab++; 2765d3d39e93Sdrh openTempIndex(pParse, p, distinct, 0); 2766832508b7Sdrh }else{ 2767832508b7Sdrh distinct = -1; 2768efb7251dSdrh } 2769832508b7Sdrh 2770832508b7Sdrh /* Begin the database scan 2771832508b7Sdrh */ 2772e6f85e71Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 2773e4e72072Sdrh pGroupBy ? 0 : &pOrderBy, p->pFetch); 27741d83f052Sdrh if( pWInfo==0 ) goto select_end; 2775cce7d176Sdrh 27762282792aSdrh /* Use the standard inner loop if we are not dealing with 27772282792aSdrh ** aggregates 2778cce7d176Sdrh */ 2779da9d6c45Sdrh if( !isAgg ){ 2780df199a25Sdrh if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 278184ac9d02Sdanielk1977 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ 27821d83f052Sdrh goto select_end; 2783cce7d176Sdrh } 2784da9d6c45Sdrh } 2785cce7d176Sdrh 2786e3184744Sdrh /* If we are dealing with aggregates, then do the special aggregate 27872282792aSdrh ** processing. 2788efb7251dSdrh */ 27892282792aSdrh else{ 2790268380caSdrh AggExpr *pAgg; 27912282792aSdrh if( pGroupBy ){ 27921bee3d7bSdrh int lbl1; 27932282792aSdrh for(i=0; i<pGroupBy->nExpr; i++){ 27944adee20fSdanielk1977 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr); 2795efb7251dSdrh } 2796ededfd5eSdanielk1977 /* No affinity string is attached to the following OP_MakeRecord 2797d3d39e93Sdrh ** because we do not need to do any coercion of datatypes. */ 2798ededfd5eSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, pGroupBy->nExpr, 0); 27994adee20fSdanielk1977 lbl1 = sqlite3VdbeMakeLabel(v); 28004adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1); 2801268380caSdrh for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){ 2802268380caSdrh if( pAgg->isAgg ) continue; 28034adee20fSdanielk1977 sqlite3ExprCode(pParse, pAgg->pExpr); 28044adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_AggSet, 0, i); 28052282792aSdrh } 28064adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, lbl1); 28072282792aSdrh } 2808268380caSdrh for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){ 28092282792aSdrh Expr *pE; 2810268380caSdrh int nExpr; 2811268380caSdrh FuncDef *pDef; 2812268380caSdrh if( !pAgg->isAgg ) continue; 2813268380caSdrh assert( pAgg->pFunc!=0 ); 2814268380caSdrh assert( pAgg->pFunc->xStep!=0 ); 2815268380caSdrh pDef = pAgg->pFunc; 2816268380caSdrh pE = pAgg->pExpr; 2817268380caSdrh assert( pE!=0 ); 28182282792aSdrh assert( pE->op==TK_AGG_FUNCTION ); 2819f9b596ebSdrh nExpr = sqlite3ExprCodeExprList(pParse, pE->pList); 28204adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, i, 0); 2821dc1bdc4fSdanielk1977 if( pDef->needCollSeq ){ 2822dc1bdc4fSdanielk1977 CollSeq *pColl = 0; 2823dc1bdc4fSdanielk1977 int j; 2824dc1bdc4fSdanielk1977 for(j=0; !pColl && j<nExpr; j++){ 2825dc1bdc4fSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, pE->pList->a[j].pExpr); 2826dc1bdc4fSdanielk1977 } 2827dc1bdc4fSdanielk1977 if( !pColl ) pColl = pParse->db->pDfltColl; 2828dc1bdc4fSdanielk1977 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); 2829dc1bdc4fSdanielk1977 } 28304adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER); 28312282792aSdrh } 28322282792aSdrh } 28332282792aSdrh 2834cce7d176Sdrh /* End the database scan loop. 2835cce7d176Sdrh */ 28364adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 2837cce7d176Sdrh 28382282792aSdrh /* If we are processing aggregates, we need to set up a second loop 28392282792aSdrh ** over all of the aggregate values and process them. 28402282792aSdrh */ 28412282792aSdrh if( isAgg ){ 28424adee20fSdanielk1977 int endagg = sqlite3VdbeMakeLabel(v); 28432282792aSdrh int startagg; 28444adee20fSdanielk1977 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg); 28452282792aSdrh pParse->useAgg = 1; 28462282792aSdrh if( pHaving ){ 28474adee20fSdanielk1977 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1); 28482282792aSdrh } 2849df199a25Sdrh if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 285084ac9d02Sdanielk1977 iParm, startagg, endagg, aff) ){ 28511d83f052Sdrh goto select_end; 28522282792aSdrh } 28534adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg); 28544adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endagg); 28554adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Noop, 0, 0); 28562282792aSdrh pParse->useAgg = 0; 28572282792aSdrh } 28582282792aSdrh 2859cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 2860cce7d176Sdrh ** and send them to the callback one by one. 2861cce7d176Sdrh */ 2862cce7d176Sdrh if( pOrderBy ){ 2863ffbc3088Sdrh generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); 2864cce7d176Sdrh } 28656a535340Sdrh 286693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 2867f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 2868f620b4e2Sdrh ** temporary table. So delete the subquery structure from the parent 2869f620b4e2Sdrh ** to prevent this subquery from being evaluated again and to force the 2870f620b4e2Sdrh ** the use of the temporary table. 2871f620b4e2Sdrh */ 2872f620b4e2Sdrh if( pParent ){ 2873f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 2874f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 28754adee20fSdanielk1977 sqlite3SelectDelete(p); 2876f620b4e2Sdrh pParent->pSrc->a[parentTab].pSelect = 0; 2877f620b4e2Sdrh } 287893758c8dSdanielk1977 #endif 2879f620b4e2Sdrh 28801d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 28811d83f052Sdrh ** to indicate no errors. 28821d83f052Sdrh */ 28831d83f052Sdrh rc = 0; 28841d83f052Sdrh 28851d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 28861d83f052Sdrh ** successful coding of the SELECT. 28871d83f052Sdrh */ 28881d83f052Sdrh select_end: 2889b3bce662Sdanielk1977 restoreAggregateInfo(pParse, &sAggInfo); 28901d83f052Sdrh return rc; 2891cce7d176Sdrh } 2892