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*7cf6e4deSdrh ** $Id: select.c,v 1.169 2004/05/19 14:56:56 drh Exp $ 16cce7d176Sdrh */ 17cce7d176Sdrh #include "sqliteInt.h" 18cce7d176Sdrh 19315555caSdrh 20cce7d176Sdrh /* 219bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 229bb61fe7Sdrh ** structure. 23cce7d176Sdrh */ 244adee20fSdanielk1977 Select *sqlite3SelectNew( 25daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 26ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 27daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 28daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 29daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 30daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 319bbca4c1Sdrh int isDistinct, /* true if the DISTINCT keyword is present */ 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; 8401f3f253Sdrh static struct { 8501f3f253Sdrh const char *zKeyword; 8601f3f253Sdrh int nChar; 8701f3f253Sdrh int 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 ){ 11901f3f253Sdrh static Token dummy = { 0, 0 }; 12001f3f253Sdrh char *zSp1 = " ", *zSp2 = " "; 12101f3f253Sdrh if( pB==0 ){ pB = &dummy; zSp1 = 0; } 12201f3f253Sdrh if( pC==0 ){ pC = &dummy; zSp2 = 0; } 1234adee20fSdanielk1977 sqlite3SetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0, 12401f3f253Sdrh pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0); 12501f3f253Sdrh pParse->nErr++; 12601f3f253Sdrh jointype = JT_INNER; 127195e6967Sdrh }else if( jointype & JT_RIGHT ){ 1284adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 129da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 130195e6967Sdrh jointype = JT_INNER; 13101f3f253Sdrh } 13201f3f253Sdrh return jointype; 13301f3f253Sdrh } 13401f3f253Sdrh 13501f3f253Sdrh /* 136ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 137ad2d8307Sdrh ** is not contained in the table. 138ad2d8307Sdrh */ 139ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 140ad2d8307Sdrh int i; 141ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 1424adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 143ad2d8307Sdrh } 144ad2d8307Sdrh return -1; 145ad2d8307Sdrh } 146ad2d8307Sdrh 147ad2d8307Sdrh /* 148ad2d8307Sdrh ** Add a term to the WHERE expression in *ppExpr that requires the 149ad2d8307Sdrh ** zCol column to be equal in the two tables pTab1 and pTab2. 150ad2d8307Sdrh */ 151ad2d8307Sdrh static void addWhereTerm( 152ad2d8307Sdrh const char *zCol, /* Name of the column */ 153ad2d8307Sdrh const Table *pTab1, /* First table */ 154ad2d8307Sdrh const Table *pTab2, /* Second table */ 155ad2d8307Sdrh Expr **ppExpr /* Add the equality term to this expression */ 156ad2d8307Sdrh ){ 157ad2d8307Sdrh Token dummy; 158ad2d8307Sdrh Expr *pE1a, *pE1b, *pE1c; 159ad2d8307Sdrh Expr *pE2a, *pE2b, *pE2c; 160ad2d8307Sdrh Expr *pE; 161ad2d8307Sdrh 162ad2d8307Sdrh dummy.z = zCol; 163ad2d8307Sdrh dummy.n = strlen(zCol); 1644b59ab5eSdrh dummy.dyn = 0; 1654adee20fSdanielk1977 pE1a = sqlite3Expr(TK_ID, 0, 0, &dummy); 1664adee20fSdanielk1977 pE2a = sqlite3Expr(TK_ID, 0, 0, &dummy); 167ad2d8307Sdrh dummy.z = pTab1->zName; 168ad2d8307Sdrh dummy.n = strlen(dummy.z); 1694adee20fSdanielk1977 pE1b = sqlite3Expr(TK_ID, 0, 0, &dummy); 170ad2d8307Sdrh dummy.z = pTab2->zName; 171ad2d8307Sdrh dummy.n = strlen(dummy.z); 1724adee20fSdanielk1977 pE2b = sqlite3Expr(TK_ID, 0, 0, &dummy); 1734adee20fSdanielk1977 pE1c = sqlite3Expr(TK_DOT, pE1b, pE1a, 0); 1744adee20fSdanielk1977 pE2c = sqlite3Expr(TK_DOT, pE2b, pE2a, 0); 1754adee20fSdanielk1977 pE = sqlite3Expr(TK_EQ, pE1c, pE2c, 0); 1761f16230bSdrh ExprSetProperty(pE, EP_FromJoin); 177ad2d8307Sdrh if( *ppExpr ){ 1784adee20fSdanielk1977 *ppExpr = sqlite3Expr(TK_AND, *ppExpr, pE, 0); 179ad2d8307Sdrh }else{ 180ad2d8307Sdrh *ppExpr = pE; 181ad2d8307Sdrh } 182ad2d8307Sdrh } 183ad2d8307Sdrh 184ad2d8307Sdrh /* 1851f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 1861cc093c2Sdrh ** 187e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 1881cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 1891f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 1901f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 1911f16230bSdrh ** WHERE clause during join processing but we need to remember that they 1921f16230bSdrh ** originated in the ON or USING clause. 1931cc093c2Sdrh */ 1941cc093c2Sdrh static void setJoinExpr(Expr *p){ 1951cc093c2Sdrh while( p ){ 1961f16230bSdrh ExprSetProperty(p, EP_FromJoin); 1971cc093c2Sdrh setJoinExpr(p->pLeft); 1981cc093c2Sdrh p = p->pRight; 1991cc093c2Sdrh } 2001cc093c2Sdrh } 2011cc093c2Sdrh 2021cc093c2Sdrh /* 203ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 204ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 205ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 206ad2d8307Sdrh ** 207ad2d8307Sdrh ** This routine returns the number of errors encountered. 208ad2d8307Sdrh */ 209ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 210ad2d8307Sdrh SrcList *pSrc; 211ad2d8307Sdrh int i, j; 212ad2d8307Sdrh pSrc = p->pSrc; 213ad2d8307Sdrh for(i=0; i<pSrc->nSrc-1; i++){ 214ad2d8307Sdrh struct SrcList_item *pTerm = &pSrc->a[i]; 215ad2d8307Sdrh struct SrcList_item *pOther = &pSrc->a[i+1]; 216ad2d8307Sdrh 217ad2d8307Sdrh if( pTerm->pTab==0 || pOther->pTab==0 ) continue; 218ad2d8307Sdrh 219ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 220ad2d8307Sdrh ** every column that the two tables have in common. 221ad2d8307Sdrh */ 222ad2d8307Sdrh if( pTerm->jointype & JT_NATURAL ){ 223ad2d8307Sdrh Table *pTab; 224ad2d8307Sdrh if( pTerm->pOn || pTerm->pUsing ){ 2254adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 226ad2d8307Sdrh "an ON or USING clause", 0); 227ad2d8307Sdrh return 1; 228ad2d8307Sdrh } 229ad2d8307Sdrh pTab = pTerm->pTab; 230ad2d8307Sdrh for(j=0; j<pTab->nCol; j++){ 231ad2d8307Sdrh if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){ 232ad2d8307Sdrh addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere); 233ad2d8307Sdrh } 234ad2d8307Sdrh } 235ad2d8307Sdrh } 236ad2d8307Sdrh 237ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 238ad2d8307Sdrh */ 239ad2d8307Sdrh if( pTerm->pOn && pTerm->pUsing ){ 2404adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 241da93d238Sdrh "clauses in the same join"); 242ad2d8307Sdrh return 1; 243ad2d8307Sdrh } 244ad2d8307Sdrh 245ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 246ad2d8307Sdrh ** and AND operator. 247ad2d8307Sdrh */ 248ad2d8307Sdrh if( pTerm->pOn ){ 2491cc093c2Sdrh setJoinExpr(pTerm->pOn); 250ad2d8307Sdrh if( p->pWhere==0 ){ 251ad2d8307Sdrh p->pWhere = pTerm->pOn; 252ad2d8307Sdrh }else{ 2534adee20fSdanielk1977 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pTerm->pOn, 0); 254ad2d8307Sdrh } 255ad2d8307Sdrh pTerm->pOn = 0; 256ad2d8307Sdrh } 257ad2d8307Sdrh 258ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 259ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 260ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 261ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 262ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 263ad2d8307Sdrh ** not contained in both tables to be joined. 264ad2d8307Sdrh */ 265ad2d8307Sdrh if( pTerm->pUsing ){ 266ad2d8307Sdrh IdList *pList; 267ad2d8307Sdrh int j; 268ad2d8307Sdrh assert( i<pSrc->nSrc-1 ); 269ad2d8307Sdrh pList = pTerm->pUsing; 270ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 271bf5cd97eSdrh if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 || 272bf5cd97eSdrh columnIndex(pOther->pTab, pList->a[j].zName)<0 ){ 2734adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 274da93d238Sdrh "not present in both tables", pList->a[j].zName); 275ad2d8307Sdrh return 1; 276ad2d8307Sdrh } 277bf5cd97eSdrh addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere); 278ad2d8307Sdrh } 279ad2d8307Sdrh } 280ad2d8307Sdrh } 281ad2d8307Sdrh return 0; 282ad2d8307Sdrh } 283ad2d8307Sdrh 284ad2d8307Sdrh /* 2859bb61fe7Sdrh ** Delete the given Select structure and all of its substructures. 2869bb61fe7Sdrh */ 2874adee20fSdanielk1977 void sqlite3SelectDelete(Select *p){ 28882c3d636Sdrh if( p==0 ) return; 2894adee20fSdanielk1977 sqlite3ExprListDelete(p->pEList); 2904adee20fSdanielk1977 sqlite3SrcListDelete(p->pSrc); 2914adee20fSdanielk1977 sqlite3ExprDelete(p->pWhere); 2924adee20fSdanielk1977 sqlite3ExprListDelete(p->pGroupBy); 2934adee20fSdanielk1977 sqlite3ExprDelete(p->pHaving); 2944adee20fSdanielk1977 sqlite3ExprListDelete(p->pOrderBy); 2954adee20fSdanielk1977 sqlite3SelectDelete(p->pPrior); 296a76b5dfcSdrh sqliteFree(p->zSelect); 2979bb61fe7Sdrh sqliteFree(p); 2989bb61fe7Sdrh } 2999bb61fe7Sdrh 3009bb61fe7Sdrh /* 3012282792aSdrh ** Delete the aggregate information from the parse structure. 3022282792aSdrh */ 3031d83f052Sdrh static void sqliteAggregateInfoReset(Parse *pParse){ 3042282792aSdrh sqliteFree(pParse->aAgg); 3052282792aSdrh pParse->aAgg = 0; 3062282792aSdrh pParse->nAgg = 0; 3072282792aSdrh pParse->useAgg = 0; 3082282792aSdrh } 3092282792aSdrh 3102282792aSdrh /* 311c926afbcSdrh ** Insert code into "v" that will push the record on the top of the 312c926afbcSdrh ** stack into the sorter. 313428702d7Sdrh ** 314428702d7Sdrh ** FIX ME: Change this so that it uses the OP_MakeKey opcode 315428702d7Sdrh ** instead of OP_SortMakeKey. Delete the OP_SortMakeKey opcode. 316428702d7Sdrh ** All columns should have affinity NONE. Handle ASC versus 317428702d7Sdrh ** DESC sort order by defining a list of comparison functions to 318428702d7Sdrh ** be used by the OP_Sort opcode. 319c926afbcSdrh */ 320c926afbcSdrh static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){ 321c926afbcSdrh char *zSortOrder; 322c926afbcSdrh int i; 323c926afbcSdrh zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 ); 324c926afbcSdrh if( zSortOrder==0 ) return; 325c926afbcSdrh for(i=0; i<pOrderBy->nExpr; i++){ 32638640e15Sdrh int order = pOrderBy->a[i].sortOrder; 32738640e15Sdrh int type; 32838640e15Sdrh int c; 32938640e15Sdrh if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){ 33038640e15Sdrh type = SQLITE_SO_TEXT; 33138640e15Sdrh }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){ 33238640e15Sdrh type = SQLITE_SO_NUM; 33338640e15Sdrh }else{ 33436a3c70bSdanielk1977 type = sqlite3ExprType(pOrderBy->a[i].pExpr); 33538640e15Sdrh } 33638640e15Sdrh if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){ 33738640e15Sdrh c = type==SQLITE_SO_TEXT ? 'A' : '+'; 33838640e15Sdrh }else{ 33938640e15Sdrh c = type==SQLITE_SO_TEXT ? 'D' : '-'; 34038640e15Sdrh } 34138640e15Sdrh zSortOrder[i] = c; 3424adee20fSdanielk1977 sqlite3ExprCode(pParse, pOrderBy->a[i].pExpr); 343c926afbcSdrh } 344c926afbcSdrh zSortOrder[pOrderBy->nExpr] = 0; 3454adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC); 3464adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_SortPut, 0, 0); 347c926afbcSdrh } 348c926afbcSdrh 349c926afbcSdrh /* 35038640e15Sdrh ** This routine adds a P3 argument to the last VDBE opcode that was 35138640e15Sdrh ** inserted. The P3 argument added is a string suitable for the 35238640e15Sdrh ** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of 35338640e15Sdrh ** characters 't' or 'n' depending on whether or not the various 35438640e15Sdrh ** fields of the key to be generated should be treated as numeric 35538640e15Sdrh ** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode 35638640e15Sdrh ** documentation for additional information about the P3 string. 3574adee20fSdanielk1977 ** See also the sqlite3AddIdxKeyType() routine. 35838640e15Sdrh */ 3594adee20fSdanielk1977 void sqlite3AddKeyType(Vdbe *v, ExprList *pEList){ 36038640e15Sdrh int nColumn = pEList->nExpr; 36138640e15Sdrh char *zType = sqliteMalloc( nColumn+1 ); 36238640e15Sdrh int i; 36338640e15Sdrh if( zType==0 ) return; 36438640e15Sdrh for(i=0; i<nColumn; i++){ 3654adee20fSdanielk1977 zType[i] = sqlite3ExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't'; 36638640e15Sdrh } 36738640e15Sdrh zType[i] = 0; 3684adee20fSdanielk1977 sqlite3VdbeChangeP3(v, -1, zType, P3_DYNAMIC); 36938640e15Sdrh } 37038640e15Sdrh 37138640e15Sdrh /* 3722282792aSdrh ** This routine generates the code for the inside of the inner loop 3732282792aSdrh ** of a SELECT. 37482c3d636Sdrh ** 37538640e15Sdrh ** If srcTab and nColumn are both zero, then the pEList expressions 37638640e15Sdrh ** are evaluated in order to get the data for this row. If nColumn>0 37738640e15Sdrh ** then data is pulled from srcTab and pEList is used only to get the 37838640e15Sdrh ** datatypes for each column. 3792282792aSdrh */ 3802282792aSdrh static int selectInnerLoop( 3812282792aSdrh Parse *pParse, /* The parser context */ 382df199a25Sdrh Select *p, /* The complete select statement being coded */ 3832282792aSdrh ExprList *pEList, /* List of values being extracted */ 38482c3d636Sdrh int srcTab, /* Pull data from this table */ 385967e8b73Sdrh int nColumn, /* Number of columns in the source table */ 3862282792aSdrh ExprList *pOrderBy, /* If not NULL, sort results using this key */ 3872282792aSdrh int distinct, /* If >=0, make sure results are distinct */ 3882282792aSdrh int eDest, /* How to dispose of the results */ 3892282792aSdrh int iParm, /* An argument to the disposal method */ 3902282792aSdrh int iContinue, /* Jump here to continue with next row */ 39184ac9d02Sdanielk1977 int iBreak, /* Jump here to break out of the inner loop */ 39284ac9d02Sdanielk1977 char *aff /* affinity string if eDest is SRT_Union */ 3932282792aSdrh ){ 3942282792aSdrh Vdbe *v = pParse->pVdbe; 3952282792aSdrh int i; 39638640e15Sdrh 397daffd0e5Sdrh if( v==0 ) return 0; 39838640e15Sdrh assert( pEList!=0 ); 3992282792aSdrh 400df199a25Sdrh /* If there was a LIMIT clause on the SELECT statement, then do the check 401df199a25Sdrh ** to see if this row should be output. 402df199a25Sdrh */ 403df199a25Sdrh if( pOrderBy==0 ){ 4047b58daeaSdrh if( p->iOffset>=0 ){ 4054adee20fSdanielk1977 int addr = sqlite3VdbeCurrentAddr(v); 4064adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+2); 4074adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); 408df199a25Sdrh } 4097b58daeaSdrh if( p->iLimit>=0 ){ 4104adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak); 411df199a25Sdrh } 412df199a25Sdrh } 413df199a25Sdrh 414967e8b73Sdrh /* Pull the requested columns. 4152282792aSdrh */ 41638640e15Sdrh if( nColumn>0 ){ 417967e8b73Sdrh for(i=0; i<nColumn; i++){ 4184adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, srcTab, i); 41982c3d636Sdrh } 42038640e15Sdrh }else{ 42138640e15Sdrh nColumn = pEList->nExpr; 42238640e15Sdrh for(i=0; i<pEList->nExpr; i++){ 4234adee20fSdanielk1977 sqlite3ExprCode(pParse, pEList->a[i].pExpr); 42438640e15Sdrh } 42582c3d636Sdrh } 4262282792aSdrh 427daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 428daffd0e5Sdrh ** and this row has been seen before, then do not make this row 429daffd0e5Sdrh ** part of the result. 4302282792aSdrh */ 431f5905aa7Sdrh if( distinct>=0 && pEList && pEList->nExpr>0 ){ 4320bd1f4eaSdrh #if NULL_ALWAYS_DISTINCT 4334adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqlite3VdbeCurrentAddr(v)+7); 4340bd1f4eaSdrh #endif 4354adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1); 43636a3c70bSdanielk1977 sqlite3AddKeyType(v, pEList); 4374adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Distinct, distinct, sqlite3VdbeCurrentAddr(v)+3); 4384adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0); 4394adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); 4404adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_String, 0, 0); 4414adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, distinct, 0); 4422282792aSdrh } 44382c3d636Sdrh 444c926afbcSdrh switch( eDest ){ 44582c3d636Sdrh /* In this mode, write each query result to the key of the temporary 44682c3d636Sdrh ** table iParm. 4472282792aSdrh */ 448c926afbcSdrh case SRT_Union: { 4494adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 45084ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 4514adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_String, 0, 0); 4524adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, iParm, 0); 453c926afbcSdrh break; 454c926afbcSdrh } 45582c3d636Sdrh 4565974a30fSdrh /* Store the result as data using a unique key. 4575974a30fSdrh */ 458c926afbcSdrh case SRT_Table: 459c926afbcSdrh case SRT_TempTable: { 4604adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 461c926afbcSdrh if( pOrderBy ){ 462c926afbcSdrh pushOntoSorter(pParse, v, pOrderBy); 463c926afbcSdrh }else{ 4644adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0); 4654adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 4664adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0); 467c926afbcSdrh } 468c926afbcSdrh break; 469c926afbcSdrh } 4705974a30fSdrh 47182c3d636Sdrh /* Construct a record from the query result, but instead of 47282c3d636Sdrh ** saving that record, use it as a key to delete elements from 47382c3d636Sdrh ** the temporary table iParm. 47482c3d636Sdrh */ 475c926afbcSdrh case SRT_Except: { 4760bd1f4eaSdrh int addr; 4774adee20fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT); 47884ac9d02Sdanielk1977 sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); 4794adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3); 4804adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Delete, iParm, 0); 481c926afbcSdrh break; 482c926afbcSdrh } 4832282792aSdrh 4842282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 4852282792aSdrh ** then there should be a single item on the stack. Write this 4862282792aSdrh ** item into the set table with bogus data. 4872282792aSdrh */ 488c926afbcSdrh case SRT_Set: { 4894adee20fSdanielk1977 int addr1 = sqlite3VdbeCurrentAddr(v); 49052b36cabSdrh int addr2; 491e014a838Sdanielk1977 492967e8b73Sdrh assert( nColumn==1 ); 4934adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3); 4944adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 4954adee20fSdanielk1977 addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); 496c926afbcSdrh if( pOrderBy ){ 497c926afbcSdrh pushOntoSorter(pParse, v, pOrderBy); 498c926afbcSdrh }else{ 499e014a838Sdanielk1977 char const *affStr; 500e014a838Sdanielk1977 char aff = (iParm>>16)&0xFF; 501e014a838Sdanielk1977 aff = sqlite3CompareAffinity(pEList->a[0].pExpr, aff); 502e014a838Sdanielk1977 affStr = sqlite3AffinityString(aff); 50384ac9d02Sdanielk1977 sqlite3VdbeOp3(v, OP_MakeKey, 1, 0, affStr, P3_STATIC); 5044adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_String, 0, 0); 505e014a838Sdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0); 506c926afbcSdrh } 5074adee20fSdanielk1977 sqlite3VdbeChangeP2(v, addr2, sqlite3VdbeCurrentAddr(v)); 508c926afbcSdrh break; 509c926afbcSdrh } 51082c3d636Sdrh 5112282792aSdrh /* If this is a scalar select that is part of an expression, then 5122282792aSdrh ** store the results in the appropriate memory cell and break out 5132282792aSdrh ** of the scan loop. 5142282792aSdrh */ 515c926afbcSdrh case SRT_Mem: { 516967e8b73Sdrh assert( nColumn==1 ); 517c926afbcSdrh if( pOrderBy ){ 518c926afbcSdrh pushOntoSorter(pParse, v, pOrderBy); 519c926afbcSdrh }else{ 5204adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 5214adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, iBreak); 522c926afbcSdrh } 523c926afbcSdrh break; 524c926afbcSdrh } 5252282792aSdrh 526f46f905aSdrh /* Send the data to the callback function. 527f46f905aSdrh */ 528f46f905aSdrh case SRT_Callback: 529f46f905aSdrh case SRT_Sorter: { 530f46f905aSdrh if( pOrderBy ){ 5314adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_SortMakeRec, nColumn, 0); 532f46f905aSdrh pushOntoSorter(pParse, v, pOrderBy); 533f46f905aSdrh }else{ 534f46f905aSdrh assert( eDest==SRT_Callback ); 5354adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); 536f46f905aSdrh } 537f46f905aSdrh break; 538f46f905aSdrh } 539f46f905aSdrh 540142e30dfSdrh /* Invoke a subroutine to handle the results. The subroutine itself 541142e30dfSdrh ** is responsible for popping the results off of the stack. 542142e30dfSdrh */ 543142e30dfSdrh case SRT_Subroutine: { 544ac82fcf5Sdrh if( pOrderBy ){ 5454adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); 546ac82fcf5Sdrh pushOntoSorter(pParse, v, pOrderBy); 547ac82fcf5Sdrh }else{ 5484adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 549ac82fcf5Sdrh } 550142e30dfSdrh break; 551142e30dfSdrh } 552142e30dfSdrh 553d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 554d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 555d7489c39Sdrh ** user-defined functions that have side effects. We do not care 556d7489c39Sdrh ** about the actual results of the select. 557d7489c39Sdrh */ 558c926afbcSdrh default: { 559f46f905aSdrh assert( eDest==SRT_Discard ); 5604adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); 561c926afbcSdrh break; 562c926afbcSdrh } 563c926afbcSdrh } 56482c3d636Sdrh return 0; 56582c3d636Sdrh } 56682c3d636Sdrh 56782c3d636Sdrh /* 568d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 569d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 570d8bc7086Sdrh ** we need to run the sorter and output the results. The following 571d8bc7086Sdrh ** routine generates the code needed to do that. 572d8bc7086Sdrh */ 573c926afbcSdrh static void generateSortTail( 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; 583f46f905aSdrh if( eDest==SRT_Sorter ) return; 5844adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Sort, 0, 0); 5854adee20fSdanielk1977 addr = sqlite3VdbeAddOp(v, OP_SortNext, 0, end1); 5867b58daeaSdrh if( p->iOffset>=0 ){ 5874adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemIncr, p->iOffset, addr+4); 5884adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 5894adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, addr); 590df199a25Sdrh } 5917b58daeaSdrh if( p->iLimit>=0 ){ 5924adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemIncr, p->iLimit, end2); 593df199a25Sdrh } 594c926afbcSdrh switch( eDest ){ 595c926afbcSdrh case SRT_Callback: { 5964adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_SortCallback, nColumn, 0); 597c926afbcSdrh break; 598c926afbcSdrh } 599c926afbcSdrh case SRT_Table: 600c926afbcSdrh case SRT_TempTable: { 6014adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NewRecno, iParm, 0); 6024adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 6034adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_PutIntKey, iParm, 0); 604c926afbcSdrh break; 605c926afbcSdrh } 606c926afbcSdrh case SRT_Set: { 607c926afbcSdrh assert( nColumn==1 ); 6084adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); 6094adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 6104adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); 611e014a838Sdanielk1977 sqlite3VdbeOp3(v, OP_MakeKey, 1, 1, "n", P3_STATIC); 6124adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_String, 0, 0); 613e014a838Sdanielk1977 sqlite3VdbeAddOp(v, OP_PutStrKey, (iParm&0x0000FFFF), 0); 614c926afbcSdrh break; 615c926afbcSdrh } 616c926afbcSdrh case SRT_Mem: { 617c926afbcSdrh assert( nColumn==1 ); 6184adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 6194adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, end1); 620c926afbcSdrh break; 621c926afbcSdrh } 622ac82fcf5Sdrh case SRT_Subroutine: { 623ac82fcf5Sdrh int i; 62484ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, p->pEList->nExpr, 0); 62584ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 626ac82fcf5Sdrh for(i=0; i<nColumn; i++){ 6274adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Column, -1-i, i); 628ac82fcf5Sdrh } 6294adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); 63084ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 2, 0); 631ac82fcf5Sdrh break; 632ac82fcf5Sdrh } 633c926afbcSdrh default: { 634f46f905aSdrh /* Do nothing */ 635c926afbcSdrh break; 636c926afbcSdrh } 637c926afbcSdrh } 6384adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, addr); 6394adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, end2); 6404adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 6414adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, end1); 6424adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_SortReset, 0, 0); 643d8bc7086Sdrh } 644d8bc7086Sdrh 645d8bc7086Sdrh /* 646fcb78a49Sdrh ** Generate code that will tell the VDBE the datatypes of 647fcb78a49Sdrh ** columns in the result set. 648e78e8284Sdrh ** 649e78e8284Sdrh ** This routine only generates code if the "PRAGMA show_datatypes=on" 650e78e8284Sdrh ** has been executed. The datatypes are reported out in the azCol 651e78e8284Sdrh ** parameter to the callback function. The first N azCol[] entries 652e78e8284Sdrh ** are the names of the columns, and the second N entries are the 653e78e8284Sdrh ** datatypes for the columns. 654e78e8284Sdrh ** 655e78e8284Sdrh ** The "datatype" for a result that is a column of a type is the 656e78e8284Sdrh ** datatype definition extracted from the CREATE TABLE statement. 657e78e8284Sdrh ** The datatype for an expression is either TEXT or NUMERIC. The 658e78e8284Sdrh ** datatype for a ROWID field is INTEGER. 659fcb78a49Sdrh */ 660fcb78a49Sdrh static void generateColumnTypes( 661fcb78a49Sdrh Parse *pParse, /* Parser context */ 662fcb78a49Sdrh SrcList *pTabList, /* List of tables */ 663fcb78a49Sdrh ExprList *pEList /* Expressions defining the result set */ 664fcb78a49Sdrh ){ 665fcb78a49Sdrh Vdbe *v = pParse->pVdbe; 6666a3ea0e6Sdrh int i, j; 667fcb78a49Sdrh for(i=0; i<pEList->nExpr; i++){ 668fcb78a49Sdrh Expr *p = pEList->a[i].pExpr; 669fcb78a49Sdrh char *zType = 0; 670fcb78a49Sdrh if( p==0 ) continue; 671fcb78a49Sdrh if( p->op==TK_COLUMN && pTabList ){ 6726a3ea0e6Sdrh Table *pTab; 673fcb78a49Sdrh int iCol = p->iColumn; 6746a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 6756a3ea0e6Sdrh assert( j<pTabList->nSrc ); 6766a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 677fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 678fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 679fcb78a49Sdrh if( iCol<0 ){ 680fcb78a49Sdrh zType = "INTEGER"; 681fcb78a49Sdrh }else{ 682fcb78a49Sdrh zType = pTab->aCol[iCol].zType; 683fcb78a49Sdrh } 684fcb78a49Sdrh }else{ 6854adee20fSdanielk1977 if( sqlite3ExprType(p)==SQLITE_SO_TEXT ){ 686fcb78a49Sdrh zType = "TEXT"; 687fcb78a49Sdrh }else{ 688fcb78a49Sdrh zType = "NUMERIC"; 689fcb78a49Sdrh } 690fcb78a49Sdrh } 6914adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0); 692fcb78a49Sdrh } 693fcb78a49Sdrh } 694fcb78a49Sdrh 695fcb78a49Sdrh /* 696fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 697fcb78a49Sdrh ** in the result set. This information is used to provide the 698fcabd464Sdrh ** azCol[] values in the callback. 69982c3d636Sdrh */ 700832508b7Sdrh static void generateColumnNames( 701832508b7Sdrh Parse *pParse, /* Parser context */ 702ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 703832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 704832508b7Sdrh ){ 705d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 7066a3ea0e6Sdrh int i, j; 707fcabd464Sdrh sqlite *db = pParse->db; 708fcabd464Sdrh int fullNames, shortNames; 709fcabd464Sdrh 710d6502758Sdrh assert( v!=0 ); 7116f8a503dSdanielk1977 if( pParse->colNamesSet || v==0 || sqlite3_malloc_failed ) return; 712d8bc7086Sdrh pParse->colNamesSet = 1; 713fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 714fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 71582c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 71682c3d636Sdrh Expr *p; 717d6502758Sdrh int p2 = i==pEList->nExpr-1; 7185a38705eSdrh p = pEList->a[i].pExpr; 7195a38705eSdrh if( p==0 ) continue; 72082c3d636Sdrh if( pEList->a[i].zName ){ 72182c3d636Sdrh char *zName = pEList->a[i].zName; 7224adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0); 72382c3d636Sdrh continue; 72482c3d636Sdrh } 725fa173a76Sdrh if( p->op==TK_COLUMN && pTabList ){ 7266a3ea0e6Sdrh Table *pTab; 72797665873Sdrh char *zCol; 7288aff1015Sdrh int iCol = p->iColumn; 7296a3ea0e6Sdrh for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){} 7306a3ea0e6Sdrh assert( j<pTabList->nSrc ); 7316a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 7328aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 73397665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 734b1363206Sdrh if( iCol<0 ){ 735b1363206Sdrh zCol = "_ROWID_"; 736b1363206Sdrh }else{ 737b1363206Sdrh zCol = pTab->aCol[iCol].zName; 738b1363206Sdrh } 739fcabd464Sdrh if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ 7404adee20fSdanielk1977 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n); 7414adee20fSdanielk1977 sqlite3VdbeCompressSpace(v, addr); 742fcabd464Sdrh }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ 74382c3d636Sdrh char *zName = 0; 74482c3d636Sdrh char *zTab; 74582c3d636Sdrh 7466a3ea0e6Sdrh zTab = pTabList->a[j].zAlias; 747fcabd464Sdrh if( fullNames || zTab==0 ) zTab = pTab->zName; 7484adee20fSdanielk1977 sqlite3SetString(&zName, zTab, ".", zCol, 0); 7494adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC); 75082c3d636Sdrh }else{ 7514adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zCol, 0); 75282c3d636Sdrh } 7536977fea8Sdrh }else if( p->span.z && p->span.z[0] ){ 7544adee20fSdanielk1977 int addr = sqlite3VdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n); 7554adee20fSdanielk1977 sqlite3VdbeCompressSpace(v, addr); 7561bee3d7bSdrh }else{ 7571bee3d7bSdrh char zName[30]; 7581bee3d7bSdrh assert( p->op!=TK_COLUMN || pTabList==0 ); 7591bee3d7bSdrh sprintf(zName, "column%d", i+1); 7604adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_ColumnName, i, p2, zName, 0); 76182c3d636Sdrh } 76282c3d636Sdrh } 7635080aaa7Sdrh } 76482c3d636Sdrh 76582c3d636Sdrh /* 766d8bc7086Sdrh ** Name of the connection operator, used for error messages. 767d8bc7086Sdrh */ 768d8bc7086Sdrh static const char *selectOpName(int id){ 769d8bc7086Sdrh char *z; 770d8bc7086Sdrh switch( id ){ 771d8bc7086Sdrh case TK_ALL: z = "UNION ALL"; break; 772d8bc7086Sdrh case TK_INTERSECT: z = "INTERSECT"; break; 773d8bc7086Sdrh case TK_EXCEPT: z = "EXCEPT"; break; 774d8bc7086Sdrh default: z = "UNION"; break; 775d8bc7086Sdrh } 776d8bc7086Sdrh return z; 777d8bc7086Sdrh } 778d8bc7086Sdrh 779d8bc7086Sdrh /* 780315555caSdrh ** Forward declaration 781315555caSdrh */ 782315555caSdrh static int fillInColumnList(Parse*, Select*); 783315555caSdrh 784315555caSdrh /* 78522f70c32Sdrh ** Given a SELECT statement, generate a Table structure that describes 78622f70c32Sdrh ** the result set of that SELECT. 78722f70c32Sdrh */ 7884adee20fSdanielk1977 Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ 78922f70c32Sdrh Table *pTab; 790b733d037Sdrh int i, j; 79122f70c32Sdrh ExprList *pEList; 792b733d037Sdrh Column *aCol; 79322f70c32Sdrh 79422f70c32Sdrh if( fillInColumnList(pParse, pSelect) ){ 79522f70c32Sdrh return 0; 79622f70c32Sdrh } 79722f70c32Sdrh pTab = sqliteMalloc( sizeof(Table) ); 79822f70c32Sdrh if( pTab==0 ){ 79922f70c32Sdrh return 0; 80022f70c32Sdrh } 80122f70c32Sdrh pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0; 80222f70c32Sdrh pEList = pSelect->pEList; 80322f70c32Sdrh pTab->nCol = pEList->nExpr; 804417be79cSdrh assert( pTab->nCol>0 ); 805b733d037Sdrh pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol ); 80622f70c32Sdrh for(i=0; i<pTab->nCol; i++){ 807b733d037Sdrh Expr *p, *pR; 80822f70c32Sdrh if( pEList->a[i].zName ){ 809b733d037Sdrh aCol[i].zName = sqliteStrDup(pEList->a[i].zName); 810b733d037Sdrh }else if( (p=pEList->a[i].pExpr)->op==TK_DOT 811b733d037Sdrh && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ 812b733d037Sdrh int cnt; 8134adee20fSdanielk1977 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0); 814b733d037Sdrh for(j=cnt=0; j<i; j++){ 8154adee20fSdanielk1977 if( sqlite3StrICmp(aCol[j].zName, aCol[i].zName)==0 ){ 816b733d037Sdrh int n; 817b733d037Sdrh char zBuf[30]; 818b733d037Sdrh sprintf(zBuf,"_%d",++cnt); 819b733d037Sdrh n = strlen(zBuf); 8204adee20fSdanielk1977 sqlite3SetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf,n,0); 821b733d037Sdrh j = -1; 822b733d037Sdrh } 823b733d037Sdrh } 824b733d037Sdrh }else if( p->span.z && p->span.z[0] ){ 8254adee20fSdanielk1977 sqlite3SetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0); 82622f70c32Sdrh }else{ 82722f70c32Sdrh char zBuf[30]; 82822f70c32Sdrh sprintf(zBuf, "column%d", i+1); 82922f70c32Sdrh pTab->aCol[i].zName = sqliteStrDup(zBuf); 83022f70c32Sdrh } 831e014a838Sdanielk1977 832e014a838Sdanielk1977 /* Affinity is always NONE, as there is no type name. */ 833e014a838Sdanielk1977 pTab->aCol[i].affinity = SQLITE_AFF_NONE; 83422f70c32Sdrh } 83522f70c32Sdrh pTab->iPKey = -1; 83622f70c32Sdrh return pTab; 83722f70c32Sdrh } 83822f70c32Sdrh 83922f70c32Sdrh /* 840ad2d8307Sdrh ** For the given SELECT statement, do three things. 841d8bc7086Sdrh ** 842ad3cab52Sdrh ** (1) Fill in the pTabList->a[].pTab fields in the SrcList that 84363eb5f29Sdrh ** defines the set of tables that should be scanned. For views, 84463eb5f29Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 84563eb5f29Sdrh ** that implements the view. A copy is made of the view's SELECT 84663eb5f29Sdrh ** statement so that we can freely modify or delete that statement 84763eb5f29Sdrh ** without worrying about messing up the presistent representation 84863eb5f29Sdrh ** of the view. 849d8bc7086Sdrh ** 850ad2d8307Sdrh ** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword 851ad2d8307Sdrh ** on joins and the ON and USING clause of joins. 852ad2d8307Sdrh ** 853ad2d8307Sdrh ** (3) Scan the list of columns in the result set (pEList) looking 85454473229Sdrh ** for instances of the "*" operator or the TABLE.* operator. 85554473229Sdrh ** If found, expand each "*" to be every column in every table 85654473229Sdrh ** and TABLE.* to be every column in TABLE. 857d8bc7086Sdrh ** 858d8bc7086Sdrh ** Return 0 on success. If there are problems, leave an error message 859d8bc7086Sdrh ** in pParse and return non-zero. 860d8bc7086Sdrh */ 861d8bc7086Sdrh static int fillInColumnList(Parse *pParse, Select *p){ 86254473229Sdrh int i, j, k, rc; 863ad3cab52Sdrh SrcList *pTabList; 864daffd0e5Sdrh ExprList *pEList; 865a76b5dfcSdrh Table *pTab; 866daffd0e5Sdrh 867daffd0e5Sdrh if( p==0 || p->pSrc==0 ) return 1; 868daffd0e5Sdrh pTabList = p->pSrc; 869daffd0e5Sdrh pEList = p->pEList; 870d8bc7086Sdrh 871d8bc7086Sdrh /* Look up every table in the table list. 872d8bc7086Sdrh */ 873ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 874d8bc7086Sdrh if( pTabList->a[i].pTab ){ 875d8bc7086Sdrh /* This routine has run before! No need to continue */ 876d8bc7086Sdrh return 0; 877d8bc7086Sdrh } 878daffd0e5Sdrh if( pTabList->a[i].zName==0 ){ 87922f70c32Sdrh /* A sub-query in the FROM clause of a SELECT */ 88022f70c32Sdrh assert( pTabList->a[i].pSelect!=0 ); 881ad2d8307Sdrh if( pTabList->a[i].zAlias==0 ){ 882ad2d8307Sdrh char zFakeName[60]; 883ad2d8307Sdrh sprintf(zFakeName, "sqlite_subquery_%p_", 884ad2d8307Sdrh (void*)pTabList->a[i].pSelect); 8854adee20fSdanielk1977 sqlite3SetString(&pTabList->a[i].zAlias, zFakeName, 0); 886ad2d8307Sdrh } 88722f70c32Sdrh pTabList->a[i].pTab = pTab = 8884adee20fSdanielk1977 sqlite3ResultSetOfSelect(pParse, pTabList->a[i].zAlias, 88922f70c32Sdrh pTabList->a[i].pSelect); 89022f70c32Sdrh if( pTab==0 ){ 891daffd0e5Sdrh return 1; 892daffd0e5Sdrh } 8935cf590c1Sdrh /* The isTransient flag indicates that the Table structure has been 8945cf590c1Sdrh ** dynamically allocated and may be freed at any time. In other words, 8955cf590c1Sdrh ** pTab is not pointing to a persistent table structure that defines 8965cf590c1Sdrh ** part of the schema. */ 89722f70c32Sdrh pTab->isTransient = 1; 89822f70c32Sdrh }else{ 899a76b5dfcSdrh /* An ordinary table or view name in the FROM clause */ 900a76b5dfcSdrh pTabList->a[i].pTab = pTab = 9014adee20fSdanielk1977 sqlite3LocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase); 902a76b5dfcSdrh if( pTab==0 ){ 903d8bc7086Sdrh return 1; 904d8bc7086Sdrh } 905a76b5dfcSdrh if( pTab->pSelect ){ 90663eb5f29Sdrh /* We reach here if the named table is a really a view */ 9074adee20fSdanielk1977 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 908417be79cSdrh return 1; 909417be79cSdrh } 91063eb5f29Sdrh /* If pTabList->a[i].pSelect!=0 it means we are dealing with a 91163eb5f29Sdrh ** view within a view. The SELECT structure has already been 91263eb5f29Sdrh ** copied by the outer view so we can skip the copy step here 91363eb5f29Sdrh ** in the inner view. 91463eb5f29Sdrh */ 91563eb5f29Sdrh if( pTabList->a[i].pSelect==0 ){ 9164adee20fSdanielk1977 pTabList->a[i].pSelect = sqlite3SelectDup(pTab->pSelect); 917a76b5dfcSdrh } 918d8bc7086Sdrh } 91922f70c32Sdrh } 92063eb5f29Sdrh } 921d8bc7086Sdrh 922ad2d8307Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 923ad2d8307Sdrh */ 924ad2d8307Sdrh if( sqliteProcessJoin(pParse, p) ) return 1; 925ad2d8307Sdrh 9267c917d19Sdrh /* For every "*" that occurs in the column list, insert the names of 92754473229Sdrh ** all columns in all tables. And for every TABLE.* insert the names 92854473229Sdrh ** of all columns in TABLE. The parser inserted a special expression 9297c917d19Sdrh ** with the TK_ALL operator for each "*" that it found in the column list. 9307c917d19Sdrh ** The following code just has to locate the TK_ALL expressions and expand 9317c917d19Sdrh ** each one to the list of all columns in all tables. 93254473229Sdrh ** 93354473229Sdrh ** The first loop just checks to see if there are any "*" operators 93454473229Sdrh ** that need expanding. 935d8bc7086Sdrh */ 9367c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 93754473229Sdrh Expr *pE = pEList->a[k].pExpr; 93854473229Sdrh if( pE->op==TK_ALL ) break; 93954473229Sdrh if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL 94054473229Sdrh && pE->pLeft && pE->pLeft->op==TK_ID ) break; 9417c917d19Sdrh } 94254473229Sdrh rc = 0; 9437c917d19Sdrh if( k<pEList->nExpr ){ 94454473229Sdrh /* 94554473229Sdrh ** If we get here it means the result set contains one or more "*" 94654473229Sdrh ** operators that need to be expanded. Loop through each expression 94754473229Sdrh ** in the result set and expand them one by one. 94854473229Sdrh */ 9497c917d19Sdrh struct ExprList_item *a = pEList->a; 9507c917d19Sdrh ExprList *pNew = 0; 9517c917d19Sdrh for(k=0; k<pEList->nExpr; k++){ 95254473229Sdrh Expr *pE = a[k].pExpr; 95354473229Sdrh if( pE->op!=TK_ALL && 95454473229Sdrh (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){ 95554473229Sdrh /* This particular expression does not need to be expanded. 95654473229Sdrh */ 9574adee20fSdanielk1977 pNew = sqlite3ExprListAppend(pNew, a[k].pExpr, 0); 9587c917d19Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 9597c917d19Sdrh a[k].pExpr = 0; 9607c917d19Sdrh a[k].zName = 0; 9617c917d19Sdrh }else{ 96254473229Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 96354473229Sdrh ** expanded. */ 96454473229Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 96554473229Sdrh Token *pName; /* text of name of TABLE */ 96654473229Sdrh if( pE->op==TK_DOT && pE->pLeft ){ 96754473229Sdrh pName = &pE->pLeft->token; 96854473229Sdrh }else{ 96954473229Sdrh pName = 0; 97054473229Sdrh } 971ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 972d8bc7086Sdrh Table *pTab = pTabList->a[i].pTab; 97354473229Sdrh char *zTabName = pTabList->a[i].zAlias; 97454473229Sdrh if( zTabName==0 || zTabName[0]==0 ){ 97554473229Sdrh zTabName = pTab->zName; 97654473229Sdrh } 97754473229Sdrh if( pName && (zTabName==0 || zTabName[0]==0 || 9784adee20fSdanielk1977 sqlite3StrNICmp(pName->z, zTabName, pName->n)!=0 || 979c754fa54Sdrh zTabName[pName->n]!=0) ){ 98054473229Sdrh continue; 98154473229Sdrh } 98254473229Sdrh tableSeen = 1; 983d8bc7086Sdrh for(j=0; j<pTab->nCol; j++){ 98422f70c32Sdrh Expr *pExpr, *pLeft, *pRight; 985ad2d8307Sdrh char *zName = pTab->aCol[j].zName; 986ad2d8307Sdrh 987ad2d8307Sdrh if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 && 988ad2d8307Sdrh columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){ 989ad2d8307Sdrh /* In a NATURAL join, omit the join columns from the 990ad2d8307Sdrh ** table on the right */ 991ad2d8307Sdrh continue; 992ad2d8307Sdrh } 9934adee20fSdanielk1977 if( i>0 && sqlite3IdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){ 994ad2d8307Sdrh /* In a join with a USING clause, omit columns in the 995ad2d8307Sdrh ** using clause from the table on the right. */ 996ad2d8307Sdrh continue; 997ad2d8307Sdrh } 9984adee20fSdanielk1977 pRight = sqlite3Expr(TK_ID, 0, 0, 0); 99922f70c32Sdrh if( pRight==0 ) break; 1000ad2d8307Sdrh pRight->token.z = zName; 1001ad2d8307Sdrh pRight->token.n = strlen(zName); 10024b59ab5eSdrh pRight->token.dyn = 0; 10034b59ab5eSdrh if( zTabName && pTabList->nSrc>1 ){ 10044adee20fSdanielk1977 pLeft = sqlite3Expr(TK_ID, 0, 0, 0); 10054adee20fSdanielk1977 pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0); 100622f70c32Sdrh if( pExpr==0 ) break; 10074b59ab5eSdrh pLeft->token.z = zTabName; 10084b59ab5eSdrh pLeft->token.n = strlen(zTabName); 10094b59ab5eSdrh pLeft->token.dyn = 0; 10104adee20fSdanielk1977 sqlite3SetString((char**)&pExpr->span.z, zTabName, ".", zName, 0); 10116977fea8Sdrh pExpr->span.n = strlen(pExpr->span.z); 10126977fea8Sdrh pExpr->span.dyn = 1; 10136977fea8Sdrh pExpr->token.z = 0; 10146977fea8Sdrh pExpr->token.n = 0; 10156977fea8Sdrh pExpr->token.dyn = 0; 101622f70c32Sdrh }else{ 101722f70c32Sdrh pExpr = pRight; 10186977fea8Sdrh pExpr->span = pExpr->token; 101922f70c32Sdrh } 10204adee20fSdanielk1977 pNew = sqlite3ExprListAppend(pNew, pExpr, 0); 1021d8bc7086Sdrh } 1022d8bc7086Sdrh } 102354473229Sdrh if( !tableSeen ){ 1024f5db2d3eSdrh if( pName ){ 10254adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no such table: %T", pName); 1026f5db2d3eSdrh }else{ 10274adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "no tables specified"); 1028f5db2d3eSdrh } 102954473229Sdrh rc = 1; 103054473229Sdrh } 10317c917d19Sdrh } 10327c917d19Sdrh } 10334adee20fSdanielk1977 sqlite3ExprListDelete(pEList); 10347c917d19Sdrh p->pEList = pNew; 1035d8bc7086Sdrh } 103654473229Sdrh return rc; 1037d8bc7086Sdrh } 1038d8bc7086Sdrh 1039d8bc7086Sdrh /* 1040ff78bd2fSdrh ** This routine recursively unlinks the Select.pSrc.a[].pTab pointers 1041ff78bd2fSdrh ** in a select structure. It just sets the pointers to NULL. This 1042ff78bd2fSdrh ** routine is recursive in the sense that if the Select.pSrc.a[].pSelect 1043ff78bd2fSdrh ** pointer is not NULL, this routine is called recursively on that pointer. 1044ff78bd2fSdrh ** 1045ff78bd2fSdrh ** This routine is called on the Select structure that defines a 1046ff78bd2fSdrh ** VIEW in order to undo any bindings to tables. This is necessary 1047ff78bd2fSdrh ** because those tables might be DROPed by a subsequent SQL command. 10485cf590c1Sdrh ** If the bindings are not removed, then the Select.pSrc->a[].pTab field 10495cf590c1Sdrh ** will be left pointing to a deallocated Table structure after the 10505cf590c1Sdrh ** DROP and a coredump will occur the next time the VIEW is used. 1051ff78bd2fSdrh */ 10524adee20fSdanielk1977 void sqlite3SelectUnbind(Select *p){ 1053ff78bd2fSdrh int i; 1054ad3cab52Sdrh SrcList *pSrc = p->pSrc; 1055ff78bd2fSdrh Table *pTab; 1056ff78bd2fSdrh if( p==0 ) return; 1057ad3cab52Sdrh for(i=0; i<pSrc->nSrc; i++){ 1058ff78bd2fSdrh if( (pTab = pSrc->a[i].pTab)!=0 ){ 1059ff78bd2fSdrh if( pTab->isTransient ){ 10604adee20fSdanielk1977 sqlite3DeleteTable(0, pTab); 1061ff78bd2fSdrh } 1062ff78bd2fSdrh pSrc->a[i].pTab = 0; 1063ff78bd2fSdrh if( pSrc->a[i].pSelect ){ 10644adee20fSdanielk1977 sqlite3SelectUnbind(pSrc->a[i].pSelect); 1065ff78bd2fSdrh } 1066ff78bd2fSdrh } 1067ff78bd2fSdrh } 1068ff78bd2fSdrh } 1069ff78bd2fSdrh 1070ff78bd2fSdrh /* 1071d8bc7086Sdrh ** This routine associates entries in an ORDER BY expression list with 1072d8bc7086Sdrh ** columns in a result. For each ORDER BY expression, the opcode of 1073967e8b73Sdrh ** the top-level node is changed to TK_COLUMN and the iColumn value of 1074d8bc7086Sdrh ** the top-level node is filled in with column number and the iTable 1075d8bc7086Sdrh ** value of the top-level node is filled with iTable parameter. 1076d8bc7086Sdrh ** 1077d8bc7086Sdrh ** If there are prior SELECT clauses, they are processed first. A match 1078d8bc7086Sdrh ** in an earlier SELECT takes precedence over a later SELECT. 1079d8bc7086Sdrh ** 1080d8bc7086Sdrh ** Any entry that does not match is flagged as an error. The number 1081d8bc7086Sdrh ** of errors is returned. 1082fcb78a49Sdrh ** 1083fcb78a49Sdrh ** This routine does NOT correctly initialize the Expr.dataType field 1084fcb78a49Sdrh ** of the ORDER BY expressions. The multiSelectSortOrder() routine 1085fcb78a49Sdrh ** must be called to do that after the individual select statements 1086fcb78a49Sdrh ** have all been analyzed. This routine is unable to compute Expr.dataType 1087fcb78a49Sdrh ** because it must be called before the individual select statements 1088fcb78a49Sdrh ** have been analyzed. 1089d8bc7086Sdrh */ 1090d8bc7086Sdrh static int matchOrderbyToColumn( 1091d8bc7086Sdrh Parse *pParse, /* A place to leave error messages */ 1092d8bc7086Sdrh Select *pSelect, /* Match to result columns of this SELECT */ 1093d8bc7086Sdrh ExprList *pOrderBy, /* The ORDER BY values to match against columns */ 1094e4de1febSdrh int iTable, /* Insert this value in iTable */ 1095d8bc7086Sdrh int mustComplete /* If TRUE all ORDER BYs must match */ 1096d8bc7086Sdrh ){ 1097d8bc7086Sdrh int nErr = 0; 1098d8bc7086Sdrh int i, j; 1099d8bc7086Sdrh ExprList *pEList; 1100d8bc7086Sdrh 1101daffd0e5Sdrh if( pSelect==0 || pOrderBy==0 ) return 1; 1102d8bc7086Sdrh if( mustComplete ){ 1103d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } 1104d8bc7086Sdrh } 1105d8bc7086Sdrh if( fillInColumnList(pParse, pSelect) ){ 1106d8bc7086Sdrh return 1; 1107d8bc7086Sdrh } 1108d8bc7086Sdrh if( pSelect->pPrior ){ 110992cd52f5Sdrh if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ 111092cd52f5Sdrh return 1; 111192cd52f5Sdrh } 1112d8bc7086Sdrh } 1113d8bc7086Sdrh pEList = pSelect->pEList; 1114d8bc7086Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 1115d8bc7086Sdrh Expr *pE = pOrderBy->a[i].pExpr; 1116e4de1febSdrh int iCol = -1; 1117d8bc7086Sdrh if( pOrderBy->a[i].done ) continue; 11184adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) ){ 1119e4de1febSdrh if( iCol<=0 || iCol>pEList->nExpr ){ 11204adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1121da93d238Sdrh "ORDER BY position %d should be between 1 and %d", 1122e4de1febSdrh iCol, pEList->nExpr); 1123e4de1febSdrh nErr++; 1124e4de1febSdrh break; 1125e4de1febSdrh } 1126fcb78a49Sdrh if( !mustComplete ) continue; 1127e4de1febSdrh iCol--; 1128e4de1febSdrh } 1129e4de1febSdrh for(j=0; iCol<0 && j<pEList->nExpr; j++){ 11304cfa7934Sdrh if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){ 1131a76b5dfcSdrh char *zName, *zLabel; 1132a76b5dfcSdrh zName = pEList->a[j].zName; 1133a76b5dfcSdrh assert( pE->token.z ); 1134a76b5dfcSdrh zLabel = sqliteStrNDup(pE->token.z, pE->token.n); 11354adee20fSdanielk1977 sqlite3Dequote(zLabel); 11364adee20fSdanielk1977 if( sqlite3StrICmp(zName, zLabel)==0 ){ 1137e4de1febSdrh iCol = j; 1138d8bc7086Sdrh } 11396e142f54Sdrh sqliteFree(zLabel); 1140d8bc7086Sdrh } 11414adee20fSdanielk1977 if( iCol<0 && sqlite3ExprCompare(pE, pEList->a[j].pExpr) ){ 1142e4de1febSdrh iCol = j; 1143d8bc7086Sdrh } 1144e4de1febSdrh } 1145e4de1febSdrh if( iCol>=0 ){ 1146967e8b73Sdrh pE->op = TK_COLUMN; 1147e4de1febSdrh pE->iColumn = iCol; 1148d8bc7086Sdrh pE->iTable = iTable; 1149d8bc7086Sdrh pOrderBy->a[i].done = 1; 1150d8bc7086Sdrh } 1151e4de1febSdrh if( iCol<0 && mustComplete ){ 11524adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 1153da93d238Sdrh "ORDER BY term number %d does not match any result column", i+1); 1154d8bc7086Sdrh nErr++; 1155d8bc7086Sdrh break; 1156d8bc7086Sdrh } 1157d8bc7086Sdrh } 1158d8bc7086Sdrh return nErr; 1159d8bc7086Sdrh } 1160d8bc7086Sdrh 1161d8bc7086Sdrh /* 1162d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1163d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1164d8bc7086Sdrh */ 11654adee20fSdanielk1977 Vdbe *sqlite3GetVdbe(Parse *pParse){ 1166d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1167d8bc7086Sdrh if( v==0 ){ 11684adee20fSdanielk1977 v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); 1169d8bc7086Sdrh } 1170d8bc7086Sdrh return v; 1171d8bc7086Sdrh } 1172d8bc7086Sdrh 1173fcb78a49Sdrh /* 1174fcb78a49Sdrh ** This routine sets the Expr.dataType field on all elements of 1175fcb78a49Sdrh ** the pOrderBy expression list. The pOrderBy list will have been 1176fcb78a49Sdrh ** set up by matchOrderbyToColumn(). Hence each expression has 1177fcb78a49Sdrh ** a TK_COLUMN as its root node. The Expr.iColumn refers to a 1178fcb78a49Sdrh ** column in the result set. The datatype is set to SQLITE_SO_TEXT 1179fcb78a49Sdrh ** if the corresponding column in p and every SELECT to the left of 1180fcb78a49Sdrh ** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column 1181fcb78a49Sdrh ** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype 1182fcb78a49Sdrh ** of the order-by expression is set to SQLITE_SO_NUM. 1183fcb78a49Sdrh ** 1184fcb78a49Sdrh ** Examples: 1185fcb78a49Sdrh ** 1186e78e8284Sdrh ** CREATE TABLE one(a INTEGER, b TEXT); 1187e78e8284Sdrh ** CREATE TABLE two(c VARCHAR(5), d FLOAT); 1188e78e8284Sdrh ** 1189e78e8284Sdrh ** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2; 1190e78e8284Sdrh ** 1191e78e8284Sdrh ** The primary sort key will use SQLITE_SO_NUM because the "d" in 1192e78e8284Sdrh ** the second SELECT is numeric. The 1st column of the first SELECT 1193e78e8284Sdrh ** is text but that does not matter because a numeric always overrides 1194e78e8284Sdrh ** a text. 1195e78e8284Sdrh ** 1196e78e8284Sdrh ** The secondary key will use the SQLITE_SO_TEXT sort order because 1197e78e8284Sdrh ** both the (second) "b" in the first SELECT and the "c" in the second 1198e78e8284Sdrh ** SELECT have a datatype of text. 1199fcb78a49Sdrh */ 1200fcb78a49Sdrh static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){ 1201fcb78a49Sdrh int i; 1202fcb78a49Sdrh ExprList *pEList; 1203fcb78a49Sdrh if( pOrderBy==0 ) return; 1204fcb78a49Sdrh if( p==0 ){ 1205fcb78a49Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 1206fcb78a49Sdrh pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT; 1207fcb78a49Sdrh } 1208fcb78a49Sdrh return; 1209fcb78a49Sdrh } 1210fcb78a49Sdrh multiSelectSortOrder(p->pPrior, pOrderBy); 1211fcb78a49Sdrh pEList = p->pEList; 1212fcb78a49Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 1213fcb78a49Sdrh Expr *pE = pOrderBy->a[i].pExpr; 1214fcb78a49Sdrh if( pE->dataType==SQLITE_SO_NUM ) continue; 1215fcb78a49Sdrh assert( pE->iColumn>=0 ); 1216fcb78a49Sdrh if( pEList->nExpr>pE->iColumn ){ 12174adee20fSdanielk1977 pE->dataType = sqlite3ExprType(pEList->a[pE->iColumn].pExpr); 1218fcb78a49Sdrh } 1219fcb78a49Sdrh } 1220fcb78a49Sdrh } 1221d8bc7086Sdrh 122284ac9d02Sdanielk1977 static void multiSelectAffinity(Select *p, char *zAff){ 122384ac9d02Sdanielk1977 int i; 122484ac9d02Sdanielk1977 122584ac9d02Sdanielk1977 if( !p ) return; 122684ac9d02Sdanielk1977 multiSelectAffinity(p->pPrior, zAff); 122784ac9d02Sdanielk1977 122884ac9d02Sdanielk1977 for(i=0; i<p->pEList->nExpr; i++){ 122984ac9d02Sdanielk1977 if( zAff[i]=='\0' ){ 123084ac9d02Sdanielk1977 zAff[i] = sqlite3ExprAffinity(p->pEList->a[i].pExpr); 123184ac9d02Sdanielk1977 } 123284ac9d02Sdanielk1977 } 123384ac9d02Sdanielk1977 } 123484ac9d02Sdanielk1977 1235d8bc7086Sdrh /* 12367b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 12377b58daeaSdrh ** nLimit and nOffset fields. nLimit and nOffset hold the integers 12387b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 12397b58daeaSdrh ** keywords. Or that hold -1 and 0 if those keywords are omitted. 12407b58daeaSdrh ** iLimit and iOffset are the integer memory register numbers for 12417b58daeaSdrh ** counters used to compute the limit and offset. If there is no 12427b58daeaSdrh ** limit and/or offset, then iLimit and iOffset are negative. 12437b58daeaSdrh ** 12447b58daeaSdrh ** This routine changes the values if iLimit and iOffset only if 12457b58daeaSdrh ** a limit or offset is defined by nLimit and nOffset. iLimit and 12467b58daeaSdrh ** iOffset should have been preset to appropriate default values 12477b58daeaSdrh ** (usually but not always -1) prior to calling this routine. 12487b58daeaSdrh ** Only if nLimit>=0 or nOffset>0 do the limit registers get 12497b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 12507b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 12517b58daeaSdrh ** SELECT statements. 12527b58daeaSdrh */ 12537b58daeaSdrh static void computeLimitRegisters(Parse *pParse, Select *p){ 12547b58daeaSdrh /* 12557b58daeaSdrh ** If the comparison is p->nLimit>0 then "LIMIT 0" shows 12567b58daeaSdrh ** all rows. It is the same as no limit. If the comparision is 12577b58daeaSdrh ** p->nLimit>=0 then "LIMIT 0" show no rows at all. 12587b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 12597b58daeaSdrh ** contraversy about what the correct behavior should be. 12607b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 12617b58daeaSdrh ** no rows. 12627b58daeaSdrh */ 12637b58daeaSdrh if( p->nLimit>=0 ){ 12647b58daeaSdrh int iMem = pParse->nMem++; 12654adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 12667b58daeaSdrh if( v==0 ) return; 12674adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, -p->nLimit, 0); 12684adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 12697b58daeaSdrh p->iLimit = iMem; 12707b58daeaSdrh } 12717b58daeaSdrh if( p->nOffset>0 ){ 12727b58daeaSdrh int iMem = pParse->nMem++; 12734adee20fSdanielk1977 Vdbe *v = sqlite3GetVdbe(pParse); 12747b58daeaSdrh if( v==0 ) return; 12754adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, -p->nOffset, 0); 12764adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 1); 12777b58daeaSdrh p->iOffset = iMem; 12787b58daeaSdrh } 12797b58daeaSdrh } 12807b58daeaSdrh 12817b58daeaSdrh /* 128282c3d636Sdrh ** This routine is called to process a query that is really the union 128382c3d636Sdrh ** or intersection of two or more separate queries. 1284c926afbcSdrh ** 1285e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 1286e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 1287e78e8284Sdrh ** in which case this routine will be called recursively. 1288e78e8284Sdrh ** 1289e78e8284Sdrh ** The results of the total query are to be written into a destination 1290e78e8284Sdrh ** of type eDest with parameter iParm. 1291e78e8284Sdrh ** 1292e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 1293e78e8284Sdrh ** 1294e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 1295e78e8284Sdrh ** 1296e78e8284Sdrh ** This statement is parsed up as follows: 1297e78e8284Sdrh ** 1298e78e8284Sdrh ** SELECT c FROM t3 1299e78e8284Sdrh ** | 1300e78e8284Sdrh ** `-----> SELECT b FROM t2 1301e78e8284Sdrh ** | 13024b11c6d3Sjplyon ** `------> SELECT a FROM t1 1303e78e8284Sdrh ** 1304e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 1305e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 1306e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 1307e78e8284Sdrh ** 1308e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 1309e78e8284Sdrh ** individual selects always group from left to right. 131082c3d636Sdrh */ 131184ac9d02Sdanielk1977 static int multiSelect( 131284ac9d02Sdanielk1977 Parse *pParse, 131384ac9d02Sdanielk1977 Select *p, 131484ac9d02Sdanielk1977 int eDest, 131584ac9d02Sdanielk1977 int iParm, 131684ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 131784ac9d02Sdanielk1977 ){ 131884ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 131910e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 132010e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 132184ac9d02Sdanielk1977 char *affStr = 0; 132284ac9d02Sdanielk1977 132384ac9d02Sdanielk1977 if( !aff ){ 132484ac9d02Sdanielk1977 int len; 132584ac9d02Sdanielk1977 rc = fillInColumnList(pParse, p); 132684ac9d02Sdanielk1977 if( rc!=SQLITE_OK ){ 132784ac9d02Sdanielk1977 goto multi_select_end; 132884ac9d02Sdanielk1977 } 132984ac9d02Sdanielk1977 len = p->pEList->nExpr+1; 133084ac9d02Sdanielk1977 affStr = (char *)sqliteMalloc(p->pEList->nExpr+1); 133184ac9d02Sdanielk1977 if( !affStr ){ 133284ac9d02Sdanielk1977 rc = SQLITE_NOMEM; 133384ac9d02Sdanielk1977 goto multi_select_end; 133484ac9d02Sdanielk1977 } 133584ac9d02Sdanielk1977 memset(affStr, (int)SQLITE_AFF_NUMERIC, len-1); 133684ac9d02Sdanielk1977 aff = affStr; 133784ac9d02Sdanielk1977 } 133882c3d636Sdrh 13397b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 13407b58daeaSdrh ** the last SELECT in the series may have an ORDER BY or LIMIT. 134182c3d636Sdrh */ 134284ac9d02Sdanielk1977 if( p==0 || p->pPrior==0 ){ 134384ac9d02Sdanielk1977 rc = 1; 134484ac9d02Sdanielk1977 goto multi_select_end; 134584ac9d02Sdanielk1977 } 1346d8bc7086Sdrh pPrior = p->pPrior; 1347d8bc7086Sdrh if( pPrior->pOrderBy ){ 13484adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 1349da93d238Sdrh selectOpName(p->op)); 135084ac9d02Sdanielk1977 rc = 1; 135184ac9d02Sdanielk1977 goto multi_select_end; 135282c3d636Sdrh } 13537b58daeaSdrh if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){ 13544adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 13557b58daeaSdrh selectOpName(p->op)); 135684ac9d02Sdanielk1977 rc = 1; 135784ac9d02Sdanielk1977 goto multi_select_end; 13587b58daeaSdrh } 135982c3d636Sdrh 1360d8bc7086Sdrh /* Make sure we have a valid query engine. If not, create a new one. 1361d8bc7086Sdrh */ 13624adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 136384ac9d02Sdanielk1977 if( v==0 ){ 136484ac9d02Sdanielk1977 rc = 1; 136584ac9d02Sdanielk1977 goto multi_select_end; 136684ac9d02Sdanielk1977 } 1367d8bc7086Sdrh 13681cc3d75fSdrh /* Create the destination temporary table if necessary 13691cc3d75fSdrh */ 13701cc3d75fSdrh if( eDest==SRT_TempTable ){ 1371b4964b72Sdanielk1977 assert( p->pEList ); 13724adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0); 1373b4964b72Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, p->pEList->nExpr); 13741cc3d75fSdrh eDest = SRT_Table; 13751cc3d75fSdrh } 13761cc3d75fSdrh 1377f46f905aSdrh /* Generate code for the left and right SELECT statements. 1378d8bc7086Sdrh */ 137982c3d636Sdrh switch( p->op ){ 1380f46f905aSdrh case TK_ALL: { 1381f46f905aSdrh if( p->pOrderBy==0 ){ 13827b58daeaSdrh pPrior->nLimit = p->nLimit; 13837b58daeaSdrh pPrior->nOffset = p->nOffset; 138484ac9d02Sdanielk1977 rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); 138584ac9d02Sdanielk1977 if( rc ){ 138684ac9d02Sdanielk1977 goto multi_select_end; 138784ac9d02Sdanielk1977 } 1388f46f905aSdrh p->pPrior = 0; 13897b58daeaSdrh p->iLimit = pPrior->iLimit; 13907b58daeaSdrh p->iOffset = pPrior->iOffset; 13917b58daeaSdrh p->nLimit = -1; 13927b58daeaSdrh p->nOffset = 0; 139384ac9d02Sdanielk1977 rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); 1394f46f905aSdrh p->pPrior = pPrior; 139584ac9d02Sdanielk1977 if( rc ){ 139684ac9d02Sdanielk1977 goto multi_select_end; 139784ac9d02Sdanielk1977 } 1398f46f905aSdrh break; 1399f46f905aSdrh } 1400f46f905aSdrh /* For UNION ALL ... ORDER BY fall through to the next case */ 1401f46f905aSdrh } 140282c3d636Sdrh case TK_EXCEPT: 140382c3d636Sdrh case TK_UNION: { 1404d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 1405d8bc7086Sdrh int op; /* One of the SRT_ operations to apply to self */ 1406d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 14077b58daeaSdrh int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */ 1408c926afbcSdrh ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */ 140982c3d636Sdrh 1410d8bc7086Sdrh priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; 14117b58daeaSdrh if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){ 1412d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 1413c926afbcSdrh ** right. 1414d8bc7086Sdrh */ 141582c3d636Sdrh unionTab = iParm; 141682c3d636Sdrh }else{ 1417d8bc7086Sdrh /* We will need to create our own temporary table to hold the 1418d8bc7086Sdrh ** intermediate results. 1419d8bc7086Sdrh */ 142082c3d636Sdrh unionTab = pParse->nTab++; 1421d8bc7086Sdrh if( p->pOrderBy 1422d8bc7086Sdrh && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){ 142384ac9d02Sdanielk1977 rc = 1; 142484ac9d02Sdanielk1977 goto multi_select_end; 1425d8bc7086Sdrh } 1426d8bc7086Sdrh if( p->op!=TK_ALL ){ 14274adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 1); 14284adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_KeyAsData, unionTab, 1); 1429345fda3eSdrh }else{ 14304adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, unionTab, 0); 143182c3d636Sdrh } 143284ac9d02Sdanielk1977 assert( p->pEList ); 1433d8bc7086Sdrh } 1434d8bc7086Sdrh 1435d8bc7086Sdrh /* Code the SELECT statements to our left 1436d8bc7086Sdrh */ 143784ac9d02Sdanielk1977 rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); 143884ac9d02Sdanielk1977 if( rc ){ 143984ac9d02Sdanielk1977 goto multi_select_end; 144084ac9d02Sdanielk1977 } 144184ac9d02Sdanielk1977 if( p->op==TK_ALL ){ 144284ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, pPrior->pEList->nExpr); 144384ac9d02Sdanielk1977 } 1444d8bc7086Sdrh 1445d8bc7086Sdrh /* Code the current SELECT statement 1446d8bc7086Sdrh */ 1447d8bc7086Sdrh switch( p->op ){ 1448d8bc7086Sdrh case TK_EXCEPT: op = SRT_Except; break; 1449d8bc7086Sdrh case TK_UNION: op = SRT_Union; break; 1450d8bc7086Sdrh case TK_ALL: op = SRT_Table; break; 1451d8bc7086Sdrh } 145282c3d636Sdrh p->pPrior = 0; 1453c926afbcSdrh pOrderBy = p->pOrderBy; 1454c926afbcSdrh p->pOrderBy = 0; 14557b58daeaSdrh nLimit = p->nLimit; 14567b58daeaSdrh p->nLimit = -1; 14577b58daeaSdrh nOffset = p->nOffset; 14587b58daeaSdrh p->nOffset = 0; 145984ac9d02Sdanielk1977 rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); 146082c3d636Sdrh p->pPrior = pPrior; 1461c926afbcSdrh p->pOrderBy = pOrderBy; 14627b58daeaSdrh p->nLimit = nLimit; 14637b58daeaSdrh p->nOffset = nOffset; 146484ac9d02Sdanielk1977 if( rc ){ 146584ac9d02Sdanielk1977 goto multi_select_end; 146684ac9d02Sdanielk1977 } 146784ac9d02Sdanielk1977 1468d8bc7086Sdrh 1469d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 1470d8bc7086Sdrh ** it is that we currently need. 1471d8bc7086Sdrh */ 1472c926afbcSdrh if( eDest!=priorOp || unionTab!=iParm ){ 14736b56344dSdrh int iCont, iBreak, iStart; 147482c3d636Sdrh assert( p->pEList ); 147541202ccaSdrh if( eDest==SRT_Callback ){ 14766a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 14776a3ea0e6Sdrh generateColumnTypes(pParse, p->pSrc, p->pEList); 147841202ccaSdrh } 14794adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 14804adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 14814adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); 14827b58daeaSdrh computeLimitRegisters(pParse, p); 14834adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 1484fcb78a49Sdrh multiSelectSortOrder(p, p->pOrderBy); 148538640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, 1486d8bc7086Sdrh p->pOrderBy, -1, eDest, iParm, 148784ac9d02Sdanielk1977 iCont, iBreak, 0); 148884ac9d02Sdanielk1977 if( rc ){ 148984ac9d02Sdanielk1977 rc = 1; 149084ac9d02Sdanielk1977 goto multi_select_end; 149184ac9d02Sdanielk1977 } 14924adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 14934adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); 14944adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 14954adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); 1496d8bc7086Sdrh if( p->pOrderBy ){ 1497c926afbcSdrh generateSortTail(p, v, p->pEList->nExpr, eDest, iParm); 1498d8bc7086Sdrh } 149982c3d636Sdrh } 150082c3d636Sdrh break; 150182c3d636Sdrh } 150282c3d636Sdrh case TK_INTERSECT: { 150382c3d636Sdrh int tab1, tab2; 15046b56344dSdrh int iCont, iBreak, iStart; 15057b58daeaSdrh int nLimit, nOffset; 150682c3d636Sdrh 1507d8bc7086Sdrh /* INTERSECT is different from the others since it requires 15086206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 1509d8bc7086Sdrh ** by allocating the tables we will need. 1510d8bc7086Sdrh */ 151182c3d636Sdrh tab1 = pParse->nTab++; 151282c3d636Sdrh tab2 = pParse->nTab++; 1513d8bc7086Sdrh if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){ 151484ac9d02Sdanielk1977 rc = 1; 151584ac9d02Sdanielk1977 goto multi_select_end; 1516d8bc7086Sdrh } 15174adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, tab1, 1); 15184adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1); 151984ac9d02Sdanielk1977 assert( p->pEList ); 1520d8bc7086Sdrh 1521d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 1522d8bc7086Sdrh */ 152384ac9d02Sdanielk1977 rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); 152484ac9d02Sdanielk1977 if( rc ){ 152584ac9d02Sdanielk1977 goto multi_select_end; 152684ac9d02Sdanielk1977 } 1527d8bc7086Sdrh 1528d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 1529d8bc7086Sdrh */ 15304adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 1); 15314adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_KeyAsData, tab2, 1); 153282c3d636Sdrh p->pPrior = 0; 15337b58daeaSdrh nLimit = p->nLimit; 15347b58daeaSdrh p->nLimit = -1; 15357b58daeaSdrh nOffset = p->nOffset; 15367b58daeaSdrh p->nOffset = 0; 153784ac9d02Sdanielk1977 rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); 153882c3d636Sdrh p->pPrior = pPrior; 15397b58daeaSdrh p->nLimit = nLimit; 15407b58daeaSdrh p->nOffset = nOffset; 154184ac9d02Sdanielk1977 if( rc ){ 154284ac9d02Sdanielk1977 goto multi_select_end; 154384ac9d02Sdanielk1977 } 1544d8bc7086Sdrh 1545d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 1546d8bc7086Sdrh ** tables. 1547d8bc7086Sdrh */ 154882c3d636Sdrh assert( p->pEList ); 154941202ccaSdrh if( eDest==SRT_Callback ){ 15506a3ea0e6Sdrh generateColumnNames(pParse, 0, p->pEList); 15516a3ea0e6Sdrh generateColumnTypes(pParse, p->pSrc, p->pEList); 155241202ccaSdrh } 15534adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 15544adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 15554adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); 15567b58daeaSdrh computeLimitRegisters(pParse, p); 15574adee20fSdanielk1977 iStart = sqlite3VdbeAddOp(v, OP_FullKey, tab1, 0); 15584adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); 1559fcb78a49Sdrh multiSelectSortOrder(p, p->pOrderBy); 156038640e15Sdrh rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, 1561d8bc7086Sdrh p->pOrderBy, -1, eDest, iParm, 156284ac9d02Sdanielk1977 iCont, iBreak, 0); 156384ac9d02Sdanielk1977 if( rc ){ 156484ac9d02Sdanielk1977 rc = 1; 156584ac9d02Sdanielk1977 goto multi_select_end; 156684ac9d02Sdanielk1977 } 15674adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 15684adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); 15694adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 15704adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab2, 0); 15714adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, tab1, 0); 1572d8bc7086Sdrh if( p->pOrderBy ){ 1573c926afbcSdrh generateSortTail(p, v, p->pEList->nExpr, eDest, iParm); 1574d8bc7086Sdrh } 157582c3d636Sdrh break; 157682c3d636Sdrh } 157782c3d636Sdrh } 157882c3d636Sdrh assert( p->pEList && pPrior->pEList ); 157982c3d636Sdrh if( p->pEList->nExpr!=pPrior->pEList->nExpr ){ 15804adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 1581da93d238Sdrh " do not have the same number of result columns", selectOpName(p->op)); 158284ac9d02Sdanielk1977 rc = 1; 158384ac9d02Sdanielk1977 goto multi_select_end; 15842282792aSdrh } 158584ac9d02Sdanielk1977 158684ac9d02Sdanielk1977 multi_select_end: 158784ac9d02Sdanielk1977 if( affStr ){ 158884ac9d02Sdanielk1977 if( rc!=SQLITE_OK ){ 158984ac9d02Sdanielk1977 sqliteFree(affStr); 159084ac9d02Sdanielk1977 }else{ 159184ac9d02Sdanielk1977 multiSelectAffinity(p, affStr); 159284ac9d02Sdanielk1977 sqlite3VdbeOp3(v, OP_Noop, 0, 0, affStr, P3_DYNAMIC); 159384ac9d02Sdanielk1977 } 159484ac9d02Sdanielk1977 } 159584ac9d02Sdanielk1977 return rc; 15962282792aSdrh } 15972282792aSdrh 15982282792aSdrh /* 1599832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 16006a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 160184e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 16026a3ea0e6Sdrh ** unchanged.) 1603832508b7Sdrh ** 1604832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 1605832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 1606832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 1607832508b7Sdrh ** FORM clause entry is iTable. This routine make the necessary 1608832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 1609832508b7Sdrh ** of the subquery rather the result set of the subquery. 1610832508b7Sdrh */ 16116a3ea0e6Sdrh static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */ 16126a3ea0e6Sdrh static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){ 1613832508b7Sdrh if( pExpr==0 ) return; 161450350a15Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){ 161550350a15Sdrh if( pExpr->iColumn<0 ){ 161650350a15Sdrh pExpr->op = TK_NULL; 161750350a15Sdrh }else{ 1618832508b7Sdrh Expr *pNew; 161984e59207Sdrh assert( pEList!=0 && pExpr->iColumn<pEList->nExpr ); 1620832508b7Sdrh assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 ); 1621832508b7Sdrh pNew = pEList->a[pExpr->iColumn].pExpr; 1622832508b7Sdrh assert( pNew!=0 ); 1623832508b7Sdrh pExpr->op = pNew->op; 1624fcb78a49Sdrh pExpr->dataType = pNew->dataType; 1625d94a6698Sdrh assert( pExpr->pLeft==0 ); 16264adee20fSdanielk1977 pExpr->pLeft = sqlite3ExprDup(pNew->pLeft); 1627d94a6698Sdrh assert( pExpr->pRight==0 ); 16284adee20fSdanielk1977 pExpr->pRight = sqlite3ExprDup(pNew->pRight); 1629d94a6698Sdrh assert( pExpr->pList==0 ); 16304adee20fSdanielk1977 pExpr->pList = sqlite3ExprListDup(pNew->pList); 1631832508b7Sdrh pExpr->iTable = pNew->iTable; 1632832508b7Sdrh pExpr->iColumn = pNew->iColumn; 1633832508b7Sdrh pExpr->iAgg = pNew->iAgg; 16344adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->token, &pNew->token); 16354adee20fSdanielk1977 sqlite3TokenCopy(&pExpr->span, &pNew->span); 163650350a15Sdrh } 1637832508b7Sdrh }else{ 16386a3ea0e6Sdrh substExpr(pExpr->pLeft, iTable, pEList); 16396a3ea0e6Sdrh substExpr(pExpr->pRight, iTable, pEList); 16406a3ea0e6Sdrh substExprList(pExpr->pList, iTable, pEList); 1641832508b7Sdrh } 1642832508b7Sdrh } 1643832508b7Sdrh static void 16446a3ea0e6Sdrh substExprList(ExprList *pList, int iTable, ExprList *pEList){ 1645832508b7Sdrh int i; 1646832508b7Sdrh if( pList==0 ) return; 1647832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 16486a3ea0e6Sdrh substExpr(pList->a[i].pExpr, iTable, pEList); 1649832508b7Sdrh } 1650832508b7Sdrh } 1651832508b7Sdrh 1652832508b7Sdrh /* 16531350b030Sdrh ** This routine attempts to flatten subqueries in order to speed 16541350b030Sdrh ** execution. It returns 1 if it makes changes and 0 if no flattening 16551350b030Sdrh ** occurs. 16561350b030Sdrh ** 16571350b030Sdrh ** To understand the concept of flattening, consider the following 16581350b030Sdrh ** query: 16591350b030Sdrh ** 16601350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 16611350b030Sdrh ** 16621350b030Sdrh ** The default way of implementing this query is to execute the 16631350b030Sdrh ** subquery first and store the results in a temporary table, then 16641350b030Sdrh ** run the outer query on that temporary table. This requires two 16651350b030Sdrh ** passes over the data. Furthermore, because the temporary table 16661350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 1667832508b7Sdrh ** optimized. 16681350b030Sdrh ** 1669832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 16701350b030Sdrh ** a single flat select, like this: 16711350b030Sdrh ** 16721350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 16731350b030Sdrh ** 16741350b030Sdrh ** The code generated for this simpification gives the same result 1675832508b7Sdrh ** but only has to scan the data once. And because indices might 1676832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 1677832508b7Sdrh ** avoided. 16781350b030Sdrh ** 1679832508b7Sdrh ** Flattening is only attempted if all of the following are true: 16801350b030Sdrh ** 1681832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 16821350b030Sdrh ** 1683832508b7Sdrh ** (2) The subquery is not an aggregate or the outer query is not a join. 1684832508b7Sdrh ** 16858af4d3acSdrh ** (3) The subquery is not the right operand of a left outer join, or 16868af4d3acSdrh ** the subquery is not itself a join. (Ticket #306) 1687832508b7Sdrh ** 1688832508b7Sdrh ** (4) The subquery is not DISTINCT or the outer query is not a join. 1689832508b7Sdrh ** 1690832508b7Sdrh ** (5) The subquery is not DISTINCT or the outer query does not use 1691832508b7Sdrh ** aggregates. 1692832508b7Sdrh ** 1693832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 1694832508b7Sdrh ** DISTINCT. 1695832508b7Sdrh ** 169608192d5fSdrh ** (7) The subquery has a FROM clause. 169708192d5fSdrh ** 1698df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 1699df199a25Sdrh ** 1700df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 1701df199a25Sdrh ** aggregates. 1702df199a25Sdrh ** 1703df199a25Sdrh ** (10) The subquery does not use aggregates or the outer query does not 1704df199a25Sdrh ** use LIMIT. 1705df199a25Sdrh ** 1706174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 1707174b6195Sdrh ** 17083fc673e6Sdrh ** (12) The subquery is not the right term of a LEFT OUTER JOIN or the 17093fc673e6Sdrh ** subquery has no WHERE clause. (added by ticket #350) 17103fc673e6Sdrh ** 1711832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 1712832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 1713832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 1714832508b7Sdrh ** 1715665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 1716832508b7Sdrh ** If flattening is attempted this routine returns 1. 1717832508b7Sdrh ** 1718832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 1719832508b7Sdrh ** the subquery before this routine runs. 17201350b030Sdrh */ 17218c74a8caSdrh static int flattenSubquery( 17228c74a8caSdrh Parse *pParse, /* The parsing context */ 17238c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 17248c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 17258c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 17268c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 17278c74a8caSdrh ){ 17280bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 1729ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 1730ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 17310bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 17326a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 1733832508b7Sdrh int i; 1734832508b7Sdrh Expr *pWhere; 17351350b030Sdrh 1736832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 1737832508b7Sdrh */ 1738832508b7Sdrh if( p==0 ) return 0; 1739832508b7Sdrh pSrc = p->pSrc; 1740ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 1741832508b7Sdrh pSub = pSrc->a[iFrom].pSelect; 1742832508b7Sdrh assert( pSub!=0 ); 1743832508b7Sdrh if( isAgg && subqueryIsAgg ) return 0; 1744ad3cab52Sdrh if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; 1745832508b7Sdrh pSubSrc = pSub->pSrc; 1746832508b7Sdrh assert( pSubSrc ); 1747c31c2eb8Sdrh if( pSubSrc->nSrc==0 ) return 0; 1748df199a25Sdrh if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){ 1749df199a25Sdrh return 0; 1750df199a25Sdrh } 1751d11d382cSdrh if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0; 1752174b6195Sdrh if( p->pOrderBy && pSub->pOrderBy ) return 0; 1753832508b7Sdrh 17548af4d3acSdrh /* Restriction 3: If the subquery is a join, make sure the subquery is 17558af4d3acSdrh ** not used as the right operand of an outer join. Examples of why this 17568af4d3acSdrh ** is not allowed: 17578af4d3acSdrh ** 17588af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 17598af4d3acSdrh ** 17608af4d3acSdrh ** If we flatten the above, we would get 17618af4d3acSdrh ** 17628af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 17638af4d3acSdrh ** 17648af4d3acSdrh ** which is not at all the same thing. 17658af4d3acSdrh */ 17668af4d3acSdrh if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){ 17678af4d3acSdrh return 0; 17688af4d3acSdrh } 17698af4d3acSdrh 17703fc673e6Sdrh /* Restriction 12: If the subquery is the right operand of a left outer 17713fc673e6Sdrh ** join, make sure the subquery has no WHERE clause. 17723fc673e6Sdrh ** An examples of why this is not allowed: 17733fc673e6Sdrh ** 17743fc673e6Sdrh ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0) 17753fc673e6Sdrh ** 17763fc673e6Sdrh ** If we flatten the above, we would get 17773fc673e6Sdrh ** 17783fc673e6Sdrh ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0 17793fc673e6Sdrh ** 17803fc673e6Sdrh ** But the t2.x>0 test will always fail on a NULL row of t2, which 17813fc673e6Sdrh ** effectively converts the OUTER JOIN into an INNER JOIN. 17823fc673e6Sdrh */ 17833fc673e6Sdrh if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 17843fc673e6Sdrh && pSub->pWhere!=0 ){ 17853fc673e6Sdrh return 0; 17863fc673e6Sdrh } 17873fc673e6Sdrh 17880bb28106Sdrh /* If we reach this point, it means flattening is permitted for the 178963eb5f29Sdrh ** iFrom-th entry of the FROM clause in the outer query. 1790832508b7Sdrh */ 1791c31c2eb8Sdrh 1792c31c2eb8Sdrh /* Move all of the FROM elements of the subquery into the 1793c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 1794c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 1795c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 1796c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 1797c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 1798c31c2eb8Sdrh ** elements we are now copying in. 1799c31c2eb8Sdrh */ 18006a3ea0e6Sdrh iParent = pSrc->a[iFrom].iCursor; 1801c31c2eb8Sdrh { 1802c31c2eb8Sdrh int nSubSrc = pSubSrc->nSrc; 18038af4d3acSdrh int jointype = pSrc->a[iFrom].jointype; 1804c31c2eb8Sdrh 1805c31c2eb8Sdrh if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){ 18064adee20fSdanielk1977 sqlite3DeleteTable(0, pSrc->a[iFrom].pTab); 1807c31c2eb8Sdrh } 1808f26e09c8Sdrh sqliteFree(pSrc->a[iFrom].zDatabase); 1809c31c2eb8Sdrh sqliteFree(pSrc->a[iFrom].zName); 1810c31c2eb8Sdrh sqliteFree(pSrc->a[iFrom].zAlias); 1811c31c2eb8Sdrh if( nSubSrc>1 ){ 1812c31c2eb8Sdrh int extra = nSubSrc - 1; 1813c31c2eb8Sdrh for(i=1; i<nSubSrc; i++){ 18144adee20fSdanielk1977 pSrc = sqlite3SrcListAppend(pSrc, 0, 0); 1815c31c2eb8Sdrh } 1816c31c2eb8Sdrh p->pSrc = pSrc; 1817c31c2eb8Sdrh for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ 1818c31c2eb8Sdrh pSrc->a[i] = pSrc->a[i-extra]; 1819c31c2eb8Sdrh } 1820c31c2eb8Sdrh } 1821c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 1822c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 1823c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 1824c31c2eb8Sdrh } 18258af4d3acSdrh pSrc->a[iFrom+nSubSrc-1].jointype = jointype; 1826c31c2eb8Sdrh } 1827c31c2eb8Sdrh 1828c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 1829c31c2eb8Sdrh ** references to the iParent in the outer query. 1830c31c2eb8Sdrh ** 1831c31c2eb8Sdrh ** Example: 1832c31c2eb8Sdrh ** 1833c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 1834c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 1835c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 1836c31c2eb8Sdrh ** 1837c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 1838c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 1839c31c2eb8Sdrh */ 18406a3ea0e6Sdrh substExprList(p->pEList, iParent, pSub->pEList); 1841832508b7Sdrh pList = p->pEList; 1842832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 18436977fea8Sdrh Expr *pExpr; 18446977fea8Sdrh if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ 18456977fea8Sdrh pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n); 1846832508b7Sdrh } 1847832508b7Sdrh } 18481b2e0329Sdrh if( isAgg ){ 18496a3ea0e6Sdrh substExprList(p->pGroupBy, iParent, pSub->pEList); 18506a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 18511b2e0329Sdrh } 1852174b6195Sdrh if( pSub->pOrderBy ){ 1853174b6195Sdrh assert( p->pOrderBy==0 ); 1854174b6195Sdrh p->pOrderBy = pSub->pOrderBy; 1855174b6195Sdrh pSub->pOrderBy = 0; 1856174b6195Sdrh }else if( p->pOrderBy ){ 18576a3ea0e6Sdrh substExprList(p->pOrderBy, iParent, pSub->pEList); 1858174b6195Sdrh } 1859832508b7Sdrh if( pSub->pWhere ){ 18604adee20fSdanielk1977 pWhere = sqlite3ExprDup(pSub->pWhere); 1861832508b7Sdrh }else{ 1862832508b7Sdrh pWhere = 0; 1863832508b7Sdrh } 1864832508b7Sdrh if( subqueryIsAgg ){ 1865832508b7Sdrh assert( p->pHaving==0 ); 18661b2e0329Sdrh p->pHaving = p->pWhere; 18671b2e0329Sdrh p->pWhere = pWhere; 18686a3ea0e6Sdrh substExpr(p->pHaving, iParent, pSub->pEList); 18691b2e0329Sdrh if( pSub->pHaving ){ 18704adee20fSdanielk1977 Expr *pHaving = sqlite3ExprDup(pSub->pHaving); 18711b2e0329Sdrh if( p->pHaving ){ 18724adee20fSdanielk1977 p->pHaving = sqlite3Expr(TK_AND, p->pHaving, pHaving, 0); 18731b2e0329Sdrh }else{ 18741b2e0329Sdrh p->pHaving = pHaving; 18751b2e0329Sdrh } 18761b2e0329Sdrh } 18771b2e0329Sdrh assert( p->pGroupBy==0 ); 18784adee20fSdanielk1977 p->pGroupBy = sqlite3ExprListDup(pSub->pGroupBy); 1879832508b7Sdrh }else if( p->pWhere==0 ){ 1880832508b7Sdrh p->pWhere = pWhere; 1881832508b7Sdrh }else{ 18826a3ea0e6Sdrh substExpr(p->pWhere, iParent, pSub->pEList); 1883832508b7Sdrh if( pWhere ){ 18844adee20fSdanielk1977 p->pWhere = sqlite3Expr(TK_AND, p->pWhere, pWhere, 0); 1885832508b7Sdrh } 1886832508b7Sdrh } 1887c31c2eb8Sdrh 1888c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 1889c31c2eb8Sdrh ** outer query is distinct. 1890c31c2eb8Sdrh */ 1891832508b7Sdrh p->isDistinct = p->isDistinct || pSub->isDistinct; 18928c74a8caSdrh 1893c31c2eb8Sdrh /* Transfer the limit expression from the subquery to the outer 1894c31c2eb8Sdrh ** query. 1895c31c2eb8Sdrh */ 1896df199a25Sdrh if( pSub->nLimit>=0 ){ 1897df199a25Sdrh if( p->nLimit<0 ){ 1898df199a25Sdrh p->nLimit = pSub->nLimit; 1899df199a25Sdrh }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){ 1900df199a25Sdrh p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset; 1901df199a25Sdrh } 1902df199a25Sdrh } 1903df199a25Sdrh p->nOffset += pSub->nOffset; 19048c74a8caSdrh 1905c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 1906c31c2eb8Sdrh ** success. 1907c31c2eb8Sdrh */ 19084adee20fSdanielk1977 sqlite3SelectDelete(pSub); 1909832508b7Sdrh return 1; 19101350b030Sdrh } 19111350b030Sdrh 19121350b030Sdrh /* 19139562b551Sdrh ** Analyze the SELECT statement passed in as an argument to see if it 19149562b551Sdrh ** is a simple min() or max() query. If it is and this query can be 19159562b551Sdrh ** satisfied using a single seek to the beginning or end of an index, 1916e78e8284Sdrh ** then generate the code for this SELECT and return 1. If this is not a 19179562b551Sdrh ** simple min() or max() query, then return 0; 19189562b551Sdrh ** 19199562b551Sdrh ** A simply min() or max() query looks like this: 19209562b551Sdrh ** 19219562b551Sdrh ** SELECT min(a) FROM table; 19229562b551Sdrh ** SELECT max(a) FROM table; 19239562b551Sdrh ** 19249562b551Sdrh ** The query may have only a single table in its FROM argument. There 19259562b551Sdrh ** can be no GROUP BY or HAVING or WHERE clauses. The result set must 19269562b551Sdrh ** be the min() or max() of a single column of the table. The column 19279562b551Sdrh ** in the min() or max() function must be indexed. 19289562b551Sdrh ** 19294adee20fSdanielk1977 ** The parameters to this routine are the same as for sqlite3Select(). 19309562b551Sdrh ** See the header comment on that routine for additional information. 19319562b551Sdrh */ 19329562b551Sdrh static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ 19339562b551Sdrh Expr *pExpr; 19349562b551Sdrh int iCol; 19359562b551Sdrh Table *pTab; 19369562b551Sdrh Index *pIdx; 19379562b551Sdrh int base; 19389562b551Sdrh Vdbe *v; 19399562b551Sdrh int seekOp; 19409562b551Sdrh int cont; 19416e17529eSdrh ExprList *pEList, *pList, eList; 19429562b551Sdrh struct ExprList_item eListItem; 19436e17529eSdrh SrcList *pSrc; 19446e17529eSdrh 19459562b551Sdrh 19469562b551Sdrh /* Check to see if this query is a simple min() or max() query. Return 19479562b551Sdrh ** zero if it is not. 19489562b551Sdrh */ 19499562b551Sdrh if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; 19506e17529eSdrh pSrc = p->pSrc; 19516e17529eSdrh if( pSrc->nSrc!=1 ) return 0; 19526e17529eSdrh pEList = p->pEList; 19536e17529eSdrh if( pEList->nExpr!=1 ) return 0; 19546e17529eSdrh pExpr = pEList->a[0].pExpr; 19559562b551Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 19566e17529eSdrh pList = pExpr->pList; 19576e17529eSdrh if( pList==0 || pList->nExpr!=1 ) return 0; 19586977fea8Sdrh if( pExpr->token.n!=3 ) return 0; 19594adee20fSdanielk1977 if( sqlite3StrNICmp(pExpr->token.z,"min",3)==0 ){ 19600bce8354Sdrh seekOp = OP_Rewind; 19614adee20fSdanielk1977 }else if( sqlite3StrNICmp(pExpr->token.z,"max",3)==0 ){ 19620bce8354Sdrh seekOp = OP_Last; 19630bce8354Sdrh }else{ 19640bce8354Sdrh return 0; 19650bce8354Sdrh } 19666e17529eSdrh pExpr = pList->a[0].pExpr; 19679562b551Sdrh if( pExpr->op!=TK_COLUMN ) return 0; 19689562b551Sdrh iCol = pExpr->iColumn; 19696e17529eSdrh pTab = pSrc->a[0].pTab; 19709562b551Sdrh 19719562b551Sdrh /* If we get to here, it means the query is of the correct form. 197217f71934Sdrh ** Check to make sure we have an index and make pIdx point to the 197317f71934Sdrh ** appropriate index. If the min() or max() is on an INTEGER PRIMARY 197417f71934Sdrh ** key column, no index is necessary so set pIdx to NULL. If no 197517f71934Sdrh ** usable index is found, return 0. 19769562b551Sdrh */ 19779562b551Sdrh if( iCol<0 ){ 19789562b551Sdrh pIdx = 0; 19799562b551Sdrh }else{ 19809562b551Sdrh for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 19819562b551Sdrh assert( pIdx->nColumn>=1 ); 19829562b551Sdrh if( pIdx->aiColumn[0]==iCol ) break; 19839562b551Sdrh } 19849562b551Sdrh if( pIdx==0 ) return 0; 19859562b551Sdrh } 19869562b551Sdrh 1987e5f50722Sdrh /* Identify column types if we will be using the callback. This 19889562b551Sdrh ** step is skipped if the output is going to a table or a memory cell. 1989e5f50722Sdrh ** The column names have already been generated in the calling function. 19909562b551Sdrh */ 19914adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 19929562b551Sdrh if( v==0 ) return 0; 19939562b551Sdrh if( eDest==SRT_Callback ){ 19946a3ea0e6Sdrh generateColumnTypes(pParse, p->pSrc, p->pEList); 19959562b551Sdrh } 19969562b551Sdrh 19970c37e630Sdrh /* If the output is destined for a temporary table, open that table. 19980c37e630Sdrh */ 19990c37e630Sdrh if( eDest==SRT_TempTable ){ 20004adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0); 2001b4964b72Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, 1); 20020c37e630Sdrh } 20030c37e630Sdrh 200417f71934Sdrh /* Generating code to find the min or the max. Basically all we have 200517f71934Sdrh ** to do is find the first or the last entry in the chosen index. If 200617f71934Sdrh ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first 200717f71934Sdrh ** or last entry in the main table. 20089562b551Sdrh */ 20094adee20fSdanielk1977 sqlite3CodeVerifySchema(pParse, pTab->iDb); 20106e17529eSdrh base = pSrc->a[0].iCursor; 20117b58daeaSdrh computeLimitRegisters(pParse, p); 20126e17529eSdrh if( pSrc->a[0].pSelect==0 ){ 20134adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0); 20144adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_OpenRead, base, pTab->tnum, pTab->zName, 0); 2015b4964b72Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, base, pTab->nCol); 20166e17529eSdrh } 20174adee20fSdanielk1977 cont = sqlite3VdbeMakeLabel(v); 20189562b551Sdrh if( pIdx==0 ){ 20194adee20fSdanielk1977 sqlite3VdbeAddOp(v, seekOp, base, 0); 20209562b551Sdrh }else{ 20214adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, pIdx->iDb, 0); 20224adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum, pIdx->zName, P3_STATIC); 20234adee20fSdanielk1977 sqlite3VdbeAddOp(v, seekOp, base+1, 0); 20244adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_IdxRecno, base+1, 0); 20254adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, base+1, 0); 2026*7cf6e4deSdrh sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); 20279562b551Sdrh } 20285cf8e8c7Sdrh eList.nExpr = 1; 20295cf8e8c7Sdrh memset(&eListItem, 0, sizeof(eListItem)); 20305cf8e8c7Sdrh eList.a = &eListItem; 20315cf8e8c7Sdrh eList.a[0].pExpr = pExpr; 203284ac9d02Sdanielk1977 selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont, 0); 20334adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, cont); 20344adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Close, base, 0); 20356e17529eSdrh 20369562b551Sdrh return 1; 20379562b551Sdrh } 20389562b551Sdrh 20399562b551Sdrh /* 20409bb61fe7Sdrh ** Generate code for the given SELECT statement. 20419bb61fe7Sdrh ** 2042fef5208cSdrh ** The results are distributed in various ways depending on the 2043fef5208cSdrh ** value of eDest and iParm. 2044fef5208cSdrh ** 2045fef5208cSdrh ** eDest Value Result 2046fef5208cSdrh ** ------------ ------------------------------------------- 2047fef5208cSdrh ** SRT_Callback Invoke the callback for each row of the result. 2048fef5208cSdrh ** 2049fef5208cSdrh ** SRT_Mem Store first result in memory cell iParm 2050fef5208cSdrh ** 2051e014a838Sdanielk1977 ** SRT_Set Store results as keys of table iParm. 2052fef5208cSdrh ** 205382c3d636Sdrh ** SRT_Union Store results as a key in a temporary table iParm 205482c3d636Sdrh ** 20554b11c6d3Sjplyon ** SRT_Except Remove results from the temporary table iParm. 2056c4a3c779Sdrh ** 2057c4a3c779Sdrh ** SRT_Table Store results in temporary table iParm 20589bb61fe7Sdrh ** 2059e78e8284Sdrh ** The table above is incomplete. Additional eDist value have be added 2060e78e8284Sdrh ** since this comment was written. See the selectInnerLoop() function for 2061e78e8284Sdrh ** a complete listing of the allowed values of eDest and their meanings. 2062e78e8284Sdrh ** 20639bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 20649bb61fe7Sdrh ** encountered, then an appropriate error message is left in 20659bb61fe7Sdrh ** pParse->zErrMsg. 20669bb61fe7Sdrh ** 20679bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 20689bb61fe7Sdrh ** calling function needs to do that. 20691b2e0329Sdrh ** 20701b2e0329Sdrh ** The pParent, parentTab, and *pParentAgg fields are filled in if this 20711b2e0329Sdrh ** SELECT is a subquery. This routine may try to combine this SELECT 20721b2e0329Sdrh ** with its parent to form a single flat query. In so doing, it might 20731b2e0329Sdrh ** change the parent query from a non-aggregate to an aggregate query. 20741b2e0329Sdrh ** For that reason, the pParentAgg flag is passed as a pointer, so it 20751b2e0329Sdrh ** can be changed. 2076e78e8284Sdrh ** 2077e78e8284Sdrh ** Example 1: The meaning of the pParent parameter. 2078e78e8284Sdrh ** 2079e78e8284Sdrh ** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3; 2080e78e8284Sdrh ** \ \_______ subquery _______/ / 2081e78e8284Sdrh ** \ / 2082e78e8284Sdrh ** \____________________ outer query ___________________/ 2083e78e8284Sdrh ** 2084e78e8284Sdrh ** This routine is called for the outer query first. For that call, 2085e78e8284Sdrh ** pParent will be NULL. During the processing of the outer query, this 2086e78e8284Sdrh ** routine is called recursively to handle the subquery. For the recursive 2087e78e8284Sdrh ** call, pParent will point to the outer query. Because the subquery is 2088e78e8284Sdrh ** the second element in a three-way join, the parentTab parameter will 2089e78e8284Sdrh ** be 1 (the 2nd value of a 0-indexed array.) 20909bb61fe7Sdrh */ 20914adee20fSdanielk1977 int sqlite3Select( 2092cce7d176Sdrh Parse *pParse, /* The parser context */ 20939bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 2094e78e8284Sdrh int eDest, /* How to dispose of the results */ 2095e78e8284Sdrh int iParm, /* A parameter used by the eDest disposal method */ 2096832508b7Sdrh Select *pParent, /* Another SELECT for which this is a sub-query */ 2097832508b7Sdrh int parentTab, /* Index in pParent->pSrc of this query */ 209884ac9d02Sdanielk1977 int *pParentAgg, /* True if pParent uses aggregate functions */ 209984ac9d02Sdanielk1977 char *aff /* If eDest is SRT_Union, the affinity string */ 2100cce7d176Sdrh ){ 2101d8bc7086Sdrh int i; 2102cce7d176Sdrh WhereInfo *pWInfo; 2103cce7d176Sdrh Vdbe *v; 2104cce7d176Sdrh int isAgg = 0; /* True for select lists like "count(*)" */ 2105a2e00042Sdrh ExprList *pEList; /* List of columns to extract. */ 2106ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 21079bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 21089bb61fe7Sdrh ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */ 21092282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 21102282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 211119a775c2Sdrh int isDistinct; /* True if the DISTINCT keyword is present */ 211219a775c2Sdrh int distinct; /* Table to use for the distinct set */ 21131d83f052Sdrh int rc = 1; /* Value to return from this function */ 21149bb61fe7Sdrh 21156f8a503dSdanielk1977 if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1; 21164adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 2117daffd0e5Sdrh 211882c3d636Sdrh /* If there is are a sequence of queries, do the earlier ones first. 211982c3d636Sdrh */ 212082c3d636Sdrh if( p->pPrior ){ 212184ac9d02Sdanielk1977 return multiSelect(pParse, p, eDest, iParm, aff); 212282c3d636Sdrh } 212382c3d636Sdrh 212482c3d636Sdrh /* Make local copies of the parameters for this query. 212582c3d636Sdrh */ 21269bb61fe7Sdrh pTabList = p->pSrc; 21279bb61fe7Sdrh pWhere = p->pWhere; 21289bb61fe7Sdrh pOrderBy = p->pOrderBy; 21292282792aSdrh pGroupBy = p->pGroupBy; 21302282792aSdrh pHaving = p->pHaving; 213119a775c2Sdrh isDistinct = p->isDistinct; 21329bb61fe7Sdrh 21336a3ea0e6Sdrh /* Allocate VDBE cursors for each table in the FROM clause 213410e5e3cfSdrh */ 21354adee20fSdanielk1977 sqlite3SrcListAssignCursors(pParse, pTabList); 213610e5e3cfSdrh 21379bb61fe7Sdrh /* 21389bb61fe7Sdrh ** Do not even attempt to generate any code if we have already seen 21399bb61fe7Sdrh ** errors before this routine starts. 21409bb61fe7Sdrh */ 21411d83f052Sdrh if( pParse->nErr>0 ) goto select_end; 2142cce7d176Sdrh 2143e78e8284Sdrh /* Expand any "*" terms in the result set. (For example the "*" in 2144e78e8284Sdrh ** "SELECT * FROM t1") The fillInColumnlist() routine also does some 2145e78e8284Sdrh ** other housekeeping - see the header comment for details. 2146cce7d176Sdrh */ 2147d8bc7086Sdrh if( fillInColumnList(pParse, p) ){ 21481d83f052Sdrh goto select_end; 2149cce7d176Sdrh } 2150ad2d8307Sdrh pWhere = p->pWhere; 2151d8bc7086Sdrh pEList = p->pEList; 21521d83f052Sdrh if( pEList==0 ) goto select_end; 2153cce7d176Sdrh 21542282792aSdrh /* If writing to memory or generating a set 21552282792aSdrh ** only a single column may be output. 215619a775c2Sdrh */ 2157fef5208cSdrh if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){ 21584adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "only a single result allowed for " 2159da93d238Sdrh "a SELECT that is part of an expression"); 21601d83f052Sdrh goto select_end; 216119a775c2Sdrh } 216219a775c2Sdrh 2163c926afbcSdrh /* ORDER BY is ignored for some destinations. 21642282792aSdrh */ 2165c926afbcSdrh switch( eDest ){ 2166c926afbcSdrh case SRT_Union: 2167c926afbcSdrh case SRT_Except: 2168c926afbcSdrh case SRT_Discard: 2169acd4c695Sdrh pOrderBy = 0; 2170c926afbcSdrh break; 2171c926afbcSdrh default: 2172c926afbcSdrh break; 21732282792aSdrh } 21742282792aSdrh 217510e5e3cfSdrh /* At this point, we should have allocated all the cursors that we 2176832508b7Sdrh ** need to handle subquerys and temporary tables. 217710e5e3cfSdrh ** 2178967e8b73Sdrh ** Resolve the column names and do a semantics check on all the expressions. 21792282792aSdrh */ 21804794b980Sdrh for(i=0; i<pEList->nExpr; i++){ 21814adee20fSdanielk1977 if( sqlite3ExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){ 21821d83f052Sdrh goto select_end; 2183cce7d176Sdrh } 21844adee20fSdanielk1977 if( sqlite3ExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){ 21851d83f052Sdrh goto select_end; 2186cce7d176Sdrh } 2187cce7d176Sdrh } 2188cce7d176Sdrh if( pWhere ){ 21894adee20fSdanielk1977 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pWhere) ){ 21901d83f052Sdrh goto select_end; 2191cce7d176Sdrh } 21924adee20fSdanielk1977 if( sqlite3ExprCheck(pParse, pWhere, 0, 0) ){ 21931d83f052Sdrh goto select_end; 2194cce7d176Sdrh } 2195cce7d176Sdrh } 2196c66c5a26Sdrh if( pHaving ){ 2197c66c5a26Sdrh if( pGroupBy==0 ){ 21984adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 2199c66c5a26Sdrh goto select_end; 2200c66c5a26Sdrh } 22014adee20fSdanielk1977 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pHaving) ){ 2202c66c5a26Sdrh goto select_end; 2203c66c5a26Sdrh } 22044adee20fSdanielk1977 if( sqlite3ExprCheck(pParse, pHaving, 1, &isAgg) ){ 2205c66c5a26Sdrh goto select_end; 2206c66c5a26Sdrh } 2207c66c5a26Sdrh } 2208cce7d176Sdrh if( pOrderBy ){ 2209cce7d176Sdrh for(i=0; i<pOrderBy->nExpr; i++){ 2210e4de1febSdrh int iCol; 221188eee38aSdrh Expr *pE = pOrderBy->a[i].pExpr; 22124adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){ 22134adee20fSdanielk1977 sqlite3ExprDelete(pE); 22144adee20fSdanielk1977 pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr); 221588eee38aSdrh } 22164adee20fSdanielk1977 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){ 221788eee38aSdrh goto select_end; 221888eee38aSdrh } 22194adee20fSdanielk1977 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){ 222088eee38aSdrh goto select_end; 222188eee38aSdrh } 22224adee20fSdanielk1977 if( sqlite3ExprIsConstant(pE) ){ 22234adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){ 22244adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 2225da93d238Sdrh "ORDER BY terms must not be non-integer constants"); 22261d83f052Sdrh goto select_end; 2227e4de1febSdrh }else if( iCol<=0 || iCol>pEList->nExpr ){ 22284adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 2229da93d238Sdrh "ORDER BY column number %d out of range - should be " 2230e4de1febSdrh "between 1 and %d", iCol, pEList->nExpr); 2231e4de1febSdrh goto select_end; 2232e4de1febSdrh } 2233cce7d176Sdrh } 2234cce7d176Sdrh } 2235cce7d176Sdrh } 22362282792aSdrh if( pGroupBy ){ 22372282792aSdrh for(i=0; i<pGroupBy->nExpr; i++){ 223888eee38aSdrh int iCol; 22392282792aSdrh Expr *pE = pGroupBy->a[i].pExpr; 22404adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){ 22414adee20fSdanielk1977 sqlite3ExprDelete(pE); 22424adee20fSdanielk1977 pE = pGroupBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr); 22439208643dSdrh } 22444adee20fSdanielk1977 if( sqlite3ExprResolveIds(pParse, pTabList, pEList, pE) ){ 22451d83f052Sdrh goto select_end; 22462282792aSdrh } 22474adee20fSdanielk1977 if( sqlite3ExprCheck(pParse, pE, isAgg, 0) ){ 22481d83f052Sdrh goto select_end; 22492282792aSdrh } 22504adee20fSdanielk1977 if( sqlite3ExprIsConstant(pE) ){ 22514adee20fSdanielk1977 if( sqlite3ExprIsInteger(pE, &iCol)==0 ){ 22524adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 2253da93d238Sdrh "GROUP BY terms must not be non-integer constants"); 225488eee38aSdrh goto select_end; 225588eee38aSdrh }else if( iCol<=0 || iCol>pEList->nExpr ){ 22564adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 2257da93d238Sdrh "GROUP BY column number %d out of range - should be " 225888eee38aSdrh "between 1 and %d", iCol, pEList->nExpr); 225988eee38aSdrh goto select_end; 226088eee38aSdrh } 226188eee38aSdrh } 22622282792aSdrh } 22632282792aSdrh } 2264cce7d176Sdrh 2265d820cb1bSdrh /* Begin generating code. 2266d820cb1bSdrh */ 22674adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2268d820cb1bSdrh if( v==0 ) goto select_end; 2269d820cb1bSdrh 2270e78e8284Sdrh /* Identify column names if we will be using them in a callback. This 2271e78e8284Sdrh ** step is skipped if the output is going to some other destination. 22720bb28106Sdrh */ 22730bb28106Sdrh if( eDest==SRT_Callback ){ 22746a3ea0e6Sdrh generateColumnNames(pParse, pTabList, pEList); 22750bb28106Sdrh } 22760bb28106Sdrh 227784ac9d02Sdanielk1977 /* If the destination is SRT_Union, then set the number of columns in 227884ac9d02Sdanielk1977 ** the records that will be inserted into the temporary table. The caller 227984ac9d02Sdanielk1977 ** couldn't do this, in case the select statement is of the form 228084ac9d02Sdanielk1977 ** "SELECT * FROM ....". 228184ac9d02Sdanielk1977 ** 228284ac9d02Sdanielk1977 ** We need to do this before we start inserting records into the 228384ac9d02Sdanielk1977 ** temporary table (which has had OP_KeyAsData executed on it), because 228484ac9d02Sdanielk1977 ** it is required by the key comparison function. So do it now, even 228584ac9d02Sdanielk1977 ** though this means that OP_SetNumColumns may be executed on the same 228684ac9d02Sdanielk1977 ** cursor more than once. 228784ac9d02Sdanielk1977 */ 228884ac9d02Sdanielk1977 if( eDest==SRT_Union ){ 228984ac9d02Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr); 229084ac9d02Sdanielk1977 } 229184ac9d02Sdanielk1977 2292d820cb1bSdrh /* Generate code for all sub-queries in the FROM clause 2293d820cb1bSdrh */ 2294ad3cab52Sdrh for(i=0; i<pTabList->nSrc; i++){ 22955cf590c1Sdrh const char *zSavedAuthContext; 2296c31c2eb8Sdrh int needRestoreContext; 2297c31c2eb8Sdrh 2298a76b5dfcSdrh if( pTabList->a[i].pSelect==0 ) continue; 22995cf590c1Sdrh if( pTabList->a[i].zName!=0 ){ 23005cf590c1Sdrh zSavedAuthContext = pParse->zAuthContext; 23015cf590c1Sdrh pParse->zAuthContext = pTabList->a[i].zName; 2302c31c2eb8Sdrh needRestoreContext = 1; 2303c31c2eb8Sdrh }else{ 2304c31c2eb8Sdrh needRestoreContext = 0; 23055cf590c1Sdrh } 23064adee20fSdanielk1977 sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable, 230784ac9d02Sdanielk1977 pTabList->a[i].iCursor, p, i, &isAgg, 0); 2308c31c2eb8Sdrh if( needRestoreContext ){ 23095cf590c1Sdrh pParse->zAuthContext = zSavedAuthContext; 23105cf590c1Sdrh } 2311832508b7Sdrh pTabList = p->pSrc; 2312832508b7Sdrh pWhere = p->pWhere; 2313c31c2eb8Sdrh if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){ 2314832508b7Sdrh pOrderBy = p->pOrderBy; 2315acd4c695Sdrh } 2316832508b7Sdrh pGroupBy = p->pGroupBy; 2317832508b7Sdrh pHaving = p->pHaving; 2318832508b7Sdrh isDistinct = p->isDistinct; 23191b2e0329Sdrh } 23201b2e0329Sdrh 23216e17529eSdrh /* Check for the special case of a min() or max() function by itself 23226e17529eSdrh ** in the result set. 23236e17529eSdrh */ 23246e17529eSdrh if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ 23256e17529eSdrh rc = 0; 23266e17529eSdrh goto select_end; 23276e17529eSdrh } 23286e17529eSdrh 23291b2e0329Sdrh /* Check to see if this is a subquery that can be "flattened" into its parent. 23301b2e0329Sdrh ** If flattening is a possiblity, do so and return immediately. 23311b2e0329Sdrh */ 23321b2e0329Sdrh if( pParent && pParentAgg && 23338c74a8caSdrh flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){ 23341b2e0329Sdrh if( isAgg ) *pParentAgg = 1; 23351b2e0329Sdrh return rc; 23361b2e0329Sdrh } 2337832508b7Sdrh 23387b58daeaSdrh /* Set the limiter. 23397b58daeaSdrh */ 23407b58daeaSdrh computeLimitRegisters(pParse, p); 23417b58daeaSdrh 2342e78e8284Sdrh /* Identify column types if we will be using a callback. This 2343e78e8284Sdrh ** step is skipped if the output is going to a destination other 2344e78e8284Sdrh ** than a callback. 2345e5f50722Sdrh ** 2346e5f50722Sdrh ** We have to do this separately from the creation of column names 2347e5f50722Sdrh ** above because if the pTabList contains views then they will not 2348e5f50722Sdrh ** have been resolved and we will not know the column types until 2349e5f50722Sdrh ** now. 2350fcb78a49Sdrh */ 2351fcb78a49Sdrh if( eDest==SRT_Callback ){ 23526a3ea0e6Sdrh generateColumnTypes(pParse, pTabList, pEList); 2353fcb78a49Sdrh } 2354fcb78a49Sdrh 23552d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 23562d0794e3Sdrh */ 23572d0794e3Sdrh if( eDest==SRT_TempTable ){ 23584adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0); 2359b4964b72Sdanielk1977 sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr); 23602d0794e3Sdrh } 23612d0794e3Sdrh 23622282792aSdrh /* Do an analysis of aggregate expressions. 2363efb7251dSdrh */ 2364d820cb1bSdrh sqliteAggregateInfoReset(pParse); 2365bb999ef6Sdrh if( isAgg || pGroupBy ){ 23660bce8354Sdrh assert( pParse->nAgg==0 ); 2367bb999ef6Sdrh isAgg = 1; 23682282792aSdrh for(i=0; i<pEList->nExpr; i++){ 23694adee20fSdanielk1977 if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){ 23701d83f052Sdrh goto select_end; 23712282792aSdrh } 23722282792aSdrh } 23732282792aSdrh if( pGroupBy ){ 23742282792aSdrh for(i=0; i<pGroupBy->nExpr; i++){ 23754adee20fSdanielk1977 if( sqlite3ExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){ 23761d83f052Sdrh goto select_end; 23772282792aSdrh } 23782282792aSdrh } 23792282792aSdrh } 23804adee20fSdanielk1977 if( pHaving && sqlite3ExprAnalyzeAggregates(pParse, pHaving) ){ 23811d83f052Sdrh goto select_end; 23822282792aSdrh } 2383191b690eSdrh if( pOrderBy ){ 2384191b690eSdrh for(i=0; i<pOrderBy->nExpr; i++){ 23854adee20fSdanielk1977 if( sqlite3ExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){ 23861d83f052Sdrh goto select_end; 2387191b690eSdrh } 2388191b690eSdrh } 2389191b690eSdrh } 2390efb7251dSdrh } 2391efb7251dSdrh 23922282792aSdrh /* Reset the aggregator 2393cce7d176Sdrh */ 2394cce7d176Sdrh if( isAgg ){ 23954adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_AggReset, 0, pParse->nAgg); 2396e5095355Sdrh for(i=0; i<pParse->nAgg; i++){ 23970bce8354Sdrh FuncDef *pFunc; 23980bce8354Sdrh if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){ 23994adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER); 2400e5095355Sdrh } 2401e5095355Sdrh } 24021bee3d7bSdrh if( pGroupBy==0 ){ 24034adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_String, 0, 0); 24044adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_AggFocus, 0, 0); 24051bee3d7bSdrh } 2406cce7d176Sdrh } 2407cce7d176Sdrh 240819a775c2Sdrh /* Initialize the memory cell to NULL 240919a775c2Sdrh */ 2410fef5208cSdrh if( eDest==SRT_Mem ){ 24114adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_String, 0, 0); 24124adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); 241319a775c2Sdrh } 241419a775c2Sdrh 2415832508b7Sdrh /* Open a temporary table to use for the distinct set. 2416cce7d176Sdrh */ 241719a775c2Sdrh if( isDistinct ){ 2418832508b7Sdrh distinct = pParse->nTab++; 24194adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_OpenTemp, distinct, 1); 2420832508b7Sdrh }else{ 2421832508b7Sdrh distinct = -1; 2422efb7251dSdrh } 2423832508b7Sdrh 2424832508b7Sdrh /* Begin the database scan 2425832508b7Sdrh */ 24264adee20fSdanielk1977 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 242768d2e591Sdrh pGroupBy ? 0 : &pOrderBy); 24281d83f052Sdrh if( pWInfo==0 ) goto select_end; 2429cce7d176Sdrh 24302282792aSdrh /* Use the standard inner loop if we are not dealing with 24312282792aSdrh ** aggregates 2432cce7d176Sdrh */ 2433da9d6c45Sdrh if( !isAgg ){ 2434df199a25Sdrh if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 243584ac9d02Sdanielk1977 iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ 24361d83f052Sdrh goto select_end; 2437cce7d176Sdrh } 2438da9d6c45Sdrh } 2439cce7d176Sdrh 2440e3184744Sdrh /* If we are dealing with aggregates, then do the special aggregate 24412282792aSdrh ** processing. 2442efb7251dSdrh */ 24432282792aSdrh else{ 2444268380caSdrh AggExpr *pAgg; 24452282792aSdrh if( pGroupBy ){ 24461bee3d7bSdrh int lbl1; 24472282792aSdrh for(i=0; i<pGroupBy->nExpr; i++){ 24484adee20fSdanielk1977 sqlite3ExprCode(pParse, pGroupBy->a[i].pExpr); 2449efb7251dSdrh } 24504adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0); 245136a3c70bSdanielk1977 sqlite3AddKeyType(v, pGroupBy); 24524adee20fSdanielk1977 lbl1 = sqlite3VdbeMakeLabel(v); 24534adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_AggFocus, 0, lbl1); 2454268380caSdrh for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){ 2455268380caSdrh if( pAgg->isAgg ) continue; 24564adee20fSdanielk1977 sqlite3ExprCode(pParse, pAgg->pExpr); 24574adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_AggSet, 0, i); 24582282792aSdrh } 24594adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, lbl1); 24602282792aSdrh } 2461268380caSdrh for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){ 24622282792aSdrh Expr *pE; 2463268380caSdrh int nExpr; 2464268380caSdrh FuncDef *pDef; 2465268380caSdrh if( !pAgg->isAgg ) continue; 2466268380caSdrh assert( pAgg->pFunc!=0 ); 2467268380caSdrh assert( pAgg->pFunc->xStep!=0 ); 2468268380caSdrh pDef = pAgg->pFunc; 2469268380caSdrh pE = pAgg->pExpr; 2470268380caSdrh assert( pE!=0 ); 24712282792aSdrh assert( pE->op==TK_AGG_FUNCTION ); 24724adee20fSdanielk1977 nExpr = sqlite3ExprCodeExprList(pParse, pE->pList, pDef->includeTypes); 24734adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Integer, i, 0); 24744adee20fSdanielk1977 sqlite3VdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER); 24752282792aSdrh } 24762282792aSdrh } 24772282792aSdrh 2478cce7d176Sdrh /* End the database scan loop. 2479cce7d176Sdrh */ 24804adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 2481cce7d176Sdrh 24822282792aSdrh /* If we are processing aggregates, we need to set up a second loop 24832282792aSdrh ** over all of the aggregate values and process them. 24842282792aSdrh */ 24852282792aSdrh if( isAgg ){ 24864adee20fSdanielk1977 int endagg = sqlite3VdbeMakeLabel(v); 24872282792aSdrh int startagg; 24884adee20fSdanielk1977 startagg = sqlite3VdbeAddOp(v, OP_AggNext, 0, endagg); 24892282792aSdrh pParse->useAgg = 1; 24902282792aSdrh if( pHaving ){ 24914adee20fSdanielk1977 sqlite3ExprIfFalse(pParse, pHaving, startagg, 1); 24922282792aSdrh } 2493df199a25Sdrh if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest, 249484ac9d02Sdanielk1977 iParm, startagg, endagg, aff) ){ 24951d83f052Sdrh goto select_end; 24962282792aSdrh } 24974adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Goto, 0, startagg); 24984adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, endagg); 24994adee20fSdanielk1977 sqlite3VdbeAddOp(v, OP_Noop, 0, 0); 25002282792aSdrh pParse->useAgg = 0; 25012282792aSdrh } 25022282792aSdrh 2503cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 2504cce7d176Sdrh ** and send them to the callback one by one. 2505cce7d176Sdrh */ 2506cce7d176Sdrh if( pOrderBy ){ 2507c926afbcSdrh generateSortTail(p, v, pEList->nExpr, eDest, iParm); 2508cce7d176Sdrh } 25096a535340Sdrh 2510f620b4e2Sdrh /* If this was a subquery, we have now converted the subquery into a 2511f620b4e2Sdrh ** temporary table. So delete the subquery structure from the parent 2512f620b4e2Sdrh ** to prevent this subquery from being evaluated again and to force the 2513f620b4e2Sdrh ** the use of the temporary table. 2514f620b4e2Sdrh */ 2515f620b4e2Sdrh if( pParent ){ 2516f620b4e2Sdrh assert( pParent->pSrc->nSrc>parentTab ); 2517f620b4e2Sdrh assert( pParent->pSrc->a[parentTab].pSelect==p ); 25184adee20fSdanielk1977 sqlite3SelectDelete(p); 2519f620b4e2Sdrh pParent->pSrc->a[parentTab].pSelect = 0; 2520f620b4e2Sdrh } 2521f620b4e2Sdrh 25221d83f052Sdrh /* The SELECT was successfully coded. Set the return code to 0 25231d83f052Sdrh ** to indicate no errors. 25241d83f052Sdrh */ 25251d83f052Sdrh rc = 0; 25261d83f052Sdrh 25271d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 25281d83f052Sdrh ** successful coding of the SELECT. 25291d83f052Sdrh */ 25301d83f052Sdrh select_end: 25311d83f052Sdrh sqliteAggregateInfoReset(pParse); 25321d83f052Sdrh return rc; 2533cce7d176Sdrh } 2534