1cce7d176Sdrh /* 2b19a2bc6Sdrh ** 2001 September 15 3cce7d176Sdrh ** 4b19a2bc6Sdrh ** The author disclaims copyright to this source code. In place of 5b19a2bc6Sdrh ** a legal notice, here is a blessing: 6cce7d176Sdrh ** 7b19a2bc6Sdrh ** May you do good and not evil. 8b19a2bc6Sdrh ** May you find forgiveness for yourself and forgive others. 9b19a2bc6Sdrh ** May you share freely, never taking more than you give. 10cce7d176Sdrh ** 11cce7d176Sdrh ************************************************************************* 12cce7d176Sdrh ** This file contains C code routines that are called by the parser 13b19a2bc6Sdrh ** to handle SELECT statements in SQLite. 14cce7d176Sdrh */ 15cce7d176Sdrh #include "sqliteInt.h" 16cce7d176Sdrh 17079a3072Sdrh /* 18abd4c723Sdrh ** Trace output macros 19abd4c723Sdrh */ 20abd4c723Sdrh #if SELECTTRACE_ENABLED 21abd4c723Sdrh /***/ int sqlite3SelectTrace = 0; 22eb9b884cSdrh # define SELECTTRACE(K,P,S,X) \ 23eb9b884cSdrh if(sqlite3SelectTrace&(K)) \ 24fef37760Sdrh sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\ 25eb9b884cSdrh sqlite3DebugPrintf X 26abd4c723Sdrh #else 27eb9b884cSdrh # define SELECTTRACE(K,P,S,X) 28abd4c723Sdrh #endif 29abd4c723Sdrh 30315555caSdrh 31cce7d176Sdrh /* 32079a3072Sdrh ** An instance of the following object is used to record information about 33079a3072Sdrh ** how to process the DISTINCT keyword, to simplify passing that information 34079a3072Sdrh ** into the selectInnerLoop() routine. 35eda639e1Sdrh */ 36079a3072Sdrh typedef struct DistinctCtx DistinctCtx; 37079a3072Sdrh struct DistinctCtx { 38079a3072Sdrh u8 isTnct; /* True if the DISTINCT keyword is present */ 39079a3072Sdrh u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ 40079a3072Sdrh int tabTnct; /* Ephemeral table used for DISTINCT processing */ 41079a3072Sdrh int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ 42079a3072Sdrh }; 43079a3072Sdrh 44079a3072Sdrh /* 45079a3072Sdrh ** An instance of the following object is used to record information about 46079a3072Sdrh ** the ORDER BY (or GROUP BY) clause of query is being coded. 4724e25d32Sdan ** 4824e25d32Sdan ** The aDefer[] array is used by the sorter-references optimization. For 4924e25d32Sdan ** example, assuming there is no index that can be used for the ORDER BY, 5024e25d32Sdan ** for the query: 5124e25d32Sdan ** 5224e25d32Sdan ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10; 5324e25d32Sdan ** 5424e25d32Sdan ** it may be more efficient to add just the "a" values to the sorter, and 5524e25d32Sdan ** retrieve the associated "bigblob" values directly from table t1 as the 5624e25d32Sdan ** 10 smallest "a" values are extracted from the sorter. 5724e25d32Sdan ** 5824e25d32Sdan ** When the sorter-reference optimization is used, there is one entry in the 5924e25d32Sdan ** aDefer[] array for each database table that may be read as values are 6024e25d32Sdan ** extracted from the sorter. 61079a3072Sdrh */ 62079a3072Sdrh typedef struct SortCtx SortCtx; 63079a3072Sdrh struct SortCtx { 64079a3072Sdrh ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ 65079a3072Sdrh int nOBSat; /* Number of ORDER BY terms satisfied by indices */ 66079a3072Sdrh int iECursor; /* Cursor number for the sorter */ 67079a3072Sdrh int regReturn; /* Register holding block-output return address */ 68079a3072Sdrh int labelBkOut; /* Start label for the block-output subroutine */ 69079a3072Sdrh int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ 70a04a8be2Sdrh int labelDone; /* Jump here when done, ex: LIMIT reached */ 716ee5a7b4Sdrh int labelOBLopt; /* Jump here when sorter is full */ 72079a3072Sdrh u8 sortFlags; /* Zero or more SORTFLAG_* bits */ 7324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 7424e25d32Sdan u8 nDefer; /* Number of valid entries in aDefer[] */ 7524e25d32Sdan struct DeferredCsr { 7624e25d32Sdan Table *pTab; /* Table definition */ 7724e25d32Sdan int iCsr; /* Cursor number for table */ 7824e25d32Sdan int nKey; /* Number of PK columns for table pTab (>=1) */ 7924e25d32Sdan } aDefer[4]; 8024e25d32Sdan #endif 81bbd4ae5aSdrh struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */ 82079a3072Sdrh }; 83079a3072Sdrh #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ 84cce7d176Sdrh 85cce7d176Sdrh /* 86b87fbed5Sdrh ** Delete all the content of a Select structure. Deallocate the structure 87a9ebfe20Sdrh ** itself depending on the value of bFree 88a9ebfe20Sdrh ** 89a9ebfe20Sdrh ** If bFree==1, call sqlite3DbFree() on the p object. 90a9ebfe20Sdrh ** If bFree==0, Leave the first Select object unfreed 91eda639e1Sdrh */ 92b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){ 93b87fbed5Sdrh while( p ){ 94b87fbed5Sdrh Select *pPrior = p->pPrior; 95633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 96633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 97633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 98633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 99633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 100633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 101633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 10267a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 103e3bf632cSdan if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){ 104e3bf632cSdan sqlite3WindowListDelete(db, p->pWinDefn); 105e3bf632cSdan } 10667a9b8edSdan #endif 1078906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith); 108dbd6a7dcSdrh if( bFree ) sqlite3DbFreeNN(db, p); 109b87fbed5Sdrh p = pPrior; 110b87fbed5Sdrh bFree = 1; 111b87fbed5Sdrh } 112eda639e1Sdrh } 113eda639e1Sdrh 1141013c932Sdrh /* 1151013c932Sdrh ** Initialize a SelectDest structure. 1161013c932Sdrh */ 1171013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 118ea678832Sdrh pDest->eDest = (u8)eDest; 1192b596da8Sdrh pDest->iSDParm = iParm; 12071c57db0Sdan pDest->zAffSdst = 0; 1212b596da8Sdrh pDest->iSdst = 0; 1222b596da8Sdrh pDest->nSdst = 0; 1231013c932Sdrh } 1241013c932Sdrh 125eda639e1Sdrh 126eda639e1Sdrh /* 1279bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 1289bb61fe7Sdrh ** structure. 129cce7d176Sdrh */ 1304adee20fSdanielk1977 Select *sqlite3SelectNew( 13117435752Sdrh Parse *pParse, /* Parsing context */ 132daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 133ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 134daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 135daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 136daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 137daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 138c3489bbfSdrh u32 selFlags, /* Flag parameters, such as SF_Distinct */ 1398c0833fbSdrh Expr *pLimit /* LIMIT value. NULL means not used */ 1409bb61fe7Sdrh ){ 1419bb61fe7Sdrh Select *pNew; 142eda639e1Sdrh Select standin; 143ef90a6b8Sdrh pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); 144daffd0e5Sdrh if( pNew==0 ){ 145ef90a6b8Sdrh assert( pParse->db->mallocFailed ); 146eda639e1Sdrh pNew = &standin; 147eda639e1Sdrh } 148b733d037Sdrh if( pEList==0 ){ 1493d240d21Sdrh pEList = sqlite3ExprListAppend(pParse, 0, 1503d240d21Sdrh sqlite3Expr(pParse->db,TK_ASTERISK,0)); 151b733d037Sdrh } 1529bb61fe7Sdrh pNew->pEList = pEList; 153ca3862dcSdrh pNew->op = TK_SELECT; 154ca3862dcSdrh pNew->selFlags = selFlags; 155ca3862dcSdrh pNew->iLimit = 0; 156ca3862dcSdrh pNew->iOffset = 0; 157fef37760Sdrh pNew->selId = ++pParse->nSelect; 158ca3862dcSdrh pNew->addrOpenEphm[0] = -1; 159ca3862dcSdrh pNew->addrOpenEphm[1] = -1; 160ca3862dcSdrh pNew->nSelectRow = 0; 161ef90a6b8Sdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); 1629bb61fe7Sdrh pNew->pSrc = pSrc; 1639bb61fe7Sdrh pNew->pWhere = pWhere; 1649bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 1659bb61fe7Sdrh pNew->pHaving = pHaving; 1669bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 167ca3862dcSdrh pNew->pPrior = 0; 168ca3862dcSdrh pNew->pNext = 0; 169a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 170ca3862dcSdrh pNew->pWith = 0; 17167a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 17286fb6e17Sdan pNew->pWin = 0; 173e3bf632cSdan pNew->pWinDefn = 0; 17467a9b8edSdan #endif 175ef90a6b8Sdrh if( pParse->db->mallocFailed ) { 176ef90a6b8Sdrh clearSelect(pParse->db, pNew, pNew!=&standin); 177eda639e1Sdrh pNew = 0; 178a464c234Sdrh }else{ 179a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 180daffd0e5Sdrh } 181338ec3e1Sdrh assert( pNew!=&standin ); 1829bb61fe7Sdrh return pNew; 1839bb61fe7Sdrh } 1849bb61fe7Sdrh 185eb9b884cSdrh 1869bb61fe7Sdrh /* 187eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 188eda639e1Sdrh */ 189633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 1908906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); 191eda639e1Sdrh } 192eda639e1Sdrh 193eda639e1Sdrh /* 194a9ebfe20Sdrh ** Delete all the substructure for p, but keep p allocated. Redefine 195a9ebfe20Sdrh ** p to be a single SELECT where every column of the result set has a 196a9ebfe20Sdrh ** value of NULL. 197a9ebfe20Sdrh */ 198a9ebfe20Sdrh void sqlite3SelectReset(Parse *pParse, Select *p){ 199a9ebfe20Sdrh if( ALWAYS(p) ){ 200a9ebfe20Sdrh clearSelect(pParse->db, p, 0); 201a9ebfe20Sdrh memset(&p->iLimit, 0, sizeof(Select) - offsetof(Select,iLimit)); 202a9ebfe20Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, 203a9ebfe20Sdrh sqlite3ExprAlloc(pParse->db,TK_NULL,0,0)); 204aa328b6aSdan p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(SrcList)); 205a9ebfe20Sdrh } 206a9ebfe20Sdrh } 207a9ebfe20Sdrh 208a9ebfe20Sdrh /* 209d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound. 210d227a291Sdrh */ 211d227a291Sdrh static Select *findRightmost(Select *p){ 212d227a291Sdrh while( p->pNext ) p = p->pNext; 213d227a291Sdrh return p; 2149bb61fe7Sdrh } 2159bb61fe7Sdrh 2169bb61fe7Sdrh /* 217f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the 21801f3f253Sdrh ** type of join. Return an integer constant that expresses that type 21901f3f253Sdrh ** in terms of the following bit values: 22001f3f253Sdrh ** 22101f3f253Sdrh ** JT_INNER 2223dec223cSdrh ** JT_CROSS 22301f3f253Sdrh ** JT_OUTER 22401f3f253Sdrh ** JT_NATURAL 22501f3f253Sdrh ** JT_LEFT 22601f3f253Sdrh ** JT_RIGHT 22701f3f253Sdrh ** 22801f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 22901f3f253Sdrh ** 23001f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 23101f3f253Sdrh ** a join type, but put an error in the pParse structure. 23201f3f253Sdrh */ 2334adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 23401f3f253Sdrh int jointype = 0; 23501f3f253Sdrh Token *apAll[3]; 23601f3f253Sdrh Token *p; 237373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 238373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 2395719628aSdrh static const struct { 240373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 241373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 242373cc2ddSdrh u8 code; /* Join type mask */ 243373cc2ddSdrh } aKeyword[] = { 244373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 245373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 246373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 247373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 248373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 249373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 250373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 25101f3f253Sdrh }; 25201f3f253Sdrh int i, j; 25301f3f253Sdrh apAll[0] = pA; 25401f3f253Sdrh apAll[1] = pB; 25501f3f253Sdrh apAll[2] = pC; 256195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 25701f3f253Sdrh p = apAll[i]; 258373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 259373cc2ddSdrh if( p->n==aKeyword[j].nChar 260373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 261373cc2ddSdrh jointype |= aKeyword[j].code; 26201f3f253Sdrh break; 26301f3f253Sdrh } 26401f3f253Sdrh } 265373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 266373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 26701f3f253Sdrh jointype |= JT_ERROR; 26801f3f253Sdrh break; 26901f3f253Sdrh } 27001f3f253Sdrh } 271ad2d8307Sdrh if( 272ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 273195e6967Sdrh (jointype & JT_ERROR)!=0 274ad2d8307Sdrh ){ 275a9671a22Sdrh const char *zSp = " "; 276a9671a22Sdrh assert( pB!=0 ); 277a9671a22Sdrh if( pC==0 ){ zSp++; } 278ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 279a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 28001f3f253Sdrh jointype = JT_INNER; 281373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 282373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 2834adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 284da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 285195e6967Sdrh jointype = JT_INNER; 28601f3f253Sdrh } 28701f3f253Sdrh return jointype; 28801f3f253Sdrh } 28901f3f253Sdrh 29001f3f253Sdrh /* 291ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 292ad2d8307Sdrh ** is not contained in the table. 293ad2d8307Sdrh */ 294ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 295ad2d8307Sdrh int i; 296ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 2974adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 298ad2d8307Sdrh } 299ad2d8307Sdrh return -1; 300ad2d8307Sdrh } 301ad2d8307Sdrh 302ad2d8307Sdrh /* 3032179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 3042179b434Sdrh ** table that has a column named zCol. 3052179b434Sdrh ** 3062179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 3072179b434Sdrh ** of the matching column and return TRUE. 3082179b434Sdrh ** 3092179b434Sdrh ** If not found, return FALSE. 3102179b434Sdrh */ 3112179b434Sdrh static int tableAndColumnIndex( 3122179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 3132179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 3142179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 3152179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 3169d41af23Sdan int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 3179d41af23Sdan int bIgnoreHidden /* True to ignore hidden columns */ 3182179b434Sdrh ){ 3192179b434Sdrh int i; /* For looping over tables in pSrc */ 3202179b434Sdrh int iCol; /* Index of column matching zCol */ 3212179b434Sdrh 3222179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 3232179b434Sdrh for(i=0; i<N; i++){ 3242179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 3259d41af23Sdan if( iCol>=0 3269d41af23Sdan && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0) 3279d41af23Sdan ){ 3282179b434Sdrh if( piTab ){ 3292179b434Sdrh *piTab = i; 3302179b434Sdrh *piCol = iCol; 3312179b434Sdrh } 3322179b434Sdrh return 1; 3332179b434Sdrh } 3342179b434Sdrh } 3352179b434Sdrh return 0; 3362179b434Sdrh } 3372179b434Sdrh 3382179b434Sdrh /* 339f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 340f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 341f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 342f7b0b0adSdan ** 343f7b0b0adSdan ** (tab1.col1 = tab2.col2) 344f7b0b0adSdan ** 345f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 346f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 347f7b0b0adSdan ** column iColRight of tab2. 348ad2d8307Sdrh */ 349ad2d8307Sdrh static void addWhereTerm( 35017435752Sdrh Parse *pParse, /* Parsing context */ 351f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 3522179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 353f7b0b0adSdan int iColLeft, /* Index of column in first table */ 3542179b434Sdrh int iRight, /* Index of second table in pSrc */ 355f7b0b0adSdan int iColRight, /* Index of column in second table */ 356f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 357f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 358ad2d8307Sdrh ){ 359f7b0b0adSdan sqlite3 *db = pParse->db; 360f7b0b0adSdan Expr *pE1; 361f7b0b0adSdan Expr *pE2; 362f7b0b0adSdan Expr *pEq; 363ad2d8307Sdrh 3642179b434Sdrh assert( iLeft<iRight ); 3652179b434Sdrh assert( pSrc->nSrc>iRight ); 3662179b434Sdrh assert( pSrc->a[iLeft].pTab ); 3672179b434Sdrh assert( pSrc->a[iRight].pTab ); 368f7b0b0adSdan 3692179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 3702179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 371f7b0b0adSdan 372abfd35eaSdrh pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); 373f7b0b0adSdan if( pEq && isOuterJoin ){ 374f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 375c5cd1249Sdrh assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); 376ebb6a65dSdrh ExprSetVVAProperty(pEq, EP_NoReduce); 377f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 378030530deSdrh } 379d5c851c1Sdrh *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq); 380ad2d8307Sdrh } 381ad2d8307Sdrh 382ad2d8307Sdrh /* 3831f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 38422d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 38522d6a53aSdrh ** expression. 3861cc093c2Sdrh ** 387e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 3881cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 3891f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 3901f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 3911f16230bSdrh ** WHERE clause during join processing but we need to remember that they 3921f16230bSdrh ** originated in the ON or USING clause. 39322d6a53aSdrh ** 39422d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 39522d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 39622d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 39722d6a53aSdrh ** for cases like this: 39822d6a53aSdrh ** 39922d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 40022d6a53aSdrh ** 40122d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 40222d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 40322d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 40422d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 40522d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 40622d6a53aSdrh ** the output, which is incorrect. 4071cc093c2Sdrh */ 4088103a036Sdrh void sqlite3SetJoinExpr(Expr *p, int iTable){ 4091cc093c2Sdrh while( p ){ 4101f16230bSdrh ExprSetProperty(p, EP_FromJoin); 411c5cd1249Sdrh assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 412ebb6a65dSdrh ExprSetVVAProperty(p, EP_NoReduce); 413cf697396Sshane p->iRightJoinTable = (i16)iTable; 414606f2344Sdrh if( p->op==TK_FUNCTION && p->x.pList ){ 415606f2344Sdrh int i; 416606f2344Sdrh for(i=0; i<p->x.pList->nExpr; i++){ 4178103a036Sdrh sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable); 418606f2344Sdrh } 419606f2344Sdrh } 4208103a036Sdrh sqlite3SetJoinExpr(p->pLeft, iTable); 4211cc093c2Sdrh p = p->pRight; 4221cc093c2Sdrh } 4231cc093c2Sdrh } 4241cc093c2Sdrh 4258103a036Sdrh /* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every 4262589787cSdrh ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into 4272589787cSdrh ** an ordinary term that omits the EP_FromJoin mark. 4282589787cSdrh ** 4292589787cSdrh ** This happens when a LEFT JOIN is simplified into an ordinary JOIN. 4302589787cSdrh */ 4312589787cSdrh static void unsetJoinExpr(Expr *p, int iTable){ 4322589787cSdrh while( p ){ 4337fbb101cSdrh if( ExprHasProperty(p, EP_FromJoin) 4347fbb101cSdrh && (iTable<0 || p->iRightJoinTable==iTable) ){ 4352589787cSdrh ExprClearProperty(p, EP_FromJoin); 4362589787cSdrh } 4372589787cSdrh if( p->op==TK_FUNCTION && p->x.pList ){ 4382589787cSdrh int i; 4392589787cSdrh for(i=0; i<p->x.pList->nExpr; i++){ 4402589787cSdrh unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); 4412589787cSdrh } 4422589787cSdrh } 4432589787cSdrh unsetJoinExpr(p->pLeft, iTable); 4442589787cSdrh p = p->pRight; 4452589787cSdrh } 4462589787cSdrh } 4472589787cSdrh 4481cc093c2Sdrh /* 449ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 450ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 451ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 452ad2d8307Sdrh ** 45391bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 45491bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 45591bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 45691bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 45791bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 45891bb0eedSdrh ** also attached to the left entry. 45991bb0eedSdrh ** 460ad2d8307Sdrh ** This routine returns the number of errors encountered. 461ad2d8307Sdrh */ 462ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 46391bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 46491bb0eedSdrh int i, j; /* Loop counters */ 46591bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 46691bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 467ad2d8307Sdrh 46891bb0eedSdrh pSrc = p->pSrc; 46991bb0eedSdrh pLeft = &pSrc->a[0]; 47091bb0eedSdrh pRight = &pLeft[1]; 47191bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 47291bb0eedSdrh Table *pRightTab = pRight->pTab; 473ad27e761Sdrh int isOuter; 47491bb0eedSdrh 475ce2c482eSdrh if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; 4768a48b9c0Sdrh isOuter = (pRight->fg.jointype & JT_OUTER)!=0; 477ad2d8307Sdrh 478ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 479ad2d8307Sdrh ** every column that the two tables have in common. 480ad2d8307Sdrh */ 4818a48b9c0Sdrh if( pRight->fg.jointype & JT_NATURAL ){ 48261dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 4834adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 484ad2d8307Sdrh "an ON or USING clause", 0); 485ad2d8307Sdrh return 1; 486ad2d8307Sdrh } 4872179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4882179b434Sdrh char *zName; /* Name of column in the right table */ 4892179b434Sdrh int iLeft; /* Matching left table */ 4902179b434Sdrh int iLeftCol; /* Matching column in the left table */ 4912179b434Sdrh 4929d41af23Sdan if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue; 4932179b434Sdrh zName = pRightTab->aCol[j].zName; 4949d41af23Sdan if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){ 4952179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 4962179b434Sdrh isOuter, &p->pWhere); 497ad2d8307Sdrh } 498ad2d8307Sdrh } 499ad2d8307Sdrh } 500ad2d8307Sdrh 501ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 502ad2d8307Sdrh */ 50361dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 5044adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 505da93d238Sdrh "clauses in the same join"); 506ad2d8307Sdrh return 1; 507ad2d8307Sdrh } 508ad2d8307Sdrh 509ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 51091bb0eedSdrh ** an AND operator. 511ad2d8307Sdrh */ 51261dfc31dSdrh if( pRight->pOn ){ 5138103a036Sdrh if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor); 514d5c851c1Sdrh p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn); 51561dfc31dSdrh pRight->pOn = 0; 516ad2d8307Sdrh } 517ad2d8307Sdrh 518ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 519ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 520ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 521ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 522ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 523ad2d8307Sdrh ** not contained in both tables to be joined. 524ad2d8307Sdrh */ 52561dfc31dSdrh if( pRight->pUsing ){ 52661dfc31dSdrh IdList *pList = pRight->pUsing; 527ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 5282179b434Sdrh char *zName; /* Name of the term in the USING clause */ 5292179b434Sdrh int iLeft; /* Table on the left with matching column name */ 5302179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 5312179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 5322179b434Sdrh 5332179b434Sdrh zName = pList->a[j].zName; 5342179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 5352179b434Sdrh if( iRightCol<0 5369d41af23Sdan || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0) 5372179b434Sdrh ){ 5384adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 53991bb0eedSdrh "not present in both tables", zName); 540ad2d8307Sdrh return 1; 541ad2d8307Sdrh } 5422179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 5432179b434Sdrh isOuter, &p->pWhere); 544ad2d8307Sdrh } 545ad2d8307Sdrh } 546ad2d8307Sdrh } 547ad2d8307Sdrh return 0; 548ad2d8307Sdrh } 549ad2d8307Sdrh 550ad2d8307Sdrh /* 551bbd4ae5aSdrh ** An instance of this object holds information (beyond pParse and pSelect) 552bbd4ae5aSdrh ** needed to load the next result row that is to be added to the sorter. 553bbd4ae5aSdrh */ 554bbd4ae5aSdrh typedef struct RowLoadInfo RowLoadInfo; 555bbd4ae5aSdrh struct RowLoadInfo { 556bbd4ae5aSdrh int regResult; /* Store results in array of registers here */ 557bbd4ae5aSdrh u8 ecelFlags; /* Flag argument to ExprCodeExprList() */ 558bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 559bbd4ae5aSdrh ExprList *pExtra; /* Extra columns needed by sorter refs */ 560bbd4ae5aSdrh int regExtraResult; /* Where to load the extra columns */ 561bbd4ae5aSdrh #endif 562bbd4ae5aSdrh }; 563bbd4ae5aSdrh 564bbd4ae5aSdrh /* 565bbd4ae5aSdrh ** This routine does the work of loading query data into an array of 566bbd4ae5aSdrh ** registers so that it can be added to the sorter. 567bbd4ae5aSdrh */ 568bbd4ae5aSdrh static void innerLoopLoadRow( 569bbd4ae5aSdrh Parse *pParse, /* Statement under construction */ 570bbd4ae5aSdrh Select *pSelect, /* The query being coded */ 571bbd4ae5aSdrh RowLoadInfo *pInfo /* Info needed to complete the row load */ 572bbd4ae5aSdrh ){ 573bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult, 574bbd4ae5aSdrh 0, pInfo->ecelFlags); 575bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 576bbd4ae5aSdrh if( pInfo->pExtra ){ 577bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0); 578bbd4ae5aSdrh sqlite3ExprListDelete(pParse->db, pInfo->pExtra); 579bbd4ae5aSdrh } 580bbd4ae5aSdrh #endif 581bbd4ae5aSdrh } 582bbd4ae5aSdrh 583bbd4ae5aSdrh /* 584bbd4ae5aSdrh ** Code the OP_MakeRecord instruction that generates the entry to be 585bbd4ae5aSdrh ** added into the sorter. 586bbd4ae5aSdrh ** 587bbd4ae5aSdrh ** Return the register in which the result is stored. 588bbd4ae5aSdrh */ 589bbd4ae5aSdrh static int makeSorterRecord( 590bbd4ae5aSdrh Parse *pParse, 591bbd4ae5aSdrh SortCtx *pSort, 592bbd4ae5aSdrh Select *pSelect, 593bbd4ae5aSdrh int regBase, 594bbd4ae5aSdrh int nBase 595bbd4ae5aSdrh ){ 596bbd4ae5aSdrh int nOBSat = pSort->nOBSat; 597bbd4ae5aSdrh Vdbe *v = pParse->pVdbe; 598bbd4ae5aSdrh int regOut = ++pParse->nMem; 599bbd4ae5aSdrh if( pSort->pDeferredRowLoad ){ 600bbd4ae5aSdrh innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad); 601bbd4ae5aSdrh } 602bbd4ae5aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut); 603bbd4ae5aSdrh return regOut; 604bbd4ae5aSdrh } 605bbd4ae5aSdrh 606bbd4ae5aSdrh /* 607f45f2326Sdrh ** Generate code that will push the record in registers regData 608f45f2326Sdrh ** through regData+nData-1 onto the sorter. 609c926afbcSdrh */ 610d59ba6ceSdrh static void pushOntoSorter( 611d59ba6ceSdrh Parse *pParse, /* Parser context */ 612079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 613b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 614f45f2326Sdrh int regData, /* First register holding data to be sorted */ 6155579d59fSdrh int regOrigData, /* First register holding data before packing */ 616bbd4ae5aSdrh int nData, /* Number of elements in the regData data array */ 617fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 618d59ba6ceSdrh ){ 619f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 62078d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 621f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 62278d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 623fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 624bbd4ae5aSdrh int regRecord = 0; /* Assembled sorter record */ 62578d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 626f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 627a04a8be2Sdrh int iLimit; /* LIMIT counter */ 628bbd4ae5aSdrh int iSkip = 0; /* End of the sorter insert loop */ 629f45f2326Sdrh 63078d58432Sdan assert( bSeq==0 || bSeq==1 ); 631bbd4ae5aSdrh 632bbd4ae5aSdrh /* Three cases: 633bbd4ae5aSdrh ** (1) The data to be sorted has already been packed into a Record 634bbd4ae5aSdrh ** by a prior OP_MakeRecord. In this case nData==1 and regData 635bbd4ae5aSdrh ** will be completely unrelated to regOrigData. 636bbd4ae5aSdrh ** (2) All output columns are included in the sort record. In that 637bbd4ae5aSdrh ** case regData==regOrigData. 638bbd4ae5aSdrh ** (3) Some output columns are omitted from the sort record due to 639bbd4ae5aSdrh ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the 640c6f36fa3Sdrh ** SQLITE_ECEL_OMITREF optimization, or due to the 641c6f36fa3Sdrh ** SortCtx.pDeferredRowLoad optimiation. In any of these cases 642c6f36fa3Sdrh ** regOrigData is 0 to prevent this routine from trying to copy 643c6f36fa3Sdrh ** values that might not yet exist. 644bbd4ae5aSdrh */ 6459af90b72Sdan assert( nData==1 || regData==regOrigData || regOrigData==0 ); 646bbd4ae5aSdrh 647fd0a2f97Sdrh if( nPrefixReg ){ 64878d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 649bbd4ae5aSdrh regBase = regData - nPrefixReg; 650fd0a2f97Sdrh }else{ 651fb0d6e56Sdrh regBase = pParse->nMem + 1; 652fb0d6e56Sdrh pParse->nMem += nBase; 653fd0a2f97Sdrh } 654a04a8be2Sdrh assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); 655a04a8be2Sdrh iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; 656ec4ccdbcSdrh pSort->labelDone = sqlite3VdbeMakeLabel(pParse); 6575579d59fSdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, 6589af90b72Sdan SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); 65978d58432Sdan if( bSeq ){ 660079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 661fd0a2f97Sdrh } 662257c13faSdan if( nPrefixReg==0 && nData>0 ){ 663236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 66478d58432Sdan } 665079a3072Sdrh if( nOBSat>0 ){ 666079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 667079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 668079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 669079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 670079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 671dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 672079a3072Sdrh 673bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 67426d7e7c6Sdrh regPrevKey = pParse->nMem+1; 67526d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 67678d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 67778d58432Sdan if( bSeq ){ 67878d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 67978d58432Sdan }else{ 68078d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 68178d58432Sdan } 68278d58432Sdan VdbeCoverage(v); 68326d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 684079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 68559b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 686fb0d6e56Sdrh pOp->p2 = nKey + nData; 687dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 6886e11892dSdan memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */ 689dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 690a485ad19Sdrh testcase( pKI->nAllField > pKI->nKeyField+2 ); 691f9eae18bSdan pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat, 692a485ad19Sdrh pKI->nAllField-pKI->nKeyField-1); 693166bc383Sdrh pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */ 694079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 695079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 696ec4ccdbcSdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse); 697079a3072Sdrh pSort->regReturn = ++pParse->nMem; 698079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 69965ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 700a04a8be2Sdrh if( iLimit ){ 701a04a8be2Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); 702a04a8be2Sdrh VdbeCoverage(v); 703a04a8be2Sdrh } 704079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 705236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 706079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 707079a3072Sdrh } 708f226f03dSdan if( iLimit ){ 709f226f03dSdan /* At this point the values for the new sorter entry are stored 710f226f03dSdan ** in an array of registers. They need to be composed into a record 711f226f03dSdan ** and inserted into the sorter if either (a) there are currently 712f226f03dSdan ** less than LIMIT+OFFSET items or (b) the new record is smaller than 713f226f03dSdan ** the largest record currently in the sorter. If (b) is true and there 714f226f03dSdan ** are already LIMIT+OFFSET items in the sorter, delete the largest 715f226f03dSdan ** entry before inserting the new one. This way there are never more 716f226f03dSdan ** than LIMIT+OFFSET items in the sorter. 717f226f03dSdan ** 718f226f03dSdan ** If the new record does not need to be inserted into the sorter, 7196ee5a7b4Sdrh ** jump to the next iteration of the loop. If the pSort->labelOBLopt 7206ee5a7b4Sdrh ** value is not zero, then it is a label of where to jump. Otherwise, 7216ee5a7b4Sdrh ** just bypass the row insert logic. See the header comment on the 7226ee5a7b4Sdrh ** sqlite3WhereOrderByLimitOptLabel() function for additional info. 723f226f03dSdan */ 724f226f03dSdan int iCsr = pSort->iECursor; 725f226f03dSdan sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4); 726f226f03dSdan VdbeCoverage(v); 727f226f03dSdan sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0); 728bbd4ae5aSdrh iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE, 729bbd4ae5aSdrh iCsr, 0, regBase+nOBSat, nExpr-nOBSat); 730f226f03dSdan VdbeCoverage(v); 731f226f03dSdan sqlite3VdbeAddOp1(v, OP_Delete, iCsr); 732f226f03dSdan } 733bbd4ae5aSdrh if( regRecord==0 ){ 734bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 735f226f03dSdan } 736079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 737c6aff30cSdrh op = OP_SorterInsert; 738c6aff30cSdrh }else{ 739c6aff30cSdrh op = OP_IdxInsert; 740c6aff30cSdrh } 7414a8b013eSdrh sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, 7424a8b013eSdrh regBase+nOBSat, nBase-nOBSat); 743bbd4ae5aSdrh if( iSkip ){ 744bbd4ae5aSdrh sqlite3VdbeChangeP2(v, iSkip, 7456ee5a7b4Sdrh pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v)); 746bbd4ae5aSdrh } 747c926afbcSdrh } 748c926afbcSdrh 749c926afbcSdrh /* 750ec7429aeSdrh ** Add code to implement the OFFSET 751ea48eb2eSdrh */ 752ec7429aeSdrh static void codeOffset( 753bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 754aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 755b7654111Sdrh int iContinue /* Jump here to skip the current record */ 756ea48eb2eSdrh ){ 757a22a75e5Sdrh if( iOffset>0 ){ 7588b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); 7598b0cf38aSdrh VdbeComment((v, "OFFSET")); 760ea48eb2eSdrh } 761ea48eb2eSdrh } 762ea48eb2eSdrh 763ea48eb2eSdrh /* 76498757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 76598757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 766a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 767a2a49dc9Sdrh ** if the current N values are new. 768a2a49dc9Sdrh ** 769a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 770a2a49dc9Sdrh ** stack if the top N elements are not distinct. 771a2a49dc9Sdrh */ 772a2a49dc9Sdrh static void codeDistinct( 7732dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 774a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 775a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 776477df4b3Sdrh int N, /* Number of elements */ 777a2a49dc9Sdrh int iMem /* First element */ 778a2a49dc9Sdrh ){ 7792dcef11bSdrh Vdbe *v; 7802dcef11bSdrh int r1; 7812dcef11bSdrh 7822dcef11bSdrh v = pParse->pVdbe; 7832dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 784688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); 7851db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 7869b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); 787a67b5cb6Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 7882dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 789a2a49dc9Sdrh } 790a2a49dc9Sdrh 79124e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 79224e25d32Sdan /* 79324e25d32Sdan ** This function is called as part of inner-loop generation for a SELECT 79424e25d32Sdan ** statement with an ORDER BY that is not optimized by an index. It 79524e25d32Sdan ** determines the expressions, if any, that the sorter-reference 79624e25d32Sdan ** optimization should be used for. The sorter-reference optimization 79724e25d32Sdan ** is used for SELECT queries like: 79824e25d32Sdan ** 79924e25d32Sdan ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 80024e25d32Sdan ** 80124e25d32Sdan ** If the optimization is used for expression "bigblob", then instead of 80224e25d32Sdan ** storing values read from that column in the sorter records, the PK of 80324e25d32Sdan ** the row from table t1 is stored instead. Then, as records are extracted from 80424e25d32Sdan ** the sorter to return to the user, the required value of bigblob is 80524e25d32Sdan ** retrieved directly from table t1. If the values are very large, this 80624e25d32Sdan ** can be more efficient than storing them directly in the sorter records. 80724e25d32Sdan ** 80824e25d32Sdan ** The ExprList_item.bSorterRef flag is set for each expression in pEList 80924e25d32Sdan ** for which the sorter-reference optimization should be enabled. 81024e25d32Sdan ** Additionally, the pSort->aDefer[] array is populated with entries 81124e25d32Sdan ** for all cursors required to evaluate all selected expressions. Finally. 81224e25d32Sdan ** output variable (*ppExtra) is set to an expression list containing 81324e25d32Sdan ** expressions for all extra PK values that should be stored in the 81424e25d32Sdan ** sorter records. 81524e25d32Sdan */ 81624e25d32Sdan static void selectExprDefer( 81724e25d32Sdan Parse *pParse, /* Leave any error here */ 81824e25d32Sdan SortCtx *pSort, /* Sorter context */ 81924e25d32Sdan ExprList *pEList, /* Expressions destined for sorter */ 82024e25d32Sdan ExprList **ppExtra /* Expressions to append to sorter record */ 82124e25d32Sdan ){ 82224e25d32Sdan int i; 82324e25d32Sdan int nDefer = 0; 82424e25d32Sdan ExprList *pExtra = 0; 82524e25d32Sdan for(i=0; i<pEList->nExpr; i++){ 82624e25d32Sdan struct ExprList_item *pItem = &pEList->a[i]; 82724e25d32Sdan if( pItem->u.x.iOrderByCol==0 ){ 82824e25d32Sdan Expr *pExpr = pItem->pExpr; 829eda079cdSdrh Table *pTab = pExpr->y.pTab; 8300f86c9d8Sdan if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab) 8312e3a5a81Sdan && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF) 83224e25d32Sdan ){ 83324e25d32Sdan int j; 83424e25d32Sdan for(j=0; j<nDefer; j++){ 83524e25d32Sdan if( pSort->aDefer[j].iCsr==pExpr->iTable ) break; 83624e25d32Sdan } 83724e25d32Sdan if( j==nDefer ){ 83824e25d32Sdan if( nDefer==ArraySize(pSort->aDefer) ){ 83924e25d32Sdan continue; 84024e25d32Sdan }else{ 84124e25d32Sdan int nKey = 1; 84224e25d32Sdan int k; 84324e25d32Sdan Index *pPk = 0; 84424e25d32Sdan if( !HasRowid(pTab) ){ 84524e25d32Sdan pPk = sqlite3PrimaryKeyIndex(pTab); 84624e25d32Sdan nKey = pPk->nKeyCol; 84724e25d32Sdan } 84824e25d32Sdan for(k=0; k<nKey; k++){ 84924e25d32Sdan Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0); 85024e25d32Sdan if( pNew ){ 85124e25d32Sdan pNew->iTable = pExpr->iTable; 852eda079cdSdrh pNew->y.pTab = pExpr->y.pTab; 85324e25d32Sdan pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; 85424e25d32Sdan pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew); 85524e25d32Sdan } 85624e25d32Sdan } 857eda079cdSdrh pSort->aDefer[nDefer].pTab = pExpr->y.pTab; 85824e25d32Sdan pSort->aDefer[nDefer].iCsr = pExpr->iTable; 85924e25d32Sdan pSort->aDefer[nDefer].nKey = nKey; 86024e25d32Sdan nDefer++; 86124e25d32Sdan } 86224e25d32Sdan } 86324e25d32Sdan pItem->bSorterRef = 1; 86424e25d32Sdan } 86524e25d32Sdan } 86624e25d32Sdan } 86724e25d32Sdan pSort->nDefer = (u8)nDefer; 86824e25d32Sdan *ppExtra = pExtra; 86924e25d32Sdan } 87024e25d32Sdan #endif 87124e25d32Sdan 872c99130fdSdrh /* 8732282792aSdrh ** This routine generates the code for the inside of the inner loop 8742282792aSdrh ** of a SELECT. 87582c3d636Sdrh ** 8762def2f7eSdrh ** If srcTab is negative, then the p->pEList expressions 877340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 8782def2f7eSdrh ** zero or more, then data is pulled from srcTab and p->pEList is used only 879257c13faSdan ** to get the number of columns and the collation sequence for each column. 8802282792aSdrh */ 881d2b3e23bSdrh static void selectInnerLoop( 8822282792aSdrh Parse *pParse, /* The parser context */ 883df199a25Sdrh Select *p, /* The complete select statement being coded */ 8842def2f7eSdrh int srcTab, /* Pull data from this table if non-negative */ 885079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 886e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 8876c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 8882282792aSdrh int iContinue, /* Jump here to continue with next row */ 889a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 8902282792aSdrh ){ 8912282792aSdrh Vdbe *v = pParse->pVdbe; 892d847eaadSdrh int i; 893ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 894d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 8952b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 896d847eaadSdrh int nResultCol; /* Number of result columns */ 897fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 898bbd4ae5aSdrh RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */ 89938640e15Sdrh 9009af90b72Sdan /* Usually, regResult is the first cell in an array of memory cells 9019af90b72Sdan ** containing the current result row. In this case regOrig is set to the 9029af90b72Sdan ** same value. However, if the results are being sent to the sorter, the 9039af90b72Sdan ** values for any expressions that are also part of the sort-key are omitted 9049af90b72Sdan ** from this array. In this case regOrig is set to zero. */ 9059af90b72Sdan int regResult; /* Start of memory holding current results */ 9069af90b72Sdan int regOrig; /* Start of memory holding full result (or 0) */ 9079af90b72Sdan 9081c767f0dSdrh assert( v ); 9092def2f7eSdrh assert( p->pEList!=0 ); 910e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 911079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 912079a3072Sdrh if( pSort==0 && !hasDistinct ){ 913a22a75e5Sdrh assert( iContinue!=0 ); 914aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 915df199a25Sdrh } 916df199a25Sdrh 917967e8b73Sdrh /* Pull the requested columns. 9182282792aSdrh */ 9192def2f7eSdrh nResultCol = p->pEList->nExpr; 92005a86c5cSdrh 9212b596da8Sdrh if( pDest->iSdst==0 ){ 922fd0a2f97Sdrh if( pSort ){ 92378d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 92478d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 925fd0a2f97Sdrh pParse->nMem += nPrefixReg; 9261013c932Sdrh } 927a2a49dc9Sdrh pDest->iSdst = pParse->nMem+1; 928477df4b3Sdrh pParse->nMem += nResultCol; 92905a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 93005a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 93105a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 93205a86c5cSdrh ** there are columns in the table on the left. The error will be caught 93305a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 93405a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 93505a86c5cSdrh pParse->nMem += nResultCol; 9364c583128Sdrh } 93705a86c5cSdrh pDest->nSdst = nResultCol; 9389af90b72Sdan regOrig = regResult = pDest->iSdst; 939340309fdSdrh if( srcTab>=0 ){ 940340309fdSdrh for(i=0; i<nResultCol; i++){ 941d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 94241cee668Sdrh VdbeComment((v, "%s", p->pEList->a[i].zEName)); 94382c3d636Sdrh } 9449ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 94524e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 94624e25d32Sdan ExprList *pExtra = 0; 94724e25d32Sdan #endif 9489ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 9499ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 9509ed1dfa8Sdanielk1977 */ 951bbd4ae5aSdrh u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */ 952bbd4ae5aSdrh ExprList *pEList; 953df553659Sdrh if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ 954df553659Sdrh ecelFlags = SQLITE_ECEL_DUP; 955df553659Sdrh }else{ 956df553659Sdrh ecelFlags = 0; 957a2a49dc9Sdrh } 958ac56ab7eSdan if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ 9592def2f7eSdrh /* For each expression in p->pEList that is a copy of an expression in 960257c13faSdan ** the ORDER BY clause (pSort->pOrderBy), set the associated 961257c13faSdan ** iOrderByCol value to one more than the index of the ORDER BY 962257c13faSdan ** expression within the sort-key that pushOntoSorter() will generate. 9632def2f7eSdrh ** This allows the p->pEList field to be omitted from the sorted record, 964257c13faSdan ** saving space and CPU cycles. */ 965257c13faSdan ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); 966bbd4ae5aSdrh 967257c13faSdan for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ 968257c13faSdan int j; 969257c13faSdan if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ 9702def2f7eSdrh p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; 971257c13faSdan } 972257c13faSdan } 97324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 97424e25d32Sdan selectExprDefer(pParse, pSort, p->pEList, &pExtra); 9755a2e65edSdrh if( pExtra && pParse->db->mallocFailed==0 ){ 97624e25d32Sdan /* If there are any extra PK columns to add to the sorter records, 97724e25d32Sdan ** allocate extra memory cells and adjust the OpenEphemeral 97824e25d32Sdan ** instruction to account for the larger records. This is only 97924e25d32Sdan ** required if there are one or more WITHOUT ROWID tables with 98024e25d32Sdan ** composite primary keys in the SortCtx.aDefer[] array. */ 98124e25d32Sdan VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 98224e25d32Sdan pOp->p2 += (pExtra->nExpr - pSort->nDefer); 98324e25d32Sdan pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); 98424e25d32Sdan pParse->nMem += pExtra->nExpr; 98524e25d32Sdan } 98624e25d32Sdan #endif 987bbd4ae5aSdrh 988bbd4ae5aSdrh /* Adjust nResultCol to account for columns that are omitted 989bbd4ae5aSdrh ** from the sorter by the optimizations in this branch */ 990bbd4ae5aSdrh pEList = p->pEList; 991bbd4ae5aSdrh for(i=0; i<pEList->nExpr; i++){ 992bbd4ae5aSdrh if( pEList->a[i].u.x.iOrderByCol>0 993bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 994bbd4ae5aSdrh || pEList->a[i].bSorterRef 995bbd4ae5aSdrh #endif 996bbd4ae5aSdrh ){ 997bbd4ae5aSdrh nResultCol--; 9989af90b72Sdan regOrig = 0; 999bbd4ae5aSdrh } 1000bbd4ae5aSdrh } 1001bbd4ae5aSdrh 1002bbd4ae5aSdrh testcase( regOrig ); 1003bbd4ae5aSdrh testcase( eDest==SRT_Set ); 1004bbd4ae5aSdrh testcase( eDest==SRT_Mem ); 1005bbd4ae5aSdrh testcase( eDest==SRT_Coroutine ); 1006bbd4ae5aSdrh testcase( eDest==SRT_Output ); 1007257c13faSdan assert( eDest==SRT_Set || eDest==SRT_Mem 1008257c13faSdan || eDest==SRT_Coroutine || eDest==SRT_Output ); 1009257c13faSdan } 1010bbd4ae5aSdrh sRowLoadInfo.regResult = regResult; 1011bbd4ae5aSdrh sRowLoadInfo.ecelFlags = ecelFlags; 101224e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 1013bbd4ae5aSdrh sRowLoadInfo.pExtra = pExtra; 1014bbd4ae5aSdrh sRowLoadInfo.regExtraResult = regResult + nResultCol; 1015bbd4ae5aSdrh if( pExtra ) nResultCol += pExtra->nExpr; 101624e25d32Sdan #endif 1017bbd4ae5aSdrh if( p->iLimit 1018bbd4ae5aSdrh && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 1019bbd4ae5aSdrh && nPrefixReg>0 1020bbd4ae5aSdrh ){ 1021bbd4ae5aSdrh assert( pSort!=0 ); 1022bbd4ae5aSdrh assert( hasDistinct==0 ); 1023bbd4ae5aSdrh pSort->pDeferredRowLoad = &sRowLoadInfo; 1024c6f36fa3Sdrh regOrig = 0; 1025bbd4ae5aSdrh }else{ 1026bbd4ae5aSdrh innerLoopLoadRow(pParse, p, &sRowLoadInfo); 1027bbd4ae5aSdrh } 1028a2a49dc9Sdrh } 10292282792aSdrh 1030daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 1031daffd0e5Sdrh ** and this row has been seen before, then do not make this row 1032daffd0e5Sdrh ** part of the result. 10332282792aSdrh */ 1034ea48eb2eSdrh if( hasDistinct ){ 1035e8e4af76Sdrh switch( pDistinct->eTnctType ){ 1036e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 1037e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 1038e8e4af76Sdrh int iJump; /* Jump destination */ 1039e8e4af76Sdrh int regPrev; /* Previous row content */ 1040e8e4af76Sdrh 1041e8e4af76Sdrh /* Allocate space for the previous row */ 1042e8e4af76Sdrh regPrev = pParse->nMem+1; 1043340309fdSdrh pParse->nMem += nResultCol; 1044e8e4af76Sdrh 1045e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 1046e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 1047e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 1048e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 1049e8e4af76Sdrh ** row is all NULLs. 1050e8e4af76Sdrh */ 1051e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 1052e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 1053e8e4af76Sdrh pOp->opcode = OP_Null; 1054e8e4af76Sdrh pOp->p1 = 1; 1055e8e4af76Sdrh pOp->p2 = regPrev; 1056166bc383Sdrh pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */ 1057e8e4af76Sdrh 1058340309fdSdrh iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 1059340309fdSdrh for(i=0; i<nResultCol; i++){ 10602def2f7eSdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr); 1061340309fdSdrh if( i<nResultCol-1 ){ 1062e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 1063688852abSdrh VdbeCoverage(v); 1064e8e4af76Sdrh }else{ 1065e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 1066688852abSdrh VdbeCoverage(v); 1067e8e4af76Sdrh } 1068e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 1069e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 1070e8e4af76Sdrh } 1071fcf2a775Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 1072340309fdSdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); 1073e8e4af76Sdrh break; 1074e8e4af76Sdrh } 1075e8e4af76Sdrh 1076e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 1077e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 1078e8e4af76Sdrh break; 1079e8e4af76Sdrh } 1080e8e4af76Sdrh 1081e8e4af76Sdrh default: { 1082e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 108338b4149cSdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, 108438b4149cSdrh regResult); 1085e8e4af76Sdrh break; 1086e8e4af76Sdrh } 1087e8e4af76Sdrh } 1088079a3072Sdrh if( pSort==0 ){ 1089aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 1090ea48eb2eSdrh } 10912282792aSdrh } 109282c3d636Sdrh 1093c926afbcSdrh switch( eDest ){ 109482c3d636Sdrh /* In this mode, write each query result to the key of the temporary 109582c3d636Sdrh ** table iParm. 10962282792aSdrh */ 109713449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1098c926afbcSdrh case SRT_Union: { 10999cbf3425Sdrh int r1; 11009cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 1101340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 11029b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 11039cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1104c926afbcSdrh break; 1105c926afbcSdrh } 110682c3d636Sdrh 110782c3d636Sdrh /* Construct a record from the query result, but instead of 110882c3d636Sdrh ** saving that record, use it as a key to delete elements from 110982c3d636Sdrh ** the temporary table iParm. 111082c3d636Sdrh */ 1111c926afbcSdrh case SRT_Except: { 1112340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 1113c926afbcSdrh break; 1114c926afbcSdrh } 1115781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 11165338a5f7Sdanielk1977 11175338a5f7Sdanielk1977 /* Store the result as data using a unique key. 11185338a5f7Sdanielk1977 */ 11198e1ee88cSdrh case SRT_Fifo: 11208e1ee88cSdrh case SRT_DistFifo: 11215338a5f7Sdanielk1977 case SRT_Table: 1122b9bb7c18Sdrh case SRT_EphemTab: { 1123fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 1124373cc2ddSdrh testcase( eDest==SRT_Table ); 1125373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 1126e2248cfdSdrh testcase( eDest==SRT_Fifo ); 1127e2248cfdSdrh testcase( eDest==SRT_DistFifo ); 1128fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 11298ce7184bSdan #ifndef SQLITE_OMIT_CTE 11308e1ee88cSdrh if( eDest==SRT_DistFifo ){ 11318e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 11328ce7184bSdan ** on an ephemeral index. If the current row is already present 11338ce7184bSdan ** in the index, do not write it to the output. If not, add the 11348ce7184bSdan ** current row to the index and proceed with writing it to the 11358ce7184bSdan ** output table as well. */ 11368ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 113738b4149cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); 113838b4149cSdrh VdbeCoverage(v); 11399b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); 1140079a3072Sdrh assert( pSort==0 ); 11418ce7184bSdan } 11428ce7184bSdan #endif 1143079a3072Sdrh if( pSort ){ 1144bbd4ae5aSdrh assert( regResult==regOrig ); 1145bbd4ae5aSdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg); 11465338a5f7Sdanielk1977 }else{ 1147b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 1148b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 1149b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 1150b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1151b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 11525338a5f7Sdanielk1977 } 1153fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 11545338a5f7Sdanielk1977 break; 11555338a5f7Sdanielk1977 } 11562282792aSdrh 115793758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 11582282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 11592282792aSdrh ** then there should be a single item on the stack. Write this 11602282792aSdrh ** item into the set table with bogus data. 11612282792aSdrh */ 1162c926afbcSdrh case SRT_Set: { 1163079a3072Sdrh if( pSort ){ 1164de941c60Sdrh /* At first glance you would think we could optimize out the 1165de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 1166de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 1167de941c60Sdrh ** case the order does matter */ 116851d82d1dSdan pushOntoSorter( 11699af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1170c926afbcSdrh }else{ 1171b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 117271c57db0Sdan assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); 117371c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 1174553168c7Sdan r1, pDest->zAffSdst, nResultCol); 11759b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 1176b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 1177c926afbcSdrh } 1178c926afbcSdrh break; 1179c926afbcSdrh } 118082c3d636Sdrh 1181504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 1182ec7429aeSdrh */ 1183ec7429aeSdrh case SRT_Exists: { 11844c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 1185ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1186ec7429aeSdrh break; 1187ec7429aeSdrh } 1188ec7429aeSdrh 11892282792aSdrh /* If this is a scalar select that is part of an expression, then 1190870a0705Sdan ** store the results in the appropriate memory cell or array of 1191870a0705Sdan ** memory cells and break out of the scan loop. 11922282792aSdrh */ 1193c926afbcSdrh case SRT_Mem: { 1194079a3072Sdrh if( pSort ){ 1195257c13faSdan assert( nResultCol<=pDest->nSdst ); 1196870a0705Sdan pushOntoSorter( 11979af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1198c926afbcSdrh }else{ 1199257c13faSdan assert( nResultCol==pDest->nSdst ); 120053932ce8Sdrh assert( regResult==iParm ); 1201ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 1202c926afbcSdrh } 1203c926afbcSdrh break; 1204c926afbcSdrh } 120593758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 12062282792aSdrh 120781cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 120881cf13ecSdrh case SRT_Output: { /* Return the results */ 1209373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 1210373cc2ddSdrh testcase( eDest==SRT_Output ); 1211079a3072Sdrh if( pSort ){ 12129af90b72Sdan pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, 12135579d59fSdrh nPrefixReg); 1214e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 12152b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1216c182d163Sdrh }else{ 1217340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 1218ac82fcf5Sdrh } 1219142e30dfSdrh break; 1220142e30dfSdrh } 1221142e30dfSdrh 1222fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 1223fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 1224fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 1225fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 1226fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 1227fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 1228fe1c6bb9Sdrh */ 1229fe1c6bb9Sdrh case SRT_DistQueue: 1230fe1c6bb9Sdrh case SRT_Queue: { 1231fe1c6bb9Sdrh int nKey; 1232fe1c6bb9Sdrh int r1, r2, r3; 1233fe1c6bb9Sdrh int addrTest = 0; 1234fe1c6bb9Sdrh ExprList *pSO; 1235fe1c6bb9Sdrh pSO = pDest->pOrderBy; 1236fe1c6bb9Sdrh assert( pSO ); 1237fe1c6bb9Sdrh nKey = pSO->nExpr; 1238fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 1239fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 1240fe1c6bb9Sdrh r3 = r2+nKey+1; 1241fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 1242fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 1243fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 12447e4efaecSdrh ** added to the queue. */ 12457e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 12467e4efaecSdrh regResult, nResultCol); 1247688852abSdrh VdbeCoverage(v); 12487e4efaecSdrh } 12497e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 12507e4efaecSdrh if( eDest==SRT_DistQueue ){ 1251fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 1252cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1253fe1c6bb9Sdrh } 1254fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 1255fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 1256fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 1257fe1c6bb9Sdrh r2+i); 1258fe1c6bb9Sdrh } 1259fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 1260fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 12619b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); 1262fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 1263fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 1264fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 1265fe1c6bb9Sdrh break; 1266fe1c6bb9Sdrh } 1267fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 1268fe1c6bb9Sdrh 1269fe1c6bb9Sdrh 1270fe1c6bb9Sdrh 12716a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 1272d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 1273d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 1274d7489c39Sdrh ** user-defined functions that have side effects. We do not care 1275d7489c39Sdrh ** about the actual results of the select. 1276d7489c39Sdrh */ 1277c926afbcSdrh default: { 1278f46f905aSdrh assert( eDest==SRT_Discard ); 1279c926afbcSdrh break; 1280c926afbcSdrh } 128193758c8dSdanielk1977 #endif 1282c926afbcSdrh } 1283ec7429aeSdrh 12845e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 12855e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 12865e87be87Sdrh ** the output for us. 1287ec7429aeSdrh */ 1288079a3072Sdrh if( pSort==0 && p->iLimit ){ 128916897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 1290ec7429aeSdrh } 129182c3d636Sdrh } 129282c3d636Sdrh 129382c3d636Sdrh /* 1294ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 1295ad124329Sdrh ** X extra columns. 1296323df790Sdrh */ 1297ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 1298d4ab003dSdrh int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); 1299d8e4b132Sdrh KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); 1300323df790Sdrh if( p ){ 13016e11892dSdan p->aSortFlags = (u8*)&p->aColl[N+X]; 1302a485ad19Sdrh p->nKeyField = (u16)N; 1303a485ad19Sdrh p->nAllField = (u16)(N+X); 1304323df790Sdrh p->enc = ENC(db); 1305323df790Sdrh p->db = db; 13062ec2fb22Sdrh p->nRef = 1; 1307c263f7c4Sdrh memset(&p[1], 0, nExtra); 13082ec2fb22Sdrh }else{ 13094a642b60Sdrh sqlite3OomFault(db); 1310323df790Sdrh } 1311323df790Sdrh return p; 1312323df790Sdrh } 1313323df790Sdrh 1314323df790Sdrh /* 13152ec2fb22Sdrh ** Deallocate a KeyInfo object 13162ec2fb22Sdrh */ 13172ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 13182ec2fb22Sdrh if( p ){ 13192ec2fb22Sdrh assert( p->nRef>0 ); 13202ec2fb22Sdrh p->nRef--; 1321dbd6a7dcSdrh if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); 13222ec2fb22Sdrh } 13232ec2fb22Sdrh } 13242ec2fb22Sdrh 13252ec2fb22Sdrh /* 13262ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 13272ec2fb22Sdrh */ 13282ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 13292ec2fb22Sdrh if( p ){ 13302ec2fb22Sdrh assert( p->nRef>0 ); 13312ec2fb22Sdrh p->nRef++; 13322ec2fb22Sdrh } 13332ec2fb22Sdrh return p; 13342ec2fb22Sdrh } 13352ec2fb22Sdrh 13362ec2fb22Sdrh #ifdef SQLITE_DEBUG 13372ec2fb22Sdrh /* 13382ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 13392ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 13402ec2fb22Sdrh ** 13412ec2fb22Sdrh ** This routine is used only inside of assert() statements. 13422ec2fb22Sdrh */ 13432ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 13442ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 13452ec2fb22Sdrh 13462ec2fb22Sdrh /* 1347dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1348dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1349dece1a84Sdrh ** 13500342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 13510342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 13520342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 13530342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 13540342b1f5Sdrh ** index to implement a DISTINCT test. 13550342b1f5Sdrh ** 135660ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1357dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 13582ec2fb22Sdrh ** freed. 1359dece1a84Sdrh */ 1360f9eae18bSdan KeyInfo *sqlite3KeyInfoFromExprList( 1361079a3072Sdrh Parse *pParse, /* Parsing context */ 1362079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1363079a3072Sdrh int iStart, /* Begin with this column of pList */ 1364079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1365079a3072Sdrh ){ 1366dece1a84Sdrh int nExpr; 1367dece1a84Sdrh KeyInfo *pInfo; 1368dece1a84Sdrh struct ExprList_item *pItem; 1369323df790Sdrh sqlite3 *db = pParse->db; 1370dece1a84Sdrh int i; 1371dece1a84Sdrh 1372dece1a84Sdrh nExpr = pList->nExpr; 13733f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1374dece1a84Sdrh if( pInfo ){ 13752ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 13766284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 137770efa84dSdrh pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr); 13786e11892dSdan pInfo->aSortFlags[i-iStart] = pItem->sortFlags; 1379dece1a84Sdrh } 1380dece1a84Sdrh } 1381dece1a84Sdrh return pInfo; 1382dece1a84Sdrh } 1383dece1a84Sdrh 13847f61e92cSdan /* 13857f61e92cSdan ** Name of the connection operator, used for error messages. 13867f61e92cSdan */ 13877f61e92cSdan static const char *selectOpName(int id){ 13887f61e92cSdan char *z; 13897f61e92cSdan switch( id ){ 13907f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 13917f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 13927f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 13937f61e92cSdan default: z = "UNION"; break; 13947f61e92cSdan } 13957f61e92cSdan return z; 13967f61e92cSdan } 13977f61e92cSdan 13982ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 139917c0bc0cSdan /* 140017c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 140117c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 140217c0bc0cSdan ** where the caption is of the form: 140317c0bc0cSdan ** 140417c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 140517c0bc0cSdan ** 140617c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 140717c0bc0cSdan ** is determined by the zUsage argument. 140817c0bc0cSdan */ 14092ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 1410e2ca99c9Sdrh ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage)); 14112ce22453Sdan } 141217c0bc0cSdan 141317c0bc0cSdan /* 1414bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1415bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1416bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1417bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1418bb2b4418Sdan ** code with #ifndef directives. 1419bb2b4418Sdan */ 1420bb2b4418Sdan # define explainSetInteger(a, b) a = b 1421bb2b4418Sdan 1422bb2b4418Sdan #else 1423bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1424bb2b4418Sdan # define explainTempTable(y,z) 1425bb2b4418Sdan # define explainSetInteger(y,z) 1426bb2b4418Sdan #endif 1427bb2b4418Sdan 1428dece1a84Sdrh 1429dece1a84Sdrh /* 1430d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1431d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1432d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1433d8bc7086Sdrh ** routine generates the code needed to do that. 1434d8bc7086Sdrh */ 1435c926afbcSdrh static void generateSortTail( 1436cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1437c926afbcSdrh Select *p, /* The SELECT statement */ 1438079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1439c926afbcSdrh int nColumn, /* Number of columns of data */ 14406c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1441c926afbcSdrh ){ 1442ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1443a04a8be2Sdrh int addrBreak = pSort->labelDone; /* Jump here to exit loop */ 1444ec4ccdbcSdrh int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */ 144524e25d32Sdan int addr; /* Top of output loop. Jump for Next. */ 1446079a3072Sdrh int addrOnce = 0; 14470342b1f5Sdrh int iTab; 1448079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 14496c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 14502b596da8Sdrh int iParm = pDest->iSDParm; 14512d401ab8Sdrh int regRow; 14522d401ab8Sdrh int regRowid; 1453257c13faSdan int iCol; 145424e25d32Sdan int nKey; /* Number of key columns in sorter record */ 1455f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1456f45f2326Sdrh int i; 145778d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 145824e25d32Sdan int nRefKey = 0; 145970f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 14602d401ab8Sdrh 1461a04a8be2Sdrh assert( addrBreak<0 ); 1462079a3072Sdrh if( pSort->labelBkOut ){ 1463079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1464076e85f5Sdrh sqlite3VdbeGoto(v, addrBreak); 1465079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1466079a3072Sdrh } 146724e25d32Sdan 146824e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 146924e25d32Sdan /* Open any cursors needed for sorter-reference expressions */ 147024e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 147124e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 147224e25d32Sdan int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 147324e25d32Sdan sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); 147424e25d32Sdan nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); 147524e25d32Sdan } 147624e25d32Sdan #endif 147724e25d32Sdan 1478079a3072Sdrh iTab = pSort->iECursor; 147971c57db0Sdan if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ 14803e9ca094Sdrh regRowid = 0; 1481f45f2326Sdrh regRow = pDest->iSdst; 1482ed24da4bSdrh }else{ 148351d82d1dSdan regRowid = sqlite3GetTempReg(pParse); 1484375afb8bSdrh if( eDest==SRT_EphemTab || eDest==SRT_Table ){ 1485375afb8bSdrh regRow = sqlite3GetTempReg(pParse); 1486375afb8bSdrh nColumn = 0; 1487375afb8bSdrh }else{ 148851d82d1dSdan regRow = sqlite3GetTempRange(pParse, nColumn); 1489cdd536f0Sdrh } 1490375afb8bSdrh } 1491079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1492079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1493c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1494f45f2326Sdrh iSortTab = pParse->nTab++; 149583553eefSdrh if( pSort->labelBkOut ){ 1496511f9e8dSdrh addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 149783553eefSdrh } 149824e25d32Sdan sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, 149924e25d32Sdan nKey+1+nColumn+nRefKey); 1500079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1501c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1502688852abSdrh VdbeCoverage(v); 1503aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 15046cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 150578d58432Sdan bSeq = 0; 1506c6aff30cSdrh }else{ 1507688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1508aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1509f45f2326Sdrh iSortTab = iTab; 151078d58432Sdan bSeq = 1; 1511f45f2326Sdrh } 1512d6189eafSdan for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){ 151324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 151424e25d32Sdan if( aOutEx[i].bSorterRef ) continue; 151524e25d32Sdan #endif 15169f895239Sdrh if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++; 15179f895239Sdrh } 151824e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 151924e25d32Sdan if( pSort->nDefer ){ 152024e25d32Sdan int iKey = iCol+1; 152124e25d32Sdan int regKey = sqlite3GetTempRange(pParse, nRefKey); 152224e25d32Sdan 152324e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 152424e25d32Sdan int iCsr = pSort->aDefer[i].iCsr; 152524e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 152624e25d32Sdan int nKey = pSort->aDefer[i].nKey; 152724e25d32Sdan 152824e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 152924e25d32Sdan if( HasRowid(pTab) ){ 153024e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); 153124e25d32Sdan sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, 153224e25d32Sdan sqlite3VdbeCurrentAddr(v)+1, regKey); 153324e25d32Sdan }else{ 153424e25d32Sdan int k; 153524e25d32Sdan int iJmp; 15367590d093Sdrh assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); 153724e25d32Sdan for(k=0; k<nKey; k++){ 153824e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k); 153924e25d32Sdan } 154024e25d32Sdan iJmp = sqlite3VdbeCurrentAddr(v); 154124e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey); 154224e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey); 154324e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 154424e25d32Sdan } 154524e25d32Sdan } 154624e25d32Sdan sqlite3ReleaseTempRange(pParse, regKey, nRefKey); 154724e25d32Sdan } 154824e25d32Sdan #endif 1549d6189eafSdan for(i=nColumn-1; i>=0; i--){ 155024e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 155124e25d32Sdan if( aOutEx[i].bSorterRef ){ 155224e25d32Sdan sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); 155324e25d32Sdan }else 155424e25d32Sdan #endif 155524e25d32Sdan { 1556257c13faSdan int iRead; 1557257c13faSdan if( aOutEx[i].u.x.iOrderByCol ){ 1558257c13faSdan iRead = aOutEx[i].u.x.iOrderByCol-1; 1559257c13faSdan }else{ 15609f895239Sdrh iRead = iCol--; 1561257c13faSdan } 1562257c13faSdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); 1563cbb9da33Sdrh VdbeComment((v, "%s", aOutEx[i].zEName)); 1564c6aff30cSdrh } 156524e25d32Sdan } 1566c926afbcSdrh switch( eDest ){ 1567ac56ab7eSdan case SRT_Table: 1568b9bb7c18Sdrh case SRT_EphemTab: { 1569375afb8bSdrh sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow); 15702d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 15712d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 15722d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1573c926afbcSdrh break; 1574c926afbcSdrh } 157593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1576c926afbcSdrh case SRT_Set: { 157771c57db0Sdan assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); 157871c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, 1579553168c7Sdan pDest->zAffSdst, nColumn); 15809b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); 1581c926afbcSdrh break; 1582c926afbcSdrh } 1583c926afbcSdrh case SRT_Mem: { 1584ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1585c926afbcSdrh break; 1586c926afbcSdrh } 158793758c8dSdanielk1977 #endif 1588373cc2ddSdrh default: { 1589373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 15901c767f0dSdrh testcase( eDest==SRT_Output ); 15911c767f0dSdrh testcase( eDest==SRT_Coroutine ); 15927d10d5a6Sdrh if( eDest==SRT_Output ){ 15932b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 1594a9671a22Sdrh }else{ 15952b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1596ce665cf6Sdrh } 1597ac82fcf5Sdrh break; 1598ac82fcf5Sdrh } 1599c926afbcSdrh } 1600f45f2326Sdrh if( regRowid ){ 160151d82d1dSdan if( eDest==SRT_Set ){ 160251d82d1dSdan sqlite3ReleaseTempRange(pParse, regRow, nColumn); 160351d82d1dSdan }else{ 16042d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 160551d82d1dSdan } 16062d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1607f45f2326Sdrh } 1608ec7429aeSdrh /* The bottom of the loop 1609ec7429aeSdrh */ 1610dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1611079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1612688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1613c6aff30cSdrh }else{ 1614688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1615c6aff30cSdrh } 1616079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1617dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1618d8bc7086Sdrh } 1619d8bc7086Sdrh 1620d8bc7086Sdrh /* 1621517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1622517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1623e78e8284Sdrh ** 16245f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 16255f3e5e74Sdrh ** result in *pEstWidth. 16265f3e5e74Sdrh ** 1627955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1628955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1629955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1630955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1631955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1632955de52cSdanielk1977 ** considered a column by this function. 1633e78e8284Sdrh ** 1634955de52cSdanielk1977 ** SELECT col FROM tbl; 1635955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1636955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1637955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1638955de52cSdanielk1977 ** 1639955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 16405f3e5e74Sdrh ** 16415f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 16425f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1643fcb78a49Sdrh */ 16445f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1645cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) 1646b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1647cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B) 1648b121dd14Sdrh #endif 16495f3e5e74Sdrh static const char *columnTypeImpl( 1650955de52cSdanielk1977 NameContext *pNC, 1651cafc2f7bSdrh #ifndef SQLITE_ENABLE_COLUMN_METADATA 1652cafc2f7bSdrh Expr *pExpr 1653cafc2f7bSdrh #else 1654955de52cSdanielk1977 Expr *pExpr, 16555f3e5e74Sdrh const char **pzOrigDb, 16565f3e5e74Sdrh const char **pzOrigTab, 1657cafc2f7bSdrh const char **pzOrigCol 1658b121dd14Sdrh #endif 1659955de52cSdanielk1977 ){ 1660955de52cSdanielk1977 char const *zType = 0; 1661517eb646Sdanielk1977 int j; 1662b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1663b121dd14Sdrh char const *zOrigDb = 0; 1664b121dd14Sdrh char const *zOrigTab = 0; 1665b121dd14Sdrh char const *zOrigCol = 0; 1666b121dd14Sdrh #endif 16675338a5f7Sdanielk1977 1668f7ce4291Sdrh assert( pExpr!=0 ); 1669f7ce4291Sdrh assert( pNC->pSrcList!=0 ); 167000e279d9Sdanielk1977 switch( pExpr->op ){ 167100e279d9Sdanielk1977 case TK_COLUMN: { 1672955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1673955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1674955de52cSdanielk1977 ** database table or a subquery. 1675955de52cSdanielk1977 */ 1676955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1677955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1678955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 167943bc88bbSdan while( pNC && !pTab ){ 1680b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1681b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1682b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 16836a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1684955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1685b3bce662Sdanielk1977 }else{ 1686b3bce662Sdanielk1977 pNC = pNC->pNext; 1687b3bce662Sdanielk1977 } 1688b3bce662Sdanielk1977 } 1689955de52cSdanielk1977 169043bc88bbSdan if( pTab==0 ){ 1691417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1692417168adSdrh ** cause this condition to run. Since then, we have restructured how 1693417168adSdrh ** trigger code is generated and so this condition is no longer 169443bc88bbSdan ** possible. However, it can still be true for statements like 169543bc88bbSdan ** the following: 169643bc88bbSdan ** 169743bc88bbSdan ** CREATE TABLE t1(col INTEGER); 169843bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 169943bc88bbSdan ** 170043bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 170143bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 170243bc88bbSdan ** though it should really be "INTEGER". 170343bc88bbSdan ** 170443bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 170543bc88bbSdan ** used. When columnType() is called on the expression 170643bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 170743bc88bbSdan ** branch below. */ 17087e62779aSdrh break; 17097e62779aSdrh } 1710955de52cSdanielk1977 1711eda079cdSdrh assert( pTab && pExpr->y.pTab==pTab ); 1712955de52cSdanielk1977 if( pS ){ 1713955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1714955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1715955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1716955de52cSdanielk1977 */ 1717f35f2f92Sdrh if( iCol>=0 && iCol<pS->pEList->nExpr ){ 1718955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1719955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1720955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1721955de52cSdanielk1977 */ 1722955de52cSdanielk1977 NameContext sNC; 1723955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1724955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 172543bc88bbSdan sNC.pNext = pNC; 1726955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1727cafc2f7bSdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 1728955de52cSdanielk1977 } 1729a78d757cSdrh }else{ 1730a78d757cSdrh /* A real table or a CTE table */ 1731955de52cSdanielk1977 assert( !pS ); 17325f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1733a78d757cSdrh if( iCol<0 ) iCol = pTab->iPKey; 1734a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 1735fcb78a49Sdrh if( iCol<0 ){ 1736fcb78a49Sdrh zType = "INTEGER"; 17375f3e5e74Sdrh zOrigCol = "rowid"; 1738fcb78a49Sdrh }else{ 17395f3e5e74Sdrh zOrigCol = pTab->aCol[iCol].zName; 1740d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 1741955de52cSdanielk1977 } 17425f3e5e74Sdrh zOrigTab = pTab->zName; 1743a78d757cSdrh if( pNC->pParse && pTab->pSchema ){ 1744955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1745e59be010Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; 1746955de52cSdanielk1977 } 17475f3e5e74Sdrh #else 1748a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 17495f3e5e74Sdrh if( iCol<0 ){ 17505f3e5e74Sdrh zType = "INTEGER"; 17515f3e5e74Sdrh }else{ 1752d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 17535f3e5e74Sdrh } 17545f3e5e74Sdrh #endif 1755fcb78a49Sdrh } 175600e279d9Sdanielk1977 break; 1757736c22b8Sdrh } 175893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 175900e279d9Sdanielk1977 case TK_SELECT: { 1760955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1761955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1762955de52cSdanielk1977 ** statement. 1763955de52cSdanielk1977 */ 1764b3bce662Sdanielk1977 NameContext sNC; 17656ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1766955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 17676ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1768955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1769b3bce662Sdanielk1977 sNC.pNext = pNC; 1770955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1771cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 177200e279d9Sdanielk1977 break; 1773fcb78a49Sdrh } 177493758c8dSdanielk1977 #endif 177500e279d9Sdanielk1977 } 177600e279d9Sdanielk1977 17775f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 17785f3e5e74Sdrh if( pzOrigDb ){ 17795f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 17805f3e5e74Sdrh *pzOrigDb = zOrigDb; 17815f3e5e74Sdrh *pzOrigTab = zOrigTab; 17825f3e5e74Sdrh *pzOrigCol = zOrigCol; 1783955de52cSdanielk1977 } 17845f3e5e74Sdrh #endif 1785517eb646Sdanielk1977 return zType; 1786517eb646Sdanielk1977 } 1787517eb646Sdanielk1977 1788517eb646Sdanielk1977 /* 1789517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1790517eb646Sdanielk1977 ** in the result set. 1791517eb646Sdanielk1977 */ 1792517eb646Sdanielk1977 static void generateColumnTypes( 1793517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1794517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1795517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1796517eb646Sdanielk1977 ){ 17973f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1798517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1799517eb646Sdanielk1977 int i; 1800b3bce662Sdanielk1977 NameContext sNC; 1801b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1802955de52cSdanielk1977 sNC.pParse = pParse; 1803eac5fc04Sdrh sNC.pNext = 0; 1804517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1805517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 18063f913576Sdrh const char *zType; 18073f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1808955de52cSdanielk1977 const char *zOrigDb = 0; 1809955de52cSdanielk1977 const char *zOrigTab = 0; 1810955de52cSdanielk1977 const char *zOrigCol = 0; 1811cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1812955de52cSdanielk1977 181385b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 18144b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 18154b1ae99dSdanielk1977 ** virtual machine is deleted. 1816fbcd585fSdanielk1977 */ 181710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 181810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 181910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 18203f913576Sdrh #else 1821cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 18223f913576Sdrh #endif 182310fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1824fcb78a49Sdrh } 18255f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1826fcb78a49Sdrh } 1827fcb78a49Sdrh 1828eac5fc04Sdrh 1829eac5fc04Sdrh /* 1830ec360a8dSdrh ** Compute the column names for a SELECT statement. 1831ec360a8dSdrh ** 1832ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1833ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1834ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1835ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1836ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1837ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1838ec360a8dSdrh ** 1839ec360a8dSdrh ** See Also: sqlite3ColumnsFromExprList() 1840ec360a8dSdrh ** 1841ec360a8dSdrh ** The PRAGMA short_column_names and PRAGMA full_column_names settings are 1842ec360a8dSdrh ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all 1843ec360a8dSdrh ** applications should operate this way. Nevertheless, we need to support the 1844ec360a8dSdrh ** other modes for legacy: 1845ec360a8dSdrh ** 1846ec360a8dSdrh ** short=OFF, full=OFF: Column name is the text of the expression has it 1847ec360a8dSdrh ** originally appears in the SELECT statement. In 1848ec360a8dSdrh ** other words, the zSpan of the result expression. 1849ec360a8dSdrh ** 1850ec360a8dSdrh ** short=ON, full=OFF: (This is the default setting). If the result 18513d240d21Sdrh ** refers directly to a table column, then the 18523d240d21Sdrh ** result column name is just the table column 18533d240d21Sdrh ** name: COLUMN. Otherwise use zSpan. 1854ec360a8dSdrh ** 1855ec360a8dSdrh ** full=ON, short=ANY: If the result refers directly to a table column, 1856ec360a8dSdrh ** then the result column name with the table name 1857ec360a8dSdrh ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. 185882c3d636Sdrh */ 1859832508b7Sdrh static void generateColumnNames( 1860832508b7Sdrh Parse *pParse, /* Parser context */ 1861f35f2f92Sdrh Select *pSelect /* Generate column names for this SELECT statement */ 1862832508b7Sdrh ){ 1863d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1864eac5fc04Sdrh int i; 1865eac5fc04Sdrh Table *pTab; 1866f35f2f92Sdrh SrcList *pTabList; 1867f35f2f92Sdrh ExprList *pEList; 18689bb575fdSdrh sqlite3 *db = pParse->db; 1869ec360a8dSdrh int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ 1870ec360a8dSdrh int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ 1871fcabd464Sdrh 1872fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 18733cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 18743cf86063Sdanielk1977 if( pParse->explain ){ 187561de0d1bSdanielk1977 return; 18763cf86063Sdanielk1977 } 18775338a5f7Sdanielk1977 #endif 18783cf86063Sdanielk1977 18795e8b9853Sdrh if( pParse->colNamesSet ) return; 1880f35f2f92Sdrh /* Column names are determined by the left-most term of a compound select */ 1881f35f2f92Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 188207859486Sdrh SELECTTRACE(1,pParse,pSelect,("generating column names\n")); 1883f35f2f92Sdrh pTabList = pSelect->pSrc; 1884f35f2f92Sdrh pEList = pSelect->pEList; 18859802947fSdrh assert( v!=0 ); 1886f7ce4291Sdrh assert( pTabList!=0 ); 1887d8bc7086Sdrh pParse->colNamesSet = 1; 1888ec360a8dSdrh fullName = (db->flags & SQLITE_FullColNames)!=0; 1889ec360a8dSdrh srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; 189022322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 189182c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 1892ec360a8dSdrh Expr *p = pEList->a[i].pExpr; 1893ec360a8dSdrh 1894ec360a8dSdrh assert( p!=0 ); 18954dd89d5aSdrh assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ 1896eda079cdSdrh assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */ 1897cbb9da33Sdrh if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){ 1898ec360a8dSdrh /* An AS clause always takes first priority */ 189941cee668Sdrh char *zName = pEList->a[i].zEName; 190010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1901f35f2f92Sdrh }else if( srcName && p->op==TK_COLUMN ){ 190297665873Sdrh char *zCol; 19038aff1015Sdrh int iCol = p->iColumn; 1904eda079cdSdrh pTab = p->y.pTab; 1905f35f2f92Sdrh assert( pTab!=0 ); 19068aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 190797665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1908b1363206Sdrh if( iCol<0 ){ 190947a6db2bSdrh zCol = "rowid"; 1910b1363206Sdrh }else{ 1911b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1912b1363206Sdrh } 1913ec360a8dSdrh if( fullName ){ 191482c3d636Sdrh char *zName = 0; 19151c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 191610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 191782c3d636Sdrh }else{ 191810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 191982c3d636Sdrh } 19201bee3d7bSdrh }else{ 1921cbb9da33Sdrh const char *z = pEList->a[i].zEName; 1922859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 1923859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 192482c3d636Sdrh } 192582c3d636Sdrh } 192676d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 19275080aaa7Sdrh } 192882c3d636Sdrh 1929d8bc7086Sdrh /* 193060ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 19317d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 19327d10d5a6Sdrh ** column names for a table that would hold the expression list. 19337d10d5a6Sdrh ** 19347d10d5a6Sdrh ** All column names will be unique. 19357d10d5a6Sdrh ** 19367d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 19377d10d5a6Sdrh ** and other fields of Column are zeroed. 19387d10d5a6Sdrh ** 19397d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 19407d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1941ec360a8dSdrh ** 1942ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1943ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1944ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1945ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1946ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1947ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1948ec360a8dSdrh ** 1949ec360a8dSdrh ** See Also: generateColumnNames() 1950315555caSdrh */ 19518981b904Sdrh int sqlite3ColumnsFromExprList( 19527d10d5a6Sdrh Parse *pParse, /* Parsing context */ 19537d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1954d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 19557d10d5a6Sdrh Column **paCol /* Write the new column list here */ 19567d10d5a6Sdrh ){ 1957dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1958dc5ea5c7Sdrh int i, j; /* Loop counters */ 1959ebed3fa3Sdrh u32 cnt; /* Index added to make the name unique */ 1960dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1961dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1962dc5ea5c7Sdrh char *zName; /* Column name */ 1963dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 19640315e3ccSdrh Hash ht; /* Hash table of column names */ 196579d5f63fSdrh 19660315e3ccSdrh sqlite3HashInit(&ht); 19678c2e0f02Sdan if( pEList ){ 19688c2e0f02Sdan nCol = pEList->nExpr; 19698c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 19708c2e0f02Sdan testcase( aCol==0 ); 19716fe3733bSdrh if( nCol>32767 ) nCol = 32767; 19728c2e0f02Sdan }else{ 19738c2e0f02Sdan nCol = 0; 19748c2e0f02Sdan aCol = 0; 19758c2e0f02Sdan } 19768836cbbcSdan assert( nCol==(i16)nCol ); 19778c2e0f02Sdan *pnCol = nCol; 19788c2e0f02Sdan *paCol = aCol; 19798c2e0f02Sdan 19800315e3ccSdrh for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ 198179d5f63fSdrh /* Get an appropriate name for the column 198279d5f63fSdrh */ 1983cbb9da33Sdrh if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){ 198479d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 19857d10d5a6Sdrh }else{ 19860d950af3Sdrh Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr); 1987b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1988b07028f7Sdrh pColExpr = pColExpr->pRight; 1989b07028f7Sdrh assert( pColExpr!=0 ); 1990b07028f7Sdrh } 1991755b0fd3Sdrh if( pColExpr->op==TK_COLUMN ){ 199293a960a0Sdrh /* For columns use the column name name */ 1993dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1994eda079cdSdrh Table *pTab = pColExpr->y.pTab; 1995755b0fd3Sdrh assert( pTab!=0 ); 1996f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 199796ceaf86Sdrh zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; 1998b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 199933e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 200096ceaf86Sdrh zName = pColExpr->u.zToken; 200193a960a0Sdrh }else{ 200279d5f63fSdrh /* Use the original text of the column expression as its name */ 2003cbb9da33Sdrh zName = pEList->a[i].zEName; 20047d10d5a6Sdrh } 200522f70c32Sdrh } 20060cbec59cSdrh if( zName && !sqlite3IsTrueOrFalse(zName) ){ 2007d7ca600eSdrh zName = sqlite3DbStrDup(db, zName); 2008d7ca600eSdrh }else{ 2009155507b3Sdrh zName = sqlite3MPrintf(db,"column%d",i+1); 2010d7ca600eSdrh } 201179d5f63fSdrh 201279d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 201360ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 201479d5f63fSdrh */ 20150315e3ccSdrh cnt = 0; 20160315e3ccSdrh while( zName && sqlite3HashFind(&ht, zName)!=0 ){ 20170315e3ccSdrh nName = sqlite3Strlen30(zName); 2018f7ee8965Sdrh if( nName>0 ){ 20190315e3ccSdrh for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} 20200315e3ccSdrh if( zName[j]==':' ) nName = j; 2021f7ee8965Sdrh } 202296ceaf86Sdrh zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); 2023ebed3fa3Sdrh if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); 202479d5f63fSdrh } 202591bb0eedSdrh pCol->zName = zName; 2026ba68f8f3Sdan sqlite3ColumnPropertiesFromName(0, pCol); 202703d69a68Sdrh if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ 20284a642b60Sdrh sqlite3OomFault(db); 20297d10d5a6Sdrh } 20300315e3ccSdrh } 20310315e3ccSdrh sqlite3HashClear(&ht); 20327d10d5a6Sdrh if( db->mallocFailed ){ 20337d10d5a6Sdrh for(j=0; j<i; j++){ 20347d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 20357d10d5a6Sdrh } 20367d10d5a6Sdrh sqlite3DbFree(db, aCol); 20377d10d5a6Sdrh *paCol = 0; 20387d10d5a6Sdrh *pnCol = 0; 2039fad3039cSmistachkin return SQLITE_NOMEM_BKPT; 20407d10d5a6Sdrh } 20417d10d5a6Sdrh return SQLITE_OK; 20427d10d5a6Sdrh } 2043e014a838Sdanielk1977 20447d10d5a6Sdrh /* 20457d10d5a6Sdrh ** Add type and collation information to a column list based on 20467d10d5a6Sdrh ** a SELECT statement. 20477d10d5a6Sdrh ** 20487d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 20497d10d5a6Sdrh ** The column list has only names, not types or collations. This 20507d10d5a6Sdrh ** routine goes through and adds the types and collations. 20517d10d5a6Sdrh ** 2052b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 20537d10d5a6Sdrh ** statement be resolved. 205479d5f63fSdrh */ 2055ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation( 20567d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 2057186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 205881506b88Sdrh Select *pSelect, /* SELECT used to determine types and collations */ 205981506b88Sdrh char aff /* Default affinity for columns */ 20607d10d5a6Sdrh ){ 20617d10d5a6Sdrh sqlite3 *db = pParse->db; 20627d10d5a6Sdrh NameContext sNC; 20637d10d5a6Sdrh Column *pCol; 20647d10d5a6Sdrh CollSeq *pColl; 20657d10d5a6Sdrh int i; 20667d10d5a6Sdrh Expr *p; 20677d10d5a6Sdrh struct ExprList_item *a; 20687d10d5a6Sdrh 20697d10d5a6Sdrh assert( pSelect!=0 ); 20707d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 2071186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 20727d10d5a6Sdrh if( db->mallocFailed ) return; 2073c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 2074b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 20757d10d5a6Sdrh a = pSelect->pEList->a; 2076186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 2077ed06a131Sdrh const char *zType; 2078ed06a131Sdrh int n, m; 20797d10d5a6Sdrh p = a[i].pExpr; 2080cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 2081cafc2f7bSdrh /* pCol->szEst = ... // Column size est for SELECT tables never used */ 2082c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 20830c4db034Sdrh if( zType ){ 20840c4db034Sdrh m = sqlite3Strlen30(zType); 2085ed06a131Sdrh n = sqlite3Strlen30(pCol->zName); 2086ed06a131Sdrh pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); 2087ed06a131Sdrh if( pCol->zName ){ 2088ed06a131Sdrh memcpy(&pCol->zName[n+1], zType, m+1); 2089ed06a131Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 2090ed06a131Sdrh } 2091ed06a131Sdrh } 209296fb16eeSdrh if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff; 2093b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 20941cb50c88Sdrh if( pColl && pCol->zColl==0 ){ 209517435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 20960202b29eSdanielk1977 } 209722f70c32Sdrh } 2098cafc2f7bSdrh pTab->szTabRow = 1; /* Any non-zero value works */ 20997d10d5a6Sdrh } 21007d10d5a6Sdrh 21017d10d5a6Sdrh /* 21027d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 21037d10d5a6Sdrh ** the result set of that SELECT. 21047d10d5a6Sdrh */ 210581506b88Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){ 21067d10d5a6Sdrh Table *pTab; 21077d10d5a6Sdrh sqlite3 *db = pParse->db; 210870d5dfbaSdrh u64 savedFlags; 21097d10d5a6Sdrh 21107d10d5a6Sdrh savedFlags = db->flags; 2111d5b44d60Sdrh db->flags &= ~(u64)SQLITE_FullColNames; 21127d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 21137d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 2114491b6d89Sdrh db->flags = savedFlags; 21157d10d5a6Sdrh if( pParse->nErr ) return 0; 21167d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 21177d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 21187d10d5a6Sdrh if( pTab==0 ){ 21197d10d5a6Sdrh return 0; 21207d10d5a6Sdrh } 212179df7782Sdrh pTab->nTabRef = 1; 21227d10d5a6Sdrh pTab->zName = 0; 2123cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 21248981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 212581506b88Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff); 212622f70c32Sdrh pTab->iPKey = -1; 21277ce72f69Sdrh if( db->mallocFailed ){ 21281feeaed2Sdan sqlite3DeleteTable(db, pTab); 21297ce72f69Sdrh return 0; 21307ce72f69Sdrh } 213122f70c32Sdrh return pTab; 213222f70c32Sdrh } 213322f70c32Sdrh 213422f70c32Sdrh /* 2135d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 2136d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 2137d8bc7086Sdrh */ 213855965619Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){ 213955965619Sdrh if( pParse->pVdbe ){ 214055965619Sdrh return pParse->pVdbe; 214155965619Sdrh } 2142e0e261a4Sdrh if( pParse->pToplevel==0 2143e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 2144e0e261a4Sdrh ){ 2145e0e261a4Sdrh pParse->okConstFactor = 1; 2146949f9cd5Sdrh } 214755965619Sdrh return sqlite3VdbeCreate(pParse); 21486f077343Sdrh } 2149d8bc7086Sdrh 215015007a99Sdrh 2151d8bc7086Sdrh /* 21527b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 21538c0833fbSdrh ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions 21547b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 2155a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 2156a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 2157a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 2158a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 21597b58daeaSdrh ** 2160d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 21618c0833fbSdrh ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit 21628c0833fbSdrh ** and iOffset should have been preset to appropriate default values (zero) 2163aa9ce707Sdrh ** prior to calling this routine. 2164aa9ce707Sdrh ** 2165aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 2166aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 2167aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 2168aa9ce707Sdrh ** 21698c0833fbSdrh ** Only if pLimit->pLeft!=0 do the limit registers get 21707b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 21717b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 21727b58daeaSdrh ** SELECT statements. 21737b58daeaSdrh */ 2174ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 217502afc861Sdrh Vdbe *v = 0; 217602afc861Sdrh int iLimit = 0; 217715007a99Sdrh int iOffset; 21788b0cf38aSdrh int n; 21798c0833fbSdrh Expr *pLimit = p->pLimit; 21808c0833fbSdrh 21810acb7e48Sdrh if( p->iLimit ) return; 218215007a99Sdrh 21837b58daeaSdrh /* 21847b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 2185f7b5496eSdrh ** controversy about what the correct behavior should be. 21867b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 21877b58daeaSdrh ** no rows. 21887b58daeaSdrh */ 21898c0833fbSdrh if( pLimit ){ 21908c0833fbSdrh assert( pLimit->op==TK_LIMIT ); 21918c0833fbSdrh assert( pLimit->pLeft!=0 ); 21920a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 219315007a99Sdrh v = sqlite3GetVdbe(pParse); 2194aa9ce707Sdrh assert( v!=0 ); 21958c0833fbSdrh if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){ 21969b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 21979b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 2198456e4e4fSdrh if( n==0 ){ 2199076e85f5Sdrh sqlite3VdbeGoto(v, iBreak); 2200c3489bbfSdrh }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ 2201c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)n); 2202c3489bbfSdrh p->selFlags |= SF_FixedLimit; 22039b918ed1Sdrh } 22049b918ed1Sdrh }else{ 22058c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); 2206688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 2207d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 220816897072Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); 22099b918ed1Sdrh } 22108c0833fbSdrh if( pLimit->pRight ){ 22110a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 2212b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 22138c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pRight, iOffset); 2214688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 2215d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 2216cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); 2217d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 2218b7654111Sdrh } 2219d59ba6ceSdrh } 22207b58daeaSdrh } 22217b58daeaSdrh 2222b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 2223fbc4ee7bSdrh /* 2224fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 2225fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 2226fbc4ee7bSdrh ** the column has no default collating sequence. 2227fbc4ee7bSdrh ** 2228fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 2229fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 2230fbc4ee7bSdrh */ 2231dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 2232fbc4ee7bSdrh CollSeq *pRet; 2233dc1bdc4fSdanielk1977 if( p->pPrior ){ 2234dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 2235fbc4ee7bSdrh }else{ 2236fbc4ee7bSdrh pRet = 0; 2237dc1bdc4fSdanielk1977 } 223810c081adSdrh assert( iCol>=0 ); 22392ec18a3cSdrh /* iCol must be less than p->pEList->nExpr. Otherwise an error would 22402ec18a3cSdrh ** have been thrown during name resolution and we would not have gotten 22412ec18a3cSdrh ** this far */ 22422ec18a3cSdrh if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ 2243dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 2244dc1bdc4fSdanielk1977 } 2245dc1bdc4fSdanielk1977 return pRet; 2246d3d39e93Sdrh } 2247d3d39e93Sdrh 224853bed45eSdan /* 224953bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 225053bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 225153bed45eSdan ** structure suitable for implementing the ORDER BY. 225253bed45eSdan ** 225353bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 225453bed45eSdan ** function is responsible for ensuring that this structure is eventually 225553bed45eSdan ** freed. 225653bed45eSdan */ 225753bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 225853bed45eSdan ExprList *pOrderBy = p->pOrderBy; 225953bed45eSdan int nOrderBy = p->pOrderBy->nExpr; 226053bed45eSdan sqlite3 *db = pParse->db; 226153bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 226253bed45eSdan if( pRet ){ 226353bed45eSdan int i; 226453bed45eSdan for(i=0; i<nOrderBy; i++){ 226553bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 226653bed45eSdan Expr *pTerm = pItem->pExpr; 226753bed45eSdan CollSeq *pColl; 226853bed45eSdan 226953bed45eSdan if( pTerm->flags & EP_Collate ){ 227053bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 227153bed45eSdan }else{ 227253bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 227353bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 227453bed45eSdan pOrderBy->a[i].pExpr = 227553bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 227653bed45eSdan } 227753bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 227853bed45eSdan pRet->aColl[i] = pColl; 22796e11892dSdan pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags; 228053bed45eSdan } 228153bed45eSdan } 228253bed45eSdan 228353bed45eSdan return pRet; 228453bed45eSdan } 2285d3d39e93Sdrh 2286781def29Sdrh #ifndef SQLITE_OMIT_CTE 2287781def29Sdrh /* 2288781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 2289781def29Sdrh ** query of the form: 2290781def29Sdrh ** 2291781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 2292781def29Sdrh ** \___________/ \_______________/ 2293781def29Sdrh ** p->pPrior p 2294781def29Sdrh ** 2295781def29Sdrh ** 2296781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 22978a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. 2298781def29Sdrh ** 2299781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 2300781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 2301fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 2302fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 2303fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 2304781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 2305781def29Sdrh ** and the iteration continues until the Queue table is empty. 2306781def29Sdrh ** 2307781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 2308781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 2309781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 2310781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 2311781def29Sdrh ** 2312781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 2313781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 2314781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 2315781def29Sdrh ** 2316781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 2317781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 2318781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 2319781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 2320781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 2321781def29Sdrh ** rows have been skipped. 2322781def29Sdrh */ 2323781def29Sdrh static void generateWithRecursiveQuery( 2324781def29Sdrh Parse *pParse, /* Parsing context */ 2325781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 2326781def29Sdrh SelectDest *pDest /* What to do with query results */ 2327781def29Sdrh ){ 2328781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 2329781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 2330781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 2331781def29Sdrh Select *pSetup = p->pPrior; /* The setup query */ 2332781def29Sdrh int addrTop; /* Top of the loop */ 2333781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 2334edf83d1eSdrh int iCurrent = 0; /* The Current table */ 2335781def29Sdrh int regCurrent; /* Register holding Current table */ 2336781def29Sdrh int iQueue; /* The Queue table */ 2337781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 23388e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 2339781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 2340781def29Sdrh int i; /* Loop counter */ 2341781def29Sdrh int rc; /* Result code */ 2342fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 23438c0833fbSdrh Expr *pLimit; /* Saved LIMIT and OFFSET */ 2344aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 2345781def29Sdrh 23466afa35c9Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 23476afa35c9Sdan if( p->pWin ){ 23486afa35c9Sdan sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries"); 23496afa35c9Sdan return; 23506afa35c9Sdan } 23516afa35c9Sdan #endif 23526afa35c9Sdan 2353781def29Sdrh /* Obtain authorization to do a recursive query */ 2354781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 2355781def29Sdrh 2356aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 2357ec4ccdbcSdrh addrBreak = sqlite3VdbeMakeLabel(pParse); 235869b9383eSdan p->nSelectRow = 320; /* 4 billion rows */ 2359aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 2360aa9ce707Sdrh pLimit = p->pLimit; 2361aa9ce707Sdrh regLimit = p->iLimit; 2362aa9ce707Sdrh regOffset = p->iOffset; 23638c0833fbSdrh p->pLimit = 0; 2364aa9ce707Sdrh p->iLimit = p->iOffset = 0; 236553bed45eSdan pOrderBy = p->pOrderBy; 2366781def29Sdrh 2367781def29Sdrh /* Locate the cursor number of the Current table */ 2368781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 23698a48b9c0Sdrh if( pSrc->a[i].fg.isRecursive ){ 2370781def29Sdrh iCurrent = pSrc->a[i].iCursor; 2371781def29Sdrh break; 2372781def29Sdrh } 2373781def29Sdrh } 2374781def29Sdrh 2375fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2376781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 23778e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2378781def29Sdrh iQueue = pParse->nTab++; 2379781def29Sdrh if( p->op==TK_UNION ){ 23808e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 2381781def29Sdrh iDistinct = pParse->nTab++; 2382fe1c6bb9Sdrh }else{ 23838e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2384781def29Sdrh } 2385781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2386781def29Sdrh 2387781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2388781def29Sdrh regCurrent = ++pParse->nMem; 2389781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2390fe1c6bb9Sdrh if( pOrderBy ){ 239153bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2392fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2393fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2394fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2395fe1c6bb9Sdrh }else{ 2396781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2397fe1c6bb9Sdrh } 2398fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2399781def29Sdrh if( iDistinct ){ 2400781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2401781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2402781def29Sdrh } 2403781def29Sdrh 240453bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 240553bed45eSdan p->pOrderBy = 0; 240653bed45eSdan 2407781def29Sdrh /* Store the results of the setup-query in Queue. */ 2408d227a291Sdrh pSetup->pNext = 0; 240984a01debSdrh ExplainQueryPlan((pParse, 1, "SETUP")); 2410781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2411d227a291Sdrh pSetup->pNext = p; 2412fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2413781def29Sdrh 2414781def29Sdrh /* Find the next row in the Queue and output that row */ 2415688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2416781def29Sdrh 2417781def29Sdrh /* Transfer the next row in Queue over to Current */ 2418781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2419fe1c6bb9Sdrh if( pOrderBy ){ 2420fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2421fe1c6bb9Sdrh }else{ 2422781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2423fe1c6bb9Sdrh } 2424781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2425781def29Sdrh 2426fe1c6bb9Sdrh /* Output the single row in Current */ 2427ec4ccdbcSdrh addrCont = sqlite3VdbeMakeLabel(pParse); 2428aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 24292def2f7eSdrh selectInnerLoop(pParse, p, iCurrent, 2430079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2431688852abSdrh if( regLimit ){ 243216897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); 2433688852abSdrh VdbeCoverage(v); 2434688852abSdrh } 2435fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2436fe1c6bb9Sdrh 2437781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2438781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2439781def29Sdrh */ 2440b63ce02fSdrh if( p->selFlags & SF_Aggregate ){ 2441b63ce02fSdrh sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); 2442b63ce02fSdrh }else{ 2443781def29Sdrh p->pPrior = 0; 244484a01debSdrh ExplainQueryPlan((pParse, 1, "RECURSIVE STEP")); 2445781def29Sdrh sqlite3Select(pParse, p, &destQueue); 2446781def29Sdrh assert( p->pPrior==0 ); 2447781def29Sdrh p->pPrior = pSetup; 2448b63ce02fSdrh } 2449781def29Sdrh 2450781def29Sdrh /* Keep running the loop until the Queue is empty */ 2451076e85f5Sdrh sqlite3VdbeGoto(v, addrTop); 2452781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2453fe1c6bb9Sdrh 2454fe1c6bb9Sdrh end_of_recursive_query: 24559afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2456fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2457aa9ce707Sdrh p->pLimit = pLimit; 2458fe1c6bb9Sdrh return; 2459781def29Sdrh } 2460b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2461781def29Sdrh 2462781def29Sdrh /* Forward references */ 2463b21e7c70Sdrh static int multiSelectOrderBy( 2464b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2465b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2466a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2467b21e7c70Sdrh ); 2468b21e7c70Sdrh 246945f54a57Sdrh /* 247045f54a57Sdrh ** Handle the special case of a compound-select that originates from a 247145f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 247245f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 247345f54a57Sdrh ** on a VALUES clause. 247445f54a57Sdrh ** 247545f54a57Sdrh ** Because the Select object originates from a VALUES clause: 2476b058d054Sdrh ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 247745f54a57Sdrh ** (2) All terms are UNION ALL 247845f54a57Sdrh ** (3) There is no ORDER BY clause 2479b058d054Sdrh ** 2480b058d054Sdrh ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES 2481b058d054Sdrh ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). 2482b058d054Sdrh ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. 2483b058d054Sdrh ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES. 248445f54a57Sdrh */ 248545f54a57Sdrh static int multiSelectValues( 248645f54a57Sdrh Parse *pParse, /* Parsing context */ 248745f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 248845f54a57Sdrh SelectDest *pDest /* What to do with query results */ 248945f54a57Sdrh ){ 249045f54a57Sdrh int nRow = 1; 249145f54a57Sdrh int rc = 0; 2492fa16f5d9Sdrh int bShowAll = p->pLimit==0; 2493772460fdSdrh assert( p->selFlags & SF_MultiValue ); 249445f54a57Sdrh do{ 249545f54a57Sdrh assert( p->selFlags & SF_Values ); 249645f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 2497923cadb1Sdan assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); 2498ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 249929cdbadfSdrh if( p->pWin ) return -1; 2500ef9f719dSdrh #endif 250145f54a57Sdrh if( p->pPrior==0 ) break; 250245f54a57Sdrh assert( p->pPrior->pNext==p ); 250345f54a57Sdrh p = p->pPrior; 2504fa16f5d9Sdrh nRow += bShowAll; 250545f54a57Sdrh }while(1); 2506fa16f5d9Sdrh ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow, 2507fa16f5d9Sdrh nRow==1 ? "" : "S")); 250845f54a57Sdrh while( p ){ 2509fa16f5d9Sdrh selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1); 2510fa16f5d9Sdrh if( !bShowAll ) break; 251145f54a57Sdrh p->nSelectRow = nRow; 251245f54a57Sdrh p = p->pNext; 251345f54a57Sdrh } 251445f54a57Sdrh return rc; 251545f54a57Sdrh } 2516b21e7c70Sdrh 2517d3d39e93Sdrh /* 251816ee60ffSdrh ** This routine is called to process a compound query form from 251916ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 252016ee60ffSdrh ** INTERSECT 2521c926afbcSdrh ** 2522e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2523e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2524e78e8284Sdrh ** in which case this routine will be called recursively. 2525e78e8284Sdrh ** 2526e78e8284Sdrh ** The results of the total query are to be written into a destination 2527e78e8284Sdrh ** of type eDest with parameter iParm. 2528e78e8284Sdrh ** 2529e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2530e78e8284Sdrh ** 2531e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2532e78e8284Sdrh ** 2533e78e8284Sdrh ** This statement is parsed up as follows: 2534e78e8284Sdrh ** 2535e78e8284Sdrh ** SELECT c FROM t3 2536e78e8284Sdrh ** | 2537e78e8284Sdrh ** `-----> SELECT b FROM t2 2538e78e8284Sdrh ** | 25394b11c6d3Sjplyon ** `------> SELECT a FROM t1 2540e78e8284Sdrh ** 2541e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2542e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2543e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2544e78e8284Sdrh ** 2545e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2546e78e8284Sdrh ** individual selects always group from left to right. 254782c3d636Sdrh */ 254884ac9d02Sdanielk1977 static int multiSelect( 2549fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2550fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2551a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 255284ac9d02Sdanielk1977 ){ 255384ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 255410e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 255510e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 25561013c932Sdrh SelectDest dest; /* Alternative data destination */ 2557eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2558633e6d57Sdrh sqlite3 *db; /* Database connection */ 255982c3d636Sdrh 25607b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2561fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 256282c3d636Sdrh */ 2563701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2564eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2565b0968b6bSdrh assert( p->selFlags & SF_Compound ); 2566633e6d57Sdrh db = pParse->db; 2567d8bc7086Sdrh pPrior = p->pPrior; 2568bc10377aSdrh dest = *pDest; 256963347e7dSdrh if( pPrior->pOrderBy || pPrior->pLimit ){ 257063347e7dSdrh sqlite3ErrorMsg(pParse,"%s clause should come after %s not before", 257163347e7dSdrh pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op)); 257284ac9d02Sdanielk1977 rc = 1; 257384ac9d02Sdanielk1977 goto multi_select_end; 25747b58daeaSdrh } 257582c3d636Sdrh 25764adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2577701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2578d8bc7086Sdrh 25791cc3d75fSdrh /* Create the destination temporary table if necessary 25801cc3d75fSdrh */ 25816c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2582b4964b72Sdanielk1977 assert( p->pEList ); 25832b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 25846c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 25851cc3d75fSdrh } 25861cc3d75fSdrh 258745f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 258845f54a57Sdrh */ 2589772460fdSdrh if( p->selFlags & SF_MultiValue ){ 259045f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 259129cdbadfSdrh if( rc>=0 ) goto multi_select_end; 259229cdbadfSdrh rc = SQLITE_OK; 259345f54a57Sdrh } 259445f54a57Sdrh 2595f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2596f6e369a1Sdrh ** in their result sets. 2597f6e369a1Sdrh */ 2598f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2599923cadb1Sdan assert( p->pEList->nExpr==pPrior->pEList->nExpr ); 2600f6e369a1Sdrh 2601eede6a53Sdan #ifndef SQLITE_OMIT_CTE 2602eae73fbfSdan if( p->selFlags & SF_Recursive ){ 2603781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 26048ce7184bSdan }else 26058ce7184bSdan #endif 2606f6e369a1Sdrh 2607a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2608a9671a22Sdrh */ 2609f6e369a1Sdrh if( p->pOrderBy ){ 2610a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 261103c3905fSdrh }else{ 2612f6e369a1Sdrh 2613c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN 261403c3905fSdrh if( pPrior->pPrior==0 ){ 26154d79983cSdrh ExplainQueryPlan((pParse, 1, "COMPOUND QUERY")); 2616c631ded5Sdrh ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); 2617c631ded5Sdrh } 2618c631ded5Sdrh #endif 2619c631ded5Sdrh 2620f46f905aSdrh /* Generate code for the left and right SELECT statements. 2621d8bc7086Sdrh */ 262282c3d636Sdrh switch( p->op ){ 2623f46f905aSdrh case TK_ALL: { 2624ec7429aeSdrh int addr = 0; 262595aa47b1Sdrh int nLimit; 2626a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2627547180baSdrh pPrior->iLimit = p->iLimit; 2628547180baSdrh pPrior->iOffset = p->iOffset; 2629a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 26307d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2631ad68cb6bSdanielk1977 p->pLimit = 0; 263284ac9d02Sdanielk1977 if( rc ){ 263384ac9d02Sdanielk1977 goto multi_select_end; 263484ac9d02Sdanielk1977 } 2635f46f905aSdrh p->pPrior = 0; 26367b58daeaSdrh p->iLimit = pPrior->iLimit; 26377b58daeaSdrh p->iOffset = pPrior->iOffset; 263892b01d53Sdrh if( p->iLimit ){ 263916897072Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); 2640d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 26419f1ef45fSdrh if( p->iOffset ){ 2642cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, 2643cc2fa4cfSdrh p->iLimit, p->iOffset+1, p->iOffset); 26449f1ef45fSdrh } 2645ec7429aeSdrh } 2646c631ded5Sdrh ExplainQueryPlan((pParse, 1, "UNION ALL")); 26477d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2648373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2649eca7e01aSdanielk1977 pDelete = p->pPrior; 2650f46f905aSdrh p->pPrior = pPrior; 2651c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 265295aa47b1Sdrh if( pPrior->pLimit 26538c0833fbSdrh && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) 2654c3489bbfSdrh && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 265595aa47b1Sdrh ){ 2656c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)nLimit); 265795aa47b1Sdrh } 2658ec7429aeSdrh if( addr ){ 2659ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2660ec7429aeSdrh } 2661f46f905aSdrh break; 2662f46f905aSdrh } 266382c3d636Sdrh case TK_EXCEPT: 266482c3d636Sdrh case TK_UNION: { 266503c3905fSdrh int unionTab; /* Cursor number of the temp table holding result */ 2666ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2667d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 26688c0833fbSdrh Expr *pLimit; /* Saved values of p->nLimit */ 2669dc1bdc4fSdanielk1977 int addr; 26706c8c8ce0Sdanielk1977 SelectDest uniondest; 267182c3d636Sdrh 2672373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2673373cc2ddSdrh testcase( p->op==TK_UNION ); 267493a960a0Sdrh priorOp = SRT_Union; 2675d227a291Sdrh if( dest.eDest==priorOp ){ 2676d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2677c926afbcSdrh ** right. 2678d8bc7086Sdrh */ 2679e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 26802b596da8Sdrh unionTab = dest.iSDParm; 268182c3d636Sdrh }else{ 2682d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2683d8bc7086Sdrh ** intermediate results. 2684d8bc7086Sdrh */ 268582c3d636Sdrh unionTab = pParse->nTab++; 268693a960a0Sdrh assert( p->pOrderBy==0 ); 268766a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2688b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2689b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2690d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 269184ac9d02Sdanielk1977 assert( p->pEList ); 2692d8bc7086Sdrh } 2693d8bc7086Sdrh 2694d8bc7086Sdrh /* Code the SELECT statements to our left 2695d8bc7086Sdrh */ 2696b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 26971013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 26987d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 269984ac9d02Sdanielk1977 if( rc ){ 270084ac9d02Sdanielk1977 goto multi_select_end; 270184ac9d02Sdanielk1977 } 2702d8bc7086Sdrh 2703d8bc7086Sdrh /* Code the current SELECT statement 2704d8bc7086Sdrh */ 27054cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 27064cfb22f7Sdrh op = SRT_Except; 27074cfb22f7Sdrh }else{ 27084cfb22f7Sdrh assert( p->op==TK_UNION ); 27094cfb22f7Sdrh op = SRT_Union; 2710d8bc7086Sdrh } 271182c3d636Sdrh p->pPrior = 0; 2712a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2713a2dc3b1aSdanielk1977 p->pLimit = 0; 27146c8c8ce0Sdanielk1977 uniondest.eDest = op; 2715c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2716c631ded5Sdrh selectOpName(p->op))); 27177d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2718373cc2ddSdrh testcase( rc!=SQLITE_OK ); 27195bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 27205bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2721633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 2722eca7e01aSdanielk1977 pDelete = p->pPrior; 272382c3d636Sdrh p->pPrior = pPrior; 2724a9671a22Sdrh p->pOrderBy = 0; 2725c3489bbfSdrh if( p->op==TK_UNION ){ 2726c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 2727c3489bbfSdrh } 2728633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2729a2dc3b1aSdanielk1977 p->pLimit = pLimit; 273092b01d53Sdrh p->iLimit = 0; 273192b01d53Sdrh p->iOffset = 0; 2732d8bc7086Sdrh 2733d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2734d8bc7086Sdrh ** it is that we currently need. 2735d8bc7086Sdrh */ 27362b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2737a9ebfe20Sdrh assert( p->pEList || db->mallocFailed ); 2738a9ebfe20Sdrh if( dest.eDest!=priorOp && db->mallocFailed==0 ){ 27396b56344dSdrh int iCont, iBreak, iStart; 2740ec4ccdbcSdrh iBreak = sqlite3VdbeMakeLabel(pParse); 2741ec4ccdbcSdrh iCont = sqlite3VdbeMakeLabel(pParse); 2742ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2743688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 27444adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 27452def2f7eSdrh selectInnerLoop(pParse, p, unionTab, 2746e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 27474adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2748688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 27494adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 275066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 275182c3d636Sdrh } 275282c3d636Sdrh break; 275382c3d636Sdrh } 2754373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 275582c3d636Sdrh int tab1, tab2; 27566b56344dSdrh int iCont, iBreak, iStart; 27578c0833fbSdrh Expr *pLimit; 2758dc1bdc4fSdanielk1977 int addr; 27591013c932Sdrh SelectDest intersectdest; 27609cbf3425Sdrh int r1; 276182c3d636Sdrh 2762d8bc7086Sdrh /* INTERSECT is different from the others since it requires 27636206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2764d8bc7086Sdrh ** by allocating the tables we will need. 2765d8bc7086Sdrh */ 276682c3d636Sdrh tab1 = pParse->nTab++; 276782c3d636Sdrh tab2 = pParse->nTab++; 276893a960a0Sdrh assert( p->pOrderBy==0 ); 2769dc1bdc4fSdanielk1977 277066a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2771b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2772b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2773d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 277484ac9d02Sdanielk1977 assert( p->pEList ); 2775d8bc7086Sdrh 2776d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2777d8bc7086Sdrh */ 27781013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 27797d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 278084ac9d02Sdanielk1977 if( rc ){ 278184ac9d02Sdanielk1977 goto multi_select_end; 278284ac9d02Sdanielk1977 } 2783d8bc7086Sdrh 2784d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2785d8bc7086Sdrh */ 278666a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2787b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2788b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 278982c3d636Sdrh p->pPrior = 0; 2790a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2791a2dc3b1aSdanielk1977 p->pLimit = 0; 27922b596da8Sdrh intersectdest.iSDParm = tab2; 2793c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2794c631ded5Sdrh selectOpName(p->op))); 27957d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 2796373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2797eca7e01aSdanielk1977 pDelete = p->pPrior; 279882c3d636Sdrh p->pPrior = pPrior; 279903c3905fSdrh if( p->nSelectRow>pPrior->nSelectRow ){ 280003c3905fSdrh p->nSelectRow = pPrior->nSelectRow; 280103c3905fSdrh } 2802633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2803a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2804d8bc7086Sdrh 2805d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2806d8bc7086Sdrh ** tables. 2807d8bc7086Sdrh */ 28085f695124Sdrh if( rc ) break; 280982c3d636Sdrh assert( p->pEList ); 2810ec4ccdbcSdrh iBreak = sqlite3VdbeMakeLabel(pParse); 2811ec4ccdbcSdrh iCont = sqlite3VdbeMakeLabel(pParse); 2812ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2813688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 28149cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 28159057fc7cSdrh iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); 281603c3905fSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); 281703c3905fSdrh VdbeCoverage(v); 28189cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 28192def2f7eSdrh selectInnerLoop(pParse, p, tab1, 2820e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 28214adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2822688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); 28234adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 282466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 282566a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 282682c3d636Sdrh break; 282782c3d636Sdrh } 282882c3d636Sdrh } 28298cdbf836Sdrh 2830c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN 2831c631ded5Sdrh if( p->pNext==0 ){ 2832e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 2833c631ded5Sdrh } 2834c631ded5Sdrh #endif 283503c3905fSdrh } 28368428b3b4Sdrh if( pParse->nErr ) goto multi_select_end; 28377f61e92cSdan 2838a9671a22Sdrh /* Compute collating sequences used by 2839a9671a22Sdrh ** temporary tables needed to implement the compound select. 2840a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 28418cdbf836Sdrh ** 28428cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 28438cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 28448cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 28458cdbf836Sdrh ** no temp tables are required. 2846fbc4ee7bSdrh */ 28477d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 2848fbc4ee7bSdrh int i; /* Loop counter */ 2849fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 28500342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 2851f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 285293a960a0Sdrh int nCol; /* Number of columns in result set */ 2853fbc4ee7bSdrh 2854d227a291Sdrh assert( p->pNext==0 ); 285593a960a0Sdrh nCol = p->pEList->nExpr; 2856ad124329Sdrh pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); 2857dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 2858fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT; 2859dc1bdc4fSdanielk1977 goto multi_select_end; 2860dc1bdc4fSdanielk1977 } 28610342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 28620342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 28630342b1f5Sdrh if( 0==*apColl ){ 2864633e6d57Sdrh *apColl = db->pDfltColl; 2865dc1bdc4fSdanielk1977 } 2866dc1bdc4fSdanielk1977 } 2867dc1bdc4fSdanielk1977 28680342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 28690342b1f5Sdrh for(i=0; i<2; i++){ 2870b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 28710342b1f5Sdrh if( addr<0 ){ 28720342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 28730342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 2874b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 28750342b1f5Sdrh break; 28760342b1f5Sdrh } 28770342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 28782ec2fb22Sdrh sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), 28792ec2fb22Sdrh P4_KEYINFO); 28800ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 28810342b1f5Sdrh } 2882dc1bdc4fSdanielk1977 } 28832ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyInfo); 2884dc1bdc4fSdanielk1977 } 2885dc1bdc4fSdanielk1977 2886dc1bdc4fSdanielk1977 multi_select_end: 28872b596da8Sdrh pDest->iSdst = dest.iSdst; 28882b596da8Sdrh pDest->nSdst = dest.nSdst; 2889633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 289084ac9d02Sdanielk1977 return rc; 28912282792aSdrh } 2892b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 28932282792aSdrh 2894b21e7c70Sdrh /* 289589b31d73Smistachkin ** Error message for when two or more terms of a compound select have different 289689b31d73Smistachkin ** size result sets. 289789b31d73Smistachkin */ 289889b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ 289989b31d73Smistachkin if( p->selFlags & SF_Values ){ 290089b31d73Smistachkin sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 290189b31d73Smistachkin }else{ 290289b31d73Smistachkin sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 290389b31d73Smistachkin " do not have the same number of result columns", selectOpName(p->op)); 290489b31d73Smistachkin } 290589b31d73Smistachkin } 290689b31d73Smistachkin 290789b31d73Smistachkin /* 2908b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 2909b21e7c70Sdrh ** SELECT statment. 29100acb7e48Sdrh ** 29112b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 29122b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 29130acb7e48Sdrh ** be sent. 29140acb7e48Sdrh ** 29150acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 29160acb7e48Sdrh ** return address. 29170acb7e48Sdrh ** 2918f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 29190acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 29200acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 29210acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 29220acb7e48Sdrh ** keys. 29230acb7e48Sdrh ** 29240acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 29250acb7e48Sdrh ** iBreak. 2926b21e7c70Sdrh */ 29270acb7e48Sdrh static int generateOutputSubroutine( 292892b01d53Sdrh Parse *pParse, /* Parsing context */ 292992b01d53Sdrh Select *p, /* The SELECT statement */ 293092b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 293192b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 293292b01d53Sdrh int regReturn, /* The return address register */ 29330acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 29340acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 293592b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 2936b21e7c70Sdrh ){ 2937b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 293892b01d53Sdrh int iContinue; 293992b01d53Sdrh int addr; 2940b21e7c70Sdrh 294192b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 2942ec4ccdbcSdrh iContinue = sqlite3VdbeMakeLabel(pParse); 29430acb7e48Sdrh 29440acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 29450acb7e48Sdrh */ 29460acb7e48Sdrh if( regPrev ){ 2947728e0f91Sdrh int addr1, addr2; 2948728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 2949728e0f91Sdrh addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 29502ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 2951728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); 2952728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 2953e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2954ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 29550acb7e48Sdrh } 29561f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 29570acb7e48Sdrh 2958d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 29590acb7e48Sdrh */ 2960aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 2961b21e7c70Sdrh 2962e2248cfdSdrh assert( pDest->eDest!=SRT_Exists ); 2963e2248cfdSdrh assert( pDest->eDest!=SRT_Table ); 2964b21e7c70Sdrh switch( pDest->eDest ){ 2965b21e7c70Sdrh /* Store the result as data using a unique key. 2966b21e7c70Sdrh */ 2967b21e7c70Sdrh case SRT_EphemTab: { 2968b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 2969b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 29702b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 29712b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 29722b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2973b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2974b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 2975b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2976b21e7c70Sdrh break; 2977b21e7c70Sdrh } 2978b21e7c70Sdrh 2979b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 29801431807aSdrh /* If we are creating a set for an "expr IN (SELECT ...)". 2981b21e7c70Sdrh */ 2982b21e7c70Sdrh case SRT_Set: { 29836fccc35aSdrh int r1; 298463cecc41Sdrh testcase( pIn->nSdst>1 ); 2985b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 298671c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 29871431807aSdrh r1, pDest->zAffSdst, pIn->nSdst); 29889b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, 29899b4eaebcSdrh pIn->iSdst, pIn->nSdst); 2990b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2991b21e7c70Sdrh break; 2992b21e7c70Sdrh } 2993b21e7c70Sdrh 2994b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2995b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2996cb99c57aSdrh ** of the scan loop. Note that the select might return multiple columns 2997cb99c57aSdrh ** if it is the RHS of a row-value IN operator. 2998b21e7c70Sdrh */ 2999b21e7c70Sdrh case SRT_Mem: { 3000cb99c57aSdrh if( pParse->nErr==0 ){ 3001cb99c57aSdrh testcase( pIn->nSdst>1 ); 3002cb99c57aSdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst); 3003cb99c57aSdrh } 3004b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 3005b21e7c70Sdrh break; 3006b21e7c70Sdrh } 3007b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 3008b21e7c70Sdrh 30097d10d5a6Sdrh /* The results are stored in a sequence of registers 30102b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 3011b21e7c70Sdrh */ 301292b01d53Sdrh case SRT_Coroutine: { 30132b596da8Sdrh if( pDest->iSdst==0 ){ 30142b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 30152b596da8Sdrh pDest->nSdst = pIn->nSdst; 3016b21e7c70Sdrh } 30174b79bde7Sdan sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); 30182b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 301992b01d53Sdrh break; 302092b01d53Sdrh } 302192b01d53Sdrh 3022ccfcbceaSdrh /* If none of the above, then the result destination must be 3023ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 3024ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 3025ccfcbceaSdrh ** 3026ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 3027ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 3028ccfcbceaSdrh ** return the next row of result. 30297d10d5a6Sdrh */ 3030ccfcbceaSdrh default: { 3031ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 30322b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 3033b21e7c70Sdrh break; 3034b21e7c70Sdrh } 3035b21e7c70Sdrh } 303692b01d53Sdrh 303792b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 303892b01d53Sdrh */ 303992b01d53Sdrh if( p->iLimit ){ 304016897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 304192b01d53Sdrh } 304292b01d53Sdrh 304392b01d53Sdrh /* Generate the subroutine return 304492b01d53Sdrh */ 30450acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 304692b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 304792b01d53Sdrh 304892b01d53Sdrh return addr; 3049b21e7c70Sdrh } 3050b21e7c70Sdrh 3051b21e7c70Sdrh /* 3052b21e7c70Sdrh ** Alternative compound select code generator for cases when there 3053b21e7c70Sdrh ** is an ORDER BY clause. 3054b21e7c70Sdrh ** 3055b21e7c70Sdrh ** We assume a query of the following form: 3056b21e7c70Sdrh ** 3057b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 3058b21e7c70Sdrh ** 3059b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 3060b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 3061b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 3062b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 3063b21e7c70Sdrh ** selectB) there are 7 subroutines: 3064b21e7c70Sdrh ** 3065b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 3066b21e7c70Sdrh ** of the compound query. 3067b21e7c70Sdrh ** 3068b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 3069b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 3070b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 3071b21e7c70Sdrh ** appears only in B.) 3072b21e7c70Sdrh ** 3073b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 3074b21e7c70Sdrh ** 3075b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 3076b21e7c70Sdrh ** 3077b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 3078b21e7c70Sdrh ** 3079b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 3080b21e7c70Sdrh ** 3081b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 3082b21e7c70Sdrh ** 3083b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 3084b21e7c70Sdrh ** <operator> is used: 3085b21e7c70Sdrh ** 3086b21e7c70Sdrh ** 3087b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 3088b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 3089b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 3090b21e7c70Sdrh ** 30910acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 3092b21e7c70Sdrh ** 3093b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 3094b21e7c70Sdrh ** 30950acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 3096b21e7c70Sdrh ** 30970acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 30980acb7e48Sdrh ** 30990acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 31000acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 31010acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 31020acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 31030acb7e48Sdrh ** 31040acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 31050acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 31060acb7e48Sdrh ** output value. A comparison is made against this value and the output 31070acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 3108b21e7c70Sdrh ** 3109b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 3110b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 3111b21e7c70Sdrh ** 3112b21e7c70Sdrh ** goto Init 3113b21e7c70Sdrh ** coA: coroutine for left query (A) 3114b21e7c70Sdrh ** coB: coroutine for right query (B) 3115b21e7c70Sdrh ** outA: output one row of A 3116b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 3117b21e7c70Sdrh ** EofA: ... 3118b21e7c70Sdrh ** EofB: ... 3119b21e7c70Sdrh ** AltB: ... 3120b21e7c70Sdrh ** AeqB: ... 3121b21e7c70Sdrh ** AgtB: ... 3122b21e7c70Sdrh ** Init: initialize coroutine registers 3123b21e7c70Sdrh ** yield coA 3124b21e7c70Sdrh ** if eof(A) goto EofA 3125b21e7c70Sdrh ** yield coB 3126b21e7c70Sdrh ** if eof(B) goto EofB 3127b21e7c70Sdrh ** Cmpr: Compare A, B 3128b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 3129b21e7c70Sdrh ** End: ... 3130b21e7c70Sdrh ** 3131b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 3132b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 3133b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 3134b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 3135b21e7c70Sdrh */ 3136de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3137b21e7c70Sdrh static int multiSelectOrderBy( 3138b21e7c70Sdrh Parse *pParse, /* Parsing context */ 3139b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 3140a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 3141b21e7c70Sdrh ){ 31420acb7e48Sdrh int i, j; /* Loop counters */ 3143b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 3144b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 3145b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 3146b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 314792b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 314892b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 314992b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 315092b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 315192b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 315292b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 315392b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 3154b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 315592b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 315681cf13ecSdrh int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ 315792b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 315892b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 315992b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 316092b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 316192b01d53Sdrh int regLimitA; /* Limit register for select-A */ 316292b01d53Sdrh int regLimitB; /* Limit register for select-A */ 31630acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 316492b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 316592b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 316692b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 316792b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 3168728e0f91Sdrh int addr1; /* Jump instructions that get retargetted */ 316992b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 317096067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 31710acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 31720acb7e48Sdrh sqlite3 *db; /* Database connection */ 31730acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 31740acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 31750acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 3176b21e7c70Sdrh 317792b01d53Sdrh assert( p->pOrderBy!=0 ); 317896067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 31790acb7e48Sdrh db = pParse->db; 318092b01d53Sdrh v = pParse->pVdbe; 3181ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 3182ec4ccdbcSdrh labelEnd = sqlite3VdbeMakeLabel(pParse); 3183ec4ccdbcSdrh labelCmpr = sqlite3VdbeMakeLabel(pParse); 31840acb7e48Sdrh 3185b21e7c70Sdrh 318692b01d53Sdrh /* Patch up the ORDER BY clause 318792b01d53Sdrh */ 318892b01d53Sdrh op = p->op; 3189b21e7c70Sdrh pPrior = p->pPrior; 319092b01d53Sdrh assert( pPrior->pOrderBy==0 ); 31910acb7e48Sdrh pOrderBy = p->pOrderBy; 319293a960a0Sdrh assert( pOrderBy ); 31930acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 319493a960a0Sdrh 31950acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 31960acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 31970acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 31980acb7e48Sdrh */ 31990acb7e48Sdrh if( op!=TK_ALL ){ 32000acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 32017d10d5a6Sdrh struct ExprList_item *pItem; 32027d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 3203c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 ); 3204c2acc4e4Sdrh if( pItem->u.x.iOrderByCol==i ) break; 32050acb7e48Sdrh } 32060acb7e48Sdrh if( j==nOrderBy ){ 3207b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 3208fad3039cSmistachkin if( pNew==0 ) return SQLITE_NOMEM_BKPT; 32090acb7e48Sdrh pNew->flags |= EP_IntValue; 321033e619fcSdrh pNew->u.iValue = i; 321143606175Sdrh p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 3212c2acc4e4Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; 32130acb7e48Sdrh } 32140acb7e48Sdrh } 32150acb7e48Sdrh } 32160acb7e48Sdrh 32170acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 321810c081adSdrh ** the permutation used to determine if the next 32190acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 32200acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 32210acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 32220acb7e48Sdrh ** collation. 32230acb7e48Sdrh */ 3224575fad65Sdrh aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); 32250acb7e48Sdrh if( aPermute ){ 32267d10d5a6Sdrh struct ExprList_item *pItem; 3227b1702026Sdrh aPermute[0] = nOrderBy; 3228b1702026Sdrh for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ 32296736618aSdrh assert( pItem->u.x.iOrderByCol>0 ); 32302ec18a3cSdrh assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 3231c2acc4e4Sdrh aPermute[i] = pItem->u.x.iOrderByCol - 1; 32320acb7e48Sdrh } 323353bed45eSdan pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 32340acb7e48Sdrh }else{ 32350acb7e48Sdrh pKeyMerge = 0; 32360acb7e48Sdrh } 32370acb7e48Sdrh 32380acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 32390acb7e48Sdrh */ 32400acb7e48Sdrh p->pOrderBy = pOrderBy; 32416ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 32420acb7e48Sdrh 32430acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 32440acb7e48Sdrh ** for the logic that removes duplicate result rows when the 32450acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 32460acb7e48Sdrh */ 32470acb7e48Sdrh if( op==TK_ALL ){ 32480acb7e48Sdrh regPrev = 0; 32490acb7e48Sdrh }else{ 32500acb7e48Sdrh int nExpr = p->pEList->nExpr; 32511c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 3252c8ac0d16Sdrh regPrev = pParse->nMem+1; 3253c8ac0d16Sdrh pParse->nMem += nExpr+1; 32540acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 3255ad124329Sdrh pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); 32560acb7e48Sdrh if( pKeyDup ){ 32572ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); 32580acb7e48Sdrh for(i=0; i<nExpr; i++){ 32590acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 32606e11892dSdan pKeyDup->aSortFlags[i] = 0; 32610acb7e48Sdrh } 32620acb7e48Sdrh } 32630acb7e48Sdrh } 326492b01d53Sdrh 326592b01d53Sdrh /* Separate the left and the right query from one another 326692b01d53Sdrh */ 326792b01d53Sdrh p->pPrior = 0; 3268d227a291Sdrh pPrior->pNext = 0; 32697d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 32700acb7e48Sdrh if( pPrior->pPrior==0 ){ 32717d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 32720acb7e48Sdrh } 327392b01d53Sdrh 327492b01d53Sdrh /* Compute the limit registers */ 327592b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 32760acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 327792b01d53Sdrh regLimitA = ++pParse->nMem; 327892b01d53Sdrh regLimitB = ++pParse->nMem; 327992b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 328092b01d53Sdrh regLimitA); 328192b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 328292b01d53Sdrh }else{ 328392b01d53Sdrh regLimitA = regLimitB = 0; 328492b01d53Sdrh } 3285633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 32860acb7e48Sdrh p->pLimit = 0; 328792b01d53Sdrh 3288b21e7c70Sdrh regAddrA = ++pParse->nMem; 3289b21e7c70Sdrh regAddrB = ++pParse->nMem; 3290b21e7c70Sdrh regOutA = ++pParse->nMem; 3291b21e7c70Sdrh regOutB = ++pParse->nMem; 3292b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 3293b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 3294e2ca99c9Sdrh 3295c631ded5Sdrh ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op))); 3296b21e7c70Sdrh 329792b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 32980acb7e48Sdrh ** left of the compound operator - the "A" select. 32990acb7e48Sdrh */ 3300ed71a839Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 3301728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 3302ed71a839Sdrh VdbeComment((v, "left SELECT")); 330392b01d53Sdrh pPrior->iLimit = regLimitA; 3304c631ded5Sdrh ExplainQueryPlan((pParse, 1, "LEFT")); 33057d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 33062fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrA); 3307728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3308b21e7c70Sdrh 330992b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 331092b01d53Sdrh ** the right - the "B" select 331192b01d53Sdrh */ 3312ed71a839Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 3313728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 3314ed71a839Sdrh VdbeComment((v, "right SELECT")); 331592b01d53Sdrh savedLimit = p->iLimit; 331692b01d53Sdrh savedOffset = p->iOffset; 331792b01d53Sdrh p->iLimit = regLimitB; 331892b01d53Sdrh p->iOffset = 0; 3319c631ded5Sdrh ExplainQueryPlan((pParse, 1, "RIGHT")); 33207d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 332192b01d53Sdrh p->iLimit = savedLimit; 332292b01d53Sdrh p->iOffset = savedOffset; 33232fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrB); 3324b21e7c70Sdrh 332592b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 33260acb7e48Sdrh ** select as the next output row of the compound select. 332792b01d53Sdrh */ 3328b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 33290acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 33300acb7e48Sdrh p, &destA, pDest, regOutA, 33312ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 3332b21e7c70Sdrh 333392b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 33340acb7e48Sdrh ** select as the next output row of the compound select. 333592b01d53Sdrh */ 33360acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 3337b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 33380acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 33390acb7e48Sdrh p, &destB, pDest, regOutB, 33402ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 33410acb7e48Sdrh } 33422ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyDup); 3343b21e7c70Sdrh 334492b01d53Sdrh /* Generate a subroutine to run when the results from select A 334592b01d53Sdrh ** are exhausted and only data in select B remains. 334692b01d53Sdrh */ 334792b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 334881cf13ecSdrh addrEofA_noB = addrEofA = labelEnd; 334992b01d53Sdrh }else{ 335081cf13ecSdrh VdbeNoopComment((v, "eof-A subroutine")); 335181cf13ecSdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 335281cf13ecSdrh addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 3353688852abSdrh VdbeCoverage(v); 3354076e85f5Sdrh sqlite3VdbeGoto(v, addrEofA); 3355c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 3356b21e7c70Sdrh } 3357b21e7c70Sdrh 335892b01d53Sdrh /* Generate a subroutine to run when the results from select B 335992b01d53Sdrh ** are exhausted and only data in select A remains. 336092b01d53Sdrh */ 3361b21e7c70Sdrh if( op==TK_INTERSECT ){ 336292b01d53Sdrh addrEofB = addrEofA; 336395aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3364b21e7c70Sdrh }else{ 336592b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 336681cf13ecSdrh addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3367688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 3368076e85f5Sdrh sqlite3VdbeGoto(v, addrEofB); 3369b21e7c70Sdrh } 3370b21e7c70Sdrh 337192b01d53Sdrh /* Generate code to handle the case of A<B 337292b01d53Sdrh */ 3373b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 33740acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3375688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3376076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3377b21e7c70Sdrh 337892b01d53Sdrh /* Generate code to handle the case of A==B 337992b01d53Sdrh */ 3380b21e7c70Sdrh if( op==TK_ALL ){ 3381b21e7c70Sdrh addrAeqB = addrAltB; 33820acb7e48Sdrh }else if( op==TK_INTERSECT ){ 33830acb7e48Sdrh addrAeqB = addrAltB; 33840acb7e48Sdrh addrAltB++; 338592b01d53Sdrh }else{ 3386b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 33870acb7e48Sdrh addrAeqB = 3388688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3389076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 339092b01d53Sdrh } 3391b21e7c70Sdrh 339292b01d53Sdrh /* Generate code to handle the case of A>B 339392b01d53Sdrh */ 3394b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 3395b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 3396b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 3397b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 339892b01d53Sdrh } 3399688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3400076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3401b21e7c70Sdrh 340292b01d53Sdrh /* This code runs once to initialize everything. 340392b01d53Sdrh */ 3404728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3405688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3406688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 340792b01d53Sdrh 340892b01d53Sdrh /* Implement the main merge loop 340992b01d53Sdrh */ 341092b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 34110acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 34122b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 34132ec2fb22Sdrh (char*)pKeyMerge, P4_KEYINFO); 3414953f7611Sdrh sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3415688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 341692b01d53Sdrh 341792b01d53Sdrh /* Jump to the this point in order to terminate the query. 341892b01d53Sdrh */ 3419b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 3420b21e7c70Sdrh 34210acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 34220acb7e48Sdrh ** by the calling function */ 34235e7ad508Sdanielk1977 if( p->pPrior ){ 3424633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 34255e7ad508Sdanielk1977 } 34260acb7e48Sdrh p->pPrior = pPrior; 3427d227a291Sdrh pPrior->pNext = p; 342892b01d53Sdrh 342992b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 343092b01d53Sdrh **** subqueries ****/ 3431e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 34323dc4cc66Sdrh return pParse->nErr!=0; 343392b01d53Sdrh } 3434de3e41e3Sdanielk1977 #endif 3435b21e7c70Sdrh 34363514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 343746967de2Sdrh 343846967de2Sdrh /* An instance of the SubstContext object describes an substitution edit 343946967de2Sdrh ** to be performed on a parse tree. 344046967de2Sdrh ** 344146967de2Sdrh ** All references to columns in table iTable are to be replaced by corresponding 344246967de2Sdrh ** expressions in pEList. 344346967de2Sdrh */ 344446967de2Sdrh typedef struct SubstContext { 344546967de2Sdrh Parse *pParse; /* The parsing context */ 344646967de2Sdrh int iTable; /* Replace references to this table */ 344731d6fd55Sdrh int iNewTable; /* New table number */ 344831d6fd55Sdrh int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ 344946967de2Sdrh ExprList *pEList; /* Replacement expressions */ 345046967de2Sdrh } SubstContext; 345146967de2Sdrh 345217435752Sdrh /* Forward Declarations */ 345346967de2Sdrh static void substExprList(SubstContext*, ExprList*); 345446967de2Sdrh static void substSelect(SubstContext*, Select*, int); 345517435752Sdrh 34562282792aSdrh /* 3457832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 34586a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 345984e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 34606a3ea0e6Sdrh ** unchanged.) 3461832508b7Sdrh ** 3462832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 3463832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 3464832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3465aca19e19Sdrh ** FORM clause entry is iTable. This routine makes the necessary 3466832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 3467832508b7Sdrh ** of the subquery rather the result set of the subquery. 3468832508b7Sdrh */ 3469b7916a78Sdrh static Expr *substExpr( 347046967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 347146967de2Sdrh Expr *pExpr /* Expr in which substitution occurs */ 347217435752Sdrh ){ 3473b7916a78Sdrh if( pExpr==0 ) return 0; 34743d240d21Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) 34753d240d21Sdrh && pExpr->iRightJoinTable==pSubst->iTable 34763d240d21Sdrh ){ 3477399c7e21Sdrh pExpr->iRightJoinTable = pSubst->iNewTable; 3478399c7e21Sdrh } 347946967de2Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){ 348050350a15Sdrh if( pExpr->iColumn<0 ){ 348150350a15Sdrh pExpr->op = TK_NULL; 348250350a15Sdrh }else{ 3483832508b7Sdrh Expr *pNew; 348446967de2Sdrh Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; 348531d6fd55Sdrh Expr ifNullRow; 348646967de2Sdrh assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr ); 34871fd4e7bbSdrh assert( pExpr->pRight==0 ); 348844c5604cSdan if( sqlite3ExprIsVector(pCopy) ){ 348946967de2Sdrh sqlite3VectorErrorMsg(pSubst->pParse, pCopy); 349044c5604cSdan }else{ 349146967de2Sdrh sqlite3 *db = pSubst->pParse->db; 349231d6fd55Sdrh if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){ 349331d6fd55Sdrh memset(&ifNullRow, 0, sizeof(ifNullRow)); 349431d6fd55Sdrh ifNullRow.op = TK_IF_NULL_ROW; 349531d6fd55Sdrh ifNullRow.pLeft = pCopy; 349631d6fd55Sdrh ifNullRow.iTable = pSubst->iNewTable; 349731d6fd55Sdrh pCopy = &ifNullRow; 349831d6fd55Sdrh } 349911df7d28Sdrh testcase( ExprHasProperty(pCopy, EP_Subquery) ); 350044c5604cSdan pNew = sqlite3ExprDup(db, pCopy, 0); 3501bd11a2acSdan if( pNew && pSubst->isLeftJoin ){ 3502bd11a2acSdan ExprSetProperty(pNew, EP_CanBeNull); 3503bd11a2acSdan } 3504bd11a2acSdan if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){ 350592ddb3bdSdan pNew->iRightJoinTable = pExpr->iRightJoinTable; 3506bd11a2acSdan ExprSetProperty(pNew, EP_FromJoin); 350792ddb3bdSdan } 3508b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 3509b7916a78Sdrh pExpr = pNew; 3510e0866394Sdan 3511fa508349Sdan /* Ensure that the expression now has an implicit collation sequence, 3512fa508349Sdan ** just as it did when it was a column of a view or sub-query. */ 3513fa508349Sdan if( pExpr ){ 3514e0866394Sdan if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){ 3515e0866394Sdan CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr); 3516e0866394Sdan pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr, 3517e0866394Sdan (pColl ? pColl->zName : "BINARY") 3518e0866394Sdan ); 3519e0866394Sdan } 3520e0866394Sdan ExprClearProperty(pExpr, EP_Collate); 3521e0866394Sdan } 352250350a15Sdrh } 352344c5604cSdan } 3524832508b7Sdrh }else{ 35257c1544e0Sdrh if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ 35267c1544e0Sdrh pExpr->iTable = pSubst->iNewTable; 35277c1544e0Sdrh } 352846967de2Sdrh pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); 352946967de2Sdrh pExpr->pRight = substExpr(pSubst, pExpr->pRight); 35306ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 353146967de2Sdrh substSelect(pSubst, pExpr->x.pSelect, 1); 35326ab3a2ecSdanielk1977 }else{ 353346967de2Sdrh substExprList(pSubst, pExpr->x.pList); 35346ab3a2ecSdanielk1977 } 35353703edf1Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 35363703edf1Sdan if( ExprHasProperty(pExpr, EP_WinFunc) ){ 35373703edf1Sdan Window *pWin = pExpr->y.pWin; 35383703edf1Sdan pWin->pFilter = substExpr(pSubst, pWin->pFilter); 35393703edf1Sdan substExprList(pSubst, pWin->pPartition); 35403703edf1Sdan substExprList(pSubst, pWin->pOrderBy); 35413703edf1Sdan } 35423703edf1Sdan #endif 3543832508b7Sdrh } 3544b7916a78Sdrh return pExpr; 3545832508b7Sdrh } 354617435752Sdrh static void substExprList( 354746967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 354846967de2Sdrh ExprList *pList /* List to scan and in which to make substitutes */ 354917435752Sdrh ){ 3550832508b7Sdrh int i; 3551832508b7Sdrh if( pList==0 ) return; 3552832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 355346967de2Sdrh pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); 3554832508b7Sdrh } 3555832508b7Sdrh } 355617435752Sdrh static void substSelect( 355746967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 355817435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 3559d12b6363Sdrh int doPrior /* Do substitutes on p->pPrior too */ 356017435752Sdrh ){ 3561588a9a1aSdrh SrcList *pSrc; 3562588a9a1aSdrh struct SrcList_item *pItem; 3563588a9a1aSdrh int i; 3564b3bce662Sdanielk1977 if( !p ) return; 3565d12b6363Sdrh do{ 356646967de2Sdrh substExprList(pSubst, p->pEList); 356746967de2Sdrh substExprList(pSubst, p->pGroupBy); 356846967de2Sdrh substExprList(pSubst, p->pOrderBy); 356946967de2Sdrh p->pHaving = substExpr(pSubst, p->pHaving); 357046967de2Sdrh p->pWhere = substExpr(pSubst, p->pWhere); 3571588a9a1aSdrh pSrc = p->pSrc; 35722906490bSdrh assert( pSrc!=0 ); 3573588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 357446967de2Sdrh substSelect(pSubst, pItem->pSelect, 1); 3575d12b6363Sdrh if( pItem->fg.isTabFunc ){ 357646967de2Sdrh substExprList(pSubst, pItem->u1.pFuncArg); 3577588a9a1aSdrh } 3578588a9a1aSdrh } 3579d12b6363Sdrh }while( doPrior && (p = p->pPrior)!=0 ); 3580b3bce662Sdanielk1977 } 35813514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3582832508b7Sdrh 35833514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3584832508b7Sdrh /* 3585*2aee514bSdrh ** pSelect is a SELECT statement and pSrcItem is one item in the FROM 3586*2aee514bSdrh ** clause of that SELECT. 3587*2aee514bSdrh ** 3588*2aee514bSdrh ** This routine scans the entire SELECT statement and recomputes the 3589*2aee514bSdrh ** pSrcItem->colUsed mask. 3590*2aee514bSdrh */ 3591*2aee514bSdrh static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){ 3592*2aee514bSdrh struct SrcList_item *pItem; 3593*2aee514bSdrh ynVar iCol; 3594*2aee514bSdrh if( pExpr->op!=TK_COLUMN ) return WRC_Continue; 3595*2aee514bSdrh pItem = pWalker->u.pSrcItem; 3596*2aee514bSdrh if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue; 3597*2aee514bSdrh iCol = pExpr->iColumn; 3598*2aee514bSdrh if( iCol<0 ) return WRC_Continue; 3599*2aee514bSdrh if( iCol>=BMS ) iCol = BMS-1; 3600*2aee514bSdrh pItem->colUsed |= ((Bitmask)1)<<iCol; 3601*2aee514bSdrh return WRC_Continue; 3602*2aee514bSdrh } 3603*2aee514bSdrh static void recomputeColumnsUsed( 3604*2aee514bSdrh Select *pSelect, /* The complete SELECT statement */ 3605*2aee514bSdrh struct SrcList_item *pSrcItem /* Which FROM clause item to recompute */ 3606*2aee514bSdrh ){ 3607*2aee514bSdrh Walker w; 3608*2aee514bSdrh if( NEVER(pSrcItem->pTab==0) ) return; 3609*2aee514bSdrh memset(&w, 0, sizeof(w)); 3610*2aee514bSdrh w.xExprCallback = recomputeColumnsUsedExpr; 3611*2aee514bSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 3612*2aee514bSdrh w.u.pSrcItem = pSrcItem; 3613*2aee514bSdrh pSrcItem->colUsed = 0; 3614*2aee514bSdrh sqlite3WalkSelect(&w, pSelect); 3615*2aee514bSdrh } 3616*2aee514bSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3617*2aee514bSdrh 3618*2aee514bSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3619*2aee514bSdrh /* 3620630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3621630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 36221350b030Sdrh ** 36231350b030Sdrh ** To understand the concept of flattening, consider the following 36241350b030Sdrh ** query: 36251350b030Sdrh ** 36261350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 36271350b030Sdrh ** 36281350b030Sdrh ** The default way of implementing this query is to execute the 36291350b030Sdrh ** subquery first and store the results in a temporary table, then 36301350b030Sdrh ** run the outer query on that temporary table. This requires two 36311350b030Sdrh ** passes over the data. Furthermore, because the temporary table 36321350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3633832508b7Sdrh ** optimized. 36341350b030Sdrh ** 3635832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 36361350b030Sdrh ** a single flat select, like this: 36371350b030Sdrh ** 36381350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 36391350b030Sdrh ** 364060ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 3641832508b7Sdrh ** but only has to scan the data once. And because indices might 3642832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 3643832508b7Sdrh ** avoided. 36441350b030Sdrh ** 3645d981e828Sdrh ** Flattening is subject to the following constraints: 36461350b030Sdrh ** 364725c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 364825c221ebSdrh ** The subquery and the outer query cannot both be aggregates. 36491350b030Sdrh ** 365025c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3651d981e828Sdrh ** (2) If the subquery is an aggregate then 3652d981e828Sdrh ** (2a) the outer query must not be a join and 3653d981e828Sdrh ** (2b) the outer query must not use subqueries 3654d981e828Sdrh ** other than the one FROM-clause subquery that is a candidate 3655d981e828Sdrh ** for flattening. (This is due to ticket [2f7170d73bf9abf80] 3656d981e828Sdrh ** from 2015-02-09.) 3657832508b7Sdrh ** 3658d981e828Sdrh ** (3) If the subquery is the right operand of a LEFT JOIN then 3659d981e828Sdrh ** (3a) the subquery may not be a join and 3660d981e828Sdrh ** (3b) the FROM clause of the subquery may not contain a virtual 3661d981e828Sdrh ** table and 3662d981e828Sdrh ** (3c) the outer query may not be an aggregate. 3663396afe6fSdrh ** (3d) the outer query may not be DISTINCT. 3664832508b7Sdrh ** 3665d981e828Sdrh ** (4) The subquery can not be DISTINCT. 3666832508b7Sdrh ** 366749ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 366849ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 366949ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 3670832508b7Sdrh ** 367125c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 367225c221ebSdrh ** If the subquery is aggregate, the outer query may not be DISTINCT. 3673832508b7Sdrh ** 3674d981e828Sdrh ** (7) The subquery must have a FROM clause. TODO: For subqueries without 367531d6fd55Sdrh ** A FROM clause, consider adding a FROM clause with the special 3676630d296cSdrh ** table sqlite_once that consists of a single row containing a 3677630d296cSdrh ** single NULL. 367808192d5fSdrh ** 3679d981e828Sdrh ** (8) If the subquery uses LIMIT then the outer query may not be a join. 3680df199a25Sdrh ** 3681d981e828Sdrh ** (9) If the subquery uses LIMIT then the outer query may not be aggregate. 3682df199a25Sdrh ** 36836092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 36846092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 3685d981e828Sdrh ** constraint: "If the subquery is aggregate then the outer query 3686d981e828Sdrh ** may not use LIMIT." 3687df199a25Sdrh ** 3688d981e828Sdrh ** (11) The subquery and the outer query may not both have ORDER BY clauses. 3689174b6195Sdrh ** 36907b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 36912b300d5dSdrh ** a separate restriction deriving from ticket #350. 36923fc673e6Sdrh ** 3693d981e828Sdrh ** (13) The subquery and outer query may not both use LIMIT. 3694ac83963aSdrh ** 3695d981e828Sdrh ** (14) The subquery may not use OFFSET. 3696ac83963aSdrh ** 3697d981e828Sdrh ** (15) If the outer query is part of a compound select, then the 3698d981e828Sdrh ** subquery may not use LIMIT. 3699f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 3700ad91c6cdSdrh ** 3701d981e828Sdrh ** (16) If the outer query is aggregate, then the subquery may not 3702d981e828Sdrh ** use ORDER BY. (Ticket #2942) This used to not matter 3703c52e355dSdrh ** until we introduced the group_concat() function. 3704c52e355dSdrh ** 3705d981e828Sdrh ** (17) If the subquery is a compound select, then 3706d981e828Sdrh ** (17a) all compound operators must be a UNION ALL, and 3707d981e828Sdrh ** (17b) no terms within the subquery compound may be aggregate 3708e76acc65Sdrh ** or DISTINCT, and 3709d981e828Sdrh ** (17c) every term within the subquery compound must have a FROM clause 3710d981e828Sdrh ** (17d) the outer query may not be 3711d981e828Sdrh ** (17d1) aggregate, or 3712d981e828Sdrh ** (17d2) DISTINCT, or 3713d981e828Sdrh ** (17d3) a join. 3714997d7434Sdan ** (17e) the subquery may not contain window functions 3715f23329a2Sdanielk1977 ** 37164914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 37174914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 3718630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 3719630d296cSdrh ** operator other than UNION ALL because all the other compound 3720630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 3721630d296cSdrh ** restriction (4). 3722f23329a2Sdanielk1977 ** 372367c70142Sdan ** Also, each component of the sub-query must return the same number 372467c70142Sdan ** of result columns. This is actually a requirement for any compound 372567c70142Sdan ** SELECT statement, but all the code here does is make sure that no 372667c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 372767c70142Sdan ** syntax error and return a detailed message. 372867c70142Sdan ** 372949fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 3730d981e828Sdrh ** ORDER BY clause of the parent must be simple references to 373149fc1f60Sdanielk1977 ** columns of the sub-query. 373249fc1f60Sdanielk1977 ** 3733d981e828Sdrh ** (19) If the subquery uses LIMIT then the outer query may not 3734229cf702Sdrh ** have a WHERE clause. 3735229cf702Sdrh ** 3736fca23557Sdrh ** (20) If the sub-query is a compound select, then it must not use 3737fca23557Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 3738fca23557Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 3739fca23557Sdrh ** appear as unmodified result columns in the outer query. But we 3740fca23557Sdrh ** have other optimizations in mind to deal with that case. 3741e8902a70Sdrh ** 3742d981e828Sdrh ** (21) If the subquery uses LIMIT then the outer query may not be 3743a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 3744a91491e5Sshaneh ** 3745d981e828Sdrh ** (22) The subquery may not be a recursive CTE. 37468290c2adSdan ** 3747cdb2f607Sdrh ** (**) Subsumed into restriction (17d3). Was: If the outer query is 3748cdb2f607Sdrh ** a recursive CTE, then the sub-query may not be a compound query. 3749cdb2f607Sdrh ** This restriction is because transforming the 37508290c2adSdan ** parent to a compound query confuses the code that handles 37518290c2adSdan ** recursive queries in multiSelect(). 37528290c2adSdan ** 3753508e2d00Sdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3754508e2d00Sdrh ** The subquery may not be an aggregate that uses the built-in min() or 37559588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 37569588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 37579588ad95Sdrh ** return the value X for which Y was maximal.) 37589588ad95Sdrh ** 37599a94722dSdan ** (25) If either the subquery or the parent query contains a window 37609a94722dSdan ** function in the select list or ORDER BY clause, flattening 37619a94722dSdan ** is not attempted. 37629a94722dSdan ** 37638290c2adSdan ** 3764832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 3765832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 376625c221ebSdrh ** uses aggregates. 3767832508b7Sdrh ** 3768665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 3769832508b7Sdrh ** If flattening is attempted this routine returns 1. 3770832508b7Sdrh ** 3771832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 3772832508b7Sdrh ** the subquery before this routine runs. 37731350b030Sdrh */ 37748c74a8caSdrh static int flattenSubquery( 3775524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 37768c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 37778c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 377825c221ebSdrh int isAgg /* True if outer SELECT uses aggregate functions */ 37798c74a8caSdrh ){ 3780524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 3781d12b6363Sdrh Select *pParent; /* Current UNION ALL term of the other query */ 37820bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 3783f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3784ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 3785ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 37866a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 3787399c7e21Sdrh int iNewParent = -1;/* Replacement table for iParent */ 3788399c7e21Sdrh int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ 378991bb0eedSdrh int i; /* Loop counter */ 379091bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 379191bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 3792524cc21eSdanielk1977 sqlite3 *db = pParse->db; 37931350b030Sdrh 3794832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 3795832508b7Sdrh */ 3796a78c22c4Sdrh assert( p!=0 ); 3797d981e828Sdrh assert( p->pPrior==0 ); 37987e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3799832508b7Sdrh pSrc = p->pSrc; 3800ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 380191bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 380249fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 380391bb0eedSdrh pSub = pSubitem->pSelect; 3804832508b7Sdrh assert( pSub!=0 ); 3805885a5b03Sdrh 380667a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 38079a94722dSdan if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ 380867a9b8edSdan #endif 380986fb6e17Sdan 3810832508b7Sdrh pSubSrc = pSub->pSrc; 3811832508b7Sdrh assert( pSubSrc ); 3812ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 381360ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3814ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 3815ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 3816ac83963aSdrh ** and (14). */ 3817ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 38188c0833fbSdrh if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ 3819d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3820ad91c6cdSdrh return 0; /* Restriction (15) */ 3821ad91c6cdSdrh } 3822ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 3823d981e828Sdrh if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ 382449ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 382549ad330dSdan return 0; /* Restrictions (8)(9) */ 3826df199a25Sdrh } 38277d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 3828ac83963aSdrh return 0; /* Restriction (11) */ 3829ac83963aSdrh } 3830c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 3831229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 3832a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 3833a91491e5Sshaneh return 0; /* Restriction (21) */ 3834a91491e5Sshaneh } 3835508e2d00Sdrh if( pSub->selFlags & (SF_Recursive) ){ 3836508e2d00Sdrh return 0; /* Restrictions (22) */ 38379588ad95Sdrh } 3838832508b7Sdrh 3839399c7e21Sdrh /* 3840399c7e21Sdrh ** If the subquery is the right operand of a LEFT JOIN, then the 3841d981e828Sdrh ** subquery may not be a join itself (3a). Example of why this is not 3842d981e828Sdrh ** allowed: 38438af4d3acSdrh ** 38448af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 38458af4d3acSdrh ** 38468af4d3acSdrh ** If we flatten the above, we would get 38478af4d3acSdrh ** 38488af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 38498af4d3acSdrh ** 38508af4d3acSdrh ** which is not at all the same thing. 38512b300d5dSdrh ** 38523c790f2aSdrh ** If the subquery is the right operand of a LEFT JOIN, then the outer 3853d981e828Sdrh ** query cannot be an aggregate. (3c) This is an artifact of the way 3854d981e828Sdrh ** aggregates are processed - there is no mechanism to determine if 3855d981e828Sdrh ** the LEFT JOIN table should be all-NULL. 38563c790f2aSdrh ** 385731d6fd55Sdrh ** See also tickets #306, #350, and #3300. 38583fc673e6Sdrh */ 38598a48b9c0Sdrh if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ 3860399c7e21Sdrh isLeftJoin = 1; 3861396afe6fSdrh if( pSubSrc->nSrc>1 /* (3a) */ 3862396afe6fSdrh || isAgg /* (3b) */ 3863396afe6fSdrh || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */ 3864396afe6fSdrh || (p->selFlags & SF_Distinct)!=0 /* (3d) */ 3865396afe6fSdrh ){ 3866d981e828Sdrh return 0; 3867399c7e21Sdrh } 38683fc673e6Sdrh } 3869dc6de479Sdrh #ifdef SQLITE_EXTRA_IFNULLROW 3870dc6de479Sdrh else if( iFrom>0 && !isAgg ){ 3871dc6de479Sdrh /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for 38723d240d21Sdrh ** every reference to any result column from subquery in a join, even 38733d240d21Sdrh ** though they are not necessary. This will stress-test the OP_IfNullRow 38743d240d21Sdrh ** opcode. */ 3875dc6de479Sdrh isLeftJoin = -1; 3876dc6de479Sdrh } 3877dc6de479Sdrh #endif 38783fc673e6Sdrh 3879d981e828Sdrh /* Restriction (17): If the sub-query is a compound SELECT, then it must 3880f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 3881f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 3882f23329a2Sdanielk1977 ** queries. 3883f23329a2Sdanielk1977 */ 3884f23329a2Sdanielk1977 if( pSub->pPrior ){ 3885fca23557Sdrh if( pSub->pOrderBy ){ 3886fca23557Sdrh return 0; /* Restriction (20) */ 3887fca23557Sdrh } 3888e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3889d981e828Sdrh return 0; /* (17d1), (17d2), or (17d3) */ 3890f23329a2Sdanielk1977 } 3891f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3892ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3893ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 38944b3ac73cSdrh assert( pSub->pSrc!=0 ); 38952ec18a3cSdrh assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); 3896d981e828Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ 3897d981e828Sdrh || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ 3898d981e828Sdrh || pSub1->pSrc->nSrc<1 /* (17c) */ 3899ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 39008d95ed78Sdrh || pSub1->pWin /* (17e) */ 3901ef9f719dSdrh #endif 390280b3c548Sdanielk1977 ){ 3903f23329a2Sdanielk1977 return 0; 3904f23329a2Sdanielk1977 } 39054b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 3906f23329a2Sdanielk1977 } 390749fc1f60Sdanielk1977 3908d981e828Sdrh /* Restriction (18). */ 390949fc1f60Sdanielk1977 if( p->pOrderBy ){ 391049fc1f60Sdanielk1977 int ii; 391149fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3912c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 391349fc1f60Sdanielk1977 } 391449fc1f60Sdanielk1977 } 3915f23329a2Sdanielk1977 } 3916f23329a2Sdanielk1977 3917cdb2f607Sdrh /* Ex-restriction (23): 3918cdb2f607Sdrh ** The only way that the recursive part of a CTE can contain a compound 3919cdb2f607Sdrh ** subquery is for the subquery to be one term of a join. But if the 3920cdb2f607Sdrh ** subquery is a join, then the flattening has already been stopped by 3921cdb2f607Sdrh ** restriction (17d3) 3922cdb2f607Sdrh */ 3923cdb2f607Sdrh assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); 3924cdb2f607Sdrh 39257d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 3926fef37760Sdrh SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n", 3927fef37760Sdrh pSub->selId, pSub, iFrom)); 39287d10d5a6Sdrh 39297d10d5a6Sdrh /* Authorize the subquery */ 3930524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 3931a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 3932a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 3933524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 3934524cc21eSdanielk1977 39357d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 39367d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 39377d10d5a6Sdrh ** be of the form: 3938f23329a2Sdanielk1977 ** 3939f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 3940f23329a2Sdanielk1977 ** 3941f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 3942a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 3943f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 3944f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 3945f23329a2Sdanielk1977 ** select statements in the compound sub-query. 3946a78c22c4Sdrh ** 3947a78c22c4Sdrh ** Example: 3948a78c22c4Sdrh ** 3949a78c22c4Sdrh ** SELECT a+1 FROM ( 3950a78c22c4Sdrh ** SELECT x FROM tab 3951a78c22c4Sdrh ** UNION ALL 3952a78c22c4Sdrh ** SELECT y FROM tab 3953a78c22c4Sdrh ** UNION ALL 3954a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 3955a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 3956a78c22c4Sdrh ** 3957a78c22c4Sdrh ** Transformed into: 3958a78c22c4Sdrh ** 3959a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 3960a78c22c4Sdrh ** UNION ALL 3961a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 3962a78c22c4Sdrh ** UNION ALL 3963a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 3964a78c22c4Sdrh ** ORDER BY 1 3965a78c22c4Sdrh ** 3966a78c22c4Sdrh ** We call this the "compound-subquery flattening". 3967f23329a2Sdanielk1977 */ 3968f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 3969f23329a2Sdanielk1977 Select *pNew; 3970f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 39714b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 3972f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 3973f23329a2Sdanielk1977 p->pOrderBy = 0; 3974f23329a2Sdanielk1977 p->pSrc = 0; 3975f23329a2Sdanielk1977 p->pPrior = 0; 39764b86ef1dSdanielk1977 p->pLimit = 0; 39776ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 39784b86ef1dSdanielk1977 p->pLimit = pLimit; 3979a78c22c4Sdrh p->pOrderBy = pOrderBy; 3980a78c22c4Sdrh p->pSrc = pSrc; 3981a78c22c4Sdrh p->op = TK_ALL; 3982a78c22c4Sdrh if( pNew==0 ){ 3983d227a291Sdrh p->pPrior = pPrior; 3984a78c22c4Sdrh }else{ 3985a78c22c4Sdrh pNew->pPrior = pPrior; 3986d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 3987d227a291Sdrh pNew->pNext = p; 3988a78c22c4Sdrh p->pPrior = pNew; 3989e2243d26Sdrh SELECTTRACE(2,pParse,p,("compound-subquery flattener" 3990fef37760Sdrh " creates %u as peer\n",pNew->selId)); 3991d227a291Sdrh } 3992a78c22c4Sdrh if( db->mallocFailed ) return 1; 3993a78c22c4Sdrh } 3994f23329a2Sdanielk1977 39957d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 39967d10d5a6Sdrh ** in the outer query. 3997832508b7Sdrh */ 3998f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 3999c31c2eb8Sdrh 4000a78c22c4Sdrh /* Delete the transient table structure associated with the 4001a78c22c4Sdrh ** subquery 4002a78c22c4Sdrh */ 4003a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 4004a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 4005a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 4006a78c22c4Sdrh pSubitem->zDatabase = 0; 4007a78c22c4Sdrh pSubitem->zName = 0; 4008a78c22c4Sdrh pSubitem->zAlias = 0; 4009a78c22c4Sdrh pSubitem->pSelect = 0; 4010a78c22c4Sdrh 4011a78c22c4Sdrh /* Defer deleting the Table object associated with the 4012a78c22c4Sdrh ** subquery until code generation is 4013a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 4014a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 4015ccfcbceaSdrh ** 4016ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 4017a78c22c4Sdrh */ 4018ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 4019a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 402079df7782Sdrh if( pTabToDel->nTabRef==1 ){ 402165a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 402265a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 402365a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 4024a78c22c4Sdrh }else{ 402579df7782Sdrh pTabToDel->nTabRef--; 4026a78c22c4Sdrh } 4027a78c22c4Sdrh pSubitem->pTab = 0; 4028a78c22c4Sdrh } 4029a78c22c4Sdrh 4030a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 4031a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 4032a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 4033a78c22c4Sdrh ** then this loop only runs once. 4034a78c22c4Sdrh ** 4035a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 4036c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 4037c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 4038c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 4039c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 4040c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 4041c31c2eb8Sdrh ** elements we are now copying in. 4042c31c2eb8Sdrh */ 4043a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 4044a78c22c4Sdrh int nSubSrc; 4045ea678832Sdrh u8 jointype = 0; 404655f66b34Sdrh assert( pSub!=0 ); 4047a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 4048a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 4049a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 4050588a9a1aSdrh 4051a78c22c4Sdrh if( pSrc ){ 4052a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 40538a48b9c0Sdrh jointype = pSubitem->fg.jointype; 4054588a9a1aSdrh }else{ 4055a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 405629c992cbSdrh pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); 405729c992cbSdrh if( pSrc==0 ) break; 405829c992cbSdrh pParent->pSrc = pSrc; 4059c31c2eb8Sdrh } 4060a78c22c4Sdrh 4061a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 4062a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 4063a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 4064a78c22c4Sdrh ** of the subquery. 4065a78c22c4Sdrh ** 4066a78c22c4Sdrh ** Example: 4067a78c22c4Sdrh ** 4068a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 4069a78c22c4Sdrh ** 4070a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 4071a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 4072d12b6363Sdrh ** block of code will expand the outer query FROM clause to 4 slots. 4073d12b6363Sdrh ** The middle slot is expanded to two slots in order to make space 4074d12b6363Sdrh ** for the two elements in the FROM clause of the subquery. 4075a78c22c4Sdrh */ 4076a78c22c4Sdrh if( nSubSrc>1 ){ 407729c992cbSdrh pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); 407829c992cbSdrh if( pSrc==0 ) break; 407929c992cbSdrh pParent->pSrc = pSrc; 4080c31c2eb8Sdrh } 4081a78c22c4Sdrh 4082a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 4083a78c22c4Sdrh ** outer query. 4084a78c22c4Sdrh */ 4085c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 4086c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 408720292310Sdrh assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); 4088c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 4089399c7e21Sdrh iNewParent = pSubSrc->a[i].iCursor; 4090c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 4091c31c2eb8Sdrh } 40928a48b9c0Sdrh pSrc->a[iFrom].fg.jointype = jointype; 4093c31c2eb8Sdrh 4094c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 4095c31c2eb8Sdrh ** references to the iParent in the outer query. 4096c31c2eb8Sdrh ** 4097c31c2eb8Sdrh ** Example: 4098c31c2eb8Sdrh ** 4099c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 4100c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 4101c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 4102c31c2eb8Sdrh ** 4103c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 4104c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 4105c31c2eb8Sdrh */ 4106174b6195Sdrh if( pSub->pOrderBy ){ 41077c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 41087c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 41097c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 41107c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 41117c0a4720Sdan ** zero them before transfering the ORDER BY clause. 41127c0a4720Sdan ** 41137c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 41147c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 41157c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 41167c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 41177c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 41187c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 41197c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 41207c0a4720Sdan } 4121f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 41227c0a4720Sdan pParent->pOrderBy = pOrderBy; 4123174b6195Sdrh pSub->pOrderBy = 0; 4124174b6195Sdrh } 412511df7d28Sdrh pWhere = pSub->pWhere; 412611df7d28Sdrh pSub->pWhere = 0; 4127dc6de479Sdrh if( isLeftJoin>0 ){ 41288103a036Sdrh sqlite3SetJoinExpr(pWhere, iNewParent); 4129399c7e21Sdrh } 4130d5c851c1Sdrh pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere); 4131c3becddbSdan if( db->mallocFailed==0 ){ 413246967de2Sdrh SubstContext x; 413346967de2Sdrh x.pParse = pParse; 413446967de2Sdrh x.iTable = iParent; 4135399c7e21Sdrh x.iNewTable = iNewParent; 413631d6fd55Sdrh x.isLeftJoin = isLeftJoin; 413746967de2Sdrh x.pEList = pSub->pEList; 413846967de2Sdrh substSelect(&x, pParent, 0); 4139c3becddbSdan } 4140c31c2eb8Sdrh 41417cd5e856Sdrh /* The flattened query is a compound if either the inner or the 41427cd5e856Sdrh ** outer query is a compound. */ 41437cd5e856Sdrh pParent->selFlags |= pSub->selFlags & SF_Compound; 41447cd5e856Sdrh assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ 41458c74a8caSdrh 4146a58fdfb1Sdanielk1977 /* 4147a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 4148ac83963aSdrh ** 4149ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 4150ac83963aSdrh ** does not work if either limit is negative. 4151a58fdfb1Sdanielk1977 */ 4152a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 4153f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 4154a2dc3b1aSdanielk1977 pSub->pLimit = 0; 4155df199a25Sdrh } 4156*2aee514bSdrh 4157*2aee514bSdrh /* Recompute the SrcList_item.colUsed masks for the flattened 4158*2aee514bSdrh ** tables. */ 4159*2aee514bSdrh for(i=0; i<nSubSrc; i++){ 4160*2aee514bSdrh recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]); 4161*2aee514bSdrh } 4162f23329a2Sdanielk1977 } 41638c74a8caSdrh 4164c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 4165c31c2eb8Sdrh ** success. 4166c31c2eb8Sdrh */ 4167633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 4168f23329a2Sdanielk1977 4169c90713d3Sdrh #if SELECTTRACE_ENABLED 4170c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 4171bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After flattening:\n")); 4172c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4173c90713d3Sdrh } 4174c90713d3Sdrh #endif 4175c90713d3Sdrh 4176832508b7Sdrh return 1; 41771350b030Sdrh } 41783514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 41791350b030Sdrh 4180660ee556Sdrh /* 41818e5bfeddSdrh ** A structure to keep track of all of the column values that are fixed to 4182efad2e23Sdrh ** a known value due to WHERE clause constraints of the form COLUMN=VALUE. 4183660ee556Sdrh */ 4184660ee556Sdrh typedef struct WhereConst WhereConst; 4185660ee556Sdrh struct WhereConst { 4186efad2e23Sdrh Parse *pParse; /* Parsing context */ 4187660ee556Sdrh int nConst; /* Number for COLUMN=CONSTANT terms */ 4188660ee556Sdrh int nChng; /* Number of times a constant is propagated */ 4189efad2e23Sdrh Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */ 4190660ee556Sdrh }; 419169b72d5aSdrh 4192660ee556Sdrh /* 41938e5bfeddSdrh ** Add a new entry to the pConst object. Except, do not add duplicate 4194f8f76d67Sdrh ** pColumn entires. Also, do not add if doing so would not be appropriate. 4195f8f76d67Sdrh ** 4196f8f76d67Sdrh ** The caller guarantees the pColumn is a column and pValue is a constant. 4197f8f76d67Sdrh ** This routine has to do some additional checks before completing the 4198f8f76d67Sdrh ** insert. 4199660ee556Sdrh */ 4200660ee556Sdrh static void constInsert( 42018e5bfeddSdrh WhereConst *pConst, /* The WhereConst into which we are inserting */ 42028e5bfeddSdrh Expr *pColumn, /* The COLUMN part of the constraint */ 4203f8f76d67Sdrh Expr *pValue, /* The VALUE part of the constraint */ 4204f8f76d67Sdrh Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */ 4205660ee556Sdrh ){ 42068e5bfeddSdrh int i; 42078e5bfeddSdrh assert( pColumn->op==TK_COLUMN ); 4208f8f76d67Sdrh assert( sqlite3ExprIsConstant(pValue) ); 4209f8f76d67Sdrh 4210fdfd45aeSdrh if( ExprHasProperty(pColumn, EP_FixedCol) ) return; 4211fdfd45aeSdrh if( sqlite3ExprAffinity(pValue)!=0 ) return; 4212f8f76d67Sdrh if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ 4213f8f76d67Sdrh return; 4214f8f76d67Sdrh } 42158e5bfeddSdrh 42168e5bfeddSdrh /* 2018-10-25 ticket [cf5ed20f] 42178e5bfeddSdrh ** Make sure the same pColumn is not inserted more than once */ 42188e5bfeddSdrh for(i=0; i<pConst->nConst; i++){ 42197be5e3ddSdrh const Expr *pE2 = pConst->apExpr[i*2]; 42207be5e3ddSdrh assert( pE2->op==TK_COLUMN ); 42217be5e3ddSdrh if( pE2->iTable==pColumn->iTable 42227be5e3ddSdrh && pE2->iColumn==pColumn->iColumn 42238e5bfeddSdrh ){ 42248e5bfeddSdrh return; /* Already present. Return without doing anything. */ 42258e5bfeddSdrh } 42268e5bfeddSdrh } 42279cbf4f35Sdrh 4228660ee556Sdrh pConst->nConst++; 4229efad2e23Sdrh pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr, 4230660ee556Sdrh pConst->nConst*2*sizeof(Expr*)); 4231660ee556Sdrh if( pConst->apExpr==0 ){ 4232660ee556Sdrh pConst->nConst = 0; 4233660ee556Sdrh }else{ 4234660ee556Sdrh pConst->apExpr[pConst->nConst*2-2] = pColumn; 4235660ee556Sdrh pConst->apExpr[pConst->nConst*2-1] = pValue; 4236660ee556Sdrh } 4237660ee556Sdrh } 4238660ee556Sdrh 4239660ee556Sdrh /* 4240efad2e23Sdrh ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE 4241efad2e23Sdrh ** is a constant expression and where the term must be true because it 4242efad2e23Sdrh ** is part of the AND-connected terms of the expression. For each term 4243efad2e23Sdrh ** found, add it to the pConst structure. 4244660ee556Sdrh */ 4245660ee556Sdrh static void findConstInWhere(WhereConst *pConst, Expr *pExpr){ 4246efad2e23Sdrh Expr *pRight, *pLeft; 4247660ee556Sdrh if( pExpr==0 ) return; 4248660ee556Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) ) return; 4249660ee556Sdrh if( pExpr->op==TK_AND ){ 4250660ee556Sdrh findConstInWhere(pConst, pExpr->pRight); 4251660ee556Sdrh findConstInWhere(pConst, pExpr->pLeft); 4252660ee556Sdrh return; 4253660ee556Sdrh } 4254660ee556Sdrh if( pExpr->op!=TK_EQ ) return; 4255efad2e23Sdrh pRight = pExpr->pRight; 4256efad2e23Sdrh pLeft = pExpr->pLeft; 4257efad2e23Sdrh assert( pRight!=0 ); 4258efad2e23Sdrh assert( pLeft!=0 ); 4259f8f76d67Sdrh if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){ 4260f8f76d67Sdrh constInsert(pConst,pRight,pLeft,pExpr); 4261f8f76d67Sdrh } 4262f8f76d67Sdrh if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){ 4263f8f76d67Sdrh constInsert(pConst,pLeft,pRight,pExpr); 4264660ee556Sdrh } 4265660ee556Sdrh } 4266660ee556Sdrh 4267660ee556Sdrh /* 4268660ee556Sdrh ** This is a Walker expression callback. pExpr is a candidate expression 4269660ee556Sdrh ** to be replaced by a value. If pExpr is equivalent to one of the 4270660ee556Sdrh ** columns named in pWalker->u.pConst, then overwrite it with its 4271660ee556Sdrh ** corresponding value. 4272660ee556Sdrh */ 4273660ee556Sdrh static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ 4274660ee556Sdrh int i; 4275660ee556Sdrh WhereConst *pConst; 4276660ee556Sdrh if( pExpr->op!=TK_COLUMN ) return WRC_Continue; 4277be0330e8Sdrh if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){ 4278be0330e8Sdrh testcase( ExprHasProperty(pExpr, EP_FixedCol) ); 4279be0330e8Sdrh testcase( ExprHasProperty(pExpr, EP_FromJoin) ); 4280be0330e8Sdrh return WRC_Continue; 4281be0330e8Sdrh } 4282660ee556Sdrh pConst = pWalker->u.pConst; 4283660ee556Sdrh for(i=0; i<pConst->nConst; i++){ 4284660ee556Sdrh Expr *pColumn = pConst->apExpr[i*2]; 4285660ee556Sdrh if( pColumn==pExpr ) continue; 4286660ee556Sdrh if( pColumn->iTable!=pExpr->iTable ) continue; 4287660ee556Sdrh if( pColumn->iColumn!=pExpr->iColumn ) continue; 4288efad2e23Sdrh /* A match is found. Add the EP_FixedCol property */ 4289660ee556Sdrh pConst->nChng++; 4290660ee556Sdrh ExprClearProperty(pExpr, EP_Leaf); 4291efad2e23Sdrh ExprSetProperty(pExpr, EP_FixedCol); 4292efad2e23Sdrh assert( pExpr->pLeft==0 ); 4293efad2e23Sdrh pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); 4294660ee556Sdrh break; 4295660ee556Sdrh } 4296660ee556Sdrh return WRC_Prune; 4297660ee556Sdrh } 4298660ee556Sdrh 4299660ee556Sdrh /* 4300660ee556Sdrh ** The WHERE-clause constant propagation optimization. 4301660ee556Sdrh ** 4302660ee556Sdrh ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or 430397bffe67Sdrh ** CONSTANT=COLUMN that are top-level AND-connected terms that are not 430497bffe67Sdrh ** part of a ON clause from a LEFT JOIN, then throughout the query 430597bffe67Sdrh ** replace all other occurrences of COLUMN with CONSTANT. 4306660ee556Sdrh ** 4307660ee556Sdrh ** For example, the query: 4308660ee556Sdrh ** 4309660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b 4310660ee556Sdrh ** 4311660ee556Sdrh ** Is transformed into 4312660ee556Sdrh ** 4313660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39 4314660ee556Sdrh ** 4315660ee556Sdrh ** Return true if any transformations where made and false if not. 4316efad2e23Sdrh ** 4317efad2e23Sdrh ** Implementation note: Constant propagation is tricky due to affinity 4318efad2e23Sdrh ** and collating sequence interactions. Consider this example: 4319efad2e23Sdrh ** 4320efad2e23Sdrh ** CREATE TABLE t1(a INT,b TEXT); 4321efad2e23Sdrh ** INSERT INTO t1 VALUES(123,'0123'); 4322efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=a; 4323efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=123; 4324efad2e23Sdrh ** 4325efad2e23Sdrh ** The two SELECT statements above should return different answers. b=a 4326efad2e23Sdrh ** is alway true because the comparison uses numeric affinity, but b=123 4327efad2e23Sdrh ** is false because it uses text affinity and '0123' is not the same as '123'. 4328efad2e23Sdrh ** To work around this, the expression tree is not actually changed from 4329efad2e23Sdrh ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol 4330efad2e23Sdrh ** and the "123" value is hung off of the pLeft pointer. Code generator 4331efad2e23Sdrh ** routines know to generate the constant "123" instead of looking up the 4332efad2e23Sdrh ** column value. Also, to avoid collation problems, this optimization is 4333efad2e23Sdrh ** only attempted if the "a=123" term uses the default BINARY collation. 4334660ee556Sdrh */ 4335660ee556Sdrh static int propagateConstants( 4336660ee556Sdrh Parse *pParse, /* The parsing context */ 4337660ee556Sdrh Select *p /* The query in which to propagate constants */ 4338660ee556Sdrh ){ 4339660ee556Sdrh WhereConst x; 4340660ee556Sdrh Walker w; 4341660ee556Sdrh int nChng = 0; 4342efad2e23Sdrh x.pParse = pParse; 4343660ee556Sdrh do{ 4344660ee556Sdrh x.nConst = 0; 4345660ee556Sdrh x.nChng = 0; 4346660ee556Sdrh x.apExpr = 0; 4347660ee556Sdrh findConstInWhere(&x, p->pWhere); 4348660ee556Sdrh if( x.nConst ){ 4349660ee556Sdrh memset(&w, 0, sizeof(w)); 4350660ee556Sdrh w.pParse = pParse; 4351660ee556Sdrh w.xExprCallback = propagateConstantExprRewrite; 4352660ee556Sdrh w.xSelectCallback = sqlite3SelectWalkNoop; 4353660ee556Sdrh w.xSelectCallback2 = 0; 4354660ee556Sdrh w.walkerDepth = 0; 4355660ee556Sdrh w.u.pConst = &x; 4356efad2e23Sdrh sqlite3WalkExpr(&w, p->pWhere); 4357efad2e23Sdrh sqlite3DbFree(x.pParse->db, x.apExpr); 4358660ee556Sdrh nChng += x.nChng; 4359660ee556Sdrh } 4360660ee556Sdrh }while( x.nChng ); 4361660ee556Sdrh return nChng; 4362660ee556Sdrh } 436369b72d5aSdrh 436469b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 436569b72d5aSdrh /* 436669b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into 436769b72d5aSdrh ** the WHERE clause of subquery. Example: 436869b72d5aSdrh ** 436969b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; 437069b72d5aSdrh ** 437169b72d5aSdrh ** Transformed into: 437269b72d5aSdrh ** 437369b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) 437469b72d5aSdrh ** WHERE x=5 AND y=10; 437569b72d5aSdrh ** 437669b72d5aSdrh ** The hope is that the terms added to the inner query will make it more 437769b72d5aSdrh ** efficient. 437869b72d5aSdrh ** 437969b72d5aSdrh ** Do not attempt this optimization if: 438069b72d5aSdrh ** 438125c221ebSdrh ** (1) (** This restriction was removed on 2017-09-29. We used to 438225c221ebSdrh ** disallow this optimization for aggregate subqueries, but now 438367cc51a4Sdrh ** it is allowed by putting the extra terms on the HAVING clause. 438467cc51a4Sdrh ** The added HAVING clause is pointless if the subquery lacks 438567cc51a4Sdrh ** a GROUP BY clause. But such a HAVING clause is also harmless 438667cc51a4Sdrh ** so there does not appear to be any reason to add extra logic 438767cc51a4Sdrh ** to suppress it. **) 438869b72d5aSdrh ** 438969b72d5aSdrh ** (2) The inner query is the recursive part of a common table expression. 439069b72d5aSdrh ** 439169b72d5aSdrh ** (3) The inner query has a LIMIT clause (since the changes to the WHERE 4392ce103735Sdan ** clause would change the meaning of the LIMIT). 439369b72d5aSdrh ** 43946a9b9527Sdrh ** (4) The inner query is the right operand of a LEFT JOIN and the 43956a9b9527Sdrh ** expression to be pushed down does not come from the ON clause 43966a9b9527Sdrh ** on that LEFT JOIN. 439769b72d5aSdrh ** 439838978dd4Sdrh ** (5) The WHERE clause expression originates in the ON or USING clause 43997fbb101cSdrh ** of a LEFT JOIN where iCursor is not the right-hand table of that 44007fbb101cSdrh ** left join. An example: 44017fbb101cSdrh ** 44027fbb101cSdrh ** SELECT * 44037fbb101cSdrh ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa 44047fbb101cSdrh ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) 44057fbb101cSdrh ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); 44067fbb101cSdrh ** 44077fbb101cSdrh ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). 44087fbb101cSdrh ** But if the (b2=2) term were to be pushed down into the bb subquery, 44097fbb101cSdrh ** then the (1,1,NULL) row would be suppressed. 441038978dd4Sdrh ** 4411ce103735Sdan ** (6) The inner query features one or more window-functions (since 4412ce103735Sdan ** changes to the WHERE clause of the inner query could change the 4413ce103735Sdan ** window over which window functions are calculated). 4414ce103735Sdan ** 441569b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause 441669b72d5aSdrh ** terms are duplicated into the subquery. 441769b72d5aSdrh */ 441869b72d5aSdrh static int pushDownWhereTerms( 441944c5604cSdan Parse *pParse, /* Parse context (for malloc() and error reporting) */ 442069b72d5aSdrh Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ 442169b72d5aSdrh Expr *pWhere, /* The WHERE clause of the outer query */ 44226a9b9527Sdrh int iCursor, /* Cursor number of the subquery */ 44236a9b9527Sdrh int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ 442469b72d5aSdrh ){ 442569b72d5aSdrh Expr *pNew; 442669b72d5aSdrh int nChng = 0; 442769b72d5aSdrh if( pWhere==0 ) return 0; 4428508e2d00Sdrh if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ 4429508e2d00Sdrh 4430ce103735Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 4431142066d4Sdrh if( pSubq->pWin ) return 0; /* restriction (6) */ 4432ce103735Sdan #endif 4433ce103735Sdan 4434508e2d00Sdrh #ifdef SQLITE_DEBUG 4435508e2d00Sdrh /* Only the first term of a compound can have a WITH clause. But make 4436508e2d00Sdrh ** sure no other terms are marked SF_Recursive in case something changes 4437508e2d00Sdrh ** in the future. 4438508e2d00Sdrh */ 4439508e2d00Sdrh { 4440508e2d00Sdrh Select *pX; 4441b1ec87afSdrh for(pX=pSubq; pX; pX=pX->pPrior){ 4442508e2d00Sdrh assert( (pX->selFlags & (SF_Recursive))==0 ); 444369b72d5aSdrh } 4444b1ec87afSdrh } 4445508e2d00Sdrh #endif 4446508e2d00Sdrh 444769b72d5aSdrh if( pSubq->pLimit!=0 ){ 444869b72d5aSdrh return 0; /* restriction (3) */ 444969b72d5aSdrh } 445069b72d5aSdrh while( pWhere->op==TK_AND ){ 44516a9b9527Sdrh nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, 44526a9b9527Sdrh iCursor, isLeftJoin); 445369b72d5aSdrh pWhere = pWhere->pLeft; 445469b72d5aSdrh } 44556a9b9527Sdrh if( isLeftJoin 44566a9b9527Sdrh && (ExprHasProperty(pWhere,EP_FromJoin)==0 44576a9b9527Sdrh || pWhere->iRightJoinTable!=iCursor) 44586a9b9527Sdrh ){ 44596a9b9527Sdrh return 0; /* restriction (4) */ 44606a9b9527Sdrh } 44617fbb101cSdrh if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){ 44627fbb101cSdrh return 0; /* restriction (5) */ 44637fbb101cSdrh } 446469b72d5aSdrh if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ 446569b72d5aSdrh nChng++; 446669b72d5aSdrh while( pSubq ){ 446746967de2Sdrh SubstContext x; 446844c5604cSdan pNew = sqlite3ExprDup(pParse->db, pWhere, 0); 44697fbb101cSdrh unsetJoinExpr(pNew, -1); 447046967de2Sdrh x.pParse = pParse; 447146967de2Sdrh x.iTable = iCursor; 4472399c7e21Sdrh x.iNewTable = iCursor; 447331d6fd55Sdrh x.isLeftJoin = 0; 447446967de2Sdrh x.pEList = pSubq->pEList; 447546967de2Sdrh pNew = substExpr(&x, pNew); 447625c221ebSdrh if( pSubq->selFlags & SF_Aggregate ){ 4477d5c851c1Sdrh pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew); 447825c221ebSdrh }else{ 4479d5c851c1Sdrh pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew); 448025c221ebSdrh } 448169b72d5aSdrh pSubq = pSubq->pPrior; 448269b72d5aSdrh } 448369b72d5aSdrh } 448469b72d5aSdrh return nChng; 448569b72d5aSdrh } 448669b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 448769b72d5aSdrh 44881350b030Sdrh /* 448947d9f839Sdrh ** The pFunc is the only aggregate function in the query. Check to see 449047d9f839Sdrh ** if the query is a candidate for the min/max optimization. 4491a9d1ccb9Sdanielk1977 ** 449247d9f839Sdrh ** If the query is a candidate for the min/max optimization, then set 449347d9f839Sdrh ** *ppMinMax to be an ORDER BY clause to be used for the optimization 449447d9f839Sdrh ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on 449547d9f839Sdrh ** whether pFunc is a min() or max() function. 4496738bdcfbSdanielk1977 ** 449747d9f839Sdrh ** If the query is not a candidate for the min/max optimization, return 449847d9f839Sdrh ** WHERE_ORDERBY_NORMAL (which must be zero). 44994ac391fcSdan ** 450047d9f839Sdrh ** This routine must be called after aggregate functions have been 450147d9f839Sdrh ** located but before their arguments have been subjected to aggregate 450247d9f839Sdrh ** analysis. 4503a9d1ccb9Sdanielk1977 */ 450447d9f839Sdrh static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ 45054ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 450647d9f839Sdrh ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */ 450747d9f839Sdrh const char *zFunc; /* Name of aggregate function pFunc */ 450847d9f839Sdrh ExprList *pOrderBy; 4509be284e4eSdrh u8 sortFlags = 0; 4510a9d1ccb9Sdanielk1977 451147d9f839Sdrh assert( *ppMinMax==0 ); 451247d9f839Sdrh assert( pFunc->op==TK_AGG_FUNCTION ); 45134f9adee2Sdan assert( !IsWindowFunc(pFunc) ); 45144f9adee2Sdan if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){ 45156ba7ab0dSdan return eRet; 45166ba7ab0dSdan } 451747d9f839Sdrh zFunc = pFunc->u.zToken; 45184ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 45194ac391fcSdan eRet = WHERE_ORDERBY_MIN; 452067e2bb92Sdan if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){ 45215b32bdffSdan sortFlags = KEYINFO_ORDER_BIGNULL; 452267e2bb92Sdan } 45234ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 45244ac391fcSdan eRet = WHERE_ORDERBY_MAX; 45255b32bdffSdan sortFlags = KEYINFO_ORDER_DESC; 452647d9f839Sdrh }else{ 452747d9f839Sdrh return eRet; 4528a9d1ccb9Sdanielk1977 } 452947d9f839Sdrh *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0); 453047d9f839Sdrh assert( pOrderBy!=0 || db->mallocFailed ); 45315b32bdffSdan if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags; 45324ac391fcSdan return eRet; 4533a9d1ccb9Sdanielk1977 } 4534a9d1ccb9Sdanielk1977 4535a9d1ccb9Sdanielk1977 /* 4536a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 453760ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 4538a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 4539a5533162Sdanielk1977 ** 4540a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4541a5533162Sdanielk1977 ** 4542a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 4543a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 4544a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 4545a5533162Sdanielk1977 */ 4546a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 4547a5533162Sdanielk1977 Table *pTab; 4548a5533162Sdanielk1977 Expr *pExpr; 4549a5533162Sdanielk1977 4550a5533162Sdanielk1977 assert( !p->pGroupBy ); 4551a5533162Sdanielk1977 45527a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 4553a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 4554a5533162Sdanielk1977 ){ 4555a5533162Sdanielk1977 return 0; 4556a5533162Sdanielk1977 } 4557a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 4558a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 455902f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 456002f33725Sdanielk1977 456102f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 4562a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 4563fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 4564d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 45654f9adee2Sdan if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0; 4566a5533162Sdanielk1977 4567a5533162Sdanielk1977 return pTab; 4568a5533162Sdanielk1977 } 4569a5533162Sdanielk1977 4570a5533162Sdanielk1977 /* 4571b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 4572b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 4573b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 4574b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 4575b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 4576b1c685b0Sdanielk1977 */ 4577b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 45788a48b9c0Sdrh if( pFrom->pTab && pFrom->fg.isIndexedBy ){ 4579b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 45808a48b9c0Sdrh char *zIndexedBy = pFrom->u1.zIndexedBy; 4581b1c685b0Sdanielk1977 Index *pIdx; 4582b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 4583d62fbb50Sdrh pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 4584b1c685b0Sdanielk1977 pIdx=pIdx->pNext 4585b1c685b0Sdanielk1977 ); 4586b1c685b0Sdanielk1977 if( !pIdx ){ 4587d62fbb50Sdrh sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); 45881db95106Sdan pParse->checkSchema = 1; 4589b1c685b0Sdanielk1977 return SQLITE_ERROR; 4590b1c685b0Sdanielk1977 } 45918a48b9c0Sdrh pFrom->pIBIndex = pIdx; 4592b1c685b0Sdanielk1977 } 4593b1c685b0Sdanielk1977 return SQLITE_OK; 4594b1c685b0Sdanielk1977 } 4595c01b7306Sdrh /* 4596c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 4597c01b7306Sdrh ** an alternative collating sequence. 4598c01b7306Sdrh ** 4599c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 4600c01b7306Sdrh ** 4601c01b7306Sdrh ** These are rewritten as a subquery: 4602c01b7306Sdrh ** 4603c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 4604c01b7306Sdrh ** ORDER BY ... COLLATE ... 4605c01b7306Sdrh ** 4606c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 4607c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 4608c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 4609c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 4610c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 4611c01b7306Sdrh ** 4612c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 4613c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 4614c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 4615c01b7306Sdrh */ 4616c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 4617c01b7306Sdrh int i; 4618c01b7306Sdrh Select *pNew; 4619c01b7306Sdrh Select *pX; 4620c01b7306Sdrh sqlite3 *db; 4621c01b7306Sdrh struct ExprList_item *a; 4622c01b7306Sdrh SrcList *pNewSrc; 4623c01b7306Sdrh Parse *pParse; 4624c01b7306Sdrh Token dummy; 4625c01b7306Sdrh 4626c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 4627c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 4628c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 4629c01b7306Sdrh if( pX==0 ) return WRC_Continue; 4630c01b7306Sdrh a = p->pOrderBy->a; 4631c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 4632c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 4633c01b7306Sdrh } 4634c01b7306Sdrh if( i<0 ) return WRC_Continue; 4635c01b7306Sdrh 4636c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 4637c01b7306Sdrh 4638c01b7306Sdrh pParse = pWalker->pParse; 4639c01b7306Sdrh db = pParse->db; 4640c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 4641c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 4642c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 4643c01b7306Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 4644c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 4645c01b7306Sdrh *pNew = *p; 4646c01b7306Sdrh p->pSrc = pNewSrc; 46471a1d3cd2Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); 4648c01b7306Sdrh p->op = TK_SELECT; 4649c01b7306Sdrh p->pWhere = 0; 4650c01b7306Sdrh pNew->pGroupBy = 0; 4651c01b7306Sdrh pNew->pHaving = 0; 4652c01b7306Sdrh pNew->pOrderBy = 0; 4653c01b7306Sdrh p->pPrior = 0; 46548af9ad95Sdrh p->pNext = 0; 4655f932f714Sdrh p->pWith = 0; 4656fcc057dbSdan #ifndef SQLITE_OMIT_WINDOWFUNC 4657fcc057dbSdan p->pWinDefn = 0; 4658fcc057dbSdan #endif 46598af9ad95Sdrh p->selFlags &= ~SF_Compound; 4660b33c50f2Sdan assert( (p->selFlags & SF_Converted)==0 ); 4661b33c50f2Sdan p->selFlags |= SF_Converted; 4662a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 4663a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 4664c01b7306Sdrh pNew->pLimit = 0; 4665c01b7306Sdrh return WRC_Continue; 4666c01b7306Sdrh } 4667b1c685b0Sdanielk1977 466820292310Sdrh /* 466920292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function 467020292310Sdrh ** arguments. If it does, leave an error message in pParse and return 467120292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function. 467220292310Sdrh */ 467320292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ 467420292310Sdrh if( pFrom->fg.isTabFunc ){ 467520292310Sdrh sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); 467620292310Sdrh return 1; 467720292310Sdrh } 467820292310Sdrh return 0; 467920292310Sdrh } 468020292310Sdrh 4681eede6a53Sdan #ifndef SQLITE_OMIT_CTE 4682eede6a53Sdan /* 4683eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 4684eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 4685eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 4686eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 4687eede6a53Sdan ** return NULL. 468898f45e53Sdan ** 468998f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 469098f45e53Sdan ** object that the returned CTE belongs to. 469160c1a2f0Sdrh */ 469298f45e53Sdan static struct Cte *searchWith( 46932476a6f2Sdrh With *pWith, /* Current innermost WITH clause */ 469498f45e53Sdan struct SrcList_item *pItem, /* FROM clause element to resolve */ 469598f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 469698f45e53Sdan ){ 46977b19f252Sdrh const char *zName; 46987b19f252Sdrh if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 4699eede6a53Sdan With *p; 4700eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 47014e9119d9Sdan int i; 4702eede6a53Sdan for(i=0; i<p->nCte; i++){ 4703eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 470498f45e53Sdan *ppContext = p; 4705eede6a53Sdan return &p->a[i]; 47064e9119d9Sdan } 47074e9119d9Sdan } 47084e9119d9Sdan } 47094e9119d9Sdan } 47104e9119d9Sdan return 0; 47114e9119d9Sdan } 47124e9119d9Sdan 4713c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 4714c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 4715c49832c2Sdrh ** 4716b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 4717b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 4718b290f117Sdan ** WITH clause will never be popped from the stack. In this case it 4719b290f117Sdan ** should be freed along with the Parse object. In other cases, when 4720b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 4721b290f117Sdan ** statement with which it is associated. 4722c49832c2Sdrh */ 4723b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 47246e772266Sdrh assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); 47254e9119d9Sdan if( pWith ){ 47262476a6f2Sdrh assert( pParse->pWith!=pWith ); 47274e9119d9Sdan pWith->pOuter = pParse->pWith; 47284e9119d9Sdan pParse->pWith = pWith; 47296e772266Sdrh if( bFree ) pParse->pWithToFree = pWith; 47304e9119d9Sdan } 47314e9119d9Sdan } 47324e9119d9Sdan 4733eede6a53Sdan /* 4734eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 4735eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And, 4736eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive 4737eede6a53Sdan ** reference to the current CTE. 4738eede6a53Sdan ** 4739eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab 4740eede6a53Sdan ** and other fields are populated accordingly. The caller should check 4741eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match 4742eede6a53Sdan ** was found. 4743eede6a53Sdan ** 4744eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error 4745eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the 4746eede6a53Sdan ** parser and some error code other than SQLITE_OK returned. 4747eede6a53Sdan */ 47488ce7184bSdan static int withExpand( 47498ce7184bSdan Walker *pWalker, 4750eede6a53Sdan struct SrcList_item *pFrom 47518ce7184bSdan ){ 47528ce7184bSdan Parse *pParse = pWalker->pParse; 47538ce7184bSdan sqlite3 *db = pParse->db; 475498f45e53Sdan struct Cte *pCte; /* Matched CTE (or NULL if no match) */ 475598f45e53Sdan With *pWith; /* WITH clause that pCte belongs to */ 47568ce7184bSdan 47578ce7184bSdan assert( pFrom->pTab==0 ); 475846a31cdfSdrh if( pParse->nErr ){ 475946a31cdfSdrh return SQLITE_ERROR; 476046a31cdfSdrh } 47618ce7184bSdan 476298f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 4763eae73fbfSdan if( pCte ){ 476498f45e53Sdan Table *pTab; 47658ce7184bSdan ExprList *pEList; 47668ce7184bSdan Select *pSel; 476760e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 4768f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 476998f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 4770f2655fe8Sdan 47710576bc59Sdrh /* If pCte->zCteErr is non-NULL at this point, then this is an illegal 4772f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 47730576bc59Sdrh ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. 4774f2655fe8Sdan ** In this case, proceed. */ 47750576bc59Sdrh if( pCte->zCteErr ){ 47760576bc59Sdrh sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); 477798f45e53Sdan return SQLITE_ERROR; 4778f2655fe8Sdan } 477920292310Sdrh if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; 47808ce7184bSdan 4781c25e2ebcSdrh assert( pFrom->pTab==0 ); 47828ce7184bSdan pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 47838ce7184bSdan if( pTab==0 ) return WRC_Abort; 478479df7782Sdrh pTab->nTabRef = 1; 47852d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 47868ce7184bSdan pTab->iPKey = -1; 4787cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4788fccda8a1Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 47898ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 4790fad3039cSmistachkin if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; 47918ce7184bSdan assert( pFrom->pSelect ); 47928ce7184bSdan 4793eae73fbfSdan /* Check if this is a recursive CTE. */ 47948ce7184bSdan pSel = pFrom->pSelect; 4795f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 4796f2655fe8Sdan if( bMayRecursive ){ 4797eae73fbfSdan int i; 4798eae73fbfSdan SrcList *pSrc = pFrom->pSelect->pSrc; 4799eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 4800eae73fbfSdan struct SrcList_item *pItem = &pSrc->a[i]; 4801eae73fbfSdan if( pItem->zDatabase==0 4802eae73fbfSdan && pItem->zName!=0 4803eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4804eae73fbfSdan ){ 4805eae73fbfSdan pItem->pTab = pTab; 48068a48b9c0Sdrh pItem->fg.isRecursive = 1; 480779df7782Sdrh pTab->nTabRef++; 4808eae73fbfSdan pSel->selFlags |= SF_Recursive; 48098ce7184bSdan } 4810eae73fbfSdan } 4811eae73fbfSdan } 4812eae73fbfSdan 4813eae73fbfSdan /* Only one recursive reference is permitted. */ 481479df7782Sdrh if( pTab->nTabRef>2 ){ 4815eae73fbfSdan sqlite3ErrorMsg( 4816727a99f1Sdrh pParse, "multiple references to recursive table: %s", pCte->zName 4817eae73fbfSdan ); 481898f45e53Sdan return SQLITE_ERROR; 4819eae73fbfSdan } 48203d240d21Sdrh assert( pTab->nTabRef==1 || 48213d240d21Sdrh ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); 4822eae73fbfSdan 48230576bc59Sdrh pCte->zCteErr = "circular reference: %s"; 482498f45e53Sdan pSavedWith = pParse->pWith; 482598f45e53Sdan pParse->pWith = pWith; 4826067cd837Sdan if( bMayRecursive ){ 4827067cd837Sdan Select *pPrior = pSel->pPrior; 4828067cd837Sdan assert( pPrior->pWith==0 ); 4829067cd837Sdan pPrior->pWith = pSel->pWith; 4830067cd837Sdan sqlite3WalkSelect(pWalker, pPrior); 4831067cd837Sdan pPrior->pWith = 0; 4832067cd837Sdan }else{ 4833067cd837Sdan sqlite3WalkSelect(pWalker, pSel); 4834067cd837Sdan } 48356e772266Sdrh pParse->pWith = pWith; 48368ce7184bSdan 48378ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 48388ce7184bSdan pEList = pLeft->pEList; 483960e7068dSdan if( pCte->pCols ){ 48408f9d0b2bSdrh if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ 4841727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 484260e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 484360e7068dSdan ); 484498f45e53Sdan pParse->pWith = pSavedWith; 484598f45e53Sdan return SQLITE_ERROR; 48468ce7184bSdan } 484760e7068dSdan pEList = pCte->pCols; 484860e7068dSdan } 48498ce7184bSdan 48508981b904Sdrh sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4851f2655fe8Sdan if( bMayRecursive ){ 4852f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 48530576bc59Sdrh pCte->zCteErr = "multiple recursive references: %s"; 4854f2655fe8Sdan }else{ 48550576bc59Sdrh pCte->zCteErr = "recursive reference in a subquery: %s"; 4856f2655fe8Sdan } 4857f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 4858f2655fe8Sdan } 48590576bc59Sdrh pCte->zCteErr = 0; 486098f45e53Sdan pParse->pWith = pSavedWith; 48618ce7184bSdan } 48628ce7184bSdan 48638ce7184bSdan return SQLITE_OK; 48648ce7184bSdan } 4865eede6a53Sdan #endif 48664e9119d9Sdan 4867b290f117Sdan #ifndef SQLITE_OMIT_CTE 486871856944Sdan /* 486971856944Sdan ** If the SELECT passed as the second argument has an associated WITH 487071856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 487171856944Sdan ** 487271856944Sdan ** This function is used as the xSelectCallback2() callback by 487371856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 487471856944Sdan ** names and other FROM clause elements. 487571856944Sdan */ 4876b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){ 4877b290f117Sdan Parse *pParse = pWalker->pParse; 48782f65b2f5Sdrh if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ 4879d227a291Sdrh With *pWith = findRightmost(p)->pWith; 4880d227a291Sdrh if( pWith!=0 ){ 488170a32703Sdan assert( pParse->pWith==pWith || pParse->nErr ); 4882d227a291Sdrh pParse->pWith = pWith->pOuter; 4883b290f117Sdan } 4884b290f117Sdan } 4885067cd837Sdan } 4886b290f117Sdan #else 4887b290f117Sdan #define selectPopWith 0 4888b290f117Sdan #endif 4889b290f117Sdan 48909a94722dSdan /* 48919a94722dSdan ** The SrcList_item structure passed as the second argument represents a 48929a94722dSdan ** sub-query in the FROM clause of a SELECT statement. This function 48939a94722dSdan ** allocates and populates the SrcList_item.pTab object. If successful, 48949a94722dSdan ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered, 48959a94722dSdan ** SQLITE_NOMEM. 48969a94722dSdan */ 4897dfa552f4Sdan int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){ 489886fb6e17Sdan Select *pSel = pFrom->pSelect; 489986fb6e17Sdan Table *pTab; 490086fb6e17Sdan 49019a94722dSdan assert( pSel ); 490286fb6e17Sdan pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table)); 49039a94722dSdan if( pTab==0 ) return SQLITE_NOMEM; 490486fb6e17Sdan pTab->nTabRef = 1; 490586fb6e17Sdan if( pFrom->zAlias ){ 490686fb6e17Sdan pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias); 490786fb6e17Sdan }else{ 4908fef37760Sdrh pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId); 490986fb6e17Sdan } 491086fb6e17Sdan while( pSel->pPrior ){ pSel = pSel->pPrior; } 491186fb6e17Sdan sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); 491286fb6e17Sdan pTab->iPKey = -1; 491386fb6e17Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 491486fb6e17Sdan pTab->tabFlags |= TF_Ephemeral; 491586fb6e17Sdan 4916f4b33153Sdrh return pParse->nErr ? SQLITE_ERROR : SQLITE_OK; 491786fb6e17Sdan } 491886fb6e17Sdan 4919b1c685b0Sdanielk1977 /* 49207d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 49217d10d5a6Sdrh ** "Expanding" means to do the following: 49227d10d5a6Sdrh ** 49237d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 49247d10d5a6Sdrh ** element of the FROM clause. 49257d10d5a6Sdrh ** 49267d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 49277d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 49287d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 49297d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 49307d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 493160ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 49327d10d5a6Sdrh ** of the view. 49337d10d5a6Sdrh ** 493460ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 49357d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 49367d10d5a6Sdrh ** 49377d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 49387d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 49397d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 49407d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 49417d10d5a6Sdrh ** 4942b3bce662Sdanielk1977 */ 49437d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 49447d10d5a6Sdrh Parse *pParse = pWalker->pParse; 49457d10d5a6Sdrh int i, j, k; 49467d10d5a6Sdrh SrcList *pTabList; 49477d10d5a6Sdrh ExprList *pEList; 49487d10d5a6Sdrh struct SrcList_item *pFrom; 49497d10d5a6Sdrh sqlite3 *db = pParse->db; 49503e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 4951785097daSdrh u16 selFlags = p->selFlags; 4952fca23557Sdrh u32 elistFlags = 0; 49537d10d5a6Sdrh 4954785097daSdrh p->selFlags |= SF_Expanded; 49557d10d5a6Sdrh if( db->mallocFailed ){ 49567d10d5a6Sdrh return WRC_Abort; 49577d10d5a6Sdrh } 49589d9c41e2Sdrh assert( p->pSrc!=0 ); 49599d9c41e2Sdrh if( (selFlags & SF_Expanded)!=0 ){ 49607d10d5a6Sdrh return WRC_Prune; 49617d10d5a6Sdrh } 496259145813Sdrh if( pWalker->eCode ){ 496359145813Sdrh /* Renumber selId because it has been copied from a view */ 496459145813Sdrh p->selId = ++pParse->nSelect; 496559145813Sdrh } 49667d10d5a6Sdrh pTabList = p->pSrc; 49677d10d5a6Sdrh pEList = p->pEList; 4968067cd837Sdan sqlite3WithPush(pParse, p->pWith, 0); 49697d10d5a6Sdrh 49707d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 49717d10d5a6Sdrh ** the FROM clause of the SELECT statement. 49727d10d5a6Sdrh */ 49737d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 49747d10d5a6Sdrh 49757d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 49767d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 49777d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 49787d10d5a6Sdrh */ 49797d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 49807d10d5a6Sdrh Table *pTab; 4981e2b7d7a0Sdrh assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); 49828a48b9c0Sdrh if( pFrom->fg.isRecursive ) continue; 4983e2b7d7a0Sdrh assert( pFrom->pTab==0 ); 49844e9119d9Sdan #ifndef SQLITE_OMIT_CTE 4985eede6a53Sdan if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4986eede6a53Sdan if( pFrom->pTab ) {} else 49874e9119d9Sdan #endif 49887d10d5a6Sdrh if( pFrom->zName==0 ){ 49897d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 49907d10d5a6Sdrh Select *pSel = pFrom->pSelect; 49917d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 49927d10d5a6Sdrh assert( pSel!=0 ); 49937d10d5a6Sdrh assert( pFrom->pTab==0 ); 49942b8c5a00Sdrh if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; 4995dfa552f4Sdan if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort; 499686fb6e17Sdan #endif 49977d10d5a6Sdrh }else{ 49987d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 49997d10d5a6Sdrh assert( pFrom->pTab==0 ); 500041fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 50017d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 500279df7782Sdrh if( pTab->nTabRef>=0xffff ){ 5003d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 5004d2a56238Sdrh pTab->zName); 5005d2a56238Sdrh pFrom->pTab = 0; 5006d2a56238Sdrh return WRC_Abort; 5007d2a56238Sdrh } 500879df7782Sdrh pTab->nTabRef++; 500920292310Sdrh if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ 501020292310Sdrh return WRC_Abort; 501120292310Sdrh } 50128c812f98Sdan #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 501320292310Sdrh if( IsVirtual(pTab) || pTab->pSelect ){ 5014bfad7be7Sdrh i16 nCol; 501559145813Sdrh u8 eCodeOrig = pWalker->eCode; 50167d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 501743152cf8Sdrh assert( pFrom->pSelect==0 ); 501811d88e68Sdrh if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){ 501911d88e68Sdrh sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited", 502011d88e68Sdrh pTab->zName); 50213f68142bSdrh } 50228c812f98Sdan #ifndef SQLITE_OMIT_VIRTUALTABLE 50233f68142bSdrh if( IsVirtual(pTab) 50243f68142bSdrh && pFrom->fg.fromDDL 50253f68142bSdrh && ALWAYS(pTab->pVTable!=0) 50263f68142bSdrh && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0) 50273f68142bSdrh ){ 502832266a10Sdrh sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"", 502932266a10Sdrh pTab->zName); 503011d88e68Sdrh } 50318c812f98Sdan #endif 50326ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 5033bfad7be7Sdrh nCol = pTab->nCol; 5034bfad7be7Sdrh pTab->nCol = -1; 503559145813Sdrh pWalker->eCode = 1; /* Turn on Select.selId renumbering */ 50367d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 503759145813Sdrh pWalker->eCode = eCodeOrig; 5038bfad7be7Sdrh pTab->nCol = nCol; 50397d10d5a6Sdrh } 50407d10d5a6Sdrh #endif 50417d10d5a6Sdrh } 504285574e31Sdanielk1977 504385574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 5044b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 504585574e31Sdanielk1977 return WRC_Abort; 504685574e31Sdanielk1977 } 50477d10d5a6Sdrh } 50487d10d5a6Sdrh 50497d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 50507d10d5a6Sdrh */ 5051a6c1a71cSdan if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 50527d10d5a6Sdrh return WRC_Abort; 50537d10d5a6Sdrh } 50547d10d5a6Sdrh 50557d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 50567d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 50577d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 50581a1d3cd2Sdrh ** with the TK_ASTERISK operator for each "*" that it found in the column 50591a1d3cd2Sdrh ** list. The following code just has to locate the TK_ASTERISK 50601a1d3cd2Sdrh ** expressions and expand each one to the list of all columns in 50611a1d3cd2Sdrh ** all tables. 50627d10d5a6Sdrh ** 50637d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 50647d10d5a6Sdrh ** that need expanding. 50657d10d5a6Sdrh */ 50667d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 50673e3f1a5bSdrh pE = pEList->a[k].pExpr; 50681a1d3cd2Sdrh if( pE->op==TK_ASTERISK ) break; 506943152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 507043152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 50711a1d3cd2Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; 5072fca23557Sdrh elistFlags |= pE->flags; 50737d10d5a6Sdrh } 50747d10d5a6Sdrh if( k<pEList->nExpr ){ 50757d10d5a6Sdrh /* 50767d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 50777d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 50787d10d5a6Sdrh ** in the result set and expand them one by one. 50797d10d5a6Sdrh */ 50807d10d5a6Sdrh struct ExprList_item *a = pEList->a; 50817d10d5a6Sdrh ExprList *pNew = 0; 50827d10d5a6Sdrh int flags = pParse->db->flags; 50837d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 508438b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 508538b384a0Sdrh 50867d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 50873e3f1a5bSdrh pE = a[k].pExpr; 5088fca23557Sdrh elistFlags |= pE->flags; 50893e3f1a5bSdrh pRight = pE->pRight; 50903e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 50911a1d3cd2Sdrh if( pE->op!=TK_ASTERISK 50921a1d3cd2Sdrh && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) 50931a1d3cd2Sdrh ){ 50947d10d5a6Sdrh /* This particular expression does not need to be expanded. 50957d10d5a6Sdrh */ 5096b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 50977d10d5a6Sdrh if( pNew ){ 509841cee668Sdrh pNew->a[pNew->nExpr-1].zEName = a[k].zEName; 5099cbb9da33Sdrh pNew->a[pNew->nExpr-1].eEName = a[k].eEName; 510041cee668Sdrh a[k].zEName = 0; 51017d10d5a6Sdrh } 51027d10d5a6Sdrh a[k].pExpr = 0; 51037d10d5a6Sdrh }else{ 51047d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 51057d10d5a6Sdrh ** expanded. */ 51067d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 51073e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 510843152cf8Sdrh if( pE->op==TK_DOT ){ 510943152cf8Sdrh assert( pE->pLeft!=0 ); 511033e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 511133e619fcSdrh zTName = pE->pLeft->u.zToken; 51127d10d5a6Sdrh } 51137d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 51147d10d5a6Sdrh Table *pTab = pFrom->pTab; 51153e3f1a5bSdrh Select *pSub = pFrom->pSelect; 51167d10d5a6Sdrh char *zTabName = pFrom->zAlias; 51173e3f1a5bSdrh const char *zSchemaName = 0; 5118c75e09c7Sdrh int iDb; 511943152cf8Sdrh if( zTabName==0 ){ 51207d10d5a6Sdrh zTabName = pTab->zName; 51217d10d5a6Sdrh } 51227d10d5a6Sdrh if( db->mallocFailed ) break; 51233e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 51243e3f1a5bSdrh pSub = 0; 51257d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 51267d10d5a6Sdrh continue; 51277d10d5a6Sdrh } 51283e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 512969c33826Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; 51303e3f1a5bSdrh } 51317d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 51327d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 5133b7916a78Sdrh char *zColname; /* The computed column name */ 5134b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 5135b7916a78Sdrh Token sColname; /* Computed column name as a token */ 51367d10d5a6Sdrh 5137c75e09c7Sdrh assert( zName ); 51383e3f1a5bSdrh if( zTName && pSub 5139c4938ea2Sdrh && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0 51403e3f1a5bSdrh ){ 51413e3f1a5bSdrh continue; 51423e3f1a5bSdrh } 51433e3f1a5bSdrh 514480090f92Sdrh /* If a column is marked as 'hidden', omit it from the expanded 514580090f92Sdrh ** result-set list unless the SELECT has the SF_IncludeHidden 514680090f92Sdrh ** bit set. 51477d10d5a6Sdrh */ 514880090f92Sdrh if( (p->selFlags & SF_IncludeHidden)==0 514980090f92Sdrh && IsHiddenColumn(&pTab->aCol[j]) 515080090f92Sdrh ){ 51517d10d5a6Sdrh continue; 51527d10d5a6Sdrh } 51533e3f1a5bSdrh tableSeen = 1; 51547d10d5a6Sdrh 5155da55c48aSdrh if( i>0 && zTName==0 ){ 51568a48b9c0Sdrh if( (pFrom->fg.jointype & JT_NATURAL)!=0 51579d41af23Sdan && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1) 51582179b434Sdrh ){ 51597d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 51602179b434Sdrh ** table to the right of the join */ 51617d10d5a6Sdrh continue; 51627d10d5a6Sdrh } 51632179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 51647d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 51657d10d5a6Sdrh ** using clause from the table on the right. */ 51667d10d5a6Sdrh continue; 51677d10d5a6Sdrh } 51687d10d5a6Sdrh } 5169b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 5170b7916a78Sdrh zColname = zName; 5171b7916a78Sdrh zToFree = 0; 51727d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 5173b7916a78Sdrh Expr *pLeft; 5174b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 5175abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); 517638b384a0Sdrh if( zSchemaName ){ 5177c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 5178abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); 5179c75e09c7Sdrh } 5180b7916a78Sdrh if( longNames ){ 5181b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 5182b7916a78Sdrh zToFree = zColname; 5183b7916a78Sdrh } 51847d10d5a6Sdrh }else{ 51857d10d5a6Sdrh pExpr = pRight; 51867d10d5a6Sdrh } 5187b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 518840aced5cSdrh sqlite3TokenInit(&sColname, zColname); 5189b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 51900990c415Sdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){ 51913e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 5192cbb9da33Sdrh sqlite3DbFree(db, pX->zEName); 51933e3f1a5bSdrh if( pSub ){ 5194cbb9da33Sdrh pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName); 5195cbb9da33Sdrh testcase( pX->zEName==0 ); 51963e3f1a5bSdrh }else{ 5197cbb9da33Sdrh pX->zEName = sqlite3MPrintf(db, "%s.%s.%s", 51983e3f1a5bSdrh zSchemaName, zTabName, zColname); 5199cbb9da33Sdrh testcase( pX->zEName==0 ); 52003e3f1a5bSdrh } 5201cbb9da33Sdrh pX->eEName = ENAME_TAB; 52028f25d18bSdrh } 5203b7916a78Sdrh sqlite3DbFree(db, zToFree); 52047d10d5a6Sdrh } 52057d10d5a6Sdrh } 52067d10d5a6Sdrh if( !tableSeen ){ 52077d10d5a6Sdrh if( zTName ){ 52087d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 52097d10d5a6Sdrh }else{ 52107d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 52117d10d5a6Sdrh } 52127d10d5a6Sdrh } 52137d10d5a6Sdrh } 52147d10d5a6Sdrh } 52157d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 52167d10d5a6Sdrh p->pEList = pNew; 52177d10d5a6Sdrh } 5218fca23557Sdrh if( p->pEList ){ 5219fca23557Sdrh if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 52207d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 52218836cbbcSdan return WRC_Abort; 52227d10d5a6Sdrh } 5223fca23557Sdrh if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ 5224fca23557Sdrh p->selFlags |= SF_ComplexResult; 5225fca23557Sdrh } 5226fca23557Sdrh } 52277d10d5a6Sdrh return WRC_Continue; 52287d10d5a6Sdrh } 52297d10d5a6Sdrh 52307d10d5a6Sdrh /* 52317d10d5a6Sdrh ** No-op routine for the parse-tree walker. 52327d10d5a6Sdrh ** 52337d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 52347d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 52357d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 52367d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 52377d10d5a6Sdrh ** subquery in the parser tree. 52387d10d5a6Sdrh */ 52395b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 524062c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 52417d10d5a6Sdrh return WRC_Continue; 52427d10d5a6Sdrh } 52437d10d5a6Sdrh 52447d10d5a6Sdrh /* 5245979dd1beSdrh ** No-op routine for the parse-tree walker for SELECT statements. 5246979dd1beSdrh ** subquery in the parser tree. 5247979dd1beSdrh */ 5248979dd1beSdrh int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ 5249979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 5250979dd1beSdrh return WRC_Continue; 5251979dd1beSdrh } 5252979dd1beSdrh 5253979dd1beSdrh #if SQLITE_DEBUG 5254979dd1beSdrh /* 5255979dd1beSdrh ** Always assert. This xSelectCallback2 implementation proves that the 5256979dd1beSdrh ** xSelectCallback2 is never invoked. 5257979dd1beSdrh */ 5258979dd1beSdrh void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ 5259979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 5260979dd1beSdrh assert( 0 ); 5261979dd1beSdrh } 5262979dd1beSdrh #endif 5263979dd1beSdrh /* 52647d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 52657d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 52667d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 52677d10d5a6Sdrh ** 52687d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 52697d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 52707d10d5a6Sdrh ** name resolution is performed. 52717d10d5a6Sdrh ** 52727d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 52737d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 52747d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 52757d10d5a6Sdrh */ 52767d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 52777d10d5a6Sdrh Walker w; 52785b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 52797d10d5a6Sdrh w.pParse = pParse; 5280878fcf9dSdrh if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ 5281d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 5282979dd1beSdrh w.xSelectCallback2 = 0; 52837d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 5284d58d3278Sdrh } 5285c01b7306Sdrh w.xSelectCallback = selectExpander; 5286b290f117Sdan w.xSelectCallback2 = selectPopWith; 528759145813Sdrh w.eCode = 0; 5288c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 52897d10d5a6Sdrh } 52907d10d5a6Sdrh 52917d10d5a6Sdrh 52927d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 52937d10d5a6Sdrh /* 52947d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 52957d10d5a6Sdrh ** interface. 52967d10d5a6Sdrh ** 52977d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 52987d10d5a6Sdrh ** information to the Table structure that represents the result set 52997d10d5a6Sdrh ** of that subquery. 53007d10d5a6Sdrh ** 53017d10d5a6Sdrh ** The Table structure that represents the result set was constructed 53027d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 53037d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 53047d10d5a6Sdrh ** routine is called after identifier resolution. 53057d10d5a6Sdrh */ 5306b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 53077d10d5a6Sdrh Parse *pParse; 53087d10d5a6Sdrh int i; 53097d10d5a6Sdrh SrcList *pTabList; 53107d10d5a6Sdrh struct SrcList_item *pFrom; 53117d10d5a6Sdrh 53129d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 5313cc464418Sdan if( p->selFlags & SF_HasTypeInfo ) return; 53147d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 53157d10d5a6Sdrh pParse = pWalker->pParse; 53167d10d5a6Sdrh pTabList = p->pSrc; 53177d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 53187d10d5a6Sdrh Table *pTab = pFrom->pTab; 5319e2b7d7a0Sdrh assert( pTab!=0 ); 5320e2b7d7a0Sdrh if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ 53217d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 53227d10d5a6Sdrh Select *pSel = pFrom->pSelect; 53238ce7184bSdan if( pSel ){ 53247d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 532596fb16eeSdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel, 532696fb16eeSdrh SQLITE_AFF_NONE); 53277d10d5a6Sdrh } 53287d10d5a6Sdrh } 53295a29d9cbSdrh } 53308ce7184bSdan } 53317d10d5a6Sdrh #endif 53327d10d5a6Sdrh 53337d10d5a6Sdrh 53347d10d5a6Sdrh /* 53357d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 53367d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 53377d10d5a6Sdrh ** SELECT statement. 53387d10d5a6Sdrh ** 53397d10d5a6Sdrh ** Use this routine after name resolution. 53407d10d5a6Sdrh */ 53417d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 53427d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 53437d10d5a6Sdrh Walker w; 5344979dd1beSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 5345b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 53465b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 53477d10d5a6Sdrh w.pParse = pParse; 53487d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 53497d10d5a6Sdrh #endif 53507d10d5a6Sdrh } 53517d10d5a6Sdrh 53527d10d5a6Sdrh 53537d10d5a6Sdrh /* 5354030796dfSdrh ** This routine sets up a SELECT statement for processing. The 53557d10d5a6Sdrh ** following is accomplished: 53567d10d5a6Sdrh ** 53577d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 53587d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 53597d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 53607d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 53617d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 53627d10d5a6Sdrh ** 53637d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 53647d10d5a6Sdrh */ 53657d10d5a6Sdrh void sqlite3SelectPrep( 5366b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 5367b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 53687d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 5369b3bce662Sdanielk1977 ){ 5370e2463398Sdrh assert( p!=0 || pParse->db->mallocFailed ); 5371e2463398Sdrh if( pParse->db->mallocFailed ) return; 53727d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 53737d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 5374b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 53757d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 5376b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 53777d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 5378f6bbe022Sdrh } 5379b3bce662Sdanielk1977 5380b3bce662Sdanielk1977 /* 538113449892Sdrh ** Reset the aggregate accumulator. 538213449892Sdrh ** 538313449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 538413449892Sdrh ** intermediate results while calculating an aggregate. This 5385030796dfSdrh ** routine generates code that stores NULLs in all of those memory 5386030796dfSdrh ** cells. 5387b3bce662Sdanielk1977 */ 538813449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 538913449892Sdrh Vdbe *v = pParse->pVdbe; 539013449892Sdrh int i; 5391c99130fdSdrh struct AggInfo_func *pFunc; 53927e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 53937e61d18eSdrh if( nReg==0 ) return; 53947e61d18eSdrh #ifdef SQLITE_DEBUG 53957e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 53967e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 53977e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 539813449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 53997e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 54007e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 540113449892Sdrh } 54027e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 54037e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 54047e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 54057e61d18eSdrh } 54067e61d18eSdrh #endif 54077e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 5408c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 5409c99130fdSdrh if( pFunc->iDistinct>=0 ){ 5410c99130fdSdrh Expr *pE = pFunc->pExpr; 54116ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 54126ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 54130daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 54140daa002cSdrh "argument"); 5415c99130fdSdrh pFunc->iDistinct = -1; 5416c99130fdSdrh }else{ 5417f9eae18bSdan KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0); 541866a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 54192ec2fb22Sdrh (char*)pKeyInfo, P4_KEYINFO); 5420c99130fdSdrh } 5421c99130fdSdrh } 542213449892Sdrh } 5423b3bce662Sdanielk1977 } 5424b3bce662Sdanielk1977 5425b3bce662Sdanielk1977 /* 542613449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 542713449892Sdrh ** in the AggInfo structure. 5428b3bce662Sdanielk1977 */ 542913449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 543013449892Sdrh Vdbe *v = pParse->pVdbe; 543113449892Sdrh int i; 543213449892Sdrh struct AggInfo_func *pF; 543313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 54346ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 54356ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 54362700acaaSdrh sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); 54372700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5438b3bce662Sdanielk1977 } 543913449892Sdrh } 544013449892Sdrh 5441280c894bSdan 544213449892Sdrh /* 544313449892Sdrh ** Update the accumulator memory cells for an aggregate based on 544413449892Sdrh ** the current cursor position. 5445280c894bSdan ** 5446280c894bSdan ** If regAcc is non-zero and there are no min() or max() aggregates 5447280c894bSdan ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator 544810cc16c9Sdrh ** registers if register regAcc contains 0. The caller will take care 5449280c894bSdan ** of setting and clearing regAcc. 545013449892Sdrh */ 5451280c894bSdan static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){ 545213449892Sdrh Vdbe *v = pParse->pVdbe; 545313449892Sdrh int i; 54547a95789cSdrh int regHit = 0; 54557a95789cSdrh int addrHitTest = 0; 545613449892Sdrh struct AggInfo_func *pF; 545713449892Sdrh struct AggInfo_col *pC; 545813449892Sdrh 545913449892Sdrh pAggInfo->directMode = 1; 546013449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 546113449892Sdrh int nArg; 5462c99130fdSdrh int addrNext = 0; 546398757157Sdrh int regAgg; 54646ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 54656ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 54664f9adee2Sdan assert( !IsWindowFunc(pF->pExpr) ); 54674f9adee2Sdan if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){ 54684f9adee2Sdan Expr *pFilter = pF->pExpr->y.pWin->pFilter; 5469ed09dddeSdan if( pAggInfo->nAccumulator 5470ed09dddeSdan && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) 5471ed09dddeSdan ){ 5472ed09dddeSdan if( regHit==0 ) regHit = ++pParse->nMem; 5473ed09dddeSdan /* If this is the first row of the group (regAcc==0), clear the 5474ed09dddeSdan ** "magnet" register regHit so that the accumulator registers 5475af9b58b3Sdan ** are populated if the FILTER clause jumps over the the 5476af9b58b3Sdan ** invocation of min() or max() altogether. Or, if this is not 5477af9b58b3Sdan ** the first row (regAcc==1), set the magnet register so that the 5478af9b58b3Sdan ** accumulators are not populated unless the min()/max() is invoked and 5479af9b58b3Sdan ** indicates that they should be. */ 5480ed09dddeSdan sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit); 5481ed09dddeSdan } 54826ba7ab0dSdan addrNext = sqlite3VdbeMakeLabel(pParse); 54836ba7ab0dSdan sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL); 54846ba7ab0dSdan } 548513449892Sdrh if( pList ){ 548613449892Sdrh nArg = pList->nExpr; 5487892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 54885579d59fSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); 548913449892Sdrh }else{ 549013449892Sdrh nArg = 0; 549198757157Sdrh regAgg = 0; 549213449892Sdrh } 5493c99130fdSdrh if( pF->iDistinct>=0 ){ 54946ba7ab0dSdan if( addrNext==0 ){ 5495ec4ccdbcSdrh addrNext = sqlite3VdbeMakeLabel(pParse); 54966ba7ab0dSdan } 54977c052da5Sdrh testcase( nArg==0 ); /* Error condition */ 54987c052da5Sdrh testcase( nArg>1 ); /* Also an error */ 54992dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 5500c99130fdSdrh } 5501d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 550213449892Sdrh CollSeq *pColl = 0; 550313449892Sdrh struct ExprList_item *pItem; 550413449892Sdrh int j; 5505e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 550643617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 550713449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 550813449892Sdrh } 550913449892Sdrh if( !pColl ){ 551013449892Sdrh pColl = pParse->db->pDfltColl; 551113449892Sdrh } 55127a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 55137a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 551413449892Sdrh } 55158f26da6cSdrh sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem); 55162700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5517ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 5518f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 5519c99130fdSdrh if( addrNext ){ 5520c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 5521c99130fdSdrh } 552213449892Sdrh } 5523280c894bSdan if( regHit==0 && pAggInfo->nAccumulator ){ 5524280c894bSdan regHit = regAcc; 5525280c894bSdan } 55267a95789cSdrh if( regHit ){ 5527688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 55287a95789cSdrh } 552913449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 5530389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 553113449892Sdrh } 5532ed09dddeSdan 553313449892Sdrh pAggInfo->directMode = 0; 55347a95789cSdrh if( addrHitTest ){ 5535dc4f6fc0Sdrh sqlite3VdbeJumpHereOrPopInst(v, addrHitTest); 55367a95789cSdrh } 553713449892Sdrh } 553813449892Sdrh 5539b3bce662Sdanielk1977 /* 5540ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 5541ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 5542ef7075deSdan */ 5543ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 5544ef7075deSdan static void explainSimpleCount( 5545ef7075deSdan Parse *pParse, /* Parse context */ 5546ef7075deSdan Table *pTab, /* Table being queried */ 5547ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 5548ef7075deSdan ){ 5549ef7075deSdan if( pParse->explain==2 ){ 555048dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 5551e2ca99c9Sdrh sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s", 5552ef7075deSdan pTab->zName, 5553e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 5554e96f2df3Sdan bCover ? pIdx->zName : "" 5555ef7075deSdan ); 5556ef7075deSdan } 5557ef7075deSdan } 5558ef7075deSdan #else 5559ef7075deSdan # define explainSimpleCount(a,b,c) 5560ef7075deSdan #endif 5561ef7075deSdan 5562ef7075deSdan /* 5563ab31a845Sdan ** sqlite3WalkExpr() callback used by havingToWhere(). 5564ab31a845Sdan ** 5565ab31a845Sdan ** If the node passed to the callback is a TK_AND node, return 5566ab31a845Sdan ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes. 5567ab31a845Sdan ** 5568ab31a845Sdan ** Otherwise, return WRC_Prune. In this case, also check if the 5569ab31a845Sdan ** sub-expression matches the criteria for being moved to the WHERE 5570ab31a845Sdan ** clause. If so, add it to the WHERE clause and replace the sub-expression 5571ab31a845Sdan ** within the HAVING expression with a constant "1". 5572ab31a845Sdan */ 5573ab31a845Sdan static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ 5574ab31a845Sdan if( pExpr->op!=TK_AND ){ 5575cd0abc24Sdrh Select *pS = pWalker->u.pSelect; 5576cd0abc24Sdrh if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){ 5577ab31a845Sdan sqlite3 *db = pWalker->pParse->db; 55785776ee5cSdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1"); 5579ab31a845Sdan if( pNew ){ 5580cd0abc24Sdrh Expr *pWhere = pS->pWhere; 5581ab31a845Sdan SWAP(Expr, *pNew, *pExpr); 5582d5c851c1Sdrh pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew); 5583cd0abc24Sdrh pS->pWhere = pNew; 5584cd0abc24Sdrh pWalker->eCode = 1; 5585ab31a845Sdan } 5586ab31a845Sdan } 5587ab31a845Sdan return WRC_Prune; 5588ab31a845Sdan } 5589ab31a845Sdan return WRC_Continue; 5590ab31a845Sdan } 5591ab31a845Sdan 5592ab31a845Sdan /* 5593ab31a845Sdan ** Transfer eligible terms from the HAVING clause of a query, which is 5594ab31a845Sdan ** processed after grouping, to the WHERE clause, which is processed before 5595ab31a845Sdan ** grouping. For example, the query: 5596ab31a845Sdan ** 5597ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=? 5598ab31a845Sdan ** 5599ab31a845Sdan ** can be rewritten as: 5600ab31a845Sdan ** 5601ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=? 5602ab31a845Sdan ** 5603ab31a845Sdan ** A term of the HAVING expression is eligible for transfer if it consists 5604ab31a845Sdan ** entirely of constants and expressions that are also GROUP BY terms that 5605ab31a845Sdan ** use the "BINARY" collation sequence. 5606ab31a845Sdan */ 5607cd0abc24Sdrh static void havingToWhere(Parse *pParse, Select *p){ 5608ab31a845Sdan Walker sWalker; 5609ab31a845Sdan memset(&sWalker, 0, sizeof(sWalker)); 5610ab31a845Sdan sWalker.pParse = pParse; 5611ab31a845Sdan sWalker.xExprCallback = havingToWhereExprCb; 5612cd0abc24Sdrh sWalker.u.pSelect = p; 5613cd0abc24Sdrh sqlite3WalkExpr(&sWalker, p->pHaving); 5614cd0abc24Sdrh #if SELECTTRACE_ENABLED 5615cd0abc24Sdrh if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){ 5616cd0abc24Sdrh SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); 5617cd0abc24Sdrh sqlite3TreeViewSelect(0, p, 0); 5618cd0abc24Sdrh } 5619cd0abc24Sdrh #endif 5620ab31a845Sdan } 5621ab31a845Sdan 5622ab31a845Sdan /* 5623e08e8d6bSdrh ** Check to see if the pThis entry of pTabList is a self-join of a prior view. 5624e08e8d6bSdrh ** If it is, then return the SrcList_item for the prior view. If it is not, 5625e08e8d6bSdrh ** then return 0. 5626e08e8d6bSdrh */ 5627e08e8d6bSdrh static struct SrcList_item *isSelfJoinView( 5628e08e8d6bSdrh SrcList *pTabList, /* Search for self-joins in this FROM clause */ 5629e08e8d6bSdrh struct SrcList_item *pThis /* Search for prior reference to this subquery */ 5630e08e8d6bSdrh ){ 5631e08e8d6bSdrh struct SrcList_item *pItem; 5632e08e8d6bSdrh for(pItem = pTabList->a; pItem<pThis; pItem++){ 5633bdefaf08Sdrh Select *pS1; 5634e08e8d6bSdrh if( pItem->pSelect==0 ) continue; 5635e08e8d6bSdrh if( pItem->fg.viaCoroutine ) continue; 563633543c23Sdrh if( pItem->zName==0 ) continue; 563730ad79aeSdrh assert( pItem->pTab!=0 ); 563830ad79aeSdrh assert( pThis->pTab!=0 ); 563930ad79aeSdrh if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue; 5640ed712980Sdrh if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; 5641bdefaf08Sdrh pS1 = pItem->pSelect; 564230ad79aeSdrh if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){ 5643bdefaf08Sdrh /* The query flattener left two different CTE tables with identical 5644bdefaf08Sdrh ** names in the same FROM clause. */ 5645bdefaf08Sdrh continue; 5646bdefaf08Sdrh } 5647ac4085bcSdan if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1) 5648ac4085bcSdan || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1) 5649ac4085bcSdan ){ 5650ed712980Sdrh /* The view was modified by some other optimization such as 5651ed712980Sdrh ** pushDownWhereTerms() */ 5652ed712980Sdrh continue; 5653ed712980Sdrh } 5654ed712980Sdrh return pItem; 5655e08e8d6bSdrh } 5656e08e8d6bSdrh return 0; 5657e08e8d6bSdrh } 5658e08e8d6bSdrh 5659269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5660269ba804Sdrh /* 5661269ba804Sdrh ** Attempt to transform a query of the form 5662269ba804Sdrh ** 5663269ba804Sdrh ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) 5664269ba804Sdrh ** 5665269ba804Sdrh ** Into this: 5666269ba804Sdrh ** 5667269ba804Sdrh ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) 5668269ba804Sdrh ** 5669269ba804Sdrh ** The transformation only works if all of the following are true: 5670269ba804Sdrh ** 5671269ba804Sdrh ** * The subquery is a UNION ALL of two or more terms 5672a4b5fb55Sdan ** * The subquery does not have a LIMIT clause 5673269ba804Sdrh ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries 567473c53b39Sdrh ** * The outer query is a simple count(*) with no WHERE clause or other 567573c53b39Sdrh ** extraneous syntax. 5676269ba804Sdrh ** 5677269ba804Sdrh ** Return TRUE if the optimization is undertaken. 5678269ba804Sdrh */ 5679269ba804Sdrh static int countOfViewOptimization(Parse *pParse, Select *p){ 5680269ba804Sdrh Select *pSub, *pPrior; 5681269ba804Sdrh Expr *pExpr; 5682269ba804Sdrh Expr *pCount; 5683269ba804Sdrh sqlite3 *db; 56843d240d21Sdrh if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ 5685269ba804Sdrh if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ 568673c53b39Sdrh if( p->pWhere ) return 0; 568773c53b39Sdrh if( p->pGroupBy ) return 0; 5688269ba804Sdrh pExpr = p->pEList->a[0].pExpr; 5689269ba804Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ 56903d240d21Sdrh if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ 5691269ba804Sdrh if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ 56923d240d21Sdrh if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ 5693269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5694269ba804Sdrh if( pSub==0 ) return 0; /* The FROM is a subquery */ 56953d240d21Sdrh if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ 5696269ba804Sdrh do{ 5697269ba804Sdrh if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ 5698269ba804Sdrh if( pSub->pWhere ) return 0; /* No WHERE clause */ 5699a4b5fb55Sdan if( pSub->pLimit ) return 0; /* No LIMIT clause */ 5700269ba804Sdrh if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ 57013d240d21Sdrh pSub = pSub->pPrior; /* Repeat over compound */ 5702269ba804Sdrh }while( pSub ); 5703269ba804Sdrh 57043d240d21Sdrh /* If we reach this point then it is OK to perform the transformation */ 5705269ba804Sdrh 5706269ba804Sdrh db = pParse->db; 5707269ba804Sdrh pCount = pExpr; 5708269ba804Sdrh pExpr = 0; 5709269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5710269ba804Sdrh p->pSrc->a[0].pSelect = 0; 5711269ba804Sdrh sqlite3SrcListDelete(db, p->pSrc); 5712269ba804Sdrh p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); 5713269ba804Sdrh while( pSub ){ 5714269ba804Sdrh Expr *pTerm; 5715269ba804Sdrh pPrior = pSub->pPrior; 5716269ba804Sdrh pSub->pPrior = 0; 5717269ba804Sdrh pSub->pNext = 0; 5718269ba804Sdrh pSub->selFlags |= SF_Aggregate; 5719269ba804Sdrh pSub->selFlags &= ~SF_Compound; 5720269ba804Sdrh pSub->nSelectRow = 0; 5721269ba804Sdrh sqlite3ExprListDelete(db, pSub->pEList); 5722269ba804Sdrh pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; 5723269ba804Sdrh pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm); 5724269ba804Sdrh pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0); 5725269ba804Sdrh sqlite3PExprAddSelect(pParse, pTerm, pSub); 5726269ba804Sdrh if( pExpr==0 ){ 5727269ba804Sdrh pExpr = pTerm; 5728269ba804Sdrh }else{ 5729269ba804Sdrh pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); 5730269ba804Sdrh } 5731269ba804Sdrh pSub = pPrior; 5732269ba804Sdrh } 5733269ba804Sdrh p->pEList->a[0].pExpr = pExpr; 5734269ba804Sdrh p->selFlags &= ~SF_Aggregate; 5735269ba804Sdrh 5736269ba804Sdrh #if SELECTTRACE_ENABLED 5737269ba804Sdrh if( sqlite3SelectTrace & 0x400 ){ 5738269ba804Sdrh SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); 5739269ba804Sdrh sqlite3TreeViewSelect(0, p, 0); 5740269ba804Sdrh } 5741269ba804Sdrh #endif 5742269ba804Sdrh return 1; 5743269ba804Sdrh } 5744269ba804Sdrh #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ 5745269ba804Sdrh 5746e08e8d6bSdrh /* 57477d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 57489bb61fe7Sdrh ** 5749340309fdSdrh ** The results are returned according to the SelectDest structure. 5750340309fdSdrh ** See comments in sqliteInt.h for further information. 5751e78e8284Sdrh ** 57529bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 57539bb61fe7Sdrh ** encountered, then an appropriate error message is left in 57549bb61fe7Sdrh ** pParse->zErrMsg. 57559bb61fe7Sdrh ** 57569bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 57579bb61fe7Sdrh ** calling function needs to do that. 57589bb61fe7Sdrh */ 57594adee20fSdanielk1977 int sqlite3Select( 5760cce7d176Sdrh Parse *pParse, /* The parser context */ 57619bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 57627d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 5763cce7d176Sdrh ){ 576413449892Sdrh int i, j; /* Loop counters */ 576513449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 576613449892Sdrh Vdbe *v; /* The virtual machine under construction */ 5767b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 5768c29cbb0bSmistachkin ExprList *pEList = 0; /* List of columns to extract. */ 5769ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 57709bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 57712282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 57722282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 57731d83f052Sdrh int rc = 1; /* Value to return from this function */ 5774e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 5775079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 577613449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 5777ec7429aeSdrh int iEnd; /* Address of the end of the query */ 577817435752Sdrh sqlite3 *db; /* The database connection */ 577947d9f839Sdrh ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ 578047d9f839Sdrh u8 minMaxFlag; /* Flag for min/max queries */ 57819bb61fe7Sdrh 578217435752Sdrh db = pParse->db; 5783e2ca99c9Sdrh v = sqlite3GetVdbe(pParse); 578417435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 57856f7adc8aSdrh return 1; 57866f7adc8aSdrh } 57874adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 578813449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 5789e2ca99c9Sdrh #if SELECTTRACE_ENABLED 5790e2ca99c9Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain)); 5791c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 5792c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 5793c90713d3Sdrh } 5794eb9b884cSdrh #endif 5795daffd0e5Sdrh 57968e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 57978e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 57989afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 57999afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 58006c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 58019ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 58029afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 58038e1ee88cSdrh pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || 58048e1ee88cSdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); 5805ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 5806ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 5807ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 5808ccfcbceaSdrh p->pOrderBy = 0; 58097d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 58109a99334dSdrh } 58117d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 5812956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 58139a99334dSdrh goto select_end; 58149a99334dSdrh } 5815adc57f68Sdrh assert( p->pEList!=0 ); 581617645f5eSdrh #if SELECTTRACE_ENABLED 5817e2243d26Sdrh if( sqlite3SelectTrace & 0x104 ){ 5818e2243d26Sdrh SELECTTRACE(0x104,pParse,p, ("after name resolution:\n")); 581917645f5eSdrh sqlite3TreeViewSelect(0, p, 0); 582017645f5eSdrh } 582117645f5eSdrh #endif 5822cce7d176Sdrh 5823f35f2f92Sdrh if( pDest->eDest==SRT_Output ){ 5824f35f2f92Sdrh generateColumnNames(pParse, p); 5825f35f2f92Sdrh } 5826f35f2f92Sdrh 582767a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 5828a9ebfe20Sdrh rc = sqlite3WindowRewrite(pParse, p); 5829a9ebfe20Sdrh if( rc ){ 5830aaa5ba06Sdrh assert( db->mallocFailed || pParse->nErr>0 ); 583186fb6e17Sdan goto select_end; 583286fb6e17Sdan } 5833dfa552f4Sdan #if SELECTTRACE_ENABLED 5834a0fe5fe5Sdrh if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){ 5835dfa552f4Sdan SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n")); 5836dfa552f4Sdan sqlite3TreeViewSelect(0, p, 0); 5837dfa552f4Sdan } 5838dfa552f4Sdan #endif 583967a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 584086fb6e17Sdan pTabList = p->pSrc; 58417392569fSdan isAgg = (p->selFlags & SF_Aggregate)!=0; 5842f02cdd37Sdan memset(&sSort, 0, sizeof(sSort)); 5843f02cdd37Sdan sSort.pOrderBy = p->pOrderBy; 584486fb6e17Sdan 58452589787cSdrh /* Try to various optimizations (flattening subqueries, and strength 58462589787cSdrh ** reduction of join operators) in the FROM clause up into the main query 5847d820cb1bSdrh */ 584851522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5849f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 585013449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 5851daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 58522679f14fSdrh Table *pTab = pItem->pTab; 58532589787cSdrh 58542589787cSdrh /* Convert LEFT JOIN into JOIN if there are terms of the right table 58552589787cSdrh ** of the LEFT JOIN used in the WHERE clause. 58562589787cSdrh */ 58572589787cSdrh if( (pItem->fg.jointype & JT_LEFT)!=0 58582589787cSdrh && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) 58592589787cSdrh && OptimizationEnabled(db, SQLITE_SimplifyJoin) 58602589787cSdrh ){ 58612589787cSdrh SELECTTRACE(0x100,pParse,p, 58622589787cSdrh ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); 5863efce69deSdrh pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); 58642589787cSdrh unsetJoinExpr(p->pWhere, pItem->iCursor); 58652589787cSdrh } 58662589787cSdrh 58672589787cSdrh /* No futher action if this term of the FROM clause is no a subquery */ 58684490c40bSdrh if( pSub==0 ) continue; 58692679f14fSdrh 58702679f14fSdrh /* Catch mismatch in the declared columns of a view and the number of 58712679f14fSdrh ** columns in the SELECT on the RHS */ 58722679f14fSdrh if( pTab->nCol!=pSub->pEList->nExpr ){ 58732679f14fSdrh sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", 58742679f14fSdrh pTab->nCol, pTab->zName, pSub->pEList->nExpr); 58752679f14fSdrh goto select_end; 58762679f14fSdrh } 58772679f14fSdrh 587825c221ebSdrh /* Do not try to flatten an aggregate subquery. 587925c221ebSdrh ** 588025c221ebSdrh ** Flattening an aggregate subquery is only possible if the outer query 588125c221ebSdrh ** is not a join. But if the outer query is not a join, then the subquery 588225c221ebSdrh ** will be implemented as a co-routine and there is no advantage to 588325c221ebSdrh ** flattening in that case. 588425c221ebSdrh */ 588525c221ebSdrh if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; 588625c221ebSdrh assert( pSub->pGroupBy==0 ); 588725c221ebSdrh 5888fca23557Sdrh /* If the outer query contains a "complex" result set (that is, 5889fca23557Sdrh ** if the result set of the outer query uses functions or subqueries) 5890fca23557Sdrh ** and if the subquery contains an ORDER BY clause and if 5891648fe49fSdrh ** it will be implemented as a co-routine, then do not flatten. This 5892648fe49fSdrh ** restriction allows SQL constructs like this: 5893648fe49fSdrh ** 5894648fe49fSdrh ** SELECT expensive_function(x) 5895648fe49fSdrh ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5896648fe49fSdrh ** 5897648fe49fSdrh ** The expensive_function() is only computed on the 10 rows that 5898648fe49fSdrh ** are output, rather than every row of the table. 5899fca23557Sdrh ** 5900fca23557Sdrh ** The requirement that the outer query have a complex result set 5901fca23557Sdrh ** means that flattening does occur on simpler SQL constraints without 5902fca23557Sdrh ** the expensive_function() like: 5903fca23557Sdrh ** 5904fca23557Sdrh ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5905648fe49fSdrh */ 590625c221ebSdrh if( pSub->pOrderBy!=0 5907648fe49fSdrh && i==0 5908fca23557Sdrh && (p->selFlags & SF_ComplexResult)!=0 5909648fe49fSdrh && (pTabList->nSrc==1 5910648fe49fSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) 5911648fe49fSdrh ){ 5912648fe49fSdrh continue; 5913648fe49fSdrh } 5914648fe49fSdrh 591525c221ebSdrh if( flattenSubquery(pParse, p, i, isAgg) ){ 59164acd754cSdrh if( pParse->nErr ) goto select_end; 59174490c40bSdrh /* This subquery can be absorbed into its parent. */ 59184490c40bSdrh i = -1; 59194490c40bSdrh } 59204490c40bSdrh pTabList = p->pSrc; 59214490c40bSdrh if( db->mallocFailed ) goto select_end; 59224490c40bSdrh if( !IgnorableOrderby(pDest) ){ 59234490c40bSdrh sSort.pOrderBy = p->pOrderBy; 59244490c40bSdrh } 59254490c40bSdrh } 59264490c40bSdrh #endif 59274490c40bSdrh 59284490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 59294490c40bSdrh /* Handle compound SELECT statements using the separate multiSelect() 59304490c40bSdrh ** procedure. 59314490c40bSdrh */ 59324490c40bSdrh if( p->pPrior ){ 59334490c40bSdrh rc = multiSelect(pParse, p, pDest); 59344490c40bSdrh #if SELECTTRACE_ENABLED 5935f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end compound-select processing\n")); 5936e2ca99c9Sdrh if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 5937f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 5938f20609d1Sdrh } 59394490c40bSdrh #endif 5940c631ded5Sdrh if( p->pNext==0 ) ExplainQueryPlanPop(pParse); 59414490c40bSdrh return rc; 59424490c40bSdrh } 59434490c40bSdrh #endif 59444490c40bSdrh 59457810ab64Sdrh /* Do the WHERE-clause constant propagation optimization if this is 59467810ab64Sdrh ** a join. No need to speed time on this operation for non-join queries 59477810ab64Sdrh ** as the equivalent optimization will be handled by query planner in 59487810ab64Sdrh ** sqlite3WhereBegin(). 59497810ab64Sdrh */ 59507810ab64Sdrh if( pTabList->nSrc>1 59517810ab64Sdrh && OptimizationEnabled(db, SQLITE_PropagateConst) 595224e1116eSdrh && propagateConstants(pParse, p) 595324e1116eSdrh ){ 595424e1116eSdrh #if SELECTTRACE_ENABLED 595524e1116eSdrh if( sqlite3SelectTrace & 0x100 ){ 595624e1116eSdrh SELECTTRACE(0x100,pParse,p,("After constant propagation:\n")); 595724e1116eSdrh sqlite3TreeViewSelect(0, p, 0); 595824e1116eSdrh } 595924e1116eSdrh #endif 596024e1116eSdrh }else{ 59617810ab64Sdrh SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n")); 596224e1116eSdrh } 596324e1116eSdrh 5964a4b5fb55Sdan #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5965a4b5fb55Sdan if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) 5966a4b5fb55Sdan && countOfViewOptimization(pParse, p) 5967a4b5fb55Sdan ){ 5968a4b5fb55Sdan if( db->mallocFailed ) goto select_end; 5969a4b5fb55Sdan pEList = p->pEList; 5970a4b5fb55Sdan pTabList = p->pSrc; 5971a4b5fb55Sdan } 5972a4b5fb55Sdan #endif 5973a4b5fb55Sdan 5974701caf1eSdrh /* For each term in the FROM clause, do two things: 5975701caf1eSdrh ** (1) Authorized unreferenced tables 5976701caf1eSdrh ** (2) Generate code for all sub-queries 5977d820cb1bSdrh */ 59784490c40bSdrh for(i=0; i<pTabList->nSrc; i++){ 5979742f947bSdanielk1977 struct SrcList_item *pItem = &pTabList->a[i]; 5980c31c2eb8Sdrh SelectDest dest; 5981701caf1eSdrh Select *pSub; 5982824d21afSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5983824d21afSdrh const char *zSavedAuthContext; 5984824d21afSdrh #endif 5985701caf1eSdrh 59863d240d21Sdrh /* Issue SQLITE_READ authorizations with a fake column name for any 59873d240d21Sdrh ** tables that are referenced but from which no values are extracted. 59883d240d21Sdrh ** Examples of where these kinds of null SQLITE_READ authorizations 59893d240d21Sdrh ** would occur: 5990701caf1eSdrh ** 59912336c935Sdrh ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" 59922336c935Sdrh ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" 59932336c935Sdrh ** 59942336c935Sdrh ** The fake column name is an empty string. It is possible for a table to 59952336c935Sdrh ** have a column named by the empty string, in which case there is no way to 59962336c935Sdrh ** distinguish between an unreferenced table and an actual reference to the 59972336c935Sdrh ** "" column. The original design was for the fake column name to be a NULL, 59982336c935Sdrh ** which would be unambiguous. But legacy authorization callbacks might 59993d240d21Sdrh ** assume the column name is non-NULL and segfault. The use of an empty 60003d240d21Sdrh ** string for the fake column name seems safer. 6001701caf1eSdrh */ 600274c490e0Sdrh if( pItem->colUsed==0 && pItem->zName!=0 ){ 60032336c935Sdrh sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); 6004701caf1eSdrh } 6005701caf1eSdrh 6006701caf1eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 6007701caf1eSdrh /* Generate code for all sub-queries in the FROM clause 6008701caf1eSdrh */ 6009701caf1eSdrh pSub = pItem->pSelect; 60105b6a9ed4Sdrh if( pSub==0 ) continue; 601121172c4cSdrh 6012d471bcb3Sdrh /* The code for a subquery should only be generated once, though it is 6013d471bcb3Sdrh ** technically harmless for it to be generated multiple times. The 6014d471bcb3Sdrh ** following assert() will detect if something changes to cause 6015d471bcb3Sdrh ** the same subquery to be coded multiple times, as a signal to the 601600c12a51Sdrh ** developers to try to optimize the situation. 601700c12a51Sdrh ** 601800c12a51Sdrh ** Update 2019-07-24: 601900c12a51Sdrh ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40. 602000c12a51Sdrh ** The dbsqlfuzz fuzzer found a case where the same subquery gets 602100c12a51Sdrh ** coded twice. So this assert() now becomes a testcase(). It should 602200c12a51Sdrh ** be very rare, though. 602300c12a51Sdrh */ 602400c12a51Sdrh testcase( pItem->addrFillSub!=0 ); 6025daf79acbSdanielk1977 6026fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 6027f7b5496eSdrh ** tree referred to by this, the parent select. The child select 6028fc976065Sdanielk1977 ** may contain expression trees of at most 6029fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 6030fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 6031fc976065Sdanielk1977 ** an exact limit. 6032fc976065Sdanielk1977 */ 6033fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 6034daf79acbSdanielk1977 6035adc57f68Sdrh /* Make copies of constant WHERE-clause terms in the outer query down 6036adc57f68Sdrh ** inside the subquery. This can help the subquery to run more efficiently. 6037adc57f68Sdrh */ 60387fbb101cSdrh if( OptimizationEnabled(db, SQLITE_PushDown) 60396a9b9527Sdrh && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, 60406a9b9527Sdrh (pItem->fg.jointype & JT_OUTER)!=0) 604169b72d5aSdrh ){ 604269b72d5aSdrh #if SELECTTRACE_ENABLED 604369b72d5aSdrh if( sqlite3SelectTrace & 0x100 ){ 6044d2a4401cSdrh SELECTTRACE(0x100,pParse,p, 6045d2a4401cSdrh ("After WHERE-clause push-down into subquery %d:\n", pSub->selId)); 604669b72d5aSdrh sqlite3TreeViewSelect(0, p, 0); 6047daf79acbSdanielk1977 } 604869b72d5aSdrh #endif 60492d277bb5Sdrh }else{ 60502d277bb5Sdrh SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); 605169b72d5aSdrh } 6052adc57f68Sdrh 6053824d21afSdrh zSavedAuthContext = pParse->zAuthContext; 6054824d21afSdrh pParse->zAuthContext = pItem->zName; 6055824d21afSdrh 6056adc57f68Sdrh /* Generate code to implement the subquery 60570ff47e9eSdrh ** 605825c221ebSdrh ** The subquery is implemented as a co-routine if the subquery is 605925c221ebSdrh ** guaranteed to be the outer loop (so that it does not need to be 606025c221ebSdrh ** computed more than once) 60610ff47e9eSdrh ** 60620ff47e9eSdrh ** TODO: Are there other reasons beside (1) to use a co-routine 60630ff47e9eSdrh ** implementation? 6064adc57f68Sdrh */ 60650ff47e9eSdrh if( i==0 60660ff47e9eSdrh && (pTabList->nSrc==1 60670ff47e9eSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ 6068a5759677Sdrh ){ 606921172c4cSdrh /* Implement a co-routine that will return a single row of the result 607021172c4cSdrh ** set on each invocation. 607121172c4cSdrh */ 6072725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 6073824d21afSdrh 607421172c4cSdrh pItem->regReturn = ++pParse->nMem; 6075725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 6076725de29aSdrh VdbeComment((v, "%s", pItem->pTab->zName)); 607721172c4cSdrh pItem->addrFillSub = addrTop; 607821172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 6079fef37760Sdrh ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId)); 608021172c4cSdrh sqlite3Select(pParse, pSub, &dest); 6081c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 60828a48b9c0Sdrh pItem->fg.viaCoroutine = 1; 60835f612295Sdrh pItem->regResult = dest.iSdst; 60842fade2f7Sdrh sqlite3VdbeEndCoroutine(v, pItem->regReturn); 608521172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 608621172c4cSdrh sqlite3ClearTempRegCache(pParse); 6087daf79acbSdanielk1977 }else{ 60885b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 60895b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 60905b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 60915b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 60925b6a9ed4Sdrh */ 60937157e8eaSdrh int topAddr; 609448f2d3b1Sdrh int onceAddr = 0; 60957157e8eaSdrh int retAddr; 6096e08e8d6bSdrh struct SrcList_item *pPrior; 6097e08e8d6bSdrh 609800c12a51Sdrh testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */ 60995b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 61007157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 61017157e8eaSdrh pItem->addrFillSub = topAddr+1; 61028a48b9c0Sdrh if( pItem->fg.isCorrelated==0 ){ 6103ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 61045b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 61055b6a9ed4Sdrh ** once. */ 6106511f9e8dSdrh onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 6107725de29aSdrh VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 6108725de29aSdrh }else{ 6109725de29aSdrh VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 61105b6a9ed4Sdrh } 6111e08e8d6bSdrh pPrior = isSelfJoinView(pTabList, pItem); 6112e08e8d6bSdrh if( pPrior ){ 6113e08e8d6bSdrh sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); 6114eafc6dfeSdrh assert( pPrior->pSelect!=0 ); 6115eafc6dfeSdrh pSub->nSelectRow = pPrior->pSelect->nSelectRow; 6116e08e8d6bSdrh }else{ 61171013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 6118fef37760Sdrh ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId)); 61197d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 6120e08e8d6bSdrh } 6121c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 612248f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 61237157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 61247157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 61257157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 6126cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 6127daf79acbSdanielk1977 } 6128adc57f68Sdrh if( db->mallocFailed ) goto select_end; 6129fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 6130824d21afSdrh pParse->zAuthContext = zSavedAuthContext; 6131daf79acbSdanielk1977 #endif 6132701caf1eSdrh } 6133adc57f68Sdrh 613438b4149cSdrh /* Various elements of the SELECT copied into local variables for 613538b4149cSdrh ** convenience */ 6136adc57f68Sdrh pEList = p->pEList; 6137daf79acbSdanielk1977 pWhere = p->pWhere; 6138832508b7Sdrh pGroupBy = p->pGroupBy; 6139832508b7Sdrh pHaving = p->pHaving; 6140e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 6141832508b7Sdrh 6142bc8edba1Sdrh #if SELECTTRACE_ENABLED 6143bc8edba1Sdrh if( sqlite3SelectTrace & 0x400 ){ 6144bc8edba1Sdrh SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); 6145bc8edba1Sdrh sqlite3TreeViewSelect(0, p, 0); 6146f23329a2Sdanielk1977 } 6147f23329a2Sdanielk1977 #endif 6148f23329a2Sdanielk1977 614950118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 615050118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 615150118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 615250118cdfSdan ** 615350118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 615450118cdfSdan ** 615550118cdfSdan ** is transformed to: 615650118cdfSdan ** 6157dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 615850118cdfSdan ** 615950118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 616050118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 616150118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 616250118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 616350118cdfSdan */ 616450118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 6165adc57f68Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 6166ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 6167e59c562bSdan && p->pWin==0 6168ef9f719dSdrh #endif 616950118cdfSdan ){ 617050118cdfSdan p->selFlags &= ~SF_Distinct; 6171adc57f68Sdrh pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); 61729e10f9abSdan p->selFlags |= SF_Aggregate; 6173e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 6174e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 6175e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 6176e8e4af76Sdrh assert( sDistinct.isTnct ); 61777512cb47Sdrh 61787512cb47Sdrh #if SELECTTRACE_ENABLED 61797512cb47Sdrh if( sqlite3SelectTrace & 0x400 ){ 61807512cb47Sdrh SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); 61817512cb47Sdrh sqlite3TreeViewSelect(0, p, 0); 61827512cb47Sdrh } 61837512cb47Sdrh #endif 618450118cdfSdan } 618550118cdfSdan 6186adc57f68Sdrh /* If there is an ORDER BY clause, then create an ephemeral index to 6187adc57f68Sdrh ** do the sorting. But this sorting ephemeral index might end up 6188adc57f68Sdrh ** being unused if the data can be extracted in pre-sorted order. 6189adc57f68Sdrh ** If that is the case, then the OP_OpenEphemeral instruction will be 6190adc57f68Sdrh ** changed to an OP_Noop once we figure out that the sorting index is 6191adc57f68Sdrh ** not needed. The sSort.addrSortIndex variable is used to facilitate 6192adc57f68Sdrh ** that change. 61937cedc8d4Sdanielk1977 */ 6194079a3072Sdrh if( sSort.pOrderBy ){ 61950342b1f5Sdrh KeyInfo *pKeyInfo; 6196f9eae18bSdan pKeyInfo = sqlite3KeyInfoFromExprList( 6197f9eae18bSdan pParse, sSort.pOrderBy, 0, pEList->nExpr); 6198079a3072Sdrh sSort.iECursor = pParse->nTab++; 6199079a3072Sdrh sSort.addrSortIndex = 620066a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 6201f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 6202f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 6203f45f2326Sdrh ); 62049d2985c7Sdrh }else{ 6205079a3072Sdrh sSort.addrSortIndex = -1; 62067cedc8d4Sdanielk1977 } 62077cedc8d4Sdanielk1977 62082d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 62092d0794e3Sdrh */ 62106c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 62112b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 62122d0794e3Sdrh } 62132d0794e3Sdrh 6214f42bacc2Sdrh /* Set the limiter. 6215f42bacc2Sdrh */ 6216ec4ccdbcSdrh iEnd = sqlite3VdbeMakeLabel(pParse); 621769b9383eSdan if( (p->selFlags & SF_FixedLimit)==0 ){ 6218c3489bbfSdrh p->nSelectRow = 320; /* 4 billion rows */ 621969b9383eSdan } 6220f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 6221079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 62220ff287fbSdrh sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); 6223079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 6224c6aff30cSdrh } 6225f42bacc2Sdrh 6226adc57f68Sdrh /* Open an ephemeral index to use for the distinct set. 6227cce7d176Sdrh */ 62282ce22453Sdan if( p->selFlags & SF_Distinct ){ 6229e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 6230e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 6231e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 6232f9eae18bSdan (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0), 62332ec2fb22Sdrh P4_KEYINFO); 6234d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 6235e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 6236832508b7Sdrh }else{ 6237e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 6238efb7251dSdrh } 6239832508b7Sdrh 624013449892Sdrh if( !isAgg && pGroupBy==0 ){ 6241e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 624267a9b8edSdan u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0) 624367a9b8edSdan | (p->selFlags & SF_FixedLimit); 624467a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 624567a9b8edSdan Window *pWin = p->pWin; /* Master window object (or NULL) */ 6246f9eae18bSdan if( pWin ){ 62474ea562eeSdan sqlite3WindowCodeInit(pParse, p); 624886fb6e17Sdan } 624967a9b8edSdan #endif 625067a9b8edSdan assert( WHERE_USE_LIMIT==SF_FixedLimit ); 625167a9b8edSdan 625286fb6e17Sdan 625338cc40c2Sdan /* Begin the database scan. */ 6254cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 6255079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 6256c3489bbfSdrh p->pEList, wctrlFlags, p->nSelectRow); 62571d83f052Sdrh if( pWInfo==0 ) goto select_end; 62586f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 62596f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 62606f32848dSdrh } 62616457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 62626f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 62636f32848dSdrh } 6264079a3072Sdrh if( sSort.pOrderBy ){ 6265079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 62666ee5a7b4Sdrh sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo); 6267079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 6268079a3072Sdrh sSort.pOrderBy = 0; 6269079a3072Sdrh } 6270079a3072Sdrh } 6271cce7d176Sdrh 6272b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 6273b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 62749d2985c7Sdrh ** into an OP_Noop. 62759d2985c7Sdrh */ 6276079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 6277079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 62789d2985c7Sdrh } 62799d2985c7Sdrh 62802def2f7eSdrh assert( p->pEList==pEList ); 628167a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 6282f9eae18bSdan if( pWin ){ 6283ec4ccdbcSdrh int addrGosub = sqlite3VdbeMakeLabel(pParse); 6284ec4ccdbcSdrh int iCont = sqlite3VdbeMakeLabel(pParse); 6285ec4ccdbcSdrh int iBreak = sqlite3VdbeMakeLabel(pParse); 6286f9eae18bSdan int regGosub = ++pParse->nMem; 628786fb6e17Sdan 6288dacf1de9Sdan sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub); 628986fb6e17Sdan 6290efa3a3c9Sdan sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 6291f9eae18bSdan sqlite3VdbeResolveLabel(v, addrGosub); 6292b0225bc5Sdrh VdbeNoopComment((v, "inner-loop subroutine")); 6293d4cb09e3Sdrh sSort.labelOBLopt = 0; 6294efa3a3c9Sdan selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak); 6295dacf1de9Sdan sqlite3VdbeResolveLabel(v, iCont); 629686fb6e17Sdan sqlite3VdbeAddOp1(v, OP_Return, regGosub); 62970b3b0dd1Sdrh VdbeComment((v, "end inner-loop subroutine")); 6298efa3a3c9Sdan sqlite3VdbeResolveLabel(v, iBreak); 629967a9b8edSdan }else 630067a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 630167a9b8edSdan { 630286fb6e17Sdan /* Use the standard inner loop. */ 63032def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, 63046f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 63056f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 63062282792aSdrh 6307cce7d176Sdrh /* End the database scan loop. 6308cce7d176Sdrh */ 63094adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 631086fb6e17Sdan } 631113449892Sdrh }else{ 6312e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 6313e8e4af76Sdrh ** or both */ 631413449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 631513449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 631613449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 631713449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 631813449892Sdrh ** one row of the input to the aggregator has been 631913449892Sdrh ** processed */ 632013449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 632113449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 6322d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 63231c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 63241c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 6325374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 6326d176611bSdrh 6327d176611bSdrh /* Remove any and all aliases between the result set and the 6328d176611bSdrh ** GROUP BY clause. 6329d176611bSdrh */ 6330d176611bSdrh if( pGroupBy ){ 6331dc5ea5c7Sdrh int k; /* Loop counter */ 6332d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 6333d176611bSdrh 6334dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 6335c2acc4e4Sdrh pItem->u.x.iAlias = 0; 6336d176611bSdrh } 6337dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 6338c2acc4e4Sdrh pItem->u.x.iAlias = 0; 6339d176611bSdrh } 6340c3489bbfSdrh assert( 66==sqlite3LogEst(100) ); 6341c3489bbfSdrh if( p->nSelectRow>66 ) p->nSelectRow = 66; 6342cce7d176Sdrh 6343374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 6344374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 6345374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 6346adc57f68Sdrh ** in the correct order. It also may not - the GROUP BY might use a 6347374cd78cSdan ** database index that causes rows to be grouped together as required 6348374cd78cSdan ** but not actually sorted. Either way, record the fact that the 6349374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 6350374cd78cSdan ** variable. */ 63518c9bcb23Sdan if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){ 6352e39f388eSdrh int ii; 63538c9bcb23Sdan /* The GROUP BY processing doesn't care whether rows are delivered in 63548c9bcb23Sdan ** ASC or DESC order - only that each group is returned contiguously. 63558c9bcb23Sdan ** So set the ASC/DESC flags in the GROUP BY to match those in the 63568c9bcb23Sdan ** ORDER BY to maximize the chances of rows being delivered in an 63578c9bcb23Sdan ** order that makes the ORDER BY redundant. */ 6358e39f388eSdrh for(ii=0; ii<pGroupBy->nExpr; ii++){ 6359e39f388eSdrh u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC; 6360e39f388eSdrh pGroupBy->a[ii].sortFlags = sortFlags; 63618c9bcb23Sdan } 6362374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 6363374cd78cSdan orderByGrp = 1; 6364374cd78cSdan } 63658c9bcb23Sdan } 63668c9bcb23Sdan }else{ 63678c9bcb23Sdan assert( 0==sqlite3LogEst(1) ); 63688c9bcb23Sdan p->nSelectRow = 0; 63698c9bcb23Sdan } 637013449892Sdrh 6371d176611bSdrh /* Create a label to jump to when we want to abort the query */ 6372ec4ccdbcSdrh addrEnd = sqlite3VdbeMakeLabel(pParse); 637313449892Sdrh 637413449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 637513449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 637613449892Sdrh ** SELECT statement. 63772282792aSdrh */ 637813449892Sdrh memset(&sNC, 0, sizeof(sNC)); 637913449892Sdrh sNC.pParse = pParse; 638013449892Sdrh sNC.pSrcList = pTabList; 638125c3b8caSdrh sNC.uNC.pAggInfo = &sAggInfo; 638225c3b8caSdrh VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) 63837e61d18eSdrh sAggInfo.mnReg = pParse->nMem+1; 6384dd23c6bfSdan sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 63859d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 6386d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 6387079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 6388d2b3e23bSdrh if( pHaving ){ 6389ab31a845Sdan if( pGroupBy ){ 6390ab31a845Sdan assert( pWhere==p->pWhere ); 6391cd0abc24Sdrh assert( pHaving==p->pHaving ); 6392cd0abc24Sdrh assert( pGroupBy==p->pGroupBy ); 6393cd0abc24Sdrh havingToWhere(pParse, p); 6394ab31a845Sdan pWhere = p->pWhere; 6395ab31a845Sdan } 6396d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 639713449892Sdrh } 639813449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 639947d9f839Sdrh if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){ 640047d9f839Sdrh minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy); 640147d9f839Sdrh }else{ 640247d9f839Sdrh minMaxFlag = WHERE_ORDERBY_NORMAL; 640347d9f839Sdrh } 640413449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 64056ba7ab0dSdan Expr *pExpr = sAggInfo.aFunc[i].pExpr; 64066ba7ab0dSdan assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 64073a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 64086ba7ab0dSdan sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList); 64096ba7ab0dSdan #ifndef SQLITE_OMIT_WINDOWFUNC 64104f9adee2Sdan assert( !IsWindowFunc(pExpr) ); 64114f9adee2Sdan if( ExprHasProperty(pExpr, EP_WinFunc) ){ 64124f9adee2Sdan sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter); 6413b28c4e56Sdan } 64146ba7ab0dSdan #endif 64153a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 641613449892Sdrh } 64177e61d18eSdrh sAggInfo.mxReg = pParse->nMem; 641817435752Sdrh if( db->mallocFailed ) goto select_end; 64197ea11066Sdrh #if SELECTTRACE_ENABLED 64207ea11066Sdrh if( sqlite3SelectTrace & 0x400 ){ 64217ea11066Sdrh int ii; 64227ea11066Sdrh SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n")); 64237ea11066Sdrh sqlite3TreeViewSelect(0, p, 0); 64247ea11066Sdrh for(ii=0; ii<sAggInfo.nColumn; ii++){ 64257ea11066Sdrh sqlite3DebugPrintf("agg-column[%d] iMem=%d\n", 64267ea11066Sdrh ii, sAggInfo.aCol[ii].iMem); 64277ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0); 64287ea11066Sdrh } 64297ea11066Sdrh for(ii=0; ii<sAggInfo.nFunc; ii++){ 64307ea11066Sdrh sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", 64317ea11066Sdrh ii, sAggInfo.aFunc[ii].iMem); 64327ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0); 64337ea11066Sdrh } 64347ea11066Sdrh } 64357ea11066Sdrh #endif 64367ea11066Sdrh 643713449892Sdrh 643813449892Sdrh /* Processing for aggregates with GROUP BY is very different and 64393c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 644013449892Sdrh */ 644113449892Sdrh if( pGroupBy ){ 644213449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 6443728e0f91Sdrh int addr1; /* A-vs-B comparision jump */ 6444d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 6445d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 6446d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 6447d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 6448d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 6449d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 6450d176611bSdrh int regReset; /* Return address register for reset subroutine */ 645113449892Sdrh 645213449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 645313449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 64541c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 645513449892Sdrh ** will be converted into a Noop. 645613449892Sdrh */ 645713449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 6458f9eae18bSdan pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn); 64591c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 6460cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 64612ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 646213449892Sdrh 646313449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 646413449892Sdrh */ 64650a07c107Sdrh iUseFlag = ++pParse->nMem; 64660a07c107Sdrh iAbortFlag = ++pParse->nMem; 6467d176611bSdrh regOutputRow = ++pParse->nMem; 6468ec4ccdbcSdrh addrOutputRow = sqlite3VdbeMakeLabel(pParse); 6469d176611bSdrh regReset = ++pParse->nMem; 6470ec4ccdbcSdrh addrReset = sqlite3VdbeMakeLabel(pParse); 64710a07c107Sdrh iAMem = pParse->nMem + 1; 647213449892Sdrh pParse->nMem += pGroupBy->nExpr; 64730a07c107Sdrh iBMem = pParse->nMem + 1; 647413449892Sdrh pParse->nMem += pGroupBy->nExpr; 64754c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 6476d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 6477b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 6478e313382eSdrh 647913449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 648013449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 648113449892Sdrh ** it might be a single loop that uses an index to extract information 648213449892Sdrh ** in the right order to begin with. 648313449892Sdrh */ 64842eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 6485cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 648693ec45d5Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 6487374cd78cSdan WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 6488374cd78cSdan ); 64895360ad34Sdrh if( pWInfo==0 ) goto select_end; 6490ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 649113449892Sdrh /* The optimizer is able to deliver rows in group by order so 6492b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 649313449892Sdrh ** cancelled later because we still need to use the pKeyInfo 649413449892Sdrh */ 649513449892Sdrh groupBySort = 0; 649613449892Sdrh }else{ 649713449892Sdrh /* Rows are coming out in undetermined order. We have to push 649813449892Sdrh ** each row into a sorting index, terminate the first loop, 649913449892Sdrh ** then loop over the sorting index in order to get the output 650013449892Sdrh ** in sorted order 650113449892Sdrh */ 6502892d3179Sdrh int regBase; 6503892d3179Sdrh int regRecord; 6504892d3179Sdrh int nCol; 6505892d3179Sdrh int nGroupBy; 6506892d3179Sdrh 65072ce22453Sdan explainTempTable(pParse, 6508e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 6509e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 65102ce22453Sdan 651113449892Sdrh groupBySort = 1; 6512892d3179Sdrh nGroupBy = pGroupBy->nExpr; 6513dd23c6bfSdan nCol = nGroupBy; 6514dd23c6bfSdan j = nGroupBy; 651513449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6516892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 6517892d3179Sdrh nCol++; 651813449892Sdrh j++; 651913449892Sdrh } 6520892d3179Sdrh } 6521892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 65225579d59fSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); 6523dd23c6bfSdan j = nGroupBy; 6524892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6525892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 6526892d3179Sdrh if( pCol->iSorterColumn>=j ){ 6527e55cbd72Sdrh int r1 = j + regBase; 65288c607191Sdrh sqlite3ExprCodeGetColumnOfTable(v, 65298c607191Sdrh pCol->pTab, pCol->iTable, pCol->iColumn, r1); 65306a012f04Sdrh j++; 6531892d3179Sdrh } 6532892d3179Sdrh } 6533892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 65341db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 65351c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 6536892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 6537892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 653813449892Sdrh sqlite3WhereEnd(pWInfo); 65395134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 65401c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 65411c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 65421c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 6543688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 654413449892Sdrh sAggInfo.useSortingIdx = 1; 6545374cd78cSdan } 6546374cd78cSdan 6547374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 6548374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 6549374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 6550374cd78cSdan ** 6551374cd78cSdan ** This is an optimization - the correct answer should result regardless. 6552374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 6553374cd78cSdan ** disable this optimization for testing purposes. */ 6554374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 6555374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 6556374cd78cSdan ){ 6557374cd78cSdan sSort.pOrderBy = 0; 6558374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 655913449892Sdrh } 656013449892Sdrh 656113449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 656213449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 656313449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 656413449892Sdrh ** from the previous row currently stored in a0, a1, a2... 656513449892Sdrh */ 656613449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 65671c9d835dSdrh if( groupBySort ){ 656838b4149cSdrh sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, 656938b4149cSdrh sortOut, sortPTab); 65701c9d835dSdrh } 657113449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 657213449892Sdrh if( groupBySort ){ 65731c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 657413449892Sdrh }else{ 657513449892Sdrh sAggInfo.directMode = 1; 65762dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 657713449892Sdrh } 657813449892Sdrh } 657916ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 65802ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 6581728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 6582728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); 658313449892Sdrh 658413449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 6585e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 658613449892Sdrh ** block. If there were no changes, this block is skipped. 658713449892Sdrh ** 658813449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 658913449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 659013449892Sdrh ** and resets the aggregate accumulator registers in preparation 659113449892Sdrh ** for the next GROUP BY batch. 659213449892Sdrh */ 6593b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 65942eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6595d4e70ebdSdrh VdbeComment((v, "output one row")); 6596688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 6597d4e70ebdSdrh VdbeComment((v, "check abort flag")); 65982eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 6599d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 660013449892Sdrh 660113449892Sdrh /* Update the aggregate accumulators based on the content of 660213449892Sdrh ** the current row 660313449892Sdrh */ 6604728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 6605280c894bSdan updateAccumulator(pParse, iUseFlag, &sAggInfo); 66064c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 6607d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 660813449892Sdrh 660913449892Sdrh /* End of the loop 661013449892Sdrh */ 661113449892Sdrh if( groupBySort ){ 66121c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 6613688852abSdrh VdbeCoverage(v); 661413449892Sdrh }else{ 661513449892Sdrh sqlite3WhereEnd(pWInfo); 661648f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 661713449892Sdrh } 661813449892Sdrh 661913449892Sdrh /* Output the final row of result 662013449892Sdrh */ 66212eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6622d4e70ebdSdrh VdbeComment((v, "output final row")); 662313449892Sdrh 6624d176611bSdrh /* Jump over the subroutines 6625d176611bSdrh */ 6626076e85f5Sdrh sqlite3VdbeGoto(v, addrEnd); 6627d176611bSdrh 6628d176611bSdrh /* Generate a subroutine that outputs a single row of the result 6629d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 6630d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 6631d176611bSdrh ** the processing calls for the query to abort, this subroutine 6632d176611bSdrh ** increments the iAbortFlag memory location before returning in 6633d176611bSdrh ** order to signal the caller to abort. 6634d176611bSdrh */ 6635d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 6636d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 6637d176611bSdrh VdbeComment((v, "set abort flag")); 6638d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6639d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 6640d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 6641d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 664238b4149cSdrh VdbeCoverage(v); 6643d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 6644d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6645d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 6646d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 66472def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, 6648e8e4af76Sdrh &sDistinct, pDest, 6649d176611bSdrh addrOutputRow+1, addrSetAbort); 6650d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6651d176611bSdrh VdbeComment((v, "end groupby result generator")); 6652d176611bSdrh 6653d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 6654d176611bSdrh */ 6655d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 6656d176611bSdrh resetAccumulator(pParse, &sAggInfo); 6657280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 6658280c894bSdan VdbeComment((v, "indicate accumulator empty")); 6659d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 6660d176611bSdrh 666143152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 666213449892Sdrh else { 6663a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 6664a5533162Sdanielk1977 Table *pTab; 6665a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 6666a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 6667a5533162Sdanielk1977 ** the SQL statement is of the form: 6668a5533162Sdanielk1977 ** 6669a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 6670a5533162Sdanielk1977 ** 6671a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 6672a5533162Sdanielk1977 ** 6673a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 6674a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 6675a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 6676a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 6677a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 6678a5533162Sdanielk1977 */ 6679a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 6680a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 6681a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 6682a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 6683a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 6684a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 6685a9d1ccb9Sdanielk1977 6686a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 6687a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 6688a5533162Sdanielk1977 6689d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 6690a5533162Sdanielk1977 ** 66913e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 66923e9548b3Sdrh ** 6693abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 66945f33f375Sdrh ** 6695a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 6696a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 6697a5533162Sdanielk1977 */ 66985c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 6699a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 6700d9e3cad2Sdrh if( pIdx->bUnordered==0 6701e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 6702d3037a41Sdrh && pIdx->pPartIdxWhere==0 6703e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 6704d9e3cad2Sdrh ){ 6705a5533162Sdanielk1977 pBest = pIdx; 6706a5533162Sdanielk1977 } 6707a5533162Sdanielk1977 } 6708d9e3cad2Sdrh if( pBest ){ 6709a5533162Sdanielk1977 iRoot = pBest->tnum; 67102ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 6711a5533162Sdanielk1977 } 6712a5533162Sdanielk1977 6713a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 6714261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); 6715a5533162Sdanielk1977 if( pKeyInfo ){ 67162ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 6717a5533162Sdanielk1977 } 6718a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 6719a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 6720ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 6721a5533162Sdanielk1977 }else 6722a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 6723a5533162Sdanielk1977 { 6724280c894bSdan int regAcc = 0; /* "populate accumulators" flag */ 6725280c894bSdan 6726ed09dddeSdan /* If there are accumulator registers but no min() or max() functions 6727ed09dddeSdan ** without FILTER clauses, allocate register regAcc. Register regAcc 6728ed09dddeSdan ** will contain 0 the first time the inner loop runs, and 1 thereafter. 6729ed09dddeSdan ** The code generated by updateAccumulator() uses this to ensure 6730ed09dddeSdan ** that the accumulator registers are (a) updated only once if 6731ed09dddeSdan ** there are no min() or max functions or (b) always updated for the 6732ed09dddeSdan ** first row visited by the aggregate, so that they are updated at 6733ed09dddeSdan ** least once even if the FILTER clause means the min() or max() 6734ed09dddeSdan ** function visits zero rows. */ 6735280c894bSdan if( sAggInfo.nAccumulator ){ 6736280c894bSdan for(i=0; i<sAggInfo.nFunc; i++){ 6737ed09dddeSdan if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue; 6738280c894bSdan if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break; 6739280c894bSdan } 6740280c894bSdan if( i==sAggInfo.nFunc ){ 6741280c894bSdan regAcc = ++pParse->nMem; 6742280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc); 6743280c894bSdan } 6744280c894bSdan } 6745280c894bSdan 674613449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 674713449892Sdrh ** processing is much simpler since there is only a single row 674813449892Sdrh ** of output. 674913449892Sdrh */ 675047d9f839Sdrh assert( p->pGroupBy==0 ); 675113449892Sdrh resetAccumulator(pParse, &sAggInfo); 675247d9f839Sdrh 675347d9f839Sdrh /* If this query is a candidate for the min/max optimization, then 675447d9f839Sdrh ** minMaxFlag will have been previously set to either 675547d9f839Sdrh ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will 675647d9f839Sdrh ** be an appropriate ORDER BY expression for the optimization. 675747d9f839Sdrh */ 675847d9f839Sdrh assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); 675947d9f839Sdrh assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); 676047d9f839Sdrh 6761cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 676247d9f839Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, 676347d9f839Sdrh 0, minMaxFlag, 0); 6764dba0137eSdanielk1977 if( pWInfo==0 ){ 6765dba0137eSdanielk1977 goto select_end; 6766dba0137eSdanielk1977 } 6767280c894bSdan updateAccumulator(pParse, regAcc, &sAggInfo); 6768280c894bSdan if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc); 6769ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 6770076e85f5Sdrh sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); 6771a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 677247d9f839Sdrh (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max"))); 6773a9d1ccb9Sdanielk1977 } 677413449892Sdrh sqlite3WhereEnd(pWInfo); 677513449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 67767a895a80Sdanielk1977 } 67777a895a80Sdanielk1977 6778079a3072Sdrh sSort.pOrderBy = 0; 677935573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 67802def2f7eSdrh selectInnerLoop(pParse, p, -1, 0, 0, 6781a9671a22Sdrh pDest, addrEnd, addrEnd); 678213449892Sdrh } 678313449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 678413449892Sdrh 678513449892Sdrh } /* endif aggregate query */ 67862282792aSdrh 6787e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 67882ce22453Sdan explainTempTable(pParse, "DISTINCT"); 67892ce22453Sdan } 67902ce22453Sdan 6791cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 6792cce7d176Sdrh ** and send them to the callback one by one. 6793cce7d176Sdrh */ 6794079a3072Sdrh if( sSort.pOrderBy ){ 679538b4149cSdrh explainTempTable(pParse, 679638b4149cSdrh sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 679724e25d32Sdan assert( p->pEList==pEList ); 6798079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 6799cce7d176Sdrh } 68006a535340Sdrh 6801ec7429aeSdrh /* Jump here to skip this query 6802ec7429aeSdrh */ 6803ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 6804ec7429aeSdrh 68055b1c07e7Sdan /* The SELECT has been coded. If there is an error in the Parse structure, 68065b1c07e7Sdan ** set the return code to 1. Otherwise 0. */ 68075b1c07e7Sdan rc = (pParse->nErr>0); 68081d83f052Sdrh 68091d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 68101d83f052Sdrh ** successful coding of the SELECT. 68111d83f052Sdrh */ 68121d83f052Sdrh select_end: 681347d9f839Sdrh sqlite3ExprListDelete(db, pMinMaxOrderBy); 6814633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 6815633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 6816eb9b884cSdrh #if SELECTTRACE_ENABLED 6817f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end processing\n")); 6818e2ca99c9Sdrh if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 6819f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 6820f20609d1Sdrh } 6821eb9b884cSdrh #endif 6822e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 68231d83f052Sdrh return rc; 6824cce7d176Sdrh } 6825