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 } 1063703edf1Sdan assert( p->pWin==0 ); 10767a9b8edSdan #endif 1088906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith); 109dbd6a7dcSdrh if( bFree ) sqlite3DbFreeNN(db, p); 110b87fbed5Sdrh p = pPrior; 111b87fbed5Sdrh bFree = 1; 112b87fbed5Sdrh } 113eda639e1Sdrh } 114eda639e1Sdrh 1151013c932Sdrh /* 1161013c932Sdrh ** Initialize a SelectDest structure. 1171013c932Sdrh */ 1181013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 119ea678832Sdrh pDest->eDest = (u8)eDest; 1202b596da8Sdrh pDest->iSDParm = iParm; 12171c57db0Sdan pDest->zAffSdst = 0; 1222b596da8Sdrh pDest->iSdst = 0; 1232b596da8Sdrh pDest->nSdst = 0; 1241013c932Sdrh } 1251013c932Sdrh 126eda639e1Sdrh 127eda639e1Sdrh /* 1289bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 1299bb61fe7Sdrh ** structure. 130cce7d176Sdrh */ 1314adee20fSdanielk1977 Select *sqlite3SelectNew( 13217435752Sdrh Parse *pParse, /* Parsing context */ 133daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 134ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 135daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 136daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 137daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 138daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 139c3489bbfSdrh u32 selFlags, /* Flag parameters, such as SF_Distinct */ 1408c0833fbSdrh Expr *pLimit /* LIMIT value. NULL means not used */ 1419bb61fe7Sdrh ){ 1429bb61fe7Sdrh Select *pNew; 143eda639e1Sdrh Select standin; 144ef90a6b8Sdrh pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); 145daffd0e5Sdrh if( pNew==0 ){ 146ef90a6b8Sdrh assert( pParse->db->mallocFailed ); 147eda639e1Sdrh pNew = &standin; 148eda639e1Sdrh } 149b733d037Sdrh if( pEList==0 ){ 1503d240d21Sdrh pEList = sqlite3ExprListAppend(pParse, 0, 1513d240d21Sdrh sqlite3Expr(pParse->db,TK_ASTERISK,0)); 152b733d037Sdrh } 1539bb61fe7Sdrh pNew->pEList = pEList; 154ca3862dcSdrh pNew->op = TK_SELECT; 155ca3862dcSdrh pNew->selFlags = selFlags; 156ca3862dcSdrh pNew->iLimit = 0; 157ca3862dcSdrh pNew->iOffset = 0; 158fef37760Sdrh pNew->selId = ++pParse->nSelect; 159ca3862dcSdrh pNew->addrOpenEphm[0] = -1; 160ca3862dcSdrh pNew->addrOpenEphm[1] = -1; 161ca3862dcSdrh pNew->nSelectRow = 0; 162ef90a6b8Sdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); 1639bb61fe7Sdrh pNew->pSrc = pSrc; 1649bb61fe7Sdrh pNew->pWhere = pWhere; 1659bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 1669bb61fe7Sdrh pNew->pHaving = pHaving; 1679bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 168ca3862dcSdrh pNew->pPrior = 0; 169ca3862dcSdrh pNew->pNext = 0; 170a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 171ca3862dcSdrh pNew->pWith = 0; 17267a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 17386fb6e17Sdan pNew->pWin = 0; 174e3bf632cSdan pNew->pWinDefn = 0; 17567a9b8edSdan #endif 176ef90a6b8Sdrh if( pParse->db->mallocFailed ) { 177ef90a6b8Sdrh clearSelect(pParse->db, pNew, pNew!=&standin); 178eda639e1Sdrh pNew = 0; 179a464c234Sdrh }else{ 180a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 181daffd0e5Sdrh } 182338ec3e1Sdrh assert( pNew!=&standin ); 1839bb61fe7Sdrh return pNew; 1849bb61fe7Sdrh } 1859bb61fe7Sdrh 186eb9b884cSdrh 1879bb61fe7Sdrh /* 188eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 189eda639e1Sdrh */ 190633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 1918906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); 192eda639e1Sdrh } 193eda639e1Sdrh 194eda639e1Sdrh /* 195a9ebfe20Sdrh ** Delete all the substructure for p, but keep p allocated. Redefine 196a9ebfe20Sdrh ** p to be a single SELECT where every column of the result set has a 197a9ebfe20Sdrh ** value of NULL. 198a9ebfe20Sdrh */ 199a9ebfe20Sdrh void sqlite3SelectReset(Parse *pParse, Select *p){ 200a9ebfe20Sdrh if( ALWAYS(p) ){ 201a9ebfe20Sdrh clearSelect(pParse->db, p, 0); 202a9ebfe20Sdrh memset(&p->iLimit, 0, sizeof(Select) - offsetof(Select,iLimit)); 203a9ebfe20Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, 204a9ebfe20Sdrh sqlite3ExprAlloc(pParse->db,TK_NULL,0,0)); 205aa328b6aSdan p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(SrcList)); 206a9ebfe20Sdrh } 207a9ebfe20Sdrh } 208a9ebfe20Sdrh 209a9ebfe20Sdrh /* 210d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound. 211d227a291Sdrh */ 212d227a291Sdrh static Select *findRightmost(Select *p){ 213d227a291Sdrh while( p->pNext ) p = p->pNext; 214d227a291Sdrh return p; 2159bb61fe7Sdrh } 2169bb61fe7Sdrh 2179bb61fe7Sdrh /* 218f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the 21901f3f253Sdrh ** type of join. Return an integer constant that expresses that type 22001f3f253Sdrh ** in terms of the following bit values: 22101f3f253Sdrh ** 22201f3f253Sdrh ** JT_INNER 2233dec223cSdrh ** JT_CROSS 22401f3f253Sdrh ** JT_OUTER 22501f3f253Sdrh ** JT_NATURAL 22601f3f253Sdrh ** JT_LEFT 22701f3f253Sdrh ** JT_RIGHT 22801f3f253Sdrh ** 22901f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 23001f3f253Sdrh ** 23101f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 23201f3f253Sdrh ** a join type, but put an error in the pParse structure. 23301f3f253Sdrh */ 2344adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 23501f3f253Sdrh int jointype = 0; 23601f3f253Sdrh Token *apAll[3]; 23701f3f253Sdrh Token *p; 238373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 239373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 2405719628aSdrh static const struct { 241373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 242373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 243373cc2ddSdrh u8 code; /* Join type mask */ 244373cc2ddSdrh } aKeyword[] = { 245373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 246373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 247373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 248373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 249373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 250373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 251373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 25201f3f253Sdrh }; 25301f3f253Sdrh int i, j; 25401f3f253Sdrh apAll[0] = pA; 25501f3f253Sdrh apAll[1] = pB; 25601f3f253Sdrh apAll[2] = pC; 257195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 25801f3f253Sdrh p = apAll[i]; 259373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 260373cc2ddSdrh if( p->n==aKeyword[j].nChar 261373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 262373cc2ddSdrh jointype |= aKeyword[j].code; 26301f3f253Sdrh break; 26401f3f253Sdrh } 26501f3f253Sdrh } 266373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 267373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 26801f3f253Sdrh jointype |= JT_ERROR; 26901f3f253Sdrh break; 27001f3f253Sdrh } 27101f3f253Sdrh } 272ad2d8307Sdrh if( 273ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 274195e6967Sdrh (jointype & JT_ERROR)!=0 275ad2d8307Sdrh ){ 276a9671a22Sdrh const char *zSp = " "; 277a9671a22Sdrh assert( pB!=0 ); 278a9671a22Sdrh if( pC==0 ){ zSp++; } 279ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 280a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 28101f3f253Sdrh jointype = JT_INNER; 282373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 283373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 2844adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 285da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 286195e6967Sdrh jointype = JT_INNER; 28701f3f253Sdrh } 28801f3f253Sdrh return jointype; 28901f3f253Sdrh } 29001f3f253Sdrh 29101f3f253Sdrh /* 292ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 293ad2d8307Sdrh ** is not contained in the table. 294ad2d8307Sdrh */ 295ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 296ad2d8307Sdrh int i; 297ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 2984adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 299ad2d8307Sdrh } 300ad2d8307Sdrh return -1; 301ad2d8307Sdrh } 302ad2d8307Sdrh 303ad2d8307Sdrh /* 3042179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 3052179b434Sdrh ** table that has a column named zCol. 3062179b434Sdrh ** 3072179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 3082179b434Sdrh ** of the matching column and return TRUE. 3092179b434Sdrh ** 3102179b434Sdrh ** If not found, return FALSE. 3112179b434Sdrh */ 3122179b434Sdrh static int tableAndColumnIndex( 3132179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 3142179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 3152179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 3162179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 3179d41af23Sdan int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 3189d41af23Sdan int bIgnoreHidden /* True to ignore hidden columns */ 3192179b434Sdrh ){ 3202179b434Sdrh int i; /* For looping over tables in pSrc */ 3212179b434Sdrh int iCol; /* Index of column matching zCol */ 3222179b434Sdrh 3232179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 3242179b434Sdrh for(i=0; i<N; i++){ 3252179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 3269d41af23Sdan if( iCol>=0 3279d41af23Sdan && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0) 3289d41af23Sdan ){ 3292179b434Sdrh if( piTab ){ 3302179b434Sdrh *piTab = i; 3312179b434Sdrh *piCol = iCol; 3322179b434Sdrh } 3332179b434Sdrh return 1; 3342179b434Sdrh } 3352179b434Sdrh } 3362179b434Sdrh return 0; 3372179b434Sdrh } 3382179b434Sdrh 3392179b434Sdrh /* 340f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 341f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 342f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 343f7b0b0adSdan ** 344f7b0b0adSdan ** (tab1.col1 = tab2.col2) 345f7b0b0adSdan ** 346f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 347f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 348f7b0b0adSdan ** column iColRight of tab2. 349ad2d8307Sdrh */ 350ad2d8307Sdrh static void addWhereTerm( 35117435752Sdrh Parse *pParse, /* Parsing context */ 352f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 3532179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 354f7b0b0adSdan int iColLeft, /* Index of column in first table */ 3552179b434Sdrh int iRight, /* Index of second table in pSrc */ 356f7b0b0adSdan int iColRight, /* Index of column in second table */ 357f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 358f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 359ad2d8307Sdrh ){ 360f7b0b0adSdan sqlite3 *db = pParse->db; 361f7b0b0adSdan Expr *pE1; 362f7b0b0adSdan Expr *pE2; 363f7b0b0adSdan Expr *pEq; 364ad2d8307Sdrh 3652179b434Sdrh assert( iLeft<iRight ); 3662179b434Sdrh assert( pSrc->nSrc>iRight ); 3672179b434Sdrh assert( pSrc->a[iLeft].pTab ); 3682179b434Sdrh assert( pSrc->a[iRight].pTab ); 369f7b0b0adSdan 3702179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 3712179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 372f7b0b0adSdan 373abfd35eaSdrh pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); 374f7b0b0adSdan if( pEq && isOuterJoin ){ 375f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 376c5cd1249Sdrh assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); 377ebb6a65dSdrh ExprSetVVAProperty(pEq, EP_NoReduce); 378f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 379030530deSdrh } 380d5c851c1Sdrh *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq); 381ad2d8307Sdrh } 382ad2d8307Sdrh 383ad2d8307Sdrh /* 3841f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 38522d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 38622d6a53aSdrh ** expression. 3871cc093c2Sdrh ** 388e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 3891cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 3901f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 3911f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 3921f16230bSdrh ** WHERE clause during join processing but we need to remember that they 3931f16230bSdrh ** originated in the ON or USING clause. 39422d6a53aSdrh ** 39522d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 39622d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 39722d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 39822d6a53aSdrh ** for cases like this: 39922d6a53aSdrh ** 40022d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 40122d6a53aSdrh ** 40222d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 40322d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 40422d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 40522d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 40622d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 40722d6a53aSdrh ** the output, which is incorrect. 4081cc093c2Sdrh */ 4098103a036Sdrh void sqlite3SetJoinExpr(Expr *p, int iTable){ 4101cc093c2Sdrh while( p ){ 4111f16230bSdrh ExprSetProperty(p, EP_FromJoin); 412c5cd1249Sdrh assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 413ebb6a65dSdrh ExprSetVVAProperty(p, EP_NoReduce); 414cf697396Sshane p->iRightJoinTable = (i16)iTable; 415606f2344Sdrh if( p->op==TK_FUNCTION && p->x.pList ){ 416606f2344Sdrh int i; 417606f2344Sdrh for(i=0; i<p->x.pList->nExpr; i++){ 4188103a036Sdrh sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable); 419606f2344Sdrh } 420606f2344Sdrh } 4218103a036Sdrh sqlite3SetJoinExpr(p->pLeft, iTable); 4221cc093c2Sdrh p = p->pRight; 4231cc093c2Sdrh } 4241cc093c2Sdrh } 4251cc093c2Sdrh 4268103a036Sdrh /* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every 4272589787cSdrh ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into 4282589787cSdrh ** an ordinary term that omits the EP_FromJoin mark. 4292589787cSdrh ** 4302589787cSdrh ** This happens when a LEFT JOIN is simplified into an ordinary JOIN. 4312589787cSdrh */ 4322589787cSdrh static void unsetJoinExpr(Expr *p, int iTable){ 4332589787cSdrh while( p ){ 4347fbb101cSdrh if( ExprHasProperty(p, EP_FromJoin) 4357fbb101cSdrh && (iTable<0 || p->iRightJoinTable==iTable) ){ 4362589787cSdrh ExprClearProperty(p, EP_FromJoin); 4372589787cSdrh } 4382589787cSdrh if( p->op==TK_FUNCTION && p->x.pList ){ 4392589787cSdrh int i; 4402589787cSdrh for(i=0; i<p->x.pList->nExpr; i++){ 4412589787cSdrh unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); 4422589787cSdrh } 4432589787cSdrh } 4442589787cSdrh unsetJoinExpr(p->pLeft, iTable); 4452589787cSdrh p = p->pRight; 4462589787cSdrh } 4472589787cSdrh } 4482589787cSdrh 4491cc093c2Sdrh /* 450ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 451ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 452ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 453ad2d8307Sdrh ** 45491bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 45591bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 45691bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 45791bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 45891bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 45991bb0eedSdrh ** also attached to the left entry. 46091bb0eedSdrh ** 461ad2d8307Sdrh ** This routine returns the number of errors encountered. 462ad2d8307Sdrh */ 463ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 46491bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 46591bb0eedSdrh int i, j; /* Loop counters */ 46691bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 46791bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 468ad2d8307Sdrh 46991bb0eedSdrh pSrc = p->pSrc; 47091bb0eedSdrh pLeft = &pSrc->a[0]; 47191bb0eedSdrh pRight = &pLeft[1]; 47291bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 47391bb0eedSdrh Table *pRightTab = pRight->pTab; 474ad27e761Sdrh int isOuter; 47591bb0eedSdrh 476ce2c482eSdrh if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; 4778a48b9c0Sdrh isOuter = (pRight->fg.jointype & JT_OUTER)!=0; 478ad2d8307Sdrh 479ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 480ad2d8307Sdrh ** every column that the two tables have in common. 481ad2d8307Sdrh */ 4828a48b9c0Sdrh if( pRight->fg.jointype & JT_NATURAL ){ 48361dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 4844adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 485ad2d8307Sdrh "an ON or USING clause", 0); 486ad2d8307Sdrh return 1; 487ad2d8307Sdrh } 4882179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4892179b434Sdrh char *zName; /* Name of column in the right table */ 4902179b434Sdrh int iLeft; /* Matching left table */ 4912179b434Sdrh int iLeftCol; /* Matching column in the left table */ 4922179b434Sdrh 4939d41af23Sdan if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue; 4942179b434Sdrh zName = pRightTab->aCol[j].zName; 4959d41af23Sdan if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){ 4962179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 4972179b434Sdrh isOuter, &p->pWhere); 498ad2d8307Sdrh } 499ad2d8307Sdrh } 500ad2d8307Sdrh } 501ad2d8307Sdrh 502ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 503ad2d8307Sdrh */ 50461dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 5054adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 506da93d238Sdrh "clauses in the same join"); 507ad2d8307Sdrh return 1; 508ad2d8307Sdrh } 509ad2d8307Sdrh 510ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 51191bb0eedSdrh ** an AND operator. 512ad2d8307Sdrh */ 51361dfc31dSdrh if( pRight->pOn ){ 5148103a036Sdrh if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor); 515d5c851c1Sdrh p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn); 51661dfc31dSdrh pRight->pOn = 0; 517ad2d8307Sdrh } 518ad2d8307Sdrh 519ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 520ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 521ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 522ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 523ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 524ad2d8307Sdrh ** not contained in both tables to be joined. 525ad2d8307Sdrh */ 52661dfc31dSdrh if( pRight->pUsing ){ 52761dfc31dSdrh IdList *pList = pRight->pUsing; 528ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 5292179b434Sdrh char *zName; /* Name of the term in the USING clause */ 5302179b434Sdrh int iLeft; /* Table on the left with matching column name */ 5312179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 5322179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 5332179b434Sdrh 5342179b434Sdrh zName = pList->a[j].zName; 5352179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 5362179b434Sdrh if( iRightCol<0 5379d41af23Sdan || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0) 5382179b434Sdrh ){ 5394adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 54091bb0eedSdrh "not present in both tables", zName); 541ad2d8307Sdrh return 1; 542ad2d8307Sdrh } 5432179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 5442179b434Sdrh isOuter, &p->pWhere); 545ad2d8307Sdrh } 546ad2d8307Sdrh } 547ad2d8307Sdrh } 548ad2d8307Sdrh return 0; 549ad2d8307Sdrh } 550ad2d8307Sdrh 551ad2d8307Sdrh /* 552bbd4ae5aSdrh ** An instance of this object holds information (beyond pParse and pSelect) 553bbd4ae5aSdrh ** needed to load the next result row that is to be added to the sorter. 554bbd4ae5aSdrh */ 555bbd4ae5aSdrh typedef struct RowLoadInfo RowLoadInfo; 556bbd4ae5aSdrh struct RowLoadInfo { 557bbd4ae5aSdrh int regResult; /* Store results in array of registers here */ 558bbd4ae5aSdrh u8 ecelFlags; /* Flag argument to ExprCodeExprList() */ 559bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 560bbd4ae5aSdrh ExprList *pExtra; /* Extra columns needed by sorter refs */ 561bbd4ae5aSdrh int regExtraResult; /* Where to load the extra columns */ 562bbd4ae5aSdrh #endif 563bbd4ae5aSdrh }; 564bbd4ae5aSdrh 565bbd4ae5aSdrh /* 566bbd4ae5aSdrh ** This routine does the work of loading query data into an array of 567bbd4ae5aSdrh ** registers so that it can be added to the sorter. 568bbd4ae5aSdrh */ 569bbd4ae5aSdrh static void innerLoopLoadRow( 570bbd4ae5aSdrh Parse *pParse, /* Statement under construction */ 571bbd4ae5aSdrh Select *pSelect, /* The query being coded */ 572bbd4ae5aSdrh RowLoadInfo *pInfo /* Info needed to complete the row load */ 573bbd4ae5aSdrh ){ 574bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult, 575bbd4ae5aSdrh 0, pInfo->ecelFlags); 576bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 577bbd4ae5aSdrh if( pInfo->pExtra ){ 578bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0); 579bbd4ae5aSdrh sqlite3ExprListDelete(pParse->db, pInfo->pExtra); 580bbd4ae5aSdrh } 581bbd4ae5aSdrh #endif 582bbd4ae5aSdrh } 583bbd4ae5aSdrh 584bbd4ae5aSdrh /* 585bbd4ae5aSdrh ** Code the OP_MakeRecord instruction that generates the entry to be 586bbd4ae5aSdrh ** added into the sorter. 587bbd4ae5aSdrh ** 588bbd4ae5aSdrh ** Return the register in which the result is stored. 589bbd4ae5aSdrh */ 590bbd4ae5aSdrh static int makeSorterRecord( 591bbd4ae5aSdrh Parse *pParse, 592bbd4ae5aSdrh SortCtx *pSort, 593bbd4ae5aSdrh Select *pSelect, 594bbd4ae5aSdrh int regBase, 595bbd4ae5aSdrh int nBase 596bbd4ae5aSdrh ){ 597bbd4ae5aSdrh int nOBSat = pSort->nOBSat; 598bbd4ae5aSdrh Vdbe *v = pParse->pVdbe; 599bbd4ae5aSdrh int regOut = ++pParse->nMem; 600bbd4ae5aSdrh if( pSort->pDeferredRowLoad ){ 601bbd4ae5aSdrh innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad); 602bbd4ae5aSdrh } 603bbd4ae5aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut); 604bbd4ae5aSdrh return regOut; 605bbd4ae5aSdrh } 606bbd4ae5aSdrh 607bbd4ae5aSdrh /* 608f45f2326Sdrh ** Generate code that will push the record in registers regData 609f45f2326Sdrh ** through regData+nData-1 onto the sorter. 610c926afbcSdrh */ 611d59ba6ceSdrh static void pushOntoSorter( 612d59ba6ceSdrh Parse *pParse, /* Parser context */ 613079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 614b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 615f45f2326Sdrh int regData, /* First register holding data to be sorted */ 6165579d59fSdrh int regOrigData, /* First register holding data before packing */ 617bbd4ae5aSdrh int nData, /* Number of elements in the regData data array */ 618fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 619d59ba6ceSdrh ){ 620f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 62178d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 622f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 62378d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 624fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 625bbd4ae5aSdrh int regRecord = 0; /* Assembled sorter record */ 62678d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 627f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 628a04a8be2Sdrh int iLimit; /* LIMIT counter */ 629bbd4ae5aSdrh int iSkip = 0; /* End of the sorter insert loop */ 630f45f2326Sdrh 63178d58432Sdan assert( bSeq==0 || bSeq==1 ); 632bbd4ae5aSdrh 633bbd4ae5aSdrh /* Three cases: 634bbd4ae5aSdrh ** (1) The data to be sorted has already been packed into a Record 635bbd4ae5aSdrh ** by a prior OP_MakeRecord. In this case nData==1 and regData 636bbd4ae5aSdrh ** will be completely unrelated to regOrigData. 637bbd4ae5aSdrh ** (2) All output columns are included in the sort record. In that 638bbd4ae5aSdrh ** case regData==regOrigData. 639bbd4ae5aSdrh ** (3) Some output columns are omitted from the sort record due to 640bbd4ae5aSdrh ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the 641c6f36fa3Sdrh ** SQLITE_ECEL_OMITREF optimization, or due to the 642c6f36fa3Sdrh ** SortCtx.pDeferredRowLoad optimiation. In any of these cases 643c6f36fa3Sdrh ** regOrigData is 0 to prevent this routine from trying to copy 644c6f36fa3Sdrh ** values that might not yet exist. 645bbd4ae5aSdrh */ 6469af90b72Sdan assert( nData==1 || regData==regOrigData || regOrigData==0 ); 647bbd4ae5aSdrh 648fd0a2f97Sdrh if( nPrefixReg ){ 64978d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 650bbd4ae5aSdrh regBase = regData - nPrefixReg; 651fd0a2f97Sdrh }else{ 652fb0d6e56Sdrh regBase = pParse->nMem + 1; 653fb0d6e56Sdrh pParse->nMem += nBase; 654fd0a2f97Sdrh } 655a04a8be2Sdrh assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); 656a04a8be2Sdrh iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; 657ec4ccdbcSdrh pSort->labelDone = sqlite3VdbeMakeLabel(pParse); 6585579d59fSdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, 6599af90b72Sdan SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); 66078d58432Sdan if( bSeq ){ 661079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 662fd0a2f97Sdrh } 663257c13faSdan if( nPrefixReg==0 && nData>0 ){ 664236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 66578d58432Sdan } 666079a3072Sdrh if( nOBSat>0 ){ 667079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 668079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 669079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 670079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 671079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 672dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 673079a3072Sdrh 674bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 67526d7e7c6Sdrh regPrevKey = pParse->nMem+1; 67626d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 67778d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 67878d58432Sdan if( bSeq ){ 67978d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 68078d58432Sdan }else{ 68178d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 68278d58432Sdan } 68378d58432Sdan VdbeCoverage(v); 68426d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 685079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 68659b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 687fb0d6e56Sdrh pOp->p2 = nKey + nData; 688dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 6896e11892dSdan memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */ 690dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 691a485ad19Sdrh testcase( pKI->nAllField > pKI->nKeyField+2 ); 692f9eae18bSdan pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat, 693a485ad19Sdrh pKI->nAllField-pKI->nKeyField-1); 694166bc383Sdrh pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */ 695079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 696079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 697ec4ccdbcSdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse); 698079a3072Sdrh pSort->regReturn = ++pParse->nMem; 699079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 70065ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 701a04a8be2Sdrh if( iLimit ){ 702a04a8be2Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); 703a04a8be2Sdrh VdbeCoverage(v); 704a04a8be2Sdrh } 705079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 706236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 707079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 708079a3072Sdrh } 709f226f03dSdan if( iLimit ){ 710f226f03dSdan /* At this point the values for the new sorter entry are stored 711f226f03dSdan ** in an array of registers. They need to be composed into a record 712f226f03dSdan ** and inserted into the sorter if either (a) there are currently 713f226f03dSdan ** less than LIMIT+OFFSET items or (b) the new record is smaller than 714f226f03dSdan ** the largest record currently in the sorter. If (b) is true and there 715f226f03dSdan ** are already LIMIT+OFFSET items in the sorter, delete the largest 716f226f03dSdan ** entry before inserting the new one. This way there are never more 717f226f03dSdan ** than LIMIT+OFFSET items in the sorter. 718f226f03dSdan ** 719f226f03dSdan ** If the new record does not need to be inserted into the sorter, 7206ee5a7b4Sdrh ** jump to the next iteration of the loop. If the pSort->labelOBLopt 7216ee5a7b4Sdrh ** value is not zero, then it is a label of where to jump. Otherwise, 7226ee5a7b4Sdrh ** just bypass the row insert logic. See the header comment on the 7236ee5a7b4Sdrh ** sqlite3WhereOrderByLimitOptLabel() function for additional info. 724f226f03dSdan */ 725f226f03dSdan int iCsr = pSort->iECursor; 726f226f03dSdan sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4); 727f226f03dSdan VdbeCoverage(v); 728f226f03dSdan sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0); 729bbd4ae5aSdrh iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE, 730bbd4ae5aSdrh iCsr, 0, regBase+nOBSat, nExpr-nOBSat); 731f226f03dSdan VdbeCoverage(v); 732f226f03dSdan sqlite3VdbeAddOp1(v, OP_Delete, iCsr); 733f226f03dSdan } 734bbd4ae5aSdrh if( regRecord==0 ){ 735bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 736f226f03dSdan } 737079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 738c6aff30cSdrh op = OP_SorterInsert; 739c6aff30cSdrh }else{ 740c6aff30cSdrh op = OP_IdxInsert; 741c6aff30cSdrh } 7424a8b013eSdrh sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, 7434a8b013eSdrh regBase+nOBSat, nBase-nOBSat); 744bbd4ae5aSdrh if( iSkip ){ 745bbd4ae5aSdrh sqlite3VdbeChangeP2(v, iSkip, 7466ee5a7b4Sdrh pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v)); 747bbd4ae5aSdrh } 748c926afbcSdrh } 749c926afbcSdrh 750c926afbcSdrh /* 751ec7429aeSdrh ** Add code to implement the OFFSET 752ea48eb2eSdrh */ 753ec7429aeSdrh static void codeOffset( 754bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 755aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 756b7654111Sdrh int iContinue /* Jump here to skip the current record */ 757ea48eb2eSdrh ){ 758a22a75e5Sdrh if( iOffset>0 ){ 7598b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); 7608b0cf38aSdrh VdbeComment((v, "OFFSET")); 761ea48eb2eSdrh } 762ea48eb2eSdrh } 763ea48eb2eSdrh 764ea48eb2eSdrh /* 76598757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 76698757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 767a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 768a2a49dc9Sdrh ** if the current N values are new. 769a2a49dc9Sdrh ** 770a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 771a2a49dc9Sdrh ** stack if the top N elements are not distinct. 772a2a49dc9Sdrh */ 773a2a49dc9Sdrh static void codeDistinct( 7742dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 775a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 776a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 777477df4b3Sdrh int N, /* Number of elements */ 778a2a49dc9Sdrh int iMem /* First element */ 779a2a49dc9Sdrh ){ 7802dcef11bSdrh Vdbe *v; 7812dcef11bSdrh int r1; 7822dcef11bSdrh 7832dcef11bSdrh v = pParse->pVdbe; 7842dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 785688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); 7861db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 7879b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); 788a67b5cb6Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 7892dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 790a2a49dc9Sdrh } 791a2a49dc9Sdrh 79224e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 79324e25d32Sdan /* 79424e25d32Sdan ** This function is called as part of inner-loop generation for a SELECT 79524e25d32Sdan ** statement with an ORDER BY that is not optimized by an index. It 79624e25d32Sdan ** determines the expressions, if any, that the sorter-reference 79724e25d32Sdan ** optimization should be used for. The sorter-reference optimization 79824e25d32Sdan ** is used for SELECT queries like: 79924e25d32Sdan ** 80024e25d32Sdan ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 80124e25d32Sdan ** 80224e25d32Sdan ** If the optimization is used for expression "bigblob", then instead of 80324e25d32Sdan ** storing values read from that column in the sorter records, the PK of 80424e25d32Sdan ** the row from table t1 is stored instead. Then, as records are extracted from 80524e25d32Sdan ** the sorter to return to the user, the required value of bigblob is 80624e25d32Sdan ** retrieved directly from table t1. If the values are very large, this 80724e25d32Sdan ** can be more efficient than storing them directly in the sorter records. 80824e25d32Sdan ** 80924e25d32Sdan ** The ExprList_item.bSorterRef flag is set for each expression in pEList 81024e25d32Sdan ** for which the sorter-reference optimization should be enabled. 81124e25d32Sdan ** Additionally, the pSort->aDefer[] array is populated with entries 81224e25d32Sdan ** for all cursors required to evaluate all selected expressions. Finally. 81324e25d32Sdan ** output variable (*ppExtra) is set to an expression list containing 81424e25d32Sdan ** expressions for all extra PK values that should be stored in the 81524e25d32Sdan ** sorter records. 81624e25d32Sdan */ 81724e25d32Sdan static void selectExprDefer( 81824e25d32Sdan Parse *pParse, /* Leave any error here */ 81924e25d32Sdan SortCtx *pSort, /* Sorter context */ 82024e25d32Sdan ExprList *pEList, /* Expressions destined for sorter */ 82124e25d32Sdan ExprList **ppExtra /* Expressions to append to sorter record */ 82224e25d32Sdan ){ 82324e25d32Sdan int i; 82424e25d32Sdan int nDefer = 0; 82524e25d32Sdan ExprList *pExtra = 0; 82624e25d32Sdan for(i=0; i<pEList->nExpr; i++){ 82724e25d32Sdan struct ExprList_item *pItem = &pEList->a[i]; 82824e25d32Sdan if( pItem->u.x.iOrderByCol==0 ){ 82924e25d32Sdan Expr *pExpr = pItem->pExpr; 830eda079cdSdrh Table *pTab = pExpr->y.pTab; 8310f86c9d8Sdan if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab) 8322e3a5a81Sdan && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF) 83324e25d32Sdan ){ 83424e25d32Sdan int j; 83524e25d32Sdan for(j=0; j<nDefer; j++){ 83624e25d32Sdan if( pSort->aDefer[j].iCsr==pExpr->iTable ) break; 83724e25d32Sdan } 83824e25d32Sdan if( j==nDefer ){ 83924e25d32Sdan if( nDefer==ArraySize(pSort->aDefer) ){ 84024e25d32Sdan continue; 84124e25d32Sdan }else{ 84224e25d32Sdan int nKey = 1; 84324e25d32Sdan int k; 84424e25d32Sdan Index *pPk = 0; 84524e25d32Sdan if( !HasRowid(pTab) ){ 84624e25d32Sdan pPk = sqlite3PrimaryKeyIndex(pTab); 84724e25d32Sdan nKey = pPk->nKeyCol; 84824e25d32Sdan } 84924e25d32Sdan for(k=0; k<nKey; k++){ 85024e25d32Sdan Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0); 85124e25d32Sdan if( pNew ){ 85224e25d32Sdan pNew->iTable = pExpr->iTable; 853eda079cdSdrh pNew->y.pTab = pExpr->y.pTab; 85424e25d32Sdan pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; 85524e25d32Sdan pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew); 85624e25d32Sdan } 85724e25d32Sdan } 858eda079cdSdrh pSort->aDefer[nDefer].pTab = pExpr->y.pTab; 85924e25d32Sdan pSort->aDefer[nDefer].iCsr = pExpr->iTable; 86024e25d32Sdan pSort->aDefer[nDefer].nKey = nKey; 86124e25d32Sdan nDefer++; 86224e25d32Sdan } 86324e25d32Sdan } 86424e25d32Sdan pItem->bSorterRef = 1; 86524e25d32Sdan } 86624e25d32Sdan } 86724e25d32Sdan } 86824e25d32Sdan pSort->nDefer = (u8)nDefer; 86924e25d32Sdan *ppExtra = pExtra; 87024e25d32Sdan } 87124e25d32Sdan #endif 87224e25d32Sdan 873c99130fdSdrh /* 8742282792aSdrh ** This routine generates the code for the inside of the inner loop 8752282792aSdrh ** of a SELECT. 87682c3d636Sdrh ** 8772def2f7eSdrh ** If srcTab is negative, then the p->pEList expressions 878340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 8792def2f7eSdrh ** zero or more, then data is pulled from srcTab and p->pEList is used only 880257c13faSdan ** to get the number of columns and the collation sequence for each column. 8812282792aSdrh */ 882d2b3e23bSdrh static void selectInnerLoop( 8832282792aSdrh Parse *pParse, /* The parser context */ 884df199a25Sdrh Select *p, /* The complete select statement being coded */ 8852def2f7eSdrh int srcTab, /* Pull data from this table if non-negative */ 886079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 887e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 8886c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 8892282792aSdrh int iContinue, /* Jump here to continue with next row */ 890a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 8912282792aSdrh ){ 8922282792aSdrh Vdbe *v = pParse->pVdbe; 893d847eaadSdrh int i; 894ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 895d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 8962b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 897d847eaadSdrh int nResultCol; /* Number of result columns */ 898fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 899bbd4ae5aSdrh RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */ 90038640e15Sdrh 9019af90b72Sdan /* Usually, regResult is the first cell in an array of memory cells 9029af90b72Sdan ** containing the current result row. In this case regOrig is set to the 9039af90b72Sdan ** same value. However, if the results are being sent to the sorter, the 9049af90b72Sdan ** values for any expressions that are also part of the sort-key are omitted 9059af90b72Sdan ** from this array. In this case regOrig is set to zero. */ 9069af90b72Sdan int regResult; /* Start of memory holding current results */ 9079af90b72Sdan int regOrig; /* Start of memory holding full result (or 0) */ 9089af90b72Sdan 9091c767f0dSdrh assert( v ); 9102def2f7eSdrh assert( p->pEList!=0 ); 911e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 912079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 913079a3072Sdrh if( pSort==0 && !hasDistinct ){ 914a22a75e5Sdrh assert( iContinue!=0 ); 915aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 916df199a25Sdrh } 917df199a25Sdrh 918967e8b73Sdrh /* Pull the requested columns. 9192282792aSdrh */ 9202def2f7eSdrh nResultCol = p->pEList->nExpr; 92105a86c5cSdrh 9222b596da8Sdrh if( pDest->iSdst==0 ){ 923fd0a2f97Sdrh if( pSort ){ 92478d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 92578d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 926fd0a2f97Sdrh pParse->nMem += nPrefixReg; 9271013c932Sdrh } 928a2a49dc9Sdrh pDest->iSdst = pParse->nMem+1; 929477df4b3Sdrh pParse->nMem += nResultCol; 93005a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 93105a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 93205a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 93305a86c5cSdrh ** there are columns in the table on the left. The error will be caught 93405a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 93505a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 93605a86c5cSdrh pParse->nMem += nResultCol; 9374c583128Sdrh } 93805a86c5cSdrh pDest->nSdst = nResultCol; 9399af90b72Sdan regOrig = regResult = pDest->iSdst; 940340309fdSdrh if( srcTab>=0 ){ 941340309fdSdrh for(i=0; i<nResultCol; i++){ 942d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 94341cee668Sdrh VdbeComment((v, "%s", p->pEList->a[i].zEName)); 94482c3d636Sdrh } 9459ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 94624e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 94724e25d32Sdan ExprList *pExtra = 0; 94824e25d32Sdan #endif 9499ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 9509ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 9519ed1dfa8Sdanielk1977 */ 952bbd4ae5aSdrh u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */ 953bbd4ae5aSdrh ExprList *pEList; 954df553659Sdrh if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ 955df553659Sdrh ecelFlags = SQLITE_ECEL_DUP; 956df553659Sdrh }else{ 957df553659Sdrh ecelFlags = 0; 958a2a49dc9Sdrh } 959ac56ab7eSdan if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ 9602def2f7eSdrh /* For each expression in p->pEList that is a copy of an expression in 961257c13faSdan ** the ORDER BY clause (pSort->pOrderBy), set the associated 962257c13faSdan ** iOrderByCol value to one more than the index of the ORDER BY 963257c13faSdan ** expression within the sort-key that pushOntoSorter() will generate. 9642def2f7eSdrh ** This allows the p->pEList field to be omitted from the sorted record, 965257c13faSdan ** saving space and CPU cycles. */ 966257c13faSdan ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); 967bbd4ae5aSdrh 968257c13faSdan for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ 969257c13faSdan int j; 970257c13faSdan if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ 9712def2f7eSdrh p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; 972257c13faSdan } 973257c13faSdan } 97424e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 97524e25d32Sdan selectExprDefer(pParse, pSort, p->pEList, &pExtra); 9765a2e65edSdrh if( pExtra && pParse->db->mallocFailed==0 ){ 97724e25d32Sdan /* If there are any extra PK columns to add to the sorter records, 97824e25d32Sdan ** allocate extra memory cells and adjust the OpenEphemeral 97924e25d32Sdan ** instruction to account for the larger records. This is only 98024e25d32Sdan ** required if there are one or more WITHOUT ROWID tables with 98124e25d32Sdan ** composite primary keys in the SortCtx.aDefer[] array. */ 98224e25d32Sdan VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 98324e25d32Sdan pOp->p2 += (pExtra->nExpr - pSort->nDefer); 98424e25d32Sdan pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); 98524e25d32Sdan pParse->nMem += pExtra->nExpr; 98624e25d32Sdan } 98724e25d32Sdan #endif 988bbd4ae5aSdrh 989bbd4ae5aSdrh /* Adjust nResultCol to account for columns that are omitted 990bbd4ae5aSdrh ** from the sorter by the optimizations in this branch */ 991bbd4ae5aSdrh pEList = p->pEList; 992bbd4ae5aSdrh for(i=0; i<pEList->nExpr; i++){ 993bbd4ae5aSdrh if( pEList->a[i].u.x.iOrderByCol>0 994bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 995bbd4ae5aSdrh || pEList->a[i].bSorterRef 996bbd4ae5aSdrh #endif 997bbd4ae5aSdrh ){ 998bbd4ae5aSdrh nResultCol--; 9999af90b72Sdan regOrig = 0; 1000bbd4ae5aSdrh } 1001bbd4ae5aSdrh } 1002bbd4ae5aSdrh 1003bbd4ae5aSdrh testcase( regOrig ); 1004bbd4ae5aSdrh testcase( eDest==SRT_Set ); 1005bbd4ae5aSdrh testcase( eDest==SRT_Mem ); 1006bbd4ae5aSdrh testcase( eDest==SRT_Coroutine ); 1007bbd4ae5aSdrh testcase( eDest==SRT_Output ); 1008257c13faSdan assert( eDest==SRT_Set || eDest==SRT_Mem 1009257c13faSdan || eDest==SRT_Coroutine || eDest==SRT_Output ); 1010257c13faSdan } 1011bbd4ae5aSdrh sRowLoadInfo.regResult = regResult; 1012bbd4ae5aSdrh sRowLoadInfo.ecelFlags = ecelFlags; 101324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 1014bbd4ae5aSdrh sRowLoadInfo.pExtra = pExtra; 1015bbd4ae5aSdrh sRowLoadInfo.regExtraResult = regResult + nResultCol; 1016bbd4ae5aSdrh if( pExtra ) nResultCol += pExtra->nExpr; 101724e25d32Sdan #endif 1018bbd4ae5aSdrh if( p->iLimit 1019bbd4ae5aSdrh && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 1020bbd4ae5aSdrh && nPrefixReg>0 1021bbd4ae5aSdrh ){ 1022bbd4ae5aSdrh assert( pSort!=0 ); 1023bbd4ae5aSdrh assert( hasDistinct==0 ); 1024bbd4ae5aSdrh pSort->pDeferredRowLoad = &sRowLoadInfo; 1025c6f36fa3Sdrh regOrig = 0; 1026bbd4ae5aSdrh }else{ 1027bbd4ae5aSdrh innerLoopLoadRow(pParse, p, &sRowLoadInfo); 1028bbd4ae5aSdrh } 1029a2a49dc9Sdrh } 10302282792aSdrh 1031daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 1032daffd0e5Sdrh ** and this row has been seen before, then do not make this row 1033daffd0e5Sdrh ** part of the result. 10342282792aSdrh */ 1035ea48eb2eSdrh if( hasDistinct ){ 1036e8e4af76Sdrh switch( pDistinct->eTnctType ){ 1037e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 1038e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 1039e8e4af76Sdrh int iJump; /* Jump destination */ 1040e8e4af76Sdrh int regPrev; /* Previous row content */ 1041e8e4af76Sdrh 1042e8e4af76Sdrh /* Allocate space for the previous row */ 1043e8e4af76Sdrh regPrev = pParse->nMem+1; 1044340309fdSdrh pParse->nMem += nResultCol; 1045e8e4af76Sdrh 1046e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 1047e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 1048e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 1049e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 1050e8e4af76Sdrh ** row is all NULLs. 1051e8e4af76Sdrh */ 1052e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 1053e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 1054e8e4af76Sdrh pOp->opcode = OP_Null; 1055e8e4af76Sdrh pOp->p1 = 1; 1056e8e4af76Sdrh pOp->p2 = regPrev; 1057166bc383Sdrh pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */ 1058e8e4af76Sdrh 1059340309fdSdrh iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 1060340309fdSdrh for(i=0; i<nResultCol; i++){ 10612def2f7eSdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr); 1062340309fdSdrh if( i<nResultCol-1 ){ 1063e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 1064688852abSdrh VdbeCoverage(v); 1065e8e4af76Sdrh }else{ 1066e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 1067688852abSdrh VdbeCoverage(v); 1068e8e4af76Sdrh } 1069e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 1070e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 1071e8e4af76Sdrh } 1072fcf2a775Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 1073340309fdSdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); 1074e8e4af76Sdrh break; 1075e8e4af76Sdrh } 1076e8e4af76Sdrh 1077e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 1078e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 1079e8e4af76Sdrh break; 1080e8e4af76Sdrh } 1081e8e4af76Sdrh 1082e8e4af76Sdrh default: { 1083e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 108438b4149cSdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, 108538b4149cSdrh regResult); 1086e8e4af76Sdrh break; 1087e8e4af76Sdrh } 1088e8e4af76Sdrh } 1089079a3072Sdrh if( pSort==0 ){ 1090aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 1091ea48eb2eSdrh } 10922282792aSdrh } 109382c3d636Sdrh 1094c926afbcSdrh switch( eDest ){ 109582c3d636Sdrh /* In this mode, write each query result to the key of the temporary 109682c3d636Sdrh ** table iParm. 10972282792aSdrh */ 109813449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1099c926afbcSdrh case SRT_Union: { 11009cbf3425Sdrh int r1; 11019cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 1102340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 11039b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 11049cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1105c926afbcSdrh break; 1106c926afbcSdrh } 110782c3d636Sdrh 110882c3d636Sdrh /* Construct a record from the query result, but instead of 110982c3d636Sdrh ** saving that record, use it as a key to delete elements from 111082c3d636Sdrh ** the temporary table iParm. 111182c3d636Sdrh */ 1112c926afbcSdrh case SRT_Except: { 1113340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 1114c926afbcSdrh break; 1115c926afbcSdrh } 1116781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 11175338a5f7Sdanielk1977 11185338a5f7Sdanielk1977 /* Store the result as data using a unique key. 11195338a5f7Sdanielk1977 */ 11208e1ee88cSdrh case SRT_Fifo: 11218e1ee88cSdrh case SRT_DistFifo: 11225338a5f7Sdanielk1977 case SRT_Table: 1123b9bb7c18Sdrh case SRT_EphemTab: { 1124fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 1125373cc2ddSdrh testcase( eDest==SRT_Table ); 1126373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 1127e2248cfdSdrh testcase( eDest==SRT_Fifo ); 1128e2248cfdSdrh testcase( eDest==SRT_DistFifo ); 1129fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 11308ce7184bSdan #ifndef SQLITE_OMIT_CTE 11318e1ee88cSdrh if( eDest==SRT_DistFifo ){ 11328e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 11338ce7184bSdan ** on an ephemeral index. If the current row is already present 11348ce7184bSdan ** in the index, do not write it to the output. If not, add the 11358ce7184bSdan ** current row to the index and proceed with writing it to the 11368ce7184bSdan ** output table as well. */ 11378ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 113838b4149cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); 113938b4149cSdrh VdbeCoverage(v); 11409b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); 1141079a3072Sdrh assert( pSort==0 ); 11428ce7184bSdan } 11438ce7184bSdan #endif 1144079a3072Sdrh if( pSort ){ 1145bbd4ae5aSdrh assert( regResult==regOrig ); 1146bbd4ae5aSdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg); 11475338a5f7Sdanielk1977 }else{ 1148b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 1149b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 1150b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 1151b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1152b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 11535338a5f7Sdanielk1977 } 1154fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 11555338a5f7Sdanielk1977 break; 11565338a5f7Sdanielk1977 } 11572282792aSdrh 115893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 11592282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 11602282792aSdrh ** then there should be a single item on the stack. Write this 11612282792aSdrh ** item into the set table with bogus data. 11622282792aSdrh */ 1163c926afbcSdrh case SRT_Set: { 1164079a3072Sdrh if( pSort ){ 1165de941c60Sdrh /* At first glance you would think we could optimize out the 1166de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 1167de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 1168de941c60Sdrh ** case the order does matter */ 116951d82d1dSdan pushOntoSorter( 11709af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1171c926afbcSdrh }else{ 1172b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 117371c57db0Sdan assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); 117471c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 1175553168c7Sdan r1, pDest->zAffSdst, nResultCol); 11769b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 1177b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 1178c926afbcSdrh } 1179c926afbcSdrh break; 1180c926afbcSdrh } 118182c3d636Sdrh 1182504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 1183ec7429aeSdrh */ 1184ec7429aeSdrh case SRT_Exists: { 11854c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 1186ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1187ec7429aeSdrh break; 1188ec7429aeSdrh } 1189ec7429aeSdrh 11902282792aSdrh /* If this is a scalar select that is part of an expression, then 1191870a0705Sdan ** store the results in the appropriate memory cell or array of 1192870a0705Sdan ** memory cells and break out of the scan loop. 11932282792aSdrh */ 1194c926afbcSdrh case SRT_Mem: { 1195079a3072Sdrh if( pSort ){ 1196257c13faSdan assert( nResultCol<=pDest->nSdst ); 1197870a0705Sdan pushOntoSorter( 11989af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1199c926afbcSdrh }else{ 1200257c13faSdan assert( nResultCol==pDest->nSdst ); 120153932ce8Sdrh assert( regResult==iParm ); 1202ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 1203c926afbcSdrh } 1204c926afbcSdrh break; 1205c926afbcSdrh } 120693758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 12072282792aSdrh 120881cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 120981cf13ecSdrh case SRT_Output: { /* Return the results */ 1210373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 1211373cc2ddSdrh testcase( eDest==SRT_Output ); 1212079a3072Sdrh if( pSort ){ 12139af90b72Sdan pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, 12145579d59fSdrh nPrefixReg); 1215e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 12162b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1217c182d163Sdrh }else{ 1218340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 1219ac82fcf5Sdrh } 1220142e30dfSdrh break; 1221142e30dfSdrh } 1222142e30dfSdrh 1223fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 1224fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 1225fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 1226fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 1227fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 1228fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 1229fe1c6bb9Sdrh */ 1230fe1c6bb9Sdrh case SRT_DistQueue: 1231fe1c6bb9Sdrh case SRT_Queue: { 1232fe1c6bb9Sdrh int nKey; 1233fe1c6bb9Sdrh int r1, r2, r3; 1234fe1c6bb9Sdrh int addrTest = 0; 1235fe1c6bb9Sdrh ExprList *pSO; 1236fe1c6bb9Sdrh pSO = pDest->pOrderBy; 1237fe1c6bb9Sdrh assert( pSO ); 1238fe1c6bb9Sdrh nKey = pSO->nExpr; 1239fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 1240fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 1241fe1c6bb9Sdrh r3 = r2+nKey+1; 1242fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 1243fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 1244fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 12457e4efaecSdrh ** added to the queue. */ 12467e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 12477e4efaecSdrh regResult, nResultCol); 1248688852abSdrh VdbeCoverage(v); 12497e4efaecSdrh } 12507e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 12517e4efaecSdrh if( eDest==SRT_DistQueue ){ 1252fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 1253cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1254fe1c6bb9Sdrh } 1255fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 1256fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 1257fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 1258fe1c6bb9Sdrh r2+i); 1259fe1c6bb9Sdrh } 1260fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 1261fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 12629b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); 1263fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 1264fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 1265fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 1266fe1c6bb9Sdrh break; 1267fe1c6bb9Sdrh } 1268fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 1269fe1c6bb9Sdrh 1270fe1c6bb9Sdrh 1271fe1c6bb9Sdrh 12726a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 1273d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 1274d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 1275d7489c39Sdrh ** user-defined functions that have side effects. We do not care 1276d7489c39Sdrh ** about the actual results of the select. 1277d7489c39Sdrh */ 1278c926afbcSdrh default: { 1279f46f905aSdrh assert( eDest==SRT_Discard ); 1280c926afbcSdrh break; 1281c926afbcSdrh } 128293758c8dSdanielk1977 #endif 1283c926afbcSdrh } 1284ec7429aeSdrh 12855e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 12865e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 12875e87be87Sdrh ** the output for us. 1288ec7429aeSdrh */ 1289079a3072Sdrh if( pSort==0 && p->iLimit ){ 129016897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 1291ec7429aeSdrh } 129282c3d636Sdrh } 129382c3d636Sdrh 129482c3d636Sdrh /* 1295ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 1296ad124329Sdrh ** X extra columns. 1297323df790Sdrh */ 1298ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 1299d4ab003dSdrh int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); 1300d8e4b132Sdrh KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); 1301323df790Sdrh if( p ){ 13026e11892dSdan p->aSortFlags = (u8*)&p->aColl[N+X]; 1303a485ad19Sdrh p->nKeyField = (u16)N; 1304a485ad19Sdrh p->nAllField = (u16)(N+X); 1305323df790Sdrh p->enc = ENC(db); 1306323df790Sdrh p->db = db; 13072ec2fb22Sdrh p->nRef = 1; 1308c263f7c4Sdrh memset(&p[1], 0, nExtra); 13092ec2fb22Sdrh }else{ 13104a642b60Sdrh sqlite3OomFault(db); 1311323df790Sdrh } 1312323df790Sdrh return p; 1313323df790Sdrh } 1314323df790Sdrh 1315323df790Sdrh /* 13162ec2fb22Sdrh ** Deallocate a KeyInfo object 13172ec2fb22Sdrh */ 13182ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 13192ec2fb22Sdrh if( p ){ 13202ec2fb22Sdrh assert( p->nRef>0 ); 13212ec2fb22Sdrh p->nRef--; 1322dbd6a7dcSdrh if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); 13232ec2fb22Sdrh } 13242ec2fb22Sdrh } 13252ec2fb22Sdrh 13262ec2fb22Sdrh /* 13272ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 13282ec2fb22Sdrh */ 13292ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 13302ec2fb22Sdrh if( p ){ 13312ec2fb22Sdrh assert( p->nRef>0 ); 13322ec2fb22Sdrh p->nRef++; 13332ec2fb22Sdrh } 13342ec2fb22Sdrh return p; 13352ec2fb22Sdrh } 13362ec2fb22Sdrh 13372ec2fb22Sdrh #ifdef SQLITE_DEBUG 13382ec2fb22Sdrh /* 13392ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 13402ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 13412ec2fb22Sdrh ** 13422ec2fb22Sdrh ** This routine is used only inside of assert() statements. 13432ec2fb22Sdrh */ 13442ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 13452ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 13462ec2fb22Sdrh 13472ec2fb22Sdrh /* 1348dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1349dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1350dece1a84Sdrh ** 13510342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 13520342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 13530342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 13540342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 13550342b1f5Sdrh ** index to implement a DISTINCT test. 13560342b1f5Sdrh ** 135760ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1358dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 13592ec2fb22Sdrh ** freed. 1360dece1a84Sdrh */ 1361f9eae18bSdan KeyInfo *sqlite3KeyInfoFromExprList( 1362079a3072Sdrh Parse *pParse, /* Parsing context */ 1363079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1364079a3072Sdrh int iStart, /* Begin with this column of pList */ 1365079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1366079a3072Sdrh ){ 1367dece1a84Sdrh int nExpr; 1368dece1a84Sdrh KeyInfo *pInfo; 1369dece1a84Sdrh struct ExprList_item *pItem; 1370323df790Sdrh sqlite3 *db = pParse->db; 1371dece1a84Sdrh int i; 1372dece1a84Sdrh 1373dece1a84Sdrh nExpr = pList->nExpr; 13743f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1375dece1a84Sdrh if( pInfo ){ 13762ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 13776284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 137870efa84dSdrh pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr); 13796e11892dSdan pInfo->aSortFlags[i-iStart] = pItem->sortFlags; 1380dece1a84Sdrh } 1381dece1a84Sdrh } 1382dece1a84Sdrh return pInfo; 1383dece1a84Sdrh } 1384dece1a84Sdrh 13857f61e92cSdan /* 13867f61e92cSdan ** Name of the connection operator, used for error messages. 13877f61e92cSdan */ 13887f61e92cSdan static const char *selectOpName(int id){ 13897f61e92cSdan char *z; 13907f61e92cSdan switch( id ){ 13917f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 13927f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 13937f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 13947f61e92cSdan default: z = "UNION"; break; 13957f61e92cSdan } 13967f61e92cSdan return z; 13977f61e92cSdan } 13987f61e92cSdan 13992ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 140017c0bc0cSdan /* 140117c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 140217c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 140317c0bc0cSdan ** where the caption is of the form: 140417c0bc0cSdan ** 140517c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 140617c0bc0cSdan ** 140717c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 140817c0bc0cSdan ** is determined by the zUsage argument. 140917c0bc0cSdan */ 14102ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 1411e2ca99c9Sdrh ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage)); 14122ce22453Sdan } 141317c0bc0cSdan 141417c0bc0cSdan /* 1415bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1416bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1417bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1418bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1419bb2b4418Sdan ** code with #ifndef directives. 1420bb2b4418Sdan */ 1421bb2b4418Sdan # define explainSetInteger(a, b) a = b 1422bb2b4418Sdan 1423bb2b4418Sdan #else 1424bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1425bb2b4418Sdan # define explainTempTable(y,z) 1426bb2b4418Sdan # define explainSetInteger(y,z) 1427bb2b4418Sdan #endif 1428bb2b4418Sdan 1429dece1a84Sdrh 1430dece1a84Sdrh /* 1431d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1432d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1433d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1434d8bc7086Sdrh ** routine generates the code needed to do that. 1435d8bc7086Sdrh */ 1436c926afbcSdrh static void generateSortTail( 1437cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1438c926afbcSdrh Select *p, /* The SELECT statement */ 1439079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1440c926afbcSdrh int nColumn, /* Number of columns of data */ 14416c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1442c926afbcSdrh ){ 1443ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1444a04a8be2Sdrh int addrBreak = pSort->labelDone; /* Jump here to exit loop */ 1445ec4ccdbcSdrh int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */ 144624e25d32Sdan int addr; /* Top of output loop. Jump for Next. */ 1447079a3072Sdrh int addrOnce = 0; 14480342b1f5Sdrh int iTab; 1449079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 14506c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 14512b596da8Sdrh int iParm = pDest->iSDParm; 14522d401ab8Sdrh int regRow; 14532d401ab8Sdrh int regRowid; 1454257c13faSdan int iCol; 145524e25d32Sdan int nKey; /* Number of key columns in sorter record */ 1456f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1457f45f2326Sdrh int i; 145878d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 145924e25d32Sdan int nRefKey = 0; 146070f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 14612d401ab8Sdrh 1462a04a8be2Sdrh assert( addrBreak<0 ); 1463079a3072Sdrh if( pSort->labelBkOut ){ 1464079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1465076e85f5Sdrh sqlite3VdbeGoto(v, addrBreak); 1466079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1467079a3072Sdrh } 146824e25d32Sdan 146924e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 147024e25d32Sdan /* Open any cursors needed for sorter-reference expressions */ 147124e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 147224e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 147324e25d32Sdan int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 147424e25d32Sdan sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); 147524e25d32Sdan nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); 147624e25d32Sdan } 147724e25d32Sdan #endif 147824e25d32Sdan 1479079a3072Sdrh iTab = pSort->iECursor; 148071c57db0Sdan if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ 14813e9ca094Sdrh regRowid = 0; 1482f45f2326Sdrh regRow = pDest->iSdst; 1483ed24da4bSdrh }else{ 148451d82d1dSdan regRowid = sqlite3GetTempReg(pParse); 1485375afb8bSdrh if( eDest==SRT_EphemTab || eDest==SRT_Table ){ 1486375afb8bSdrh regRow = sqlite3GetTempReg(pParse); 1487375afb8bSdrh nColumn = 0; 1488375afb8bSdrh }else{ 148951d82d1dSdan regRow = sqlite3GetTempRange(pParse, nColumn); 1490cdd536f0Sdrh } 1491375afb8bSdrh } 1492079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1493079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1494c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1495f45f2326Sdrh iSortTab = pParse->nTab++; 149683553eefSdrh if( pSort->labelBkOut ){ 1497511f9e8dSdrh addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 149883553eefSdrh } 149924e25d32Sdan sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, 150024e25d32Sdan nKey+1+nColumn+nRefKey); 1501079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1502c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1503688852abSdrh VdbeCoverage(v); 1504aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 15056cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 150678d58432Sdan bSeq = 0; 1507c6aff30cSdrh }else{ 1508688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1509aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1510f45f2326Sdrh iSortTab = iTab; 151178d58432Sdan bSeq = 1; 1512f45f2326Sdrh } 1513d6189eafSdan for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){ 151424e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 151524e25d32Sdan if( aOutEx[i].bSorterRef ) continue; 151624e25d32Sdan #endif 15179f895239Sdrh if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++; 15189f895239Sdrh } 151924e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 152024e25d32Sdan if( pSort->nDefer ){ 152124e25d32Sdan int iKey = iCol+1; 152224e25d32Sdan int regKey = sqlite3GetTempRange(pParse, nRefKey); 152324e25d32Sdan 152424e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 152524e25d32Sdan int iCsr = pSort->aDefer[i].iCsr; 152624e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 152724e25d32Sdan int nKey = pSort->aDefer[i].nKey; 152824e25d32Sdan 152924e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 153024e25d32Sdan if( HasRowid(pTab) ){ 153124e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); 153224e25d32Sdan sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, 153324e25d32Sdan sqlite3VdbeCurrentAddr(v)+1, regKey); 153424e25d32Sdan }else{ 153524e25d32Sdan int k; 153624e25d32Sdan int iJmp; 15377590d093Sdrh assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); 153824e25d32Sdan for(k=0; k<nKey; k++){ 153924e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k); 154024e25d32Sdan } 154124e25d32Sdan iJmp = sqlite3VdbeCurrentAddr(v); 154224e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey); 154324e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey); 154424e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 154524e25d32Sdan } 154624e25d32Sdan } 154724e25d32Sdan sqlite3ReleaseTempRange(pParse, regKey, nRefKey); 154824e25d32Sdan } 154924e25d32Sdan #endif 1550d6189eafSdan for(i=nColumn-1; i>=0; i--){ 155124e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 155224e25d32Sdan if( aOutEx[i].bSorterRef ){ 155324e25d32Sdan sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); 155424e25d32Sdan }else 155524e25d32Sdan #endif 155624e25d32Sdan { 1557257c13faSdan int iRead; 1558257c13faSdan if( aOutEx[i].u.x.iOrderByCol ){ 1559257c13faSdan iRead = aOutEx[i].u.x.iOrderByCol-1; 1560257c13faSdan }else{ 15619f895239Sdrh iRead = iCol--; 1562257c13faSdan } 1563257c13faSdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); 1564cbb9da33Sdrh VdbeComment((v, "%s", aOutEx[i].zEName)); 1565c6aff30cSdrh } 156624e25d32Sdan } 1567c926afbcSdrh switch( eDest ){ 1568ac56ab7eSdan case SRT_Table: 1569b9bb7c18Sdrh case SRT_EphemTab: { 1570375afb8bSdrh sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow); 15712d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 15722d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 15732d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1574c926afbcSdrh break; 1575c926afbcSdrh } 157693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1577c926afbcSdrh case SRT_Set: { 157871c57db0Sdan assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); 157971c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, 1580553168c7Sdan pDest->zAffSdst, nColumn); 15819b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); 1582c926afbcSdrh break; 1583c926afbcSdrh } 1584c926afbcSdrh case SRT_Mem: { 1585ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1586c926afbcSdrh break; 1587c926afbcSdrh } 158893758c8dSdanielk1977 #endif 1589373cc2ddSdrh default: { 1590373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 15911c767f0dSdrh testcase( eDest==SRT_Output ); 15921c767f0dSdrh testcase( eDest==SRT_Coroutine ); 15937d10d5a6Sdrh if( eDest==SRT_Output ){ 15942b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 1595a9671a22Sdrh }else{ 15962b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1597ce665cf6Sdrh } 1598ac82fcf5Sdrh break; 1599ac82fcf5Sdrh } 1600c926afbcSdrh } 1601f45f2326Sdrh if( regRowid ){ 160251d82d1dSdan if( eDest==SRT_Set ){ 160351d82d1dSdan sqlite3ReleaseTempRange(pParse, regRow, nColumn); 160451d82d1dSdan }else{ 16052d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 160651d82d1dSdan } 16072d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1608f45f2326Sdrh } 1609ec7429aeSdrh /* The bottom of the loop 1610ec7429aeSdrh */ 1611dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1612079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1613688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1614c6aff30cSdrh }else{ 1615688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1616c6aff30cSdrh } 1617079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1618dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1619d8bc7086Sdrh } 1620d8bc7086Sdrh 1621d8bc7086Sdrh /* 1622517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1623517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1624e78e8284Sdrh ** 16255f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 16265f3e5e74Sdrh ** result in *pEstWidth. 16275f3e5e74Sdrh ** 1628955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1629955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1630955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1631955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1632955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1633955de52cSdanielk1977 ** considered a column by this function. 1634e78e8284Sdrh ** 1635955de52cSdanielk1977 ** SELECT col FROM tbl; 1636955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1637955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1638955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1639955de52cSdanielk1977 ** 1640955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 16415f3e5e74Sdrh ** 16425f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 16435f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1644fcb78a49Sdrh */ 16455f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1646cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) 1647b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1648cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B) 1649b121dd14Sdrh #endif 16505f3e5e74Sdrh static const char *columnTypeImpl( 1651955de52cSdanielk1977 NameContext *pNC, 1652cafc2f7bSdrh #ifndef SQLITE_ENABLE_COLUMN_METADATA 1653cafc2f7bSdrh Expr *pExpr 1654cafc2f7bSdrh #else 1655955de52cSdanielk1977 Expr *pExpr, 16565f3e5e74Sdrh const char **pzOrigDb, 16575f3e5e74Sdrh const char **pzOrigTab, 1658cafc2f7bSdrh const char **pzOrigCol 1659b121dd14Sdrh #endif 1660955de52cSdanielk1977 ){ 1661955de52cSdanielk1977 char const *zType = 0; 1662517eb646Sdanielk1977 int j; 1663b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1664b121dd14Sdrh char const *zOrigDb = 0; 1665b121dd14Sdrh char const *zOrigTab = 0; 1666b121dd14Sdrh char const *zOrigCol = 0; 1667b121dd14Sdrh #endif 16685338a5f7Sdanielk1977 1669f7ce4291Sdrh assert( pExpr!=0 ); 1670f7ce4291Sdrh assert( pNC->pSrcList!=0 ); 167100e279d9Sdanielk1977 switch( pExpr->op ){ 167200e279d9Sdanielk1977 case TK_COLUMN: { 1673955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1674955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1675955de52cSdanielk1977 ** database table or a subquery. 1676955de52cSdanielk1977 */ 1677955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1678955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1679955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 168043bc88bbSdan while( pNC && !pTab ){ 1681b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1682b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1683b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 16846a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1685955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1686b3bce662Sdanielk1977 }else{ 1687b3bce662Sdanielk1977 pNC = pNC->pNext; 1688b3bce662Sdanielk1977 } 1689b3bce662Sdanielk1977 } 1690955de52cSdanielk1977 169143bc88bbSdan if( pTab==0 ){ 1692417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1693417168adSdrh ** cause this condition to run. Since then, we have restructured how 1694417168adSdrh ** trigger code is generated and so this condition is no longer 169543bc88bbSdan ** possible. However, it can still be true for statements like 169643bc88bbSdan ** the following: 169743bc88bbSdan ** 169843bc88bbSdan ** CREATE TABLE t1(col INTEGER); 169943bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 170043bc88bbSdan ** 170143bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 170243bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 170343bc88bbSdan ** though it should really be "INTEGER". 170443bc88bbSdan ** 170543bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 170643bc88bbSdan ** used. When columnType() is called on the expression 170743bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 170843bc88bbSdan ** branch below. */ 17097e62779aSdrh break; 17107e62779aSdrh } 1711955de52cSdanielk1977 1712eda079cdSdrh assert( pTab && pExpr->y.pTab==pTab ); 1713955de52cSdanielk1977 if( pS ){ 1714955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1715955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1716955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1717955de52cSdanielk1977 */ 1718f35f2f92Sdrh if( iCol>=0 && iCol<pS->pEList->nExpr ){ 1719955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1720955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1721955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1722955de52cSdanielk1977 */ 1723955de52cSdanielk1977 NameContext sNC; 1724955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1725955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 172643bc88bbSdan sNC.pNext = pNC; 1727955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1728cafc2f7bSdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 1729955de52cSdanielk1977 } 1730a78d757cSdrh }else{ 1731a78d757cSdrh /* A real table or a CTE table */ 1732955de52cSdanielk1977 assert( !pS ); 17335f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1734a78d757cSdrh if( iCol<0 ) iCol = pTab->iPKey; 1735a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 1736fcb78a49Sdrh if( iCol<0 ){ 1737fcb78a49Sdrh zType = "INTEGER"; 17385f3e5e74Sdrh zOrigCol = "rowid"; 1739fcb78a49Sdrh }else{ 17405f3e5e74Sdrh zOrigCol = pTab->aCol[iCol].zName; 1741d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 1742955de52cSdanielk1977 } 17435f3e5e74Sdrh zOrigTab = pTab->zName; 1744a78d757cSdrh if( pNC->pParse && pTab->pSchema ){ 1745955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1746e59be010Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; 1747955de52cSdanielk1977 } 17485f3e5e74Sdrh #else 1749a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 17505f3e5e74Sdrh if( iCol<0 ){ 17515f3e5e74Sdrh zType = "INTEGER"; 17525f3e5e74Sdrh }else{ 1753d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 17545f3e5e74Sdrh } 17555f3e5e74Sdrh #endif 1756fcb78a49Sdrh } 175700e279d9Sdanielk1977 break; 1758736c22b8Sdrh } 175993758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 176000e279d9Sdanielk1977 case TK_SELECT: { 1761955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1762955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1763955de52cSdanielk1977 ** statement. 1764955de52cSdanielk1977 */ 1765b3bce662Sdanielk1977 NameContext sNC; 17666ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1767955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 17686ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1769955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1770b3bce662Sdanielk1977 sNC.pNext = pNC; 1771955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1772cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 177300e279d9Sdanielk1977 break; 1774fcb78a49Sdrh } 177593758c8dSdanielk1977 #endif 177600e279d9Sdanielk1977 } 177700e279d9Sdanielk1977 17785f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 17795f3e5e74Sdrh if( pzOrigDb ){ 17805f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 17815f3e5e74Sdrh *pzOrigDb = zOrigDb; 17825f3e5e74Sdrh *pzOrigTab = zOrigTab; 17835f3e5e74Sdrh *pzOrigCol = zOrigCol; 1784955de52cSdanielk1977 } 17855f3e5e74Sdrh #endif 1786517eb646Sdanielk1977 return zType; 1787517eb646Sdanielk1977 } 1788517eb646Sdanielk1977 1789517eb646Sdanielk1977 /* 1790517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1791517eb646Sdanielk1977 ** in the result set. 1792517eb646Sdanielk1977 */ 1793517eb646Sdanielk1977 static void generateColumnTypes( 1794517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1795517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1796517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1797517eb646Sdanielk1977 ){ 17983f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1799517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1800517eb646Sdanielk1977 int i; 1801b3bce662Sdanielk1977 NameContext sNC; 1802b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1803955de52cSdanielk1977 sNC.pParse = pParse; 1804eac5fc04Sdrh sNC.pNext = 0; 1805517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1806517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 18073f913576Sdrh const char *zType; 18083f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1809955de52cSdanielk1977 const char *zOrigDb = 0; 1810955de52cSdanielk1977 const char *zOrigTab = 0; 1811955de52cSdanielk1977 const char *zOrigCol = 0; 1812cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1813955de52cSdanielk1977 181485b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 18154b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 18164b1ae99dSdanielk1977 ** virtual machine is deleted. 1817fbcd585fSdanielk1977 */ 181810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 181910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 182010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 18213f913576Sdrh #else 1822cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 18233f913576Sdrh #endif 182410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1825fcb78a49Sdrh } 18265f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1827fcb78a49Sdrh } 1828fcb78a49Sdrh 1829eac5fc04Sdrh 1830eac5fc04Sdrh /* 1831ec360a8dSdrh ** Compute the column names for a SELECT statement. 1832ec360a8dSdrh ** 1833ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1834ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1835ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1836ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1837ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1838ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1839ec360a8dSdrh ** 1840ec360a8dSdrh ** See Also: sqlite3ColumnsFromExprList() 1841ec360a8dSdrh ** 1842ec360a8dSdrh ** The PRAGMA short_column_names and PRAGMA full_column_names settings are 1843ec360a8dSdrh ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all 1844ec360a8dSdrh ** applications should operate this way. Nevertheless, we need to support the 1845ec360a8dSdrh ** other modes for legacy: 1846ec360a8dSdrh ** 1847ec360a8dSdrh ** short=OFF, full=OFF: Column name is the text of the expression has it 1848ec360a8dSdrh ** originally appears in the SELECT statement. In 1849ec360a8dSdrh ** other words, the zSpan of the result expression. 1850ec360a8dSdrh ** 1851ec360a8dSdrh ** short=ON, full=OFF: (This is the default setting). If the result 18523d240d21Sdrh ** refers directly to a table column, then the 18533d240d21Sdrh ** result column name is just the table column 18543d240d21Sdrh ** name: COLUMN. Otherwise use zSpan. 1855ec360a8dSdrh ** 1856ec360a8dSdrh ** full=ON, short=ANY: If the result refers directly to a table column, 1857ec360a8dSdrh ** then the result column name with the table name 1858ec360a8dSdrh ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. 185982c3d636Sdrh */ 1860832508b7Sdrh static void generateColumnNames( 1861832508b7Sdrh Parse *pParse, /* Parser context */ 1862f35f2f92Sdrh Select *pSelect /* Generate column names for this SELECT statement */ 1863832508b7Sdrh ){ 1864d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1865eac5fc04Sdrh int i; 1866eac5fc04Sdrh Table *pTab; 1867f35f2f92Sdrh SrcList *pTabList; 1868f35f2f92Sdrh ExprList *pEList; 18699bb575fdSdrh sqlite3 *db = pParse->db; 1870ec360a8dSdrh int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ 1871ec360a8dSdrh int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ 1872fcabd464Sdrh 1873fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 18743cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 18753cf86063Sdanielk1977 if( pParse->explain ){ 187661de0d1bSdanielk1977 return; 18773cf86063Sdanielk1977 } 18785338a5f7Sdanielk1977 #endif 18793cf86063Sdanielk1977 18805e8b9853Sdrh if( pParse->colNamesSet ) return; 1881f35f2f92Sdrh /* Column names are determined by the left-most term of a compound select */ 1882f35f2f92Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 188307859486Sdrh SELECTTRACE(1,pParse,pSelect,("generating column names\n")); 1884f35f2f92Sdrh pTabList = pSelect->pSrc; 1885f35f2f92Sdrh pEList = pSelect->pEList; 18869802947fSdrh assert( v!=0 ); 1887f7ce4291Sdrh assert( pTabList!=0 ); 1888d8bc7086Sdrh pParse->colNamesSet = 1; 1889ec360a8dSdrh fullName = (db->flags & SQLITE_FullColNames)!=0; 1890ec360a8dSdrh srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; 189122322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 189282c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 1893ec360a8dSdrh Expr *p = pEList->a[i].pExpr; 1894ec360a8dSdrh 1895ec360a8dSdrh assert( p!=0 ); 18964dd89d5aSdrh assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ 1897eda079cdSdrh assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */ 1898cbb9da33Sdrh if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){ 1899ec360a8dSdrh /* An AS clause always takes first priority */ 190041cee668Sdrh char *zName = pEList->a[i].zEName; 190110fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1902f35f2f92Sdrh }else if( srcName && p->op==TK_COLUMN ){ 190397665873Sdrh char *zCol; 19048aff1015Sdrh int iCol = p->iColumn; 1905eda079cdSdrh pTab = p->y.pTab; 1906f35f2f92Sdrh assert( pTab!=0 ); 19078aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 190897665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1909b1363206Sdrh if( iCol<0 ){ 191047a6db2bSdrh zCol = "rowid"; 1911b1363206Sdrh }else{ 1912b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1913b1363206Sdrh } 1914ec360a8dSdrh if( fullName ){ 191582c3d636Sdrh char *zName = 0; 19161c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 191710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 191882c3d636Sdrh }else{ 191910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 192082c3d636Sdrh } 19211bee3d7bSdrh }else{ 1922cbb9da33Sdrh const char *z = pEList->a[i].zEName; 1923859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 1924859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 192582c3d636Sdrh } 192682c3d636Sdrh } 192776d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 19285080aaa7Sdrh } 192982c3d636Sdrh 1930d8bc7086Sdrh /* 193160ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 19327d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 19337d10d5a6Sdrh ** column names for a table that would hold the expression list. 19347d10d5a6Sdrh ** 19357d10d5a6Sdrh ** All column names will be unique. 19367d10d5a6Sdrh ** 19377d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 19387d10d5a6Sdrh ** and other fields of Column are zeroed. 19397d10d5a6Sdrh ** 19407d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 19417d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1942ec360a8dSdrh ** 1943ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1944ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1945ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1946ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1947ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1948ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1949ec360a8dSdrh ** 1950ec360a8dSdrh ** See Also: generateColumnNames() 1951315555caSdrh */ 19528981b904Sdrh int sqlite3ColumnsFromExprList( 19537d10d5a6Sdrh Parse *pParse, /* Parsing context */ 19547d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1955d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 19567d10d5a6Sdrh Column **paCol /* Write the new column list here */ 19577d10d5a6Sdrh ){ 1958dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1959dc5ea5c7Sdrh int i, j; /* Loop counters */ 1960ebed3fa3Sdrh u32 cnt; /* Index added to make the name unique */ 1961dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1962dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1963dc5ea5c7Sdrh char *zName; /* Column name */ 1964dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 19650315e3ccSdrh Hash ht; /* Hash table of column names */ 196679d5f63fSdrh 19670315e3ccSdrh sqlite3HashInit(&ht); 19688c2e0f02Sdan if( pEList ){ 19698c2e0f02Sdan nCol = pEList->nExpr; 19708c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 19718c2e0f02Sdan testcase( aCol==0 ); 19726fe3733bSdrh if( nCol>32767 ) nCol = 32767; 19738c2e0f02Sdan }else{ 19748c2e0f02Sdan nCol = 0; 19758c2e0f02Sdan aCol = 0; 19768c2e0f02Sdan } 19778836cbbcSdan assert( nCol==(i16)nCol ); 19788c2e0f02Sdan *pnCol = nCol; 19798c2e0f02Sdan *paCol = aCol; 19808c2e0f02Sdan 19810315e3ccSdrh for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ 198279d5f63fSdrh /* Get an appropriate name for the column 198379d5f63fSdrh */ 1984cbb9da33Sdrh if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){ 198579d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 19867d10d5a6Sdrh }else{ 19870d950af3Sdrh Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr); 1988b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1989b07028f7Sdrh pColExpr = pColExpr->pRight; 1990b07028f7Sdrh assert( pColExpr!=0 ); 1991b07028f7Sdrh } 1992755b0fd3Sdrh if( pColExpr->op==TK_COLUMN ){ 199393a960a0Sdrh /* For columns use the column name name */ 1994dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1995eda079cdSdrh Table *pTab = pColExpr->y.pTab; 1996755b0fd3Sdrh assert( pTab!=0 ); 1997f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 199896ceaf86Sdrh zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; 1999b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 200033e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 200196ceaf86Sdrh zName = pColExpr->u.zToken; 200293a960a0Sdrh }else{ 200379d5f63fSdrh /* Use the original text of the column expression as its name */ 2004cbb9da33Sdrh zName = pEList->a[i].zEName; 20057d10d5a6Sdrh } 200622f70c32Sdrh } 20070cbec59cSdrh if( zName && !sqlite3IsTrueOrFalse(zName) ){ 2008d7ca600eSdrh zName = sqlite3DbStrDup(db, zName); 2009d7ca600eSdrh }else{ 2010155507b3Sdrh zName = sqlite3MPrintf(db,"column%d",i+1); 2011d7ca600eSdrh } 201279d5f63fSdrh 201379d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 201460ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 201579d5f63fSdrh */ 20160315e3ccSdrh cnt = 0; 20170315e3ccSdrh while( zName && sqlite3HashFind(&ht, zName)!=0 ){ 20180315e3ccSdrh nName = sqlite3Strlen30(zName); 2019f7ee8965Sdrh if( nName>0 ){ 20200315e3ccSdrh for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} 20210315e3ccSdrh if( zName[j]==':' ) nName = j; 2022f7ee8965Sdrh } 202396ceaf86Sdrh zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); 2024ebed3fa3Sdrh if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); 202579d5f63fSdrh } 202691bb0eedSdrh pCol->zName = zName; 2027ba68f8f3Sdan sqlite3ColumnPropertiesFromName(0, pCol); 202803d69a68Sdrh if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ 20294a642b60Sdrh sqlite3OomFault(db); 20307d10d5a6Sdrh } 20310315e3ccSdrh } 20320315e3ccSdrh sqlite3HashClear(&ht); 20337d10d5a6Sdrh if( db->mallocFailed ){ 20347d10d5a6Sdrh for(j=0; j<i; j++){ 20357d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 20367d10d5a6Sdrh } 20377d10d5a6Sdrh sqlite3DbFree(db, aCol); 20387d10d5a6Sdrh *paCol = 0; 20397d10d5a6Sdrh *pnCol = 0; 2040fad3039cSmistachkin return SQLITE_NOMEM_BKPT; 20417d10d5a6Sdrh } 20427d10d5a6Sdrh return SQLITE_OK; 20437d10d5a6Sdrh } 2044e014a838Sdanielk1977 20457d10d5a6Sdrh /* 20467d10d5a6Sdrh ** Add type and collation information to a column list based on 20477d10d5a6Sdrh ** a SELECT statement. 20487d10d5a6Sdrh ** 20497d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 20507d10d5a6Sdrh ** The column list has only names, not types or collations. This 20517d10d5a6Sdrh ** routine goes through and adds the types and collations. 20527d10d5a6Sdrh ** 2053b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 20547d10d5a6Sdrh ** statement be resolved. 205579d5f63fSdrh */ 2056ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation( 20577d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 2058186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 205981506b88Sdrh Select *pSelect, /* SELECT used to determine types and collations */ 206081506b88Sdrh char aff /* Default affinity for columns */ 20617d10d5a6Sdrh ){ 20627d10d5a6Sdrh sqlite3 *db = pParse->db; 20637d10d5a6Sdrh NameContext sNC; 20647d10d5a6Sdrh Column *pCol; 20657d10d5a6Sdrh CollSeq *pColl; 20667d10d5a6Sdrh int i; 20677d10d5a6Sdrh Expr *p; 20687d10d5a6Sdrh struct ExprList_item *a; 20697d10d5a6Sdrh 20707d10d5a6Sdrh assert( pSelect!=0 ); 20717d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 2072186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 20737d10d5a6Sdrh if( db->mallocFailed ) return; 2074c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 2075b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 20767d10d5a6Sdrh a = pSelect->pEList->a; 2077186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 2078ed06a131Sdrh const char *zType; 2079ed06a131Sdrh int n, m; 20807d10d5a6Sdrh p = a[i].pExpr; 2081cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 2082cafc2f7bSdrh /* pCol->szEst = ... // Column size est for SELECT tables never used */ 2083c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 20840c4db034Sdrh if( zType ){ 20850c4db034Sdrh m = sqlite3Strlen30(zType); 2086ed06a131Sdrh n = sqlite3Strlen30(pCol->zName); 2087ed06a131Sdrh pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); 2088ed06a131Sdrh if( pCol->zName ){ 2089ed06a131Sdrh memcpy(&pCol->zName[n+1], zType, m+1); 2090ed06a131Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 2091ed06a131Sdrh } 2092ed06a131Sdrh } 209396fb16eeSdrh if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff; 2094b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 20951cb50c88Sdrh if( pColl && pCol->zColl==0 ){ 209617435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 20970202b29eSdanielk1977 } 209822f70c32Sdrh } 2099cafc2f7bSdrh pTab->szTabRow = 1; /* Any non-zero value works */ 21007d10d5a6Sdrh } 21017d10d5a6Sdrh 21027d10d5a6Sdrh /* 21037d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 21047d10d5a6Sdrh ** the result set of that SELECT. 21057d10d5a6Sdrh */ 210681506b88Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){ 21077d10d5a6Sdrh Table *pTab; 21087d10d5a6Sdrh sqlite3 *db = pParse->db; 210970d5dfbaSdrh u64 savedFlags; 21107d10d5a6Sdrh 21117d10d5a6Sdrh savedFlags = db->flags; 2112d5b44d60Sdrh db->flags &= ~(u64)SQLITE_FullColNames; 21137d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 21147d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 2115491b6d89Sdrh db->flags = savedFlags; 21167d10d5a6Sdrh if( pParse->nErr ) return 0; 21177d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 21187d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 21197d10d5a6Sdrh if( pTab==0 ){ 21207d10d5a6Sdrh return 0; 21217d10d5a6Sdrh } 212279df7782Sdrh pTab->nTabRef = 1; 21237d10d5a6Sdrh pTab->zName = 0; 2124cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 21258981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 212681506b88Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff); 212722f70c32Sdrh pTab->iPKey = -1; 21287ce72f69Sdrh if( db->mallocFailed ){ 21291feeaed2Sdan sqlite3DeleteTable(db, pTab); 21307ce72f69Sdrh return 0; 21317ce72f69Sdrh } 213222f70c32Sdrh return pTab; 213322f70c32Sdrh } 213422f70c32Sdrh 213522f70c32Sdrh /* 2136d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 2137d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 2138d8bc7086Sdrh */ 213955965619Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){ 214055965619Sdrh if( pParse->pVdbe ){ 214155965619Sdrh return pParse->pVdbe; 214255965619Sdrh } 2143e0e261a4Sdrh if( pParse->pToplevel==0 2144e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 2145e0e261a4Sdrh ){ 2146e0e261a4Sdrh pParse->okConstFactor = 1; 2147949f9cd5Sdrh } 214855965619Sdrh return sqlite3VdbeCreate(pParse); 21496f077343Sdrh } 2150d8bc7086Sdrh 215115007a99Sdrh 2152d8bc7086Sdrh /* 21537b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 21548c0833fbSdrh ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions 21557b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 2156a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 2157a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 2158a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 2159a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 21607b58daeaSdrh ** 2161d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 21628c0833fbSdrh ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit 21638c0833fbSdrh ** and iOffset should have been preset to appropriate default values (zero) 2164aa9ce707Sdrh ** prior to calling this routine. 2165aa9ce707Sdrh ** 2166aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 2167aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 2168aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 2169aa9ce707Sdrh ** 21708c0833fbSdrh ** Only if pLimit->pLeft!=0 do the limit registers get 21717b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 21727b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 21737b58daeaSdrh ** SELECT statements. 21747b58daeaSdrh */ 2175ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 217602afc861Sdrh Vdbe *v = 0; 217702afc861Sdrh int iLimit = 0; 217815007a99Sdrh int iOffset; 21798b0cf38aSdrh int n; 21808c0833fbSdrh Expr *pLimit = p->pLimit; 21818c0833fbSdrh 21820acb7e48Sdrh if( p->iLimit ) return; 218315007a99Sdrh 21847b58daeaSdrh /* 21857b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 2186f7b5496eSdrh ** controversy about what the correct behavior should be. 21877b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 21887b58daeaSdrh ** no rows. 21897b58daeaSdrh */ 21908c0833fbSdrh if( pLimit ){ 21918c0833fbSdrh assert( pLimit->op==TK_LIMIT ); 21928c0833fbSdrh assert( pLimit->pLeft!=0 ); 21930a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 219415007a99Sdrh v = sqlite3GetVdbe(pParse); 2195aa9ce707Sdrh assert( v!=0 ); 21968c0833fbSdrh if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){ 21979b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 21989b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 2199456e4e4fSdrh if( n==0 ){ 2200076e85f5Sdrh sqlite3VdbeGoto(v, iBreak); 2201c3489bbfSdrh }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ 2202c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)n); 2203c3489bbfSdrh p->selFlags |= SF_FixedLimit; 22049b918ed1Sdrh } 22059b918ed1Sdrh }else{ 22068c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); 2207688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 2208d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 220916897072Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); 22109b918ed1Sdrh } 22118c0833fbSdrh if( pLimit->pRight ){ 22120a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 2213b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 22148c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pRight, iOffset); 2215688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 2216d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 2217cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); 2218d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 2219b7654111Sdrh } 2220d59ba6ceSdrh } 22217b58daeaSdrh } 22227b58daeaSdrh 2223b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 2224fbc4ee7bSdrh /* 2225fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 2226fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 2227fbc4ee7bSdrh ** the column has no default collating sequence. 2228fbc4ee7bSdrh ** 2229fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 2230fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 2231fbc4ee7bSdrh */ 2232dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 2233fbc4ee7bSdrh CollSeq *pRet; 2234dc1bdc4fSdanielk1977 if( p->pPrior ){ 2235dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 2236fbc4ee7bSdrh }else{ 2237fbc4ee7bSdrh pRet = 0; 2238dc1bdc4fSdanielk1977 } 223910c081adSdrh assert( iCol>=0 ); 22402ec18a3cSdrh /* iCol must be less than p->pEList->nExpr. Otherwise an error would 22412ec18a3cSdrh ** have been thrown during name resolution and we would not have gotten 22422ec18a3cSdrh ** this far */ 22432ec18a3cSdrh if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ 2244dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 2245dc1bdc4fSdanielk1977 } 2246dc1bdc4fSdanielk1977 return pRet; 2247d3d39e93Sdrh } 2248d3d39e93Sdrh 224953bed45eSdan /* 225053bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 225153bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 225253bed45eSdan ** structure suitable for implementing the ORDER BY. 225353bed45eSdan ** 225453bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 225553bed45eSdan ** function is responsible for ensuring that this structure is eventually 225653bed45eSdan ** freed. 225753bed45eSdan */ 225853bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 225953bed45eSdan ExprList *pOrderBy = p->pOrderBy; 226053bed45eSdan int nOrderBy = p->pOrderBy->nExpr; 226153bed45eSdan sqlite3 *db = pParse->db; 226253bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 226353bed45eSdan if( pRet ){ 226453bed45eSdan int i; 226553bed45eSdan for(i=0; i<nOrderBy; i++){ 226653bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 226753bed45eSdan Expr *pTerm = pItem->pExpr; 226853bed45eSdan CollSeq *pColl; 226953bed45eSdan 227053bed45eSdan if( pTerm->flags & EP_Collate ){ 227153bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 227253bed45eSdan }else{ 227353bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 227453bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 227553bed45eSdan pOrderBy->a[i].pExpr = 227653bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 227753bed45eSdan } 227853bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 227953bed45eSdan pRet->aColl[i] = pColl; 22806e11892dSdan pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags; 228153bed45eSdan } 228253bed45eSdan } 228353bed45eSdan 228453bed45eSdan return pRet; 228553bed45eSdan } 2286d3d39e93Sdrh 2287781def29Sdrh #ifndef SQLITE_OMIT_CTE 2288781def29Sdrh /* 2289781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 2290781def29Sdrh ** query of the form: 2291781def29Sdrh ** 2292781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 2293781def29Sdrh ** \___________/ \_______________/ 2294781def29Sdrh ** p->pPrior p 2295781def29Sdrh ** 2296781def29Sdrh ** 2297781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 22988a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. 2299781def29Sdrh ** 2300781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 2301781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 2302fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 2303fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 2304fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 2305781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 2306781def29Sdrh ** and the iteration continues until the Queue table is empty. 2307781def29Sdrh ** 2308781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 2309781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 2310781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 2311781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 2312781def29Sdrh ** 2313781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 2314781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 2315781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 2316781def29Sdrh ** 2317781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 2318781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 2319781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 2320781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 2321781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 2322781def29Sdrh ** rows have been skipped. 2323781def29Sdrh */ 2324781def29Sdrh static void generateWithRecursiveQuery( 2325781def29Sdrh Parse *pParse, /* Parsing context */ 2326781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 2327781def29Sdrh SelectDest *pDest /* What to do with query results */ 2328781def29Sdrh ){ 2329781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 2330781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 2331781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 2332781def29Sdrh Select *pSetup = p->pPrior; /* The setup query */ 2333781def29Sdrh int addrTop; /* Top of the loop */ 2334781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 2335edf83d1eSdrh int iCurrent = 0; /* The Current table */ 2336781def29Sdrh int regCurrent; /* Register holding Current table */ 2337781def29Sdrh int iQueue; /* The Queue table */ 2338781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 23398e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 2340781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 2341781def29Sdrh int i; /* Loop counter */ 2342781def29Sdrh int rc; /* Result code */ 2343fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 23448c0833fbSdrh Expr *pLimit; /* Saved LIMIT and OFFSET */ 2345aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 2346781def29Sdrh 23476afa35c9Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 23486afa35c9Sdan if( p->pWin ){ 23496afa35c9Sdan sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries"); 23506afa35c9Sdan return; 23516afa35c9Sdan } 23526afa35c9Sdan #endif 23536afa35c9Sdan 2354781def29Sdrh /* Obtain authorization to do a recursive query */ 2355781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 2356781def29Sdrh 2357aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 2358ec4ccdbcSdrh addrBreak = sqlite3VdbeMakeLabel(pParse); 235969b9383eSdan p->nSelectRow = 320; /* 4 billion rows */ 2360aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 2361aa9ce707Sdrh pLimit = p->pLimit; 2362aa9ce707Sdrh regLimit = p->iLimit; 2363aa9ce707Sdrh regOffset = p->iOffset; 23648c0833fbSdrh p->pLimit = 0; 2365aa9ce707Sdrh p->iLimit = p->iOffset = 0; 236653bed45eSdan pOrderBy = p->pOrderBy; 2367781def29Sdrh 2368781def29Sdrh /* Locate the cursor number of the Current table */ 2369781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 23708a48b9c0Sdrh if( pSrc->a[i].fg.isRecursive ){ 2371781def29Sdrh iCurrent = pSrc->a[i].iCursor; 2372781def29Sdrh break; 2373781def29Sdrh } 2374781def29Sdrh } 2375781def29Sdrh 2376fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2377781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 23788e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2379781def29Sdrh iQueue = pParse->nTab++; 2380781def29Sdrh if( p->op==TK_UNION ){ 23818e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 2382781def29Sdrh iDistinct = pParse->nTab++; 2383fe1c6bb9Sdrh }else{ 23848e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2385781def29Sdrh } 2386781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2387781def29Sdrh 2388781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2389781def29Sdrh regCurrent = ++pParse->nMem; 2390781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2391fe1c6bb9Sdrh if( pOrderBy ){ 239253bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2393fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2394fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2395fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2396fe1c6bb9Sdrh }else{ 2397781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2398fe1c6bb9Sdrh } 2399fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2400781def29Sdrh if( iDistinct ){ 2401781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2402781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2403781def29Sdrh } 2404781def29Sdrh 240553bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 240653bed45eSdan p->pOrderBy = 0; 240753bed45eSdan 2408781def29Sdrh /* Store the results of the setup-query in Queue. */ 2409d227a291Sdrh pSetup->pNext = 0; 241084a01debSdrh ExplainQueryPlan((pParse, 1, "SETUP")); 2411781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2412d227a291Sdrh pSetup->pNext = p; 2413fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2414781def29Sdrh 2415781def29Sdrh /* Find the next row in the Queue and output that row */ 2416688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2417781def29Sdrh 2418781def29Sdrh /* Transfer the next row in Queue over to Current */ 2419781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2420fe1c6bb9Sdrh if( pOrderBy ){ 2421fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2422fe1c6bb9Sdrh }else{ 2423781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2424fe1c6bb9Sdrh } 2425781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2426781def29Sdrh 2427fe1c6bb9Sdrh /* Output the single row in Current */ 2428ec4ccdbcSdrh addrCont = sqlite3VdbeMakeLabel(pParse); 2429aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 24302def2f7eSdrh selectInnerLoop(pParse, p, iCurrent, 2431079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2432688852abSdrh if( regLimit ){ 243316897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); 2434688852abSdrh VdbeCoverage(v); 2435688852abSdrh } 2436fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2437fe1c6bb9Sdrh 2438781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2439781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2440781def29Sdrh */ 2441b63ce02fSdrh if( p->selFlags & SF_Aggregate ){ 2442b63ce02fSdrh sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); 2443b63ce02fSdrh }else{ 2444781def29Sdrh p->pPrior = 0; 244584a01debSdrh ExplainQueryPlan((pParse, 1, "RECURSIVE STEP")); 2446781def29Sdrh sqlite3Select(pParse, p, &destQueue); 2447781def29Sdrh assert( p->pPrior==0 ); 2448781def29Sdrh p->pPrior = pSetup; 2449b63ce02fSdrh } 2450781def29Sdrh 2451781def29Sdrh /* Keep running the loop until the Queue is empty */ 2452076e85f5Sdrh sqlite3VdbeGoto(v, addrTop); 2453781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2454fe1c6bb9Sdrh 2455fe1c6bb9Sdrh end_of_recursive_query: 24569afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2457fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2458aa9ce707Sdrh p->pLimit = pLimit; 2459fe1c6bb9Sdrh return; 2460781def29Sdrh } 2461b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2462781def29Sdrh 2463781def29Sdrh /* Forward references */ 2464b21e7c70Sdrh static int multiSelectOrderBy( 2465b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2466b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2467a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2468b21e7c70Sdrh ); 2469b21e7c70Sdrh 247045f54a57Sdrh /* 247145f54a57Sdrh ** Handle the special case of a compound-select that originates from a 247245f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 247345f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 247445f54a57Sdrh ** on a VALUES clause. 247545f54a57Sdrh ** 247645f54a57Sdrh ** Because the Select object originates from a VALUES clause: 2477b058d054Sdrh ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 247845f54a57Sdrh ** (2) All terms are UNION ALL 247945f54a57Sdrh ** (3) There is no ORDER BY clause 2480b058d054Sdrh ** 2481b058d054Sdrh ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES 2482b058d054Sdrh ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). 2483b058d054Sdrh ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. 2484b058d054Sdrh ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES. 248545f54a57Sdrh */ 248645f54a57Sdrh static int multiSelectValues( 248745f54a57Sdrh Parse *pParse, /* Parsing context */ 248845f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 248945f54a57Sdrh SelectDest *pDest /* What to do with query results */ 249045f54a57Sdrh ){ 249145f54a57Sdrh int nRow = 1; 249245f54a57Sdrh int rc = 0; 2493fa16f5d9Sdrh int bShowAll = p->pLimit==0; 2494772460fdSdrh assert( p->selFlags & SF_MultiValue ); 249545f54a57Sdrh do{ 249645f54a57Sdrh assert( p->selFlags & SF_Values ); 249745f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 2498923cadb1Sdan assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); 2499ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 250029cdbadfSdrh if( p->pWin ) return -1; 2501ef9f719dSdrh #endif 250245f54a57Sdrh if( p->pPrior==0 ) break; 250345f54a57Sdrh assert( p->pPrior->pNext==p ); 250445f54a57Sdrh p = p->pPrior; 2505fa16f5d9Sdrh nRow += bShowAll; 250645f54a57Sdrh }while(1); 2507fa16f5d9Sdrh ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow, 2508fa16f5d9Sdrh nRow==1 ? "" : "S")); 250945f54a57Sdrh while( p ){ 2510fa16f5d9Sdrh selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1); 2511fa16f5d9Sdrh if( !bShowAll ) break; 251245f54a57Sdrh p->nSelectRow = nRow; 251345f54a57Sdrh p = p->pNext; 251445f54a57Sdrh } 251545f54a57Sdrh return rc; 251645f54a57Sdrh } 2517b21e7c70Sdrh 2518d3d39e93Sdrh /* 251916ee60ffSdrh ** This routine is called to process a compound query form from 252016ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 252116ee60ffSdrh ** INTERSECT 2522c926afbcSdrh ** 2523e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2524e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2525e78e8284Sdrh ** in which case this routine will be called recursively. 2526e78e8284Sdrh ** 2527e78e8284Sdrh ** The results of the total query are to be written into a destination 2528e78e8284Sdrh ** of type eDest with parameter iParm. 2529e78e8284Sdrh ** 2530e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2531e78e8284Sdrh ** 2532e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2533e78e8284Sdrh ** 2534e78e8284Sdrh ** This statement is parsed up as follows: 2535e78e8284Sdrh ** 2536e78e8284Sdrh ** SELECT c FROM t3 2537e78e8284Sdrh ** | 2538e78e8284Sdrh ** `-----> SELECT b FROM t2 2539e78e8284Sdrh ** | 25404b11c6d3Sjplyon ** `------> SELECT a FROM t1 2541e78e8284Sdrh ** 2542e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2543e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2544e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2545e78e8284Sdrh ** 2546e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2547e78e8284Sdrh ** individual selects always group from left to right. 254882c3d636Sdrh */ 254984ac9d02Sdanielk1977 static int multiSelect( 2550fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2551fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2552a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 255384ac9d02Sdanielk1977 ){ 255484ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 255510e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 255610e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 25571013c932Sdrh SelectDest dest; /* Alternative data destination */ 2558eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2559633e6d57Sdrh sqlite3 *db; /* Database connection */ 256082c3d636Sdrh 25617b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2562fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 256382c3d636Sdrh */ 2564701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2565eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2566b0968b6bSdrh assert( p->selFlags & SF_Compound ); 2567633e6d57Sdrh db = pParse->db; 2568d8bc7086Sdrh pPrior = p->pPrior; 2569bc10377aSdrh dest = *pDest; 257063347e7dSdrh if( pPrior->pOrderBy || pPrior->pLimit ){ 257163347e7dSdrh sqlite3ErrorMsg(pParse,"%s clause should come after %s not before", 257263347e7dSdrh pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op)); 257384ac9d02Sdanielk1977 rc = 1; 257484ac9d02Sdanielk1977 goto multi_select_end; 25757b58daeaSdrh } 257682c3d636Sdrh 25774adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2578701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2579d8bc7086Sdrh 25801cc3d75fSdrh /* Create the destination temporary table if necessary 25811cc3d75fSdrh */ 25826c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2583b4964b72Sdanielk1977 assert( p->pEList ); 25842b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 25856c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 25861cc3d75fSdrh } 25871cc3d75fSdrh 258845f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 258945f54a57Sdrh */ 2590772460fdSdrh if( p->selFlags & SF_MultiValue ){ 259145f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 259229cdbadfSdrh if( rc>=0 ) goto multi_select_end; 259329cdbadfSdrh rc = SQLITE_OK; 259445f54a57Sdrh } 259545f54a57Sdrh 2596f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2597f6e369a1Sdrh ** in their result sets. 2598f6e369a1Sdrh */ 2599f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2600923cadb1Sdan assert( p->pEList->nExpr==pPrior->pEList->nExpr ); 2601f6e369a1Sdrh 2602eede6a53Sdan #ifndef SQLITE_OMIT_CTE 2603eae73fbfSdan if( p->selFlags & SF_Recursive ){ 2604781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 26058ce7184bSdan }else 26068ce7184bSdan #endif 2607f6e369a1Sdrh 2608a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2609a9671a22Sdrh */ 2610f6e369a1Sdrh if( p->pOrderBy ){ 2611a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 261203c3905fSdrh }else{ 2613f6e369a1Sdrh 2614c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN 261503c3905fSdrh if( pPrior->pPrior==0 ){ 26164d79983cSdrh ExplainQueryPlan((pParse, 1, "COMPOUND QUERY")); 2617c631ded5Sdrh ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); 2618c631ded5Sdrh } 2619c631ded5Sdrh #endif 2620c631ded5Sdrh 2621f46f905aSdrh /* Generate code for the left and right SELECT statements. 2622d8bc7086Sdrh */ 262382c3d636Sdrh switch( p->op ){ 2624f46f905aSdrh case TK_ALL: { 2625ec7429aeSdrh int addr = 0; 262695aa47b1Sdrh int nLimit; 2627a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2628547180baSdrh pPrior->iLimit = p->iLimit; 2629547180baSdrh pPrior->iOffset = p->iOffset; 2630a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 26317d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2632ad68cb6bSdanielk1977 p->pLimit = 0; 263384ac9d02Sdanielk1977 if( rc ){ 263484ac9d02Sdanielk1977 goto multi_select_end; 263584ac9d02Sdanielk1977 } 2636f46f905aSdrh p->pPrior = 0; 26377b58daeaSdrh p->iLimit = pPrior->iLimit; 26387b58daeaSdrh p->iOffset = pPrior->iOffset; 263992b01d53Sdrh if( p->iLimit ){ 264016897072Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); 2641d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 26429f1ef45fSdrh if( p->iOffset ){ 2643cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, 2644cc2fa4cfSdrh p->iLimit, p->iOffset+1, p->iOffset); 26459f1ef45fSdrh } 2646ec7429aeSdrh } 2647c631ded5Sdrh ExplainQueryPlan((pParse, 1, "UNION ALL")); 26487d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2649373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2650eca7e01aSdanielk1977 pDelete = p->pPrior; 2651f46f905aSdrh p->pPrior = pPrior; 2652c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 265395aa47b1Sdrh if( pPrior->pLimit 26548c0833fbSdrh && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) 2655c3489bbfSdrh && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 265695aa47b1Sdrh ){ 2657c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)nLimit); 265895aa47b1Sdrh } 2659ec7429aeSdrh if( addr ){ 2660ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2661ec7429aeSdrh } 2662f46f905aSdrh break; 2663f46f905aSdrh } 266482c3d636Sdrh case TK_EXCEPT: 266582c3d636Sdrh case TK_UNION: { 266603c3905fSdrh int unionTab; /* Cursor number of the temp table holding result */ 2667ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2668d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 26698c0833fbSdrh Expr *pLimit; /* Saved values of p->nLimit */ 2670dc1bdc4fSdanielk1977 int addr; 26716c8c8ce0Sdanielk1977 SelectDest uniondest; 267282c3d636Sdrh 2673373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2674373cc2ddSdrh testcase( p->op==TK_UNION ); 267593a960a0Sdrh priorOp = SRT_Union; 2676d227a291Sdrh if( dest.eDest==priorOp ){ 2677d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2678c926afbcSdrh ** right. 2679d8bc7086Sdrh */ 2680e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 26812b596da8Sdrh unionTab = dest.iSDParm; 268282c3d636Sdrh }else{ 2683d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2684d8bc7086Sdrh ** intermediate results. 2685d8bc7086Sdrh */ 268682c3d636Sdrh unionTab = pParse->nTab++; 268793a960a0Sdrh assert( p->pOrderBy==0 ); 268866a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2689b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2690b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2691d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 269284ac9d02Sdanielk1977 assert( p->pEList ); 2693d8bc7086Sdrh } 2694d8bc7086Sdrh 2695d8bc7086Sdrh /* Code the SELECT statements to our left 2696d8bc7086Sdrh */ 2697b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 26981013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 26997d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 270084ac9d02Sdanielk1977 if( rc ){ 270184ac9d02Sdanielk1977 goto multi_select_end; 270284ac9d02Sdanielk1977 } 2703d8bc7086Sdrh 2704d8bc7086Sdrh /* Code the current SELECT statement 2705d8bc7086Sdrh */ 27064cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 27074cfb22f7Sdrh op = SRT_Except; 27084cfb22f7Sdrh }else{ 27094cfb22f7Sdrh assert( p->op==TK_UNION ); 27104cfb22f7Sdrh op = SRT_Union; 2711d8bc7086Sdrh } 271282c3d636Sdrh p->pPrior = 0; 2713a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2714a2dc3b1aSdanielk1977 p->pLimit = 0; 27156c8c8ce0Sdanielk1977 uniondest.eDest = op; 2716c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2717c631ded5Sdrh selectOpName(p->op))); 27187d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2719373cc2ddSdrh testcase( rc!=SQLITE_OK ); 27205bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 27215bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2722633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 2723eca7e01aSdanielk1977 pDelete = p->pPrior; 272482c3d636Sdrh p->pPrior = pPrior; 2725a9671a22Sdrh p->pOrderBy = 0; 2726c3489bbfSdrh if( p->op==TK_UNION ){ 2727c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 2728c3489bbfSdrh } 2729633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2730a2dc3b1aSdanielk1977 p->pLimit = pLimit; 273192b01d53Sdrh p->iLimit = 0; 273292b01d53Sdrh p->iOffset = 0; 2733d8bc7086Sdrh 2734d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2735d8bc7086Sdrh ** it is that we currently need. 2736d8bc7086Sdrh */ 27372b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2738a9ebfe20Sdrh assert( p->pEList || db->mallocFailed ); 2739a9ebfe20Sdrh if( dest.eDest!=priorOp && db->mallocFailed==0 ){ 27406b56344dSdrh int iCont, iBreak, iStart; 2741ec4ccdbcSdrh iBreak = sqlite3VdbeMakeLabel(pParse); 2742ec4ccdbcSdrh iCont = sqlite3VdbeMakeLabel(pParse); 2743ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2744688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 27454adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 27462def2f7eSdrh selectInnerLoop(pParse, p, unionTab, 2747e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 27484adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2749688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 27504adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 275166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 275282c3d636Sdrh } 275382c3d636Sdrh break; 275482c3d636Sdrh } 2755373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 275682c3d636Sdrh int tab1, tab2; 27576b56344dSdrh int iCont, iBreak, iStart; 27588c0833fbSdrh Expr *pLimit; 2759dc1bdc4fSdanielk1977 int addr; 27601013c932Sdrh SelectDest intersectdest; 27619cbf3425Sdrh int r1; 276282c3d636Sdrh 2763d8bc7086Sdrh /* INTERSECT is different from the others since it requires 27646206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2765d8bc7086Sdrh ** by allocating the tables we will need. 2766d8bc7086Sdrh */ 276782c3d636Sdrh tab1 = pParse->nTab++; 276882c3d636Sdrh tab2 = pParse->nTab++; 276993a960a0Sdrh assert( p->pOrderBy==0 ); 2770dc1bdc4fSdanielk1977 277166a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2772b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2773b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2774d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 277584ac9d02Sdanielk1977 assert( p->pEList ); 2776d8bc7086Sdrh 2777d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2778d8bc7086Sdrh */ 27791013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 27807d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 278184ac9d02Sdanielk1977 if( rc ){ 278284ac9d02Sdanielk1977 goto multi_select_end; 278384ac9d02Sdanielk1977 } 2784d8bc7086Sdrh 2785d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2786d8bc7086Sdrh */ 278766a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2788b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2789b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 279082c3d636Sdrh p->pPrior = 0; 2791a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2792a2dc3b1aSdanielk1977 p->pLimit = 0; 27932b596da8Sdrh intersectdest.iSDParm = tab2; 2794c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2795c631ded5Sdrh selectOpName(p->op))); 27967d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 2797373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2798eca7e01aSdanielk1977 pDelete = p->pPrior; 279982c3d636Sdrh p->pPrior = pPrior; 280003c3905fSdrh if( p->nSelectRow>pPrior->nSelectRow ){ 280103c3905fSdrh p->nSelectRow = pPrior->nSelectRow; 280203c3905fSdrh } 2803633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2804a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2805d8bc7086Sdrh 2806d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2807d8bc7086Sdrh ** tables. 2808d8bc7086Sdrh */ 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 /* 3585630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3586630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 35871350b030Sdrh ** 35881350b030Sdrh ** To understand the concept of flattening, consider the following 35891350b030Sdrh ** query: 35901350b030Sdrh ** 35911350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 35921350b030Sdrh ** 35931350b030Sdrh ** The default way of implementing this query is to execute the 35941350b030Sdrh ** subquery first and store the results in a temporary table, then 35951350b030Sdrh ** run the outer query on that temporary table. This requires two 35961350b030Sdrh ** passes over the data. Furthermore, because the temporary table 35971350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3598832508b7Sdrh ** optimized. 35991350b030Sdrh ** 3600832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 36011350b030Sdrh ** a single flat select, like this: 36021350b030Sdrh ** 36031350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 36041350b030Sdrh ** 360560ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 3606832508b7Sdrh ** but only has to scan the data once. And because indices might 3607832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 3608832508b7Sdrh ** avoided. 36091350b030Sdrh ** 3610d981e828Sdrh ** Flattening is subject to the following constraints: 36111350b030Sdrh ** 361225c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 361325c221ebSdrh ** The subquery and the outer query cannot both be aggregates. 36141350b030Sdrh ** 361525c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3616d981e828Sdrh ** (2) If the subquery is an aggregate then 3617d981e828Sdrh ** (2a) the outer query must not be a join and 3618d981e828Sdrh ** (2b) the outer query must not use subqueries 3619d981e828Sdrh ** other than the one FROM-clause subquery that is a candidate 3620d981e828Sdrh ** for flattening. (This is due to ticket [2f7170d73bf9abf80] 3621d981e828Sdrh ** from 2015-02-09.) 3622832508b7Sdrh ** 3623d981e828Sdrh ** (3) If the subquery is the right operand of a LEFT JOIN then 3624d981e828Sdrh ** (3a) the subquery may not be a join and 3625d981e828Sdrh ** (3b) the FROM clause of the subquery may not contain a virtual 3626d981e828Sdrh ** table and 3627d981e828Sdrh ** (3c) the outer query may not be an aggregate. 3628396afe6fSdrh ** (3d) the outer query may not be DISTINCT. 3629832508b7Sdrh ** 3630d981e828Sdrh ** (4) The subquery can not be DISTINCT. 3631832508b7Sdrh ** 363249ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 363349ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 363449ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 3635832508b7Sdrh ** 363625c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 363725c221ebSdrh ** If the subquery is aggregate, the outer query may not be DISTINCT. 3638832508b7Sdrh ** 3639d981e828Sdrh ** (7) The subquery must have a FROM clause. TODO: For subqueries without 364031d6fd55Sdrh ** A FROM clause, consider adding a FROM clause with the special 3641630d296cSdrh ** table sqlite_once that consists of a single row containing a 3642630d296cSdrh ** single NULL. 364308192d5fSdrh ** 3644d981e828Sdrh ** (8) If the subquery uses LIMIT then the outer query may not be a join. 3645df199a25Sdrh ** 3646d981e828Sdrh ** (9) If the subquery uses LIMIT then the outer query may not be aggregate. 3647df199a25Sdrh ** 36486092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 36496092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 3650d981e828Sdrh ** constraint: "If the subquery is aggregate then the outer query 3651d981e828Sdrh ** may not use LIMIT." 3652df199a25Sdrh ** 3653d981e828Sdrh ** (11) The subquery and the outer query may not both have ORDER BY clauses. 3654174b6195Sdrh ** 36557b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 36562b300d5dSdrh ** a separate restriction deriving from ticket #350. 36573fc673e6Sdrh ** 3658d981e828Sdrh ** (13) The subquery and outer query may not both use LIMIT. 3659ac83963aSdrh ** 3660d981e828Sdrh ** (14) The subquery may not use OFFSET. 3661ac83963aSdrh ** 3662d981e828Sdrh ** (15) If the outer query is part of a compound select, then the 3663d981e828Sdrh ** subquery may not use LIMIT. 3664f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 3665ad91c6cdSdrh ** 3666d981e828Sdrh ** (16) If the outer query is aggregate, then the subquery may not 3667d981e828Sdrh ** use ORDER BY. (Ticket #2942) This used to not matter 3668c52e355dSdrh ** until we introduced the group_concat() function. 3669c52e355dSdrh ** 3670d981e828Sdrh ** (17) If the subquery is a compound select, then 3671d981e828Sdrh ** (17a) all compound operators must be a UNION ALL, and 3672d981e828Sdrh ** (17b) no terms within the subquery compound may be aggregate 3673e76acc65Sdrh ** or DISTINCT, and 3674d981e828Sdrh ** (17c) every term within the subquery compound must have a FROM clause 3675d981e828Sdrh ** (17d) the outer query may not be 3676d981e828Sdrh ** (17d1) aggregate, or 3677d981e828Sdrh ** (17d2) DISTINCT, or 3678d981e828Sdrh ** (17d3) a join. 3679997d7434Sdan ** (17e) the subquery may not contain window functions 3680f23329a2Sdanielk1977 ** 36814914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 36824914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 3683630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 3684630d296cSdrh ** operator other than UNION ALL because all the other compound 3685630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 3686630d296cSdrh ** restriction (4). 3687f23329a2Sdanielk1977 ** 368867c70142Sdan ** Also, each component of the sub-query must return the same number 368967c70142Sdan ** of result columns. This is actually a requirement for any compound 369067c70142Sdan ** SELECT statement, but all the code here does is make sure that no 369167c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 369267c70142Sdan ** syntax error and return a detailed message. 369367c70142Sdan ** 369449fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 3695d981e828Sdrh ** ORDER BY clause of the parent must be simple references to 369649fc1f60Sdanielk1977 ** columns of the sub-query. 369749fc1f60Sdanielk1977 ** 3698d981e828Sdrh ** (19) If the subquery uses LIMIT then the outer query may not 3699229cf702Sdrh ** have a WHERE clause. 3700229cf702Sdrh ** 3701fca23557Sdrh ** (20) If the sub-query is a compound select, then it must not use 3702fca23557Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 3703fca23557Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 3704fca23557Sdrh ** appear as unmodified result columns in the outer query. But we 3705fca23557Sdrh ** have other optimizations in mind to deal with that case. 3706e8902a70Sdrh ** 3707d981e828Sdrh ** (21) If the subquery uses LIMIT then the outer query may not be 3708a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 3709a91491e5Sshaneh ** 3710d981e828Sdrh ** (22) The subquery may not be a recursive CTE. 37118290c2adSdan ** 3712cdb2f607Sdrh ** (**) Subsumed into restriction (17d3). Was: If the outer query is 3713cdb2f607Sdrh ** a recursive CTE, then the sub-query may not be a compound query. 3714cdb2f607Sdrh ** This restriction is because transforming the 37158290c2adSdan ** parent to a compound query confuses the code that handles 37168290c2adSdan ** recursive queries in multiSelect(). 37178290c2adSdan ** 3718508e2d00Sdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3719508e2d00Sdrh ** The subquery may not be an aggregate that uses the built-in min() or 37209588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 37219588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 37229588ad95Sdrh ** return the value X for which Y was maximal.) 37239588ad95Sdrh ** 37249a94722dSdan ** (25) If either the subquery or the parent query contains a window 37259a94722dSdan ** function in the select list or ORDER BY clause, flattening 37269a94722dSdan ** is not attempted. 37279a94722dSdan ** 37288290c2adSdan ** 3729832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 3730832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 373125c221ebSdrh ** uses aggregates. 3732832508b7Sdrh ** 3733665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 3734832508b7Sdrh ** If flattening is attempted this routine returns 1. 3735832508b7Sdrh ** 3736832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 3737832508b7Sdrh ** the subquery before this routine runs. 37381350b030Sdrh */ 37398c74a8caSdrh static int flattenSubquery( 3740524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 37418c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 37428c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 374325c221ebSdrh int isAgg /* True if outer SELECT uses aggregate functions */ 37448c74a8caSdrh ){ 3745524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 3746d12b6363Sdrh Select *pParent; /* Current UNION ALL term of the other query */ 37470bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 3748f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3749ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 3750ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 37516a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 3752399c7e21Sdrh int iNewParent = -1;/* Replacement table for iParent */ 3753399c7e21Sdrh int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ 375491bb0eedSdrh int i; /* Loop counter */ 375591bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 375691bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 3757524cc21eSdanielk1977 sqlite3 *db = pParse->db; 37581350b030Sdrh 3759832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 3760832508b7Sdrh */ 3761a78c22c4Sdrh assert( p!=0 ); 3762d981e828Sdrh assert( p->pPrior==0 ); 37637e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3764832508b7Sdrh pSrc = p->pSrc; 3765ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 376691bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 376749fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 376891bb0eedSdrh pSub = pSubitem->pSelect; 3769832508b7Sdrh assert( pSub!=0 ); 3770885a5b03Sdrh 377167a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 37729a94722dSdan if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ 377367a9b8edSdan #endif 377486fb6e17Sdan 3775832508b7Sdrh pSubSrc = pSub->pSrc; 3776832508b7Sdrh assert( pSubSrc ); 3777ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 377860ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3779ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 3780ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 3781ac83963aSdrh ** and (14). */ 3782ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 37838c0833fbSdrh if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ 3784d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3785ad91c6cdSdrh return 0; /* Restriction (15) */ 3786ad91c6cdSdrh } 3787ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 3788d981e828Sdrh if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ 378949ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 379049ad330dSdan return 0; /* Restrictions (8)(9) */ 3791df199a25Sdrh } 37927d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 3793ac83963aSdrh return 0; /* Restriction (11) */ 3794ac83963aSdrh } 3795c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 3796229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 3797a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 3798a91491e5Sshaneh return 0; /* Restriction (21) */ 3799a91491e5Sshaneh } 3800508e2d00Sdrh if( pSub->selFlags & (SF_Recursive) ){ 3801508e2d00Sdrh return 0; /* Restrictions (22) */ 38029588ad95Sdrh } 3803832508b7Sdrh 3804399c7e21Sdrh /* 3805399c7e21Sdrh ** If the subquery is the right operand of a LEFT JOIN, then the 3806d981e828Sdrh ** subquery may not be a join itself (3a). Example of why this is not 3807d981e828Sdrh ** allowed: 38088af4d3acSdrh ** 38098af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 38108af4d3acSdrh ** 38118af4d3acSdrh ** If we flatten the above, we would get 38128af4d3acSdrh ** 38138af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 38148af4d3acSdrh ** 38158af4d3acSdrh ** which is not at all the same thing. 38162b300d5dSdrh ** 38173c790f2aSdrh ** If the subquery is the right operand of a LEFT JOIN, then the outer 3818d981e828Sdrh ** query cannot be an aggregate. (3c) This is an artifact of the way 3819d981e828Sdrh ** aggregates are processed - there is no mechanism to determine if 3820d981e828Sdrh ** the LEFT JOIN table should be all-NULL. 38213c790f2aSdrh ** 382231d6fd55Sdrh ** See also tickets #306, #350, and #3300. 38233fc673e6Sdrh */ 38248a48b9c0Sdrh if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ 3825399c7e21Sdrh isLeftJoin = 1; 3826396afe6fSdrh if( pSubSrc->nSrc>1 /* (3a) */ 3827396afe6fSdrh || isAgg /* (3b) */ 3828396afe6fSdrh || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */ 3829396afe6fSdrh || (p->selFlags & SF_Distinct)!=0 /* (3d) */ 3830396afe6fSdrh ){ 3831d981e828Sdrh return 0; 3832399c7e21Sdrh } 38333fc673e6Sdrh } 3834dc6de479Sdrh #ifdef SQLITE_EXTRA_IFNULLROW 3835dc6de479Sdrh else if( iFrom>0 && !isAgg ){ 3836dc6de479Sdrh /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for 38373d240d21Sdrh ** every reference to any result column from subquery in a join, even 38383d240d21Sdrh ** though they are not necessary. This will stress-test the OP_IfNullRow 38393d240d21Sdrh ** opcode. */ 3840dc6de479Sdrh isLeftJoin = -1; 3841dc6de479Sdrh } 3842dc6de479Sdrh #endif 38433fc673e6Sdrh 3844d981e828Sdrh /* Restriction (17): If the sub-query is a compound SELECT, then it must 3845f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 3846f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 3847f23329a2Sdanielk1977 ** queries. 3848f23329a2Sdanielk1977 */ 3849f23329a2Sdanielk1977 if( pSub->pPrior ){ 3850fca23557Sdrh if( pSub->pOrderBy ){ 3851fca23557Sdrh return 0; /* Restriction (20) */ 3852fca23557Sdrh } 3853e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3854d981e828Sdrh return 0; /* (17d1), (17d2), or (17d3) */ 3855f23329a2Sdanielk1977 } 3856f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3857ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3858ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 38594b3ac73cSdrh assert( pSub->pSrc!=0 ); 38602ec18a3cSdrh assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); 3861d981e828Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ 3862d981e828Sdrh || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ 3863d981e828Sdrh || pSub1->pSrc->nSrc<1 /* (17c) */ 3864ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 38658d95ed78Sdrh || pSub1->pWin /* (17e) */ 3866ef9f719dSdrh #endif 386780b3c548Sdanielk1977 ){ 3868f23329a2Sdanielk1977 return 0; 3869f23329a2Sdanielk1977 } 38704b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 3871f23329a2Sdanielk1977 } 387249fc1f60Sdanielk1977 3873d981e828Sdrh /* Restriction (18). */ 387449fc1f60Sdanielk1977 if( p->pOrderBy ){ 387549fc1f60Sdanielk1977 int ii; 387649fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3877c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 387849fc1f60Sdanielk1977 } 387949fc1f60Sdanielk1977 } 3880f23329a2Sdanielk1977 } 3881f23329a2Sdanielk1977 3882cdb2f607Sdrh /* Ex-restriction (23): 3883cdb2f607Sdrh ** The only way that the recursive part of a CTE can contain a compound 3884cdb2f607Sdrh ** subquery is for the subquery to be one term of a join. But if the 3885cdb2f607Sdrh ** subquery is a join, then the flattening has already been stopped by 3886cdb2f607Sdrh ** restriction (17d3) 3887cdb2f607Sdrh */ 3888cdb2f607Sdrh assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); 3889cdb2f607Sdrh 38907d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 3891fef37760Sdrh SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n", 3892fef37760Sdrh pSub->selId, pSub, iFrom)); 38937d10d5a6Sdrh 38947d10d5a6Sdrh /* Authorize the subquery */ 3895524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 3896a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 3897a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 3898524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 3899524cc21eSdanielk1977 39007d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 39017d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 39027d10d5a6Sdrh ** be of the form: 3903f23329a2Sdanielk1977 ** 3904f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 3905f23329a2Sdanielk1977 ** 3906f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 3907a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 3908f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 3909f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 3910f23329a2Sdanielk1977 ** select statements in the compound sub-query. 3911a78c22c4Sdrh ** 3912a78c22c4Sdrh ** Example: 3913a78c22c4Sdrh ** 3914a78c22c4Sdrh ** SELECT a+1 FROM ( 3915a78c22c4Sdrh ** SELECT x FROM tab 3916a78c22c4Sdrh ** UNION ALL 3917a78c22c4Sdrh ** SELECT y FROM tab 3918a78c22c4Sdrh ** UNION ALL 3919a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 3920a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 3921a78c22c4Sdrh ** 3922a78c22c4Sdrh ** Transformed into: 3923a78c22c4Sdrh ** 3924a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 3925a78c22c4Sdrh ** UNION ALL 3926a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 3927a78c22c4Sdrh ** UNION ALL 3928a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 3929a78c22c4Sdrh ** ORDER BY 1 3930a78c22c4Sdrh ** 3931a78c22c4Sdrh ** We call this the "compound-subquery flattening". 3932f23329a2Sdanielk1977 */ 3933f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 3934f23329a2Sdanielk1977 Select *pNew; 3935f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 39364b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 3937f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 3938f23329a2Sdanielk1977 p->pOrderBy = 0; 3939f23329a2Sdanielk1977 p->pSrc = 0; 3940f23329a2Sdanielk1977 p->pPrior = 0; 39414b86ef1dSdanielk1977 p->pLimit = 0; 39426ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 39434b86ef1dSdanielk1977 p->pLimit = pLimit; 3944a78c22c4Sdrh p->pOrderBy = pOrderBy; 3945a78c22c4Sdrh p->pSrc = pSrc; 3946a78c22c4Sdrh p->op = TK_ALL; 3947a78c22c4Sdrh if( pNew==0 ){ 3948d227a291Sdrh p->pPrior = pPrior; 3949a78c22c4Sdrh }else{ 3950a78c22c4Sdrh pNew->pPrior = pPrior; 3951d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 3952d227a291Sdrh pNew->pNext = p; 3953a78c22c4Sdrh p->pPrior = pNew; 3954e2243d26Sdrh SELECTTRACE(2,pParse,p,("compound-subquery flattener" 3955fef37760Sdrh " creates %u as peer\n",pNew->selId)); 3956d227a291Sdrh } 3957a78c22c4Sdrh if( db->mallocFailed ) return 1; 3958a78c22c4Sdrh } 3959f23329a2Sdanielk1977 39607d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 39617d10d5a6Sdrh ** in the outer query. 3962832508b7Sdrh */ 3963f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 3964c31c2eb8Sdrh 3965a78c22c4Sdrh /* Delete the transient table structure associated with the 3966a78c22c4Sdrh ** subquery 3967a78c22c4Sdrh */ 3968a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 3969a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 3970a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 3971a78c22c4Sdrh pSubitem->zDatabase = 0; 3972a78c22c4Sdrh pSubitem->zName = 0; 3973a78c22c4Sdrh pSubitem->zAlias = 0; 3974a78c22c4Sdrh pSubitem->pSelect = 0; 3975a78c22c4Sdrh 3976a78c22c4Sdrh /* Defer deleting the Table object associated with the 3977a78c22c4Sdrh ** subquery until code generation is 3978a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 3979a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 3980ccfcbceaSdrh ** 3981ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 3982a78c22c4Sdrh */ 3983ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 3984a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 398579df7782Sdrh if( pTabToDel->nTabRef==1 ){ 398665a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 398765a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 398865a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 3989a78c22c4Sdrh }else{ 399079df7782Sdrh pTabToDel->nTabRef--; 3991a78c22c4Sdrh } 3992a78c22c4Sdrh pSubitem->pTab = 0; 3993a78c22c4Sdrh } 3994a78c22c4Sdrh 3995a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 3996a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 3997a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 3998a78c22c4Sdrh ** then this loop only runs once. 3999a78c22c4Sdrh ** 4000a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 4001c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 4002c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 4003c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 4004c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 4005c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 4006c31c2eb8Sdrh ** elements we are now copying in. 4007c31c2eb8Sdrh */ 4008a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 4009a78c22c4Sdrh int nSubSrc; 4010ea678832Sdrh u8 jointype = 0; 401155f66b34Sdrh assert( pSub!=0 ); 4012a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 4013a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 4014a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 4015588a9a1aSdrh 4016a78c22c4Sdrh if( pSrc ){ 4017a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 40188a48b9c0Sdrh jointype = pSubitem->fg.jointype; 4019588a9a1aSdrh }else{ 4020a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 402129c992cbSdrh pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0); 402229c992cbSdrh if( pSrc==0 ) break; 402329c992cbSdrh pParent->pSrc = pSrc; 4024c31c2eb8Sdrh } 4025a78c22c4Sdrh 4026a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 4027a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 4028a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 4029a78c22c4Sdrh ** of the subquery. 4030a78c22c4Sdrh ** 4031a78c22c4Sdrh ** Example: 4032a78c22c4Sdrh ** 4033a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 4034a78c22c4Sdrh ** 4035a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 4036a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 4037d12b6363Sdrh ** block of code will expand the outer query FROM clause to 4 slots. 4038d12b6363Sdrh ** The middle slot is expanded to two slots in order to make space 4039d12b6363Sdrh ** for the two elements in the FROM clause of the subquery. 4040a78c22c4Sdrh */ 4041a78c22c4Sdrh if( nSubSrc>1 ){ 404229c992cbSdrh pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); 404329c992cbSdrh if( pSrc==0 ) break; 404429c992cbSdrh pParent->pSrc = pSrc; 4045c31c2eb8Sdrh } 4046a78c22c4Sdrh 4047a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 4048a78c22c4Sdrh ** outer query. 4049a78c22c4Sdrh */ 4050c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 4051c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 405220292310Sdrh assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); 4053c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 4054399c7e21Sdrh iNewParent = pSubSrc->a[i].iCursor; 4055c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 4056c31c2eb8Sdrh } 40578a48b9c0Sdrh pSrc->a[iFrom].fg.jointype = jointype; 4058c31c2eb8Sdrh 4059c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 4060c31c2eb8Sdrh ** references to the iParent in the outer query. 4061c31c2eb8Sdrh ** 4062c31c2eb8Sdrh ** Example: 4063c31c2eb8Sdrh ** 4064c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 4065c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 4066c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 4067c31c2eb8Sdrh ** 4068c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 4069c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 4070c31c2eb8Sdrh */ 4071174b6195Sdrh if( pSub->pOrderBy ){ 40727c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 40737c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 40747c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 40757c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 40767c0a4720Sdan ** zero them before transfering the ORDER BY clause. 40777c0a4720Sdan ** 40787c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 40797c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 40807c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 40817c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 40827c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 40837c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 40847c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 40857c0a4720Sdan } 4086f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 40877c0a4720Sdan pParent->pOrderBy = pOrderBy; 4088174b6195Sdrh pSub->pOrderBy = 0; 4089174b6195Sdrh } 409011df7d28Sdrh pWhere = pSub->pWhere; 409111df7d28Sdrh pSub->pWhere = 0; 4092dc6de479Sdrh if( isLeftJoin>0 ){ 40938103a036Sdrh sqlite3SetJoinExpr(pWhere, iNewParent); 4094399c7e21Sdrh } 4095d5c851c1Sdrh pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere); 4096c3becddbSdan if( db->mallocFailed==0 ){ 409746967de2Sdrh SubstContext x; 409846967de2Sdrh x.pParse = pParse; 409946967de2Sdrh x.iTable = iParent; 4100399c7e21Sdrh x.iNewTable = iNewParent; 410131d6fd55Sdrh x.isLeftJoin = isLeftJoin; 410246967de2Sdrh x.pEList = pSub->pEList; 410346967de2Sdrh substSelect(&x, pParent, 0); 4104c3becddbSdan } 4105c31c2eb8Sdrh 41067cd5e856Sdrh /* The flattened query is a compound if either the inner or the 41077cd5e856Sdrh ** outer query is a compound. */ 41087cd5e856Sdrh pParent->selFlags |= pSub->selFlags & SF_Compound; 41097cd5e856Sdrh assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ 41108c74a8caSdrh 4111a58fdfb1Sdanielk1977 /* 4112a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 4113ac83963aSdrh ** 4114ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 4115ac83963aSdrh ** does not work if either limit is negative. 4116a58fdfb1Sdanielk1977 */ 4117a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 4118f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 4119a2dc3b1aSdanielk1977 pSub->pLimit = 0; 4120df199a25Sdrh } 4121f23329a2Sdanielk1977 } 41228c74a8caSdrh 4123c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 4124c31c2eb8Sdrh ** success. 4125c31c2eb8Sdrh */ 4126633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 4127f23329a2Sdanielk1977 4128c90713d3Sdrh #if SELECTTRACE_ENABLED 4129c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 4130bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After flattening:\n")); 4131c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4132c90713d3Sdrh } 4133c90713d3Sdrh #endif 4134c90713d3Sdrh 4135832508b7Sdrh return 1; 41361350b030Sdrh } 41373514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 41381350b030Sdrh 4139660ee556Sdrh /* 41408e5bfeddSdrh ** A structure to keep track of all of the column values that are fixed to 4141efad2e23Sdrh ** a known value due to WHERE clause constraints of the form COLUMN=VALUE. 4142660ee556Sdrh */ 4143660ee556Sdrh typedef struct WhereConst WhereConst; 4144660ee556Sdrh struct WhereConst { 4145efad2e23Sdrh Parse *pParse; /* Parsing context */ 4146660ee556Sdrh int nConst; /* Number for COLUMN=CONSTANT terms */ 4147660ee556Sdrh int nChng; /* Number of times a constant is propagated */ 4148efad2e23Sdrh Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */ 4149660ee556Sdrh }; 415069b72d5aSdrh 4151660ee556Sdrh /* 41528e5bfeddSdrh ** Add a new entry to the pConst object. Except, do not add duplicate 4153f8f76d67Sdrh ** pColumn entires. Also, do not add if doing so would not be appropriate. 4154f8f76d67Sdrh ** 4155f8f76d67Sdrh ** The caller guarantees the pColumn is a column and pValue is a constant. 4156f8f76d67Sdrh ** This routine has to do some additional checks before completing the 4157f8f76d67Sdrh ** insert. 4158660ee556Sdrh */ 4159660ee556Sdrh static void constInsert( 41608e5bfeddSdrh WhereConst *pConst, /* The WhereConst into which we are inserting */ 41618e5bfeddSdrh Expr *pColumn, /* The COLUMN part of the constraint */ 4162f8f76d67Sdrh Expr *pValue, /* The VALUE part of the constraint */ 4163f8f76d67Sdrh Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */ 4164660ee556Sdrh ){ 41658e5bfeddSdrh int i; 41668e5bfeddSdrh assert( pColumn->op==TK_COLUMN ); 4167f8f76d67Sdrh assert( sqlite3ExprIsConstant(pValue) ); 4168f8f76d67Sdrh 4169*fdfd45aeSdrh if( ExprHasProperty(pColumn, EP_FixedCol) ) return; 4170*fdfd45aeSdrh if( sqlite3ExprAffinity(pValue)!=0 ) return; 4171f8f76d67Sdrh if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ 4172f8f76d67Sdrh return; 4173f8f76d67Sdrh } 41748e5bfeddSdrh 41758e5bfeddSdrh /* 2018-10-25 ticket [cf5ed20f] 41768e5bfeddSdrh ** Make sure the same pColumn is not inserted more than once */ 41778e5bfeddSdrh for(i=0; i<pConst->nConst; i++){ 41787be5e3ddSdrh const Expr *pE2 = pConst->apExpr[i*2]; 41797be5e3ddSdrh assert( pE2->op==TK_COLUMN ); 41807be5e3ddSdrh if( pE2->iTable==pColumn->iTable 41817be5e3ddSdrh && pE2->iColumn==pColumn->iColumn 41828e5bfeddSdrh ){ 41838e5bfeddSdrh return; /* Already present. Return without doing anything. */ 41848e5bfeddSdrh } 41858e5bfeddSdrh } 41869cbf4f35Sdrh 4187660ee556Sdrh pConst->nConst++; 4188efad2e23Sdrh pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr, 4189660ee556Sdrh pConst->nConst*2*sizeof(Expr*)); 4190660ee556Sdrh if( pConst->apExpr==0 ){ 4191660ee556Sdrh pConst->nConst = 0; 4192660ee556Sdrh }else{ 4193660ee556Sdrh pConst->apExpr[pConst->nConst*2-2] = pColumn; 4194660ee556Sdrh pConst->apExpr[pConst->nConst*2-1] = pValue; 4195660ee556Sdrh } 4196660ee556Sdrh } 4197660ee556Sdrh 4198660ee556Sdrh /* 4199efad2e23Sdrh ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE 4200efad2e23Sdrh ** is a constant expression and where the term must be true because it 4201efad2e23Sdrh ** is part of the AND-connected terms of the expression. For each term 4202efad2e23Sdrh ** found, add it to the pConst structure. 4203660ee556Sdrh */ 4204660ee556Sdrh static void findConstInWhere(WhereConst *pConst, Expr *pExpr){ 4205efad2e23Sdrh Expr *pRight, *pLeft; 4206660ee556Sdrh if( pExpr==0 ) return; 4207660ee556Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) ) return; 4208660ee556Sdrh if( pExpr->op==TK_AND ){ 4209660ee556Sdrh findConstInWhere(pConst, pExpr->pRight); 4210660ee556Sdrh findConstInWhere(pConst, pExpr->pLeft); 4211660ee556Sdrh return; 4212660ee556Sdrh } 4213660ee556Sdrh if( pExpr->op!=TK_EQ ) return; 4214efad2e23Sdrh pRight = pExpr->pRight; 4215efad2e23Sdrh pLeft = pExpr->pLeft; 4216efad2e23Sdrh assert( pRight!=0 ); 4217efad2e23Sdrh assert( pLeft!=0 ); 4218f8f76d67Sdrh if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){ 4219f8f76d67Sdrh constInsert(pConst,pRight,pLeft,pExpr); 4220f8f76d67Sdrh } 4221f8f76d67Sdrh if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){ 4222f8f76d67Sdrh constInsert(pConst,pLeft,pRight,pExpr); 4223660ee556Sdrh } 4224660ee556Sdrh } 4225660ee556Sdrh 4226660ee556Sdrh /* 4227660ee556Sdrh ** This is a Walker expression callback. pExpr is a candidate expression 4228660ee556Sdrh ** to be replaced by a value. If pExpr is equivalent to one of the 4229660ee556Sdrh ** columns named in pWalker->u.pConst, then overwrite it with its 4230660ee556Sdrh ** corresponding value. 4231660ee556Sdrh */ 4232660ee556Sdrh static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ 4233660ee556Sdrh int i; 4234660ee556Sdrh WhereConst *pConst; 4235660ee556Sdrh if( pExpr->op!=TK_COLUMN ) return WRC_Continue; 4236be0330e8Sdrh if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){ 4237be0330e8Sdrh testcase( ExprHasProperty(pExpr, EP_FixedCol) ); 4238be0330e8Sdrh testcase( ExprHasProperty(pExpr, EP_FromJoin) ); 4239be0330e8Sdrh return WRC_Continue; 4240be0330e8Sdrh } 4241660ee556Sdrh pConst = pWalker->u.pConst; 4242660ee556Sdrh for(i=0; i<pConst->nConst; i++){ 4243660ee556Sdrh Expr *pColumn = pConst->apExpr[i*2]; 4244660ee556Sdrh if( pColumn==pExpr ) continue; 4245660ee556Sdrh if( pColumn->iTable!=pExpr->iTable ) continue; 4246660ee556Sdrh if( pColumn->iColumn!=pExpr->iColumn ) continue; 4247efad2e23Sdrh /* A match is found. Add the EP_FixedCol property */ 4248660ee556Sdrh pConst->nChng++; 4249660ee556Sdrh ExprClearProperty(pExpr, EP_Leaf); 4250efad2e23Sdrh ExprSetProperty(pExpr, EP_FixedCol); 4251efad2e23Sdrh assert( pExpr->pLeft==0 ); 4252efad2e23Sdrh pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); 4253660ee556Sdrh break; 4254660ee556Sdrh } 4255660ee556Sdrh return WRC_Prune; 4256660ee556Sdrh } 4257660ee556Sdrh 4258660ee556Sdrh /* 4259660ee556Sdrh ** The WHERE-clause constant propagation optimization. 4260660ee556Sdrh ** 4261660ee556Sdrh ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or 426297bffe67Sdrh ** CONSTANT=COLUMN that are top-level AND-connected terms that are not 426397bffe67Sdrh ** part of a ON clause from a LEFT JOIN, then throughout the query 426497bffe67Sdrh ** replace all other occurrences of COLUMN with CONSTANT. 4265660ee556Sdrh ** 4266660ee556Sdrh ** For example, the query: 4267660ee556Sdrh ** 4268660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b 4269660ee556Sdrh ** 4270660ee556Sdrh ** Is transformed into 4271660ee556Sdrh ** 4272660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39 4273660ee556Sdrh ** 4274660ee556Sdrh ** Return true if any transformations where made and false if not. 4275efad2e23Sdrh ** 4276efad2e23Sdrh ** Implementation note: Constant propagation is tricky due to affinity 4277efad2e23Sdrh ** and collating sequence interactions. Consider this example: 4278efad2e23Sdrh ** 4279efad2e23Sdrh ** CREATE TABLE t1(a INT,b TEXT); 4280efad2e23Sdrh ** INSERT INTO t1 VALUES(123,'0123'); 4281efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=a; 4282efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=123; 4283efad2e23Sdrh ** 4284efad2e23Sdrh ** The two SELECT statements above should return different answers. b=a 4285efad2e23Sdrh ** is alway true because the comparison uses numeric affinity, but b=123 4286efad2e23Sdrh ** is false because it uses text affinity and '0123' is not the same as '123'. 4287efad2e23Sdrh ** To work around this, the expression tree is not actually changed from 4288efad2e23Sdrh ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol 4289efad2e23Sdrh ** and the "123" value is hung off of the pLeft pointer. Code generator 4290efad2e23Sdrh ** routines know to generate the constant "123" instead of looking up the 4291efad2e23Sdrh ** column value. Also, to avoid collation problems, this optimization is 4292efad2e23Sdrh ** only attempted if the "a=123" term uses the default BINARY collation. 4293660ee556Sdrh */ 4294660ee556Sdrh static int propagateConstants( 4295660ee556Sdrh Parse *pParse, /* The parsing context */ 4296660ee556Sdrh Select *p /* The query in which to propagate constants */ 4297660ee556Sdrh ){ 4298660ee556Sdrh WhereConst x; 4299660ee556Sdrh Walker w; 4300660ee556Sdrh int nChng = 0; 4301efad2e23Sdrh x.pParse = pParse; 4302660ee556Sdrh do{ 4303660ee556Sdrh x.nConst = 0; 4304660ee556Sdrh x.nChng = 0; 4305660ee556Sdrh x.apExpr = 0; 4306660ee556Sdrh findConstInWhere(&x, p->pWhere); 4307660ee556Sdrh if( x.nConst ){ 4308660ee556Sdrh memset(&w, 0, sizeof(w)); 4309660ee556Sdrh w.pParse = pParse; 4310660ee556Sdrh w.xExprCallback = propagateConstantExprRewrite; 4311660ee556Sdrh w.xSelectCallback = sqlite3SelectWalkNoop; 4312660ee556Sdrh w.xSelectCallback2 = 0; 4313660ee556Sdrh w.walkerDepth = 0; 4314660ee556Sdrh w.u.pConst = &x; 4315efad2e23Sdrh sqlite3WalkExpr(&w, p->pWhere); 4316efad2e23Sdrh sqlite3DbFree(x.pParse->db, x.apExpr); 4317660ee556Sdrh nChng += x.nChng; 4318660ee556Sdrh } 4319660ee556Sdrh }while( x.nChng ); 4320660ee556Sdrh return nChng; 4321660ee556Sdrh } 432269b72d5aSdrh 432369b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 432469b72d5aSdrh /* 432569b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into 432669b72d5aSdrh ** the WHERE clause of subquery. Example: 432769b72d5aSdrh ** 432869b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; 432969b72d5aSdrh ** 433069b72d5aSdrh ** Transformed into: 433169b72d5aSdrh ** 433269b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) 433369b72d5aSdrh ** WHERE x=5 AND y=10; 433469b72d5aSdrh ** 433569b72d5aSdrh ** The hope is that the terms added to the inner query will make it more 433669b72d5aSdrh ** efficient. 433769b72d5aSdrh ** 433869b72d5aSdrh ** Do not attempt this optimization if: 433969b72d5aSdrh ** 434025c221ebSdrh ** (1) (** This restriction was removed on 2017-09-29. We used to 434125c221ebSdrh ** disallow this optimization for aggregate subqueries, but now 434267cc51a4Sdrh ** it is allowed by putting the extra terms on the HAVING clause. 434367cc51a4Sdrh ** The added HAVING clause is pointless if the subquery lacks 434467cc51a4Sdrh ** a GROUP BY clause. But such a HAVING clause is also harmless 434567cc51a4Sdrh ** so there does not appear to be any reason to add extra logic 434667cc51a4Sdrh ** to suppress it. **) 434769b72d5aSdrh ** 434869b72d5aSdrh ** (2) The inner query is the recursive part of a common table expression. 434969b72d5aSdrh ** 435069b72d5aSdrh ** (3) The inner query has a LIMIT clause (since the changes to the WHERE 4351ce103735Sdan ** clause would change the meaning of the LIMIT). 435269b72d5aSdrh ** 43536a9b9527Sdrh ** (4) The inner query is the right operand of a LEFT JOIN and the 43546a9b9527Sdrh ** expression to be pushed down does not come from the ON clause 43556a9b9527Sdrh ** on that LEFT JOIN. 435669b72d5aSdrh ** 435738978dd4Sdrh ** (5) The WHERE clause expression originates in the ON or USING clause 43587fbb101cSdrh ** of a LEFT JOIN where iCursor is not the right-hand table of that 43597fbb101cSdrh ** left join. An example: 43607fbb101cSdrh ** 43617fbb101cSdrh ** SELECT * 43627fbb101cSdrh ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa 43637fbb101cSdrh ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) 43647fbb101cSdrh ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); 43657fbb101cSdrh ** 43667fbb101cSdrh ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). 43677fbb101cSdrh ** But if the (b2=2) term were to be pushed down into the bb subquery, 43687fbb101cSdrh ** then the (1,1,NULL) row would be suppressed. 436938978dd4Sdrh ** 4370ce103735Sdan ** (6) The inner query features one or more window-functions (since 4371ce103735Sdan ** changes to the WHERE clause of the inner query could change the 4372ce103735Sdan ** window over which window functions are calculated). 4373ce103735Sdan ** 437469b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause 437569b72d5aSdrh ** terms are duplicated into the subquery. 437669b72d5aSdrh */ 437769b72d5aSdrh static int pushDownWhereTerms( 437844c5604cSdan Parse *pParse, /* Parse context (for malloc() and error reporting) */ 437969b72d5aSdrh Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ 438069b72d5aSdrh Expr *pWhere, /* The WHERE clause of the outer query */ 43816a9b9527Sdrh int iCursor, /* Cursor number of the subquery */ 43826a9b9527Sdrh int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ 438369b72d5aSdrh ){ 438469b72d5aSdrh Expr *pNew; 438569b72d5aSdrh int nChng = 0; 438669b72d5aSdrh if( pWhere==0 ) return 0; 4387508e2d00Sdrh if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ 4388508e2d00Sdrh 4389ce103735Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 4390142066d4Sdrh if( pSubq->pWin ) return 0; /* restriction (6) */ 4391ce103735Sdan #endif 4392ce103735Sdan 4393508e2d00Sdrh #ifdef SQLITE_DEBUG 4394508e2d00Sdrh /* Only the first term of a compound can have a WITH clause. But make 4395508e2d00Sdrh ** sure no other terms are marked SF_Recursive in case something changes 4396508e2d00Sdrh ** in the future. 4397508e2d00Sdrh */ 4398508e2d00Sdrh { 4399508e2d00Sdrh Select *pX; 4400b1ec87afSdrh for(pX=pSubq; pX; pX=pX->pPrior){ 4401508e2d00Sdrh assert( (pX->selFlags & (SF_Recursive))==0 ); 440269b72d5aSdrh } 4403b1ec87afSdrh } 4404508e2d00Sdrh #endif 4405508e2d00Sdrh 440669b72d5aSdrh if( pSubq->pLimit!=0 ){ 440769b72d5aSdrh return 0; /* restriction (3) */ 440869b72d5aSdrh } 440969b72d5aSdrh while( pWhere->op==TK_AND ){ 44106a9b9527Sdrh nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, 44116a9b9527Sdrh iCursor, isLeftJoin); 441269b72d5aSdrh pWhere = pWhere->pLeft; 441369b72d5aSdrh } 44146a9b9527Sdrh if( isLeftJoin 44156a9b9527Sdrh && (ExprHasProperty(pWhere,EP_FromJoin)==0 44166a9b9527Sdrh || pWhere->iRightJoinTable!=iCursor) 44176a9b9527Sdrh ){ 44186a9b9527Sdrh return 0; /* restriction (4) */ 44196a9b9527Sdrh } 44207fbb101cSdrh if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){ 44217fbb101cSdrh return 0; /* restriction (5) */ 44227fbb101cSdrh } 442369b72d5aSdrh if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ 442469b72d5aSdrh nChng++; 442569b72d5aSdrh while( pSubq ){ 442646967de2Sdrh SubstContext x; 442744c5604cSdan pNew = sqlite3ExprDup(pParse->db, pWhere, 0); 44287fbb101cSdrh unsetJoinExpr(pNew, -1); 442946967de2Sdrh x.pParse = pParse; 443046967de2Sdrh x.iTable = iCursor; 4431399c7e21Sdrh x.iNewTable = iCursor; 443231d6fd55Sdrh x.isLeftJoin = 0; 443346967de2Sdrh x.pEList = pSubq->pEList; 443446967de2Sdrh pNew = substExpr(&x, pNew); 443525c221ebSdrh if( pSubq->selFlags & SF_Aggregate ){ 4436d5c851c1Sdrh pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew); 443725c221ebSdrh }else{ 4438d5c851c1Sdrh pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew); 443925c221ebSdrh } 444069b72d5aSdrh pSubq = pSubq->pPrior; 444169b72d5aSdrh } 444269b72d5aSdrh } 444369b72d5aSdrh return nChng; 444469b72d5aSdrh } 444569b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 444669b72d5aSdrh 44471350b030Sdrh /* 444847d9f839Sdrh ** The pFunc is the only aggregate function in the query. Check to see 444947d9f839Sdrh ** if the query is a candidate for the min/max optimization. 4450a9d1ccb9Sdanielk1977 ** 445147d9f839Sdrh ** If the query is a candidate for the min/max optimization, then set 445247d9f839Sdrh ** *ppMinMax to be an ORDER BY clause to be used for the optimization 445347d9f839Sdrh ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on 445447d9f839Sdrh ** whether pFunc is a min() or max() function. 4455738bdcfbSdanielk1977 ** 445647d9f839Sdrh ** If the query is not a candidate for the min/max optimization, return 445747d9f839Sdrh ** WHERE_ORDERBY_NORMAL (which must be zero). 44584ac391fcSdan ** 445947d9f839Sdrh ** This routine must be called after aggregate functions have been 446047d9f839Sdrh ** located but before their arguments have been subjected to aggregate 446147d9f839Sdrh ** analysis. 4462a9d1ccb9Sdanielk1977 */ 446347d9f839Sdrh static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ 44644ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 446547d9f839Sdrh ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */ 446647d9f839Sdrh const char *zFunc; /* Name of aggregate function pFunc */ 446747d9f839Sdrh ExprList *pOrderBy; 44685b32bdffSdan u8 sortFlags; 4469a9d1ccb9Sdanielk1977 447047d9f839Sdrh assert( *ppMinMax==0 ); 447147d9f839Sdrh assert( pFunc->op==TK_AGG_FUNCTION ); 44724f9adee2Sdan assert( !IsWindowFunc(pFunc) ); 44734f9adee2Sdan if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){ 44746ba7ab0dSdan return eRet; 44756ba7ab0dSdan } 447647d9f839Sdrh zFunc = pFunc->u.zToken; 44774ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 44784ac391fcSdan eRet = WHERE_ORDERBY_MIN; 44795b32bdffSdan sortFlags = KEYINFO_ORDER_BIGNULL; 44804ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 44814ac391fcSdan eRet = WHERE_ORDERBY_MAX; 44825b32bdffSdan sortFlags = KEYINFO_ORDER_DESC; 448347d9f839Sdrh }else{ 448447d9f839Sdrh return eRet; 4485a9d1ccb9Sdanielk1977 } 448647d9f839Sdrh *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0); 448747d9f839Sdrh assert( pOrderBy!=0 || db->mallocFailed ); 44885b32bdffSdan if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags; 44894ac391fcSdan return eRet; 4490a9d1ccb9Sdanielk1977 } 4491a9d1ccb9Sdanielk1977 4492a9d1ccb9Sdanielk1977 /* 4493a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 449460ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 4495a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 4496a5533162Sdanielk1977 ** 4497a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4498a5533162Sdanielk1977 ** 4499a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 4500a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 4501a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 4502a5533162Sdanielk1977 */ 4503a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 4504a5533162Sdanielk1977 Table *pTab; 4505a5533162Sdanielk1977 Expr *pExpr; 4506a5533162Sdanielk1977 4507a5533162Sdanielk1977 assert( !p->pGroupBy ); 4508a5533162Sdanielk1977 45097a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 4510a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 4511a5533162Sdanielk1977 ){ 4512a5533162Sdanielk1977 return 0; 4513a5533162Sdanielk1977 } 4514a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 4515a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 451602f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 451702f33725Sdanielk1977 451802f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 4519a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 4520fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 4521d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 45224f9adee2Sdan if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0; 4523a5533162Sdanielk1977 4524a5533162Sdanielk1977 return pTab; 4525a5533162Sdanielk1977 } 4526a5533162Sdanielk1977 4527a5533162Sdanielk1977 /* 4528b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 4529b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 4530b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 4531b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 4532b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 4533b1c685b0Sdanielk1977 */ 4534b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 45358a48b9c0Sdrh if( pFrom->pTab && pFrom->fg.isIndexedBy ){ 4536b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 45378a48b9c0Sdrh char *zIndexedBy = pFrom->u1.zIndexedBy; 4538b1c685b0Sdanielk1977 Index *pIdx; 4539b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 4540d62fbb50Sdrh pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 4541b1c685b0Sdanielk1977 pIdx=pIdx->pNext 4542b1c685b0Sdanielk1977 ); 4543b1c685b0Sdanielk1977 if( !pIdx ){ 4544d62fbb50Sdrh sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); 45451db95106Sdan pParse->checkSchema = 1; 4546b1c685b0Sdanielk1977 return SQLITE_ERROR; 4547b1c685b0Sdanielk1977 } 45488a48b9c0Sdrh pFrom->pIBIndex = pIdx; 4549b1c685b0Sdanielk1977 } 4550b1c685b0Sdanielk1977 return SQLITE_OK; 4551b1c685b0Sdanielk1977 } 4552c01b7306Sdrh /* 4553c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 4554c01b7306Sdrh ** an alternative collating sequence. 4555c01b7306Sdrh ** 4556c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 4557c01b7306Sdrh ** 4558c01b7306Sdrh ** These are rewritten as a subquery: 4559c01b7306Sdrh ** 4560c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 4561c01b7306Sdrh ** ORDER BY ... COLLATE ... 4562c01b7306Sdrh ** 4563c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 4564c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 4565c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 4566c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 4567c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 4568c01b7306Sdrh ** 4569c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 4570c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 4571c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 4572c01b7306Sdrh */ 4573c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 4574c01b7306Sdrh int i; 4575c01b7306Sdrh Select *pNew; 4576c01b7306Sdrh Select *pX; 4577c01b7306Sdrh sqlite3 *db; 4578c01b7306Sdrh struct ExprList_item *a; 4579c01b7306Sdrh SrcList *pNewSrc; 4580c01b7306Sdrh Parse *pParse; 4581c01b7306Sdrh Token dummy; 4582c01b7306Sdrh 4583c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 4584c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 4585c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 4586c01b7306Sdrh if( pX==0 ) return WRC_Continue; 4587c01b7306Sdrh a = p->pOrderBy->a; 4588c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 4589c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 4590c01b7306Sdrh } 4591c01b7306Sdrh if( i<0 ) return WRC_Continue; 4592c01b7306Sdrh 4593c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 4594c01b7306Sdrh 4595c01b7306Sdrh pParse = pWalker->pParse; 4596c01b7306Sdrh db = pParse->db; 4597c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 4598c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 4599c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 4600c01b7306Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 4601c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 4602c01b7306Sdrh *pNew = *p; 4603c01b7306Sdrh p->pSrc = pNewSrc; 46041a1d3cd2Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); 4605c01b7306Sdrh p->op = TK_SELECT; 4606c01b7306Sdrh p->pWhere = 0; 4607c01b7306Sdrh pNew->pGroupBy = 0; 4608c01b7306Sdrh pNew->pHaving = 0; 4609c01b7306Sdrh pNew->pOrderBy = 0; 4610c01b7306Sdrh p->pPrior = 0; 46118af9ad95Sdrh p->pNext = 0; 4612f932f714Sdrh p->pWith = 0; 4613fcc057dbSdan #ifndef SQLITE_OMIT_WINDOWFUNC 4614fcc057dbSdan p->pWinDefn = 0; 4615fcc057dbSdan #endif 46168af9ad95Sdrh p->selFlags &= ~SF_Compound; 4617b33c50f2Sdan assert( (p->selFlags & SF_Converted)==0 ); 4618b33c50f2Sdan p->selFlags |= SF_Converted; 4619a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 4620a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 4621c01b7306Sdrh pNew->pLimit = 0; 4622c01b7306Sdrh return WRC_Continue; 4623c01b7306Sdrh } 4624b1c685b0Sdanielk1977 462520292310Sdrh /* 462620292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function 462720292310Sdrh ** arguments. If it does, leave an error message in pParse and return 462820292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function. 462920292310Sdrh */ 463020292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ 463120292310Sdrh if( pFrom->fg.isTabFunc ){ 463220292310Sdrh sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); 463320292310Sdrh return 1; 463420292310Sdrh } 463520292310Sdrh return 0; 463620292310Sdrh } 463720292310Sdrh 4638eede6a53Sdan #ifndef SQLITE_OMIT_CTE 4639eede6a53Sdan /* 4640eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 4641eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 4642eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 4643eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 4644eede6a53Sdan ** return NULL. 464598f45e53Sdan ** 464698f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 464798f45e53Sdan ** object that the returned CTE belongs to. 464860c1a2f0Sdrh */ 464998f45e53Sdan static struct Cte *searchWith( 46502476a6f2Sdrh With *pWith, /* Current innermost WITH clause */ 465198f45e53Sdan struct SrcList_item *pItem, /* FROM clause element to resolve */ 465298f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 465398f45e53Sdan ){ 46547b19f252Sdrh const char *zName; 46557b19f252Sdrh if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 4656eede6a53Sdan With *p; 4657eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 46584e9119d9Sdan int i; 4659eede6a53Sdan for(i=0; i<p->nCte; i++){ 4660eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 466198f45e53Sdan *ppContext = p; 4662eede6a53Sdan return &p->a[i]; 46634e9119d9Sdan } 46644e9119d9Sdan } 46654e9119d9Sdan } 46664e9119d9Sdan } 46674e9119d9Sdan return 0; 46684e9119d9Sdan } 46694e9119d9Sdan 4670c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 4671c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 4672c49832c2Sdrh ** 4673b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 4674b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 4675b290f117Sdan ** WITH clause will never be popped from the stack. In this case it 4676b290f117Sdan ** should be freed along with the Parse object. In other cases, when 4677b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 4678b290f117Sdan ** statement with which it is associated. 4679c49832c2Sdrh */ 4680b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 46816e772266Sdrh assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); 46824e9119d9Sdan if( pWith ){ 46832476a6f2Sdrh assert( pParse->pWith!=pWith ); 46844e9119d9Sdan pWith->pOuter = pParse->pWith; 46854e9119d9Sdan pParse->pWith = pWith; 46866e772266Sdrh if( bFree ) pParse->pWithToFree = pWith; 46874e9119d9Sdan } 46884e9119d9Sdan } 46894e9119d9Sdan 4690eede6a53Sdan /* 4691eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 4692eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And, 4693eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive 4694eede6a53Sdan ** reference to the current CTE. 4695eede6a53Sdan ** 4696eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab 4697eede6a53Sdan ** and other fields are populated accordingly. The caller should check 4698eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match 4699eede6a53Sdan ** was found. 4700eede6a53Sdan ** 4701eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error 4702eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the 4703eede6a53Sdan ** parser and some error code other than SQLITE_OK returned. 4704eede6a53Sdan */ 47058ce7184bSdan static int withExpand( 47068ce7184bSdan Walker *pWalker, 4707eede6a53Sdan struct SrcList_item *pFrom 47088ce7184bSdan ){ 47098ce7184bSdan Parse *pParse = pWalker->pParse; 47108ce7184bSdan sqlite3 *db = pParse->db; 471198f45e53Sdan struct Cte *pCte; /* Matched CTE (or NULL if no match) */ 471298f45e53Sdan With *pWith; /* WITH clause that pCte belongs to */ 47138ce7184bSdan 47148ce7184bSdan assert( pFrom->pTab==0 ); 471546a31cdfSdrh if( pParse->nErr ){ 471646a31cdfSdrh return SQLITE_ERROR; 471746a31cdfSdrh } 47188ce7184bSdan 471998f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 4720eae73fbfSdan if( pCte ){ 472198f45e53Sdan Table *pTab; 47228ce7184bSdan ExprList *pEList; 47238ce7184bSdan Select *pSel; 472460e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 4725f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 472698f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 4727f2655fe8Sdan 47280576bc59Sdrh /* If pCte->zCteErr is non-NULL at this point, then this is an illegal 4729f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 47300576bc59Sdrh ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. 4731f2655fe8Sdan ** In this case, proceed. */ 47320576bc59Sdrh if( pCte->zCteErr ){ 47330576bc59Sdrh sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); 473498f45e53Sdan return SQLITE_ERROR; 4735f2655fe8Sdan } 473620292310Sdrh if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; 47378ce7184bSdan 4738c25e2ebcSdrh assert( pFrom->pTab==0 ); 47398ce7184bSdan pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 47408ce7184bSdan if( pTab==0 ) return WRC_Abort; 474179df7782Sdrh pTab->nTabRef = 1; 47422d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 47438ce7184bSdan pTab->iPKey = -1; 4744cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4745fccda8a1Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 47468ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 4747fad3039cSmistachkin if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; 47488ce7184bSdan assert( pFrom->pSelect ); 47498ce7184bSdan 4750eae73fbfSdan /* Check if this is a recursive CTE. */ 47518ce7184bSdan pSel = pFrom->pSelect; 4752f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 4753f2655fe8Sdan if( bMayRecursive ){ 4754eae73fbfSdan int i; 4755eae73fbfSdan SrcList *pSrc = pFrom->pSelect->pSrc; 4756eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 4757eae73fbfSdan struct SrcList_item *pItem = &pSrc->a[i]; 4758eae73fbfSdan if( pItem->zDatabase==0 4759eae73fbfSdan && pItem->zName!=0 4760eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4761eae73fbfSdan ){ 4762eae73fbfSdan pItem->pTab = pTab; 47638a48b9c0Sdrh pItem->fg.isRecursive = 1; 476479df7782Sdrh pTab->nTabRef++; 4765eae73fbfSdan pSel->selFlags |= SF_Recursive; 47668ce7184bSdan } 4767eae73fbfSdan } 4768eae73fbfSdan } 4769eae73fbfSdan 4770eae73fbfSdan /* Only one recursive reference is permitted. */ 477179df7782Sdrh if( pTab->nTabRef>2 ){ 4772eae73fbfSdan sqlite3ErrorMsg( 4773727a99f1Sdrh pParse, "multiple references to recursive table: %s", pCte->zName 4774eae73fbfSdan ); 477598f45e53Sdan return SQLITE_ERROR; 4776eae73fbfSdan } 47773d240d21Sdrh assert( pTab->nTabRef==1 || 47783d240d21Sdrh ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); 4779eae73fbfSdan 47800576bc59Sdrh pCte->zCteErr = "circular reference: %s"; 478198f45e53Sdan pSavedWith = pParse->pWith; 478298f45e53Sdan pParse->pWith = pWith; 4783067cd837Sdan if( bMayRecursive ){ 4784067cd837Sdan Select *pPrior = pSel->pPrior; 4785067cd837Sdan assert( pPrior->pWith==0 ); 4786067cd837Sdan pPrior->pWith = pSel->pWith; 4787067cd837Sdan sqlite3WalkSelect(pWalker, pPrior); 4788067cd837Sdan pPrior->pWith = 0; 4789067cd837Sdan }else{ 4790067cd837Sdan sqlite3WalkSelect(pWalker, pSel); 4791067cd837Sdan } 47926e772266Sdrh pParse->pWith = pWith; 47938ce7184bSdan 47948ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 47958ce7184bSdan pEList = pLeft->pEList; 479660e7068dSdan if( pCte->pCols ){ 47978f9d0b2bSdrh if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ 4798727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 479960e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 480060e7068dSdan ); 480198f45e53Sdan pParse->pWith = pSavedWith; 480298f45e53Sdan return SQLITE_ERROR; 48038ce7184bSdan } 480460e7068dSdan pEList = pCte->pCols; 480560e7068dSdan } 48068ce7184bSdan 48078981b904Sdrh sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4808f2655fe8Sdan if( bMayRecursive ){ 4809f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 48100576bc59Sdrh pCte->zCteErr = "multiple recursive references: %s"; 4811f2655fe8Sdan }else{ 48120576bc59Sdrh pCte->zCteErr = "recursive reference in a subquery: %s"; 4813f2655fe8Sdan } 4814f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 4815f2655fe8Sdan } 48160576bc59Sdrh pCte->zCteErr = 0; 481798f45e53Sdan pParse->pWith = pSavedWith; 48188ce7184bSdan } 48198ce7184bSdan 48208ce7184bSdan return SQLITE_OK; 48218ce7184bSdan } 4822eede6a53Sdan #endif 48234e9119d9Sdan 4824b290f117Sdan #ifndef SQLITE_OMIT_CTE 482571856944Sdan /* 482671856944Sdan ** If the SELECT passed as the second argument has an associated WITH 482771856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 482871856944Sdan ** 482971856944Sdan ** This function is used as the xSelectCallback2() callback by 483071856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 483171856944Sdan ** names and other FROM clause elements. 483271856944Sdan */ 4833b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){ 4834b290f117Sdan Parse *pParse = pWalker->pParse; 48352f65b2f5Sdrh if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ 4836d227a291Sdrh With *pWith = findRightmost(p)->pWith; 4837d227a291Sdrh if( pWith!=0 ){ 483870a32703Sdan assert( pParse->pWith==pWith || pParse->nErr ); 4839d227a291Sdrh pParse->pWith = pWith->pOuter; 4840b290f117Sdan } 4841b290f117Sdan } 4842067cd837Sdan } 4843b290f117Sdan #else 4844b290f117Sdan #define selectPopWith 0 4845b290f117Sdan #endif 4846b290f117Sdan 48479a94722dSdan /* 48489a94722dSdan ** The SrcList_item structure passed as the second argument represents a 48499a94722dSdan ** sub-query in the FROM clause of a SELECT statement. This function 48509a94722dSdan ** allocates and populates the SrcList_item.pTab object. If successful, 48519a94722dSdan ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered, 48529a94722dSdan ** SQLITE_NOMEM. 48539a94722dSdan */ 4854dfa552f4Sdan int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){ 485586fb6e17Sdan Select *pSel = pFrom->pSelect; 485686fb6e17Sdan Table *pTab; 485786fb6e17Sdan 48589a94722dSdan assert( pSel ); 485986fb6e17Sdan pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table)); 48609a94722dSdan if( pTab==0 ) return SQLITE_NOMEM; 486186fb6e17Sdan pTab->nTabRef = 1; 486286fb6e17Sdan if( pFrom->zAlias ){ 486386fb6e17Sdan pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias); 486486fb6e17Sdan }else{ 4865fef37760Sdrh pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId); 486686fb6e17Sdan } 486786fb6e17Sdan while( pSel->pPrior ){ pSel = pSel->pPrior; } 486886fb6e17Sdan sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); 486986fb6e17Sdan pTab->iPKey = -1; 487086fb6e17Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 487186fb6e17Sdan pTab->tabFlags |= TF_Ephemeral; 487286fb6e17Sdan 4873f4b33153Sdrh return pParse->nErr ? SQLITE_ERROR : SQLITE_OK; 487486fb6e17Sdan } 487586fb6e17Sdan 4876b1c685b0Sdanielk1977 /* 48777d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 48787d10d5a6Sdrh ** "Expanding" means to do the following: 48797d10d5a6Sdrh ** 48807d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 48817d10d5a6Sdrh ** element of the FROM clause. 48827d10d5a6Sdrh ** 48837d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 48847d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 48857d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 48867d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 48877d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 488860ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 48897d10d5a6Sdrh ** of the view. 48907d10d5a6Sdrh ** 489160ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 48927d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 48937d10d5a6Sdrh ** 48947d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 48957d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 48967d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 48977d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 48987d10d5a6Sdrh ** 4899b3bce662Sdanielk1977 */ 49007d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 49017d10d5a6Sdrh Parse *pParse = pWalker->pParse; 49027d10d5a6Sdrh int i, j, k; 49037d10d5a6Sdrh SrcList *pTabList; 49047d10d5a6Sdrh ExprList *pEList; 49057d10d5a6Sdrh struct SrcList_item *pFrom; 49067d10d5a6Sdrh sqlite3 *db = pParse->db; 49073e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 4908785097daSdrh u16 selFlags = p->selFlags; 4909fca23557Sdrh u32 elistFlags = 0; 49107d10d5a6Sdrh 4911785097daSdrh p->selFlags |= SF_Expanded; 49127d10d5a6Sdrh if( db->mallocFailed ){ 49137d10d5a6Sdrh return WRC_Abort; 49147d10d5a6Sdrh } 49159d9c41e2Sdrh assert( p->pSrc!=0 ); 49169d9c41e2Sdrh if( (selFlags & SF_Expanded)!=0 ){ 49177d10d5a6Sdrh return WRC_Prune; 49187d10d5a6Sdrh } 491959145813Sdrh if( pWalker->eCode ){ 492059145813Sdrh /* Renumber selId because it has been copied from a view */ 492159145813Sdrh p->selId = ++pParse->nSelect; 492259145813Sdrh } 49237d10d5a6Sdrh pTabList = p->pSrc; 49247d10d5a6Sdrh pEList = p->pEList; 4925067cd837Sdan sqlite3WithPush(pParse, p->pWith, 0); 49267d10d5a6Sdrh 49277d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 49287d10d5a6Sdrh ** the FROM clause of the SELECT statement. 49297d10d5a6Sdrh */ 49307d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 49317d10d5a6Sdrh 49327d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 49337d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 49347d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 49357d10d5a6Sdrh */ 49367d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 49377d10d5a6Sdrh Table *pTab; 4938e2b7d7a0Sdrh assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); 49398a48b9c0Sdrh if( pFrom->fg.isRecursive ) continue; 4940e2b7d7a0Sdrh assert( pFrom->pTab==0 ); 49414e9119d9Sdan #ifndef SQLITE_OMIT_CTE 4942eede6a53Sdan if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4943eede6a53Sdan if( pFrom->pTab ) {} else 49444e9119d9Sdan #endif 49457d10d5a6Sdrh if( pFrom->zName==0 ){ 49467d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 49477d10d5a6Sdrh Select *pSel = pFrom->pSelect; 49487d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 49497d10d5a6Sdrh assert( pSel!=0 ); 49507d10d5a6Sdrh assert( pFrom->pTab==0 ); 49512b8c5a00Sdrh if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; 4952dfa552f4Sdan if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort; 495386fb6e17Sdan #endif 49547d10d5a6Sdrh }else{ 49557d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 49567d10d5a6Sdrh assert( pFrom->pTab==0 ); 495741fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 49587d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 495979df7782Sdrh if( pTab->nTabRef>=0xffff ){ 4960d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 4961d2a56238Sdrh pTab->zName); 4962d2a56238Sdrh pFrom->pTab = 0; 4963d2a56238Sdrh return WRC_Abort; 4964d2a56238Sdrh } 496579df7782Sdrh pTab->nTabRef++; 496620292310Sdrh if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ 496720292310Sdrh return WRC_Abort; 496820292310Sdrh } 49698c812f98Sdan #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 497020292310Sdrh if( IsVirtual(pTab) || pTab->pSelect ){ 4971bfad7be7Sdrh i16 nCol; 497259145813Sdrh u8 eCodeOrig = pWalker->eCode; 49737d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 497443152cf8Sdrh assert( pFrom->pSelect==0 ); 497511d88e68Sdrh if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){ 497611d88e68Sdrh sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited", 497711d88e68Sdrh pTab->zName); 49783f68142bSdrh } 49798c812f98Sdan #ifndef SQLITE_OMIT_VIRTUALTABLE 49803f68142bSdrh if( IsVirtual(pTab) 49813f68142bSdrh && pFrom->fg.fromDDL 49823f68142bSdrh && ALWAYS(pTab->pVTable!=0) 49833f68142bSdrh && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0) 49843f68142bSdrh ){ 498532266a10Sdrh sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"", 498632266a10Sdrh pTab->zName); 498711d88e68Sdrh } 49888c812f98Sdan #endif 49896ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 4990bfad7be7Sdrh nCol = pTab->nCol; 4991bfad7be7Sdrh pTab->nCol = -1; 499259145813Sdrh pWalker->eCode = 1; /* Turn on Select.selId renumbering */ 49937d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 499459145813Sdrh pWalker->eCode = eCodeOrig; 4995bfad7be7Sdrh pTab->nCol = nCol; 49967d10d5a6Sdrh } 49977d10d5a6Sdrh #endif 49987d10d5a6Sdrh } 499985574e31Sdanielk1977 500085574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 5001b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 500285574e31Sdanielk1977 return WRC_Abort; 500385574e31Sdanielk1977 } 50047d10d5a6Sdrh } 50057d10d5a6Sdrh 50067d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 50077d10d5a6Sdrh */ 5008a6c1a71cSdan if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 50097d10d5a6Sdrh return WRC_Abort; 50107d10d5a6Sdrh } 50117d10d5a6Sdrh 50127d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 50137d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 50147d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 50151a1d3cd2Sdrh ** with the TK_ASTERISK operator for each "*" that it found in the column 50161a1d3cd2Sdrh ** list. The following code just has to locate the TK_ASTERISK 50171a1d3cd2Sdrh ** expressions and expand each one to the list of all columns in 50181a1d3cd2Sdrh ** all tables. 50197d10d5a6Sdrh ** 50207d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 50217d10d5a6Sdrh ** that need expanding. 50227d10d5a6Sdrh */ 50237d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 50243e3f1a5bSdrh pE = pEList->a[k].pExpr; 50251a1d3cd2Sdrh if( pE->op==TK_ASTERISK ) break; 502643152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 502743152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 50281a1d3cd2Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; 5029fca23557Sdrh elistFlags |= pE->flags; 50307d10d5a6Sdrh } 50317d10d5a6Sdrh if( k<pEList->nExpr ){ 50327d10d5a6Sdrh /* 50337d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 50347d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 50357d10d5a6Sdrh ** in the result set and expand them one by one. 50367d10d5a6Sdrh */ 50377d10d5a6Sdrh struct ExprList_item *a = pEList->a; 50387d10d5a6Sdrh ExprList *pNew = 0; 50397d10d5a6Sdrh int flags = pParse->db->flags; 50407d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 504138b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 504238b384a0Sdrh 50437d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 50443e3f1a5bSdrh pE = a[k].pExpr; 5045fca23557Sdrh elistFlags |= pE->flags; 50463e3f1a5bSdrh pRight = pE->pRight; 50473e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 50481a1d3cd2Sdrh if( pE->op!=TK_ASTERISK 50491a1d3cd2Sdrh && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) 50501a1d3cd2Sdrh ){ 50517d10d5a6Sdrh /* This particular expression does not need to be expanded. 50527d10d5a6Sdrh */ 5053b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 50547d10d5a6Sdrh if( pNew ){ 505541cee668Sdrh pNew->a[pNew->nExpr-1].zEName = a[k].zEName; 5056cbb9da33Sdrh pNew->a[pNew->nExpr-1].eEName = a[k].eEName; 505741cee668Sdrh a[k].zEName = 0; 50587d10d5a6Sdrh } 50597d10d5a6Sdrh a[k].pExpr = 0; 50607d10d5a6Sdrh }else{ 50617d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 50627d10d5a6Sdrh ** expanded. */ 50637d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 50643e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 506543152cf8Sdrh if( pE->op==TK_DOT ){ 506643152cf8Sdrh assert( pE->pLeft!=0 ); 506733e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 506833e619fcSdrh zTName = pE->pLeft->u.zToken; 50697d10d5a6Sdrh } 50707d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 50717d10d5a6Sdrh Table *pTab = pFrom->pTab; 50723e3f1a5bSdrh Select *pSub = pFrom->pSelect; 50737d10d5a6Sdrh char *zTabName = pFrom->zAlias; 50743e3f1a5bSdrh const char *zSchemaName = 0; 5075c75e09c7Sdrh int iDb; 507643152cf8Sdrh if( zTabName==0 ){ 50777d10d5a6Sdrh zTabName = pTab->zName; 50787d10d5a6Sdrh } 50797d10d5a6Sdrh if( db->mallocFailed ) break; 50803e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 50813e3f1a5bSdrh pSub = 0; 50827d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 50837d10d5a6Sdrh continue; 50847d10d5a6Sdrh } 50853e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 508669c33826Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; 50873e3f1a5bSdrh } 50887d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 50897d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 5090b7916a78Sdrh char *zColname; /* The computed column name */ 5091b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 5092b7916a78Sdrh Token sColname; /* Computed column name as a token */ 50937d10d5a6Sdrh 5094c75e09c7Sdrh assert( zName ); 50953e3f1a5bSdrh if( zTName && pSub 5096c4938ea2Sdrh && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0 50973e3f1a5bSdrh ){ 50983e3f1a5bSdrh continue; 50993e3f1a5bSdrh } 51003e3f1a5bSdrh 510180090f92Sdrh /* If a column is marked as 'hidden', omit it from the expanded 510280090f92Sdrh ** result-set list unless the SELECT has the SF_IncludeHidden 510380090f92Sdrh ** bit set. 51047d10d5a6Sdrh */ 510580090f92Sdrh if( (p->selFlags & SF_IncludeHidden)==0 510680090f92Sdrh && IsHiddenColumn(&pTab->aCol[j]) 510780090f92Sdrh ){ 51087d10d5a6Sdrh continue; 51097d10d5a6Sdrh } 51103e3f1a5bSdrh tableSeen = 1; 51117d10d5a6Sdrh 5112da55c48aSdrh if( i>0 && zTName==0 ){ 51138a48b9c0Sdrh if( (pFrom->fg.jointype & JT_NATURAL)!=0 51149d41af23Sdan && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1) 51152179b434Sdrh ){ 51167d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 51172179b434Sdrh ** table to the right of the join */ 51187d10d5a6Sdrh continue; 51197d10d5a6Sdrh } 51202179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 51217d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 51227d10d5a6Sdrh ** using clause from the table on the right. */ 51237d10d5a6Sdrh continue; 51247d10d5a6Sdrh } 51257d10d5a6Sdrh } 5126b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 5127b7916a78Sdrh zColname = zName; 5128b7916a78Sdrh zToFree = 0; 51297d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 5130b7916a78Sdrh Expr *pLeft; 5131b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 5132abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); 513338b384a0Sdrh if( zSchemaName ){ 5134c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 5135abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); 5136c75e09c7Sdrh } 5137b7916a78Sdrh if( longNames ){ 5138b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 5139b7916a78Sdrh zToFree = zColname; 5140b7916a78Sdrh } 51417d10d5a6Sdrh }else{ 51427d10d5a6Sdrh pExpr = pRight; 51437d10d5a6Sdrh } 5144b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 514540aced5cSdrh sqlite3TokenInit(&sColname, zColname); 5146b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 51478f25d18bSdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ 51483e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 5149cbb9da33Sdrh sqlite3DbFree(db, pX->zEName); 51503e3f1a5bSdrh if( pSub ){ 5151cbb9da33Sdrh pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName); 5152cbb9da33Sdrh testcase( pX->zEName==0 ); 51533e3f1a5bSdrh }else{ 5154cbb9da33Sdrh pX->zEName = sqlite3MPrintf(db, "%s.%s.%s", 51553e3f1a5bSdrh zSchemaName, zTabName, zColname); 5156cbb9da33Sdrh testcase( pX->zEName==0 ); 51573e3f1a5bSdrh } 5158cbb9da33Sdrh pX->eEName = ENAME_TAB; 51598f25d18bSdrh } 5160b7916a78Sdrh sqlite3DbFree(db, zToFree); 51617d10d5a6Sdrh } 51627d10d5a6Sdrh } 51637d10d5a6Sdrh if( !tableSeen ){ 51647d10d5a6Sdrh if( zTName ){ 51657d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 51667d10d5a6Sdrh }else{ 51677d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 51687d10d5a6Sdrh } 51697d10d5a6Sdrh } 51707d10d5a6Sdrh } 51717d10d5a6Sdrh } 51727d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 51737d10d5a6Sdrh p->pEList = pNew; 51747d10d5a6Sdrh } 5175fca23557Sdrh if( p->pEList ){ 5176fca23557Sdrh if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 51777d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 51788836cbbcSdan return WRC_Abort; 51797d10d5a6Sdrh } 5180fca23557Sdrh if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ 5181fca23557Sdrh p->selFlags |= SF_ComplexResult; 5182fca23557Sdrh } 5183fca23557Sdrh } 51847d10d5a6Sdrh return WRC_Continue; 51857d10d5a6Sdrh } 51867d10d5a6Sdrh 51877d10d5a6Sdrh /* 51887d10d5a6Sdrh ** No-op routine for the parse-tree walker. 51897d10d5a6Sdrh ** 51907d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 51917d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 51927d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 51937d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 51947d10d5a6Sdrh ** subquery in the parser tree. 51957d10d5a6Sdrh */ 51965b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 519762c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 51987d10d5a6Sdrh return WRC_Continue; 51997d10d5a6Sdrh } 52007d10d5a6Sdrh 52017d10d5a6Sdrh /* 5202979dd1beSdrh ** No-op routine for the parse-tree walker for SELECT statements. 5203979dd1beSdrh ** subquery in the parser tree. 5204979dd1beSdrh */ 5205979dd1beSdrh int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ 5206979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 5207979dd1beSdrh return WRC_Continue; 5208979dd1beSdrh } 5209979dd1beSdrh 5210979dd1beSdrh #if SQLITE_DEBUG 5211979dd1beSdrh /* 5212979dd1beSdrh ** Always assert. This xSelectCallback2 implementation proves that the 5213979dd1beSdrh ** xSelectCallback2 is never invoked. 5214979dd1beSdrh */ 5215979dd1beSdrh void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ 5216979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 5217979dd1beSdrh assert( 0 ); 5218979dd1beSdrh } 5219979dd1beSdrh #endif 5220979dd1beSdrh /* 52217d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 52227d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 52237d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 52247d10d5a6Sdrh ** 52257d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 52267d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 52277d10d5a6Sdrh ** name resolution is performed. 52287d10d5a6Sdrh ** 52297d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 52307d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 52317d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 52327d10d5a6Sdrh */ 52337d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 52347d10d5a6Sdrh Walker w; 52355b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 52367d10d5a6Sdrh w.pParse = pParse; 5237878fcf9dSdrh if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ 5238d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 5239979dd1beSdrh w.xSelectCallback2 = 0; 52407d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 5241d58d3278Sdrh } 5242c01b7306Sdrh w.xSelectCallback = selectExpander; 5243b290f117Sdan w.xSelectCallback2 = selectPopWith; 524459145813Sdrh w.eCode = 0; 5245c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 52467d10d5a6Sdrh } 52477d10d5a6Sdrh 52487d10d5a6Sdrh 52497d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 52507d10d5a6Sdrh /* 52517d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 52527d10d5a6Sdrh ** interface. 52537d10d5a6Sdrh ** 52547d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 52557d10d5a6Sdrh ** information to the Table structure that represents the result set 52567d10d5a6Sdrh ** of that subquery. 52577d10d5a6Sdrh ** 52587d10d5a6Sdrh ** The Table structure that represents the result set was constructed 52597d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 52607d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 52617d10d5a6Sdrh ** routine is called after identifier resolution. 52627d10d5a6Sdrh */ 5263b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 52647d10d5a6Sdrh Parse *pParse; 52657d10d5a6Sdrh int i; 52667d10d5a6Sdrh SrcList *pTabList; 52677d10d5a6Sdrh struct SrcList_item *pFrom; 52687d10d5a6Sdrh 52699d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 5270cc464418Sdan if( p->selFlags & SF_HasTypeInfo ) return; 52717d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 52727d10d5a6Sdrh pParse = pWalker->pParse; 52737d10d5a6Sdrh pTabList = p->pSrc; 52747d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 52757d10d5a6Sdrh Table *pTab = pFrom->pTab; 5276e2b7d7a0Sdrh assert( pTab!=0 ); 5277e2b7d7a0Sdrh if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ 52787d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 52797d10d5a6Sdrh Select *pSel = pFrom->pSelect; 52808ce7184bSdan if( pSel ){ 52817d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 528296fb16eeSdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel, 528396fb16eeSdrh SQLITE_AFF_NONE); 52847d10d5a6Sdrh } 52857d10d5a6Sdrh } 52865a29d9cbSdrh } 52878ce7184bSdan } 52887d10d5a6Sdrh #endif 52897d10d5a6Sdrh 52907d10d5a6Sdrh 52917d10d5a6Sdrh /* 52927d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 52937d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 52947d10d5a6Sdrh ** SELECT statement. 52957d10d5a6Sdrh ** 52967d10d5a6Sdrh ** Use this routine after name resolution. 52977d10d5a6Sdrh */ 52987d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 52997d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 53007d10d5a6Sdrh Walker w; 5301979dd1beSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 5302b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 53035b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 53047d10d5a6Sdrh w.pParse = pParse; 53057d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 53067d10d5a6Sdrh #endif 53077d10d5a6Sdrh } 53087d10d5a6Sdrh 53097d10d5a6Sdrh 53107d10d5a6Sdrh /* 5311030796dfSdrh ** This routine sets up a SELECT statement for processing. The 53127d10d5a6Sdrh ** following is accomplished: 53137d10d5a6Sdrh ** 53147d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 53157d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 53167d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 53177d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 53187d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 53197d10d5a6Sdrh ** 53207d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 53217d10d5a6Sdrh */ 53227d10d5a6Sdrh void sqlite3SelectPrep( 5323b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 5324b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 53257d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 5326b3bce662Sdanielk1977 ){ 5327e2463398Sdrh assert( p!=0 || pParse->db->mallocFailed ); 5328e2463398Sdrh if( pParse->db->mallocFailed ) return; 53297d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 53307d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 5331b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 53327d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 5333b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 53347d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 5335f6bbe022Sdrh } 5336b3bce662Sdanielk1977 5337b3bce662Sdanielk1977 /* 533813449892Sdrh ** Reset the aggregate accumulator. 533913449892Sdrh ** 534013449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 534113449892Sdrh ** intermediate results while calculating an aggregate. This 5342030796dfSdrh ** routine generates code that stores NULLs in all of those memory 5343030796dfSdrh ** cells. 5344b3bce662Sdanielk1977 */ 534513449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 534613449892Sdrh Vdbe *v = pParse->pVdbe; 534713449892Sdrh int i; 5348c99130fdSdrh struct AggInfo_func *pFunc; 53497e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 53507e61d18eSdrh if( nReg==0 ) return; 53517e61d18eSdrh #ifdef SQLITE_DEBUG 53527e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 53537e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 53547e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 535513449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 53567e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 53577e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 535813449892Sdrh } 53597e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 53607e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 53617e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 53627e61d18eSdrh } 53637e61d18eSdrh #endif 53647e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 5365c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 5366c99130fdSdrh if( pFunc->iDistinct>=0 ){ 5367c99130fdSdrh Expr *pE = pFunc->pExpr; 53686ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 53696ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 53700daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 53710daa002cSdrh "argument"); 5372c99130fdSdrh pFunc->iDistinct = -1; 5373c99130fdSdrh }else{ 5374f9eae18bSdan KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0); 537566a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 53762ec2fb22Sdrh (char*)pKeyInfo, P4_KEYINFO); 5377c99130fdSdrh } 5378c99130fdSdrh } 537913449892Sdrh } 5380b3bce662Sdanielk1977 } 5381b3bce662Sdanielk1977 5382b3bce662Sdanielk1977 /* 538313449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 538413449892Sdrh ** in the AggInfo structure. 5385b3bce662Sdanielk1977 */ 538613449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 538713449892Sdrh Vdbe *v = pParse->pVdbe; 538813449892Sdrh int i; 538913449892Sdrh struct AggInfo_func *pF; 539013449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 53916ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 53926ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 53932700acaaSdrh sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); 53942700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5395b3bce662Sdanielk1977 } 539613449892Sdrh } 539713449892Sdrh 5398280c894bSdan 539913449892Sdrh /* 540013449892Sdrh ** Update the accumulator memory cells for an aggregate based on 540113449892Sdrh ** the current cursor position. 5402280c894bSdan ** 5403280c894bSdan ** If regAcc is non-zero and there are no min() or max() aggregates 5404280c894bSdan ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator 540510cc16c9Sdrh ** registers if register regAcc contains 0. The caller will take care 5406280c894bSdan ** of setting and clearing regAcc. 540713449892Sdrh */ 5408280c894bSdan static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){ 540913449892Sdrh Vdbe *v = pParse->pVdbe; 541013449892Sdrh int i; 54117a95789cSdrh int regHit = 0; 54127a95789cSdrh int addrHitTest = 0; 541313449892Sdrh struct AggInfo_func *pF; 541413449892Sdrh struct AggInfo_col *pC; 541513449892Sdrh 541613449892Sdrh pAggInfo->directMode = 1; 541713449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 541813449892Sdrh int nArg; 5419c99130fdSdrh int addrNext = 0; 542098757157Sdrh int regAgg; 54216ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 54226ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 54234f9adee2Sdan assert( !IsWindowFunc(pF->pExpr) ); 54244f9adee2Sdan if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){ 54254f9adee2Sdan Expr *pFilter = pF->pExpr->y.pWin->pFilter; 5426ed09dddeSdan if( pAggInfo->nAccumulator 5427ed09dddeSdan && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) 5428ed09dddeSdan ){ 5429ed09dddeSdan if( regHit==0 ) regHit = ++pParse->nMem; 5430ed09dddeSdan /* If this is the first row of the group (regAcc==0), clear the 5431ed09dddeSdan ** "magnet" register regHit so that the accumulator registers 5432af9b58b3Sdan ** are populated if the FILTER clause jumps over the the 5433af9b58b3Sdan ** invocation of min() or max() altogether. Or, if this is not 5434af9b58b3Sdan ** the first row (regAcc==1), set the magnet register so that the 5435af9b58b3Sdan ** accumulators are not populated unless the min()/max() is invoked and 5436af9b58b3Sdan ** indicates that they should be. */ 5437ed09dddeSdan sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit); 5438ed09dddeSdan } 54396ba7ab0dSdan addrNext = sqlite3VdbeMakeLabel(pParse); 54406ba7ab0dSdan sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL); 54416ba7ab0dSdan } 544213449892Sdrh if( pList ){ 544313449892Sdrh nArg = pList->nExpr; 5444892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 54455579d59fSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); 544613449892Sdrh }else{ 544713449892Sdrh nArg = 0; 544898757157Sdrh regAgg = 0; 544913449892Sdrh } 5450c99130fdSdrh if( pF->iDistinct>=0 ){ 54516ba7ab0dSdan if( addrNext==0 ){ 5452ec4ccdbcSdrh addrNext = sqlite3VdbeMakeLabel(pParse); 54536ba7ab0dSdan } 54547c052da5Sdrh testcase( nArg==0 ); /* Error condition */ 54557c052da5Sdrh testcase( nArg>1 ); /* Also an error */ 54562dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 5457c99130fdSdrh } 5458d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 545913449892Sdrh CollSeq *pColl = 0; 546013449892Sdrh struct ExprList_item *pItem; 546113449892Sdrh int j; 5462e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 546343617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 546413449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 546513449892Sdrh } 546613449892Sdrh if( !pColl ){ 546713449892Sdrh pColl = pParse->db->pDfltColl; 546813449892Sdrh } 54697a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 54707a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 547113449892Sdrh } 54728f26da6cSdrh sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem); 54732700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5474ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 5475f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 5476c99130fdSdrh if( addrNext ){ 5477c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 5478c99130fdSdrh } 547913449892Sdrh } 5480280c894bSdan if( regHit==0 && pAggInfo->nAccumulator ){ 5481280c894bSdan regHit = regAcc; 5482280c894bSdan } 54837a95789cSdrh if( regHit ){ 5484688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 54857a95789cSdrh } 548613449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 5487389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 548813449892Sdrh } 5489ed09dddeSdan 549013449892Sdrh pAggInfo->directMode = 0; 54917a95789cSdrh if( addrHitTest ){ 5492dc4f6fc0Sdrh sqlite3VdbeJumpHereOrPopInst(v, addrHitTest); 54937a95789cSdrh } 549413449892Sdrh } 549513449892Sdrh 5496b3bce662Sdanielk1977 /* 5497ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 5498ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 5499ef7075deSdan */ 5500ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 5501ef7075deSdan static void explainSimpleCount( 5502ef7075deSdan Parse *pParse, /* Parse context */ 5503ef7075deSdan Table *pTab, /* Table being queried */ 5504ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 5505ef7075deSdan ){ 5506ef7075deSdan if( pParse->explain==2 ){ 550748dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 5508e2ca99c9Sdrh sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s", 5509ef7075deSdan pTab->zName, 5510e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 5511e96f2df3Sdan bCover ? pIdx->zName : "" 5512ef7075deSdan ); 5513ef7075deSdan } 5514ef7075deSdan } 5515ef7075deSdan #else 5516ef7075deSdan # define explainSimpleCount(a,b,c) 5517ef7075deSdan #endif 5518ef7075deSdan 5519ef7075deSdan /* 5520ab31a845Sdan ** sqlite3WalkExpr() callback used by havingToWhere(). 5521ab31a845Sdan ** 5522ab31a845Sdan ** If the node passed to the callback is a TK_AND node, return 5523ab31a845Sdan ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes. 5524ab31a845Sdan ** 5525ab31a845Sdan ** Otherwise, return WRC_Prune. In this case, also check if the 5526ab31a845Sdan ** sub-expression matches the criteria for being moved to the WHERE 5527ab31a845Sdan ** clause. If so, add it to the WHERE clause and replace the sub-expression 5528ab31a845Sdan ** within the HAVING expression with a constant "1". 5529ab31a845Sdan */ 5530ab31a845Sdan static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ 5531ab31a845Sdan if( pExpr->op!=TK_AND ){ 5532cd0abc24Sdrh Select *pS = pWalker->u.pSelect; 5533cd0abc24Sdrh if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){ 5534ab31a845Sdan sqlite3 *db = pWalker->pParse->db; 55355776ee5cSdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1"); 5536ab31a845Sdan if( pNew ){ 5537cd0abc24Sdrh Expr *pWhere = pS->pWhere; 5538ab31a845Sdan SWAP(Expr, *pNew, *pExpr); 5539d5c851c1Sdrh pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew); 5540cd0abc24Sdrh pS->pWhere = pNew; 5541cd0abc24Sdrh pWalker->eCode = 1; 5542ab31a845Sdan } 5543ab31a845Sdan } 5544ab31a845Sdan return WRC_Prune; 5545ab31a845Sdan } 5546ab31a845Sdan return WRC_Continue; 5547ab31a845Sdan } 5548ab31a845Sdan 5549ab31a845Sdan /* 5550ab31a845Sdan ** Transfer eligible terms from the HAVING clause of a query, which is 5551ab31a845Sdan ** processed after grouping, to the WHERE clause, which is processed before 5552ab31a845Sdan ** grouping. For example, the query: 5553ab31a845Sdan ** 5554ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=? 5555ab31a845Sdan ** 5556ab31a845Sdan ** can be rewritten as: 5557ab31a845Sdan ** 5558ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=? 5559ab31a845Sdan ** 5560ab31a845Sdan ** A term of the HAVING expression is eligible for transfer if it consists 5561ab31a845Sdan ** entirely of constants and expressions that are also GROUP BY terms that 5562ab31a845Sdan ** use the "BINARY" collation sequence. 5563ab31a845Sdan */ 5564cd0abc24Sdrh static void havingToWhere(Parse *pParse, Select *p){ 5565ab31a845Sdan Walker sWalker; 5566ab31a845Sdan memset(&sWalker, 0, sizeof(sWalker)); 5567ab31a845Sdan sWalker.pParse = pParse; 5568ab31a845Sdan sWalker.xExprCallback = havingToWhereExprCb; 5569cd0abc24Sdrh sWalker.u.pSelect = p; 5570cd0abc24Sdrh sqlite3WalkExpr(&sWalker, p->pHaving); 5571cd0abc24Sdrh #if SELECTTRACE_ENABLED 5572cd0abc24Sdrh if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){ 5573cd0abc24Sdrh SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); 5574cd0abc24Sdrh sqlite3TreeViewSelect(0, p, 0); 5575cd0abc24Sdrh } 5576cd0abc24Sdrh #endif 5577ab31a845Sdan } 5578ab31a845Sdan 5579ab31a845Sdan /* 5580e08e8d6bSdrh ** Check to see if the pThis entry of pTabList is a self-join of a prior view. 5581e08e8d6bSdrh ** If it is, then return the SrcList_item for the prior view. If it is not, 5582e08e8d6bSdrh ** then return 0. 5583e08e8d6bSdrh */ 5584e08e8d6bSdrh static struct SrcList_item *isSelfJoinView( 5585e08e8d6bSdrh SrcList *pTabList, /* Search for self-joins in this FROM clause */ 5586e08e8d6bSdrh struct SrcList_item *pThis /* Search for prior reference to this subquery */ 5587e08e8d6bSdrh ){ 5588e08e8d6bSdrh struct SrcList_item *pItem; 5589e08e8d6bSdrh for(pItem = pTabList->a; pItem<pThis; pItem++){ 5590bdefaf08Sdrh Select *pS1; 5591e08e8d6bSdrh if( pItem->pSelect==0 ) continue; 5592e08e8d6bSdrh if( pItem->fg.viaCoroutine ) continue; 559333543c23Sdrh if( pItem->zName==0 ) continue; 559430ad79aeSdrh assert( pItem->pTab!=0 ); 559530ad79aeSdrh assert( pThis->pTab!=0 ); 559630ad79aeSdrh if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue; 5597ed712980Sdrh if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; 5598bdefaf08Sdrh pS1 = pItem->pSelect; 559930ad79aeSdrh if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){ 5600bdefaf08Sdrh /* The query flattener left two different CTE tables with identical 5601bdefaf08Sdrh ** names in the same FROM clause. */ 5602bdefaf08Sdrh continue; 5603bdefaf08Sdrh } 5604ac4085bcSdan if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1) 5605ac4085bcSdan || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1) 5606ac4085bcSdan ){ 5607ed712980Sdrh /* The view was modified by some other optimization such as 5608ed712980Sdrh ** pushDownWhereTerms() */ 5609ed712980Sdrh continue; 5610ed712980Sdrh } 5611ed712980Sdrh return pItem; 5612e08e8d6bSdrh } 5613e08e8d6bSdrh return 0; 5614e08e8d6bSdrh } 5615e08e8d6bSdrh 5616269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5617269ba804Sdrh /* 5618269ba804Sdrh ** Attempt to transform a query of the form 5619269ba804Sdrh ** 5620269ba804Sdrh ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) 5621269ba804Sdrh ** 5622269ba804Sdrh ** Into this: 5623269ba804Sdrh ** 5624269ba804Sdrh ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) 5625269ba804Sdrh ** 5626269ba804Sdrh ** The transformation only works if all of the following are true: 5627269ba804Sdrh ** 5628269ba804Sdrh ** * The subquery is a UNION ALL of two or more terms 5629a4b5fb55Sdan ** * The subquery does not have a LIMIT clause 5630269ba804Sdrh ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries 563173c53b39Sdrh ** * The outer query is a simple count(*) with no WHERE clause or other 563273c53b39Sdrh ** extraneous syntax. 5633269ba804Sdrh ** 5634269ba804Sdrh ** Return TRUE if the optimization is undertaken. 5635269ba804Sdrh */ 5636269ba804Sdrh static int countOfViewOptimization(Parse *pParse, Select *p){ 5637269ba804Sdrh Select *pSub, *pPrior; 5638269ba804Sdrh Expr *pExpr; 5639269ba804Sdrh Expr *pCount; 5640269ba804Sdrh sqlite3 *db; 56413d240d21Sdrh if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ 5642269ba804Sdrh if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ 564373c53b39Sdrh if( p->pWhere ) return 0; 564473c53b39Sdrh if( p->pGroupBy ) return 0; 5645269ba804Sdrh pExpr = p->pEList->a[0].pExpr; 5646269ba804Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ 56473d240d21Sdrh if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ 5648269ba804Sdrh if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ 56493d240d21Sdrh if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ 5650269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5651269ba804Sdrh if( pSub==0 ) return 0; /* The FROM is a subquery */ 56523d240d21Sdrh if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ 5653269ba804Sdrh do{ 5654269ba804Sdrh if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ 5655269ba804Sdrh if( pSub->pWhere ) return 0; /* No WHERE clause */ 5656a4b5fb55Sdan if( pSub->pLimit ) return 0; /* No LIMIT clause */ 5657269ba804Sdrh if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ 56583d240d21Sdrh pSub = pSub->pPrior; /* Repeat over compound */ 5659269ba804Sdrh }while( pSub ); 5660269ba804Sdrh 56613d240d21Sdrh /* If we reach this point then it is OK to perform the transformation */ 5662269ba804Sdrh 5663269ba804Sdrh db = pParse->db; 5664269ba804Sdrh pCount = pExpr; 5665269ba804Sdrh pExpr = 0; 5666269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5667269ba804Sdrh p->pSrc->a[0].pSelect = 0; 5668269ba804Sdrh sqlite3SrcListDelete(db, p->pSrc); 5669269ba804Sdrh p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); 5670269ba804Sdrh while( pSub ){ 5671269ba804Sdrh Expr *pTerm; 5672269ba804Sdrh pPrior = pSub->pPrior; 5673269ba804Sdrh pSub->pPrior = 0; 5674269ba804Sdrh pSub->pNext = 0; 5675269ba804Sdrh pSub->selFlags |= SF_Aggregate; 5676269ba804Sdrh pSub->selFlags &= ~SF_Compound; 5677269ba804Sdrh pSub->nSelectRow = 0; 5678269ba804Sdrh sqlite3ExprListDelete(db, pSub->pEList); 5679269ba804Sdrh pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; 5680269ba804Sdrh pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm); 5681269ba804Sdrh pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0); 5682269ba804Sdrh sqlite3PExprAddSelect(pParse, pTerm, pSub); 5683269ba804Sdrh if( pExpr==0 ){ 5684269ba804Sdrh pExpr = pTerm; 5685269ba804Sdrh }else{ 5686269ba804Sdrh pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); 5687269ba804Sdrh } 5688269ba804Sdrh pSub = pPrior; 5689269ba804Sdrh } 5690269ba804Sdrh p->pEList->a[0].pExpr = pExpr; 5691269ba804Sdrh p->selFlags &= ~SF_Aggregate; 5692269ba804Sdrh 5693269ba804Sdrh #if SELECTTRACE_ENABLED 5694269ba804Sdrh if( sqlite3SelectTrace & 0x400 ){ 5695269ba804Sdrh SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); 5696269ba804Sdrh sqlite3TreeViewSelect(0, p, 0); 5697269ba804Sdrh } 5698269ba804Sdrh #endif 5699269ba804Sdrh return 1; 5700269ba804Sdrh } 5701269ba804Sdrh #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ 5702269ba804Sdrh 5703e08e8d6bSdrh /* 57047d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 57059bb61fe7Sdrh ** 5706340309fdSdrh ** The results are returned according to the SelectDest structure. 5707340309fdSdrh ** See comments in sqliteInt.h for further information. 5708e78e8284Sdrh ** 57099bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 57109bb61fe7Sdrh ** encountered, then an appropriate error message is left in 57119bb61fe7Sdrh ** pParse->zErrMsg. 57129bb61fe7Sdrh ** 57139bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 57149bb61fe7Sdrh ** calling function needs to do that. 57159bb61fe7Sdrh */ 57164adee20fSdanielk1977 int sqlite3Select( 5717cce7d176Sdrh Parse *pParse, /* The parser context */ 57189bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 57197d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 5720cce7d176Sdrh ){ 572113449892Sdrh int i, j; /* Loop counters */ 572213449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 572313449892Sdrh Vdbe *v; /* The virtual machine under construction */ 5724b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 5725c29cbb0bSmistachkin ExprList *pEList = 0; /* List of columns to extract. */ 5726ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 57279bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 57282282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 57292282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 57301d83f052Sdrh int rc = 1; /* Value to return from this function */ 5731e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 5732079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 573313449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 5734ec7429aeSdrh int iEnd; /* Address of the end of the query */ 573517435752Sdrh sqlite3 *db; /* The database connection */ 573647d9f839Sdrh ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ 573747d9f839Sdrh u8 minMaxFlag; /* Flag for min/max queries */ 57389bb61fe7Sdrh 573917435752Sdrh db = pParse->db; 5740e2ca99c9Sdrh v = sqlite3GetVdbe(pParse); 574117435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 57426f7adc8aSdrh return 1; 57436f7adc8aSdrh } 57444adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 574513449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 5746e2ca99c9Sdrh #if SELECTTRACE_ENABLED 5747e2ca99c9Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain)); 5748c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 5749c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 5750c90713d3Sdrh } 5751eb9b884cSdrh #endif 5752daffd0e5Sdrh 57538e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 57548e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 57559afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 57569afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 57576c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 57589ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 57599afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 57608e1ee88cSdrh pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || 57618e1ee88cSdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); 5762ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 5763ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 5764ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 5765ccfcbceaSdrh p->pOrderBy = 0; 57667d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 57679a99334dSdrh } 57687d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 5769956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 57709a99334dSdrh goto select_end; 57719a99334dSdrh } 5772adc57f68Sdrh assert( p->pEList!=0 ); 577317645f5eSdrh #if SELECTTRACE_ENABLED 5774e2243d26Sdrh if( sqlite3SelectTrace & 0x104 ){ 5775e2243d26Sdrh SELECTTRACE(0x104,pParse,p, ("after name resolution:\n")); 577617645f5eSdrh sqlite3TreeViewSelect(0, p, 0); 577717645f5eSdrh } 577817645f5eSdrh #endif 5779cce7d176Sdrh 5780f35f2f92Sdrh if( pDest->eDest==SRT_Output ){ 5781f35f2f92Sdrh generateColumnNames(pParse, p); 5782f35f2f92Sdrh } 5783f35f2f92Sdrh 578467a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 5785a9ebfe20Sdrh rc = sqlite3WindowRewrite(pParse, p); 5786a9ebfe20Sdrh if( rc ){ 5787aaa5ba06Sdrh assert( db->mallocFailed || pParse->nErr>0 ); 578886fb6e17Sdan goto select_end; 578986fb6e17Sdan } 5790dfa552f4Sdan #if SELECTTRACE_ENABLED 5791a0fe5fe5Sdrh if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){ 5792dfa552f4Sdan SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n")); 5793dfa552f4Sdan sqlite3TreeViewSelect(0, p, 0); 5794dfa552f4Sdan } 5795dfa552f4Sdan #endif 579667a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 579786fb6e17Sdan pTabList = p->pSrc; 57987392569fSdan isAgg = (p->selFlags & SF_Aggregate)!=0; 5799f02cdd37Sdan memset(&sSort, 0, sizeof(sSort)); 5800f02cdd37Sdan sSort.pOrderBy = p->pOrderBy; 580186fb6e17Sdan 58022589787cSdrh /* Try to various optimizations (flattening subqueries, and strength 58032589787cSdrh ** reduction of join operators) in the FROM clause up into the main query 5804d820cb1bSdrh */ 580551522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5806f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 580713449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 5808daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 58092679f14fSdrh Table *pTab = pItem->pTab; 58102589787cSdrh 58112589787cSdrh /* Convert LEFT JOIN into JOIN if there are terms of the right table 58122589787cSdrh ** of the LEFT JOIN used in the WHERE clause. 58132589787cSdrh */ 58142589787cSdrh if( (pItem->fg.jointype & JT_LEFT)!=0 58152589787cSdrh && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) 58162589787cSdrh && OptimizationEnabled(db, SQLITE_SimplifyJoin) 58172589787cSdrh ){ 58182589787cSdrh SELECTTRACE(0x100,pParse,p, 58192589787cSdrh ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); 5820efce69deSdrh pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); 58212589787cSdrh unsetJoinExpr(p->pWhere, pItem->iCursor); 58222589787cSdrh } 58232589787cSdrh 58242589787cSdrh /* No futher action if this term of the FROM clause is no a subquery */ 58254490c40bSdrh if( pSub==0 ) continue; 58262679f14fSdrh 58272679f14fSdrh /* Catch mismatch in the declared columns of a view and the number of 58282679f14fSdrh ** columns in the SELECT on the RHS */ 58292679f14fSdrh if( pTab->nCol!=pSub->pEList->nExpr ){ 58302679f14fSdrh sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", 58312679f14fSdrh pTab->nCol, pTab->zName, pSub->pEList->nExpr); 58322679f14fSdrh goto select_end; 58332679f14fSdrh } 58342679f14fSdrh 583525c221ebSdrh /* Do not try to flatten an aggregate subquery. 583625c221ebSdrh ** 583725c221ebSdrh ** Flattening an aggregate subquery is only possible if the outer query 583825c221ebSdrh ** is not a join. But if the outer query is not a join, then the subquery 583925c221ebSdrh ** will be implemented as a co-routine and there is no advantage to 584025c221ebSdrh ** flattening in that case. 584125c221ebSdrh */ 584225c221ebSdrh if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; 584325c221ebSdrh assert( pSub->pGroupBy==0 ); 584425c221ebSdrh 5845fca23557Sdrh /* If the outer query contains a "complex" result set (that is, 5846fca23557Sdrh ** if the result set of the outer query uses functions or subqueries) 5847fca23557Sdrh ** and if the subquery contains an ORDER BY clause and if 5848648fe49fSdrh ** it will be implemented as a co-routine, then do not flatten. This 5849648fe49fSdrh ** restriction allows SQL constructs like this: 5850648fe49fSdrh ** 5851648fe49fSdrh ** SELECT expensive_function(x) 5852648fe49fSdrh ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5853648fe49fSdrh ** 5854648fe49fSdrh ** The expensive_function() is only computed on the 10 rows that 5855648fe49fSdrh ** are output, rather than every row of the table. 5856fca23557Sdrh ** 5857fca23557Sdrh ** The requirement that the outer query have a complex result set 5858fca23557Sdrh ** means that flattening does occur on simpler SQL constraints without 5859fca23557Sdrh ** the expensive_function() like: 5860fca23557Sdrh ** 5861fca23557Sdrh ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5862648fe49fSdrh */ 586325c221ebSdrh if( pSub->pOrderBy!=0 5864648fe49fSdrh && i==0 5865fca23557Sdrh && (p->selFlags & SF_ComplexResult)!=0 5866648fe49fSdrh && (pTabList->nSrc==1 5867648fe49fSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) 5868648fe49fSdrh ){ 5869648fe49fSdrh continue; 5870648fe49fSdrh } 5871648fe49fSdrh 587225c221ebSdrh if( flattenSubquery(pParse, p, i, isAgg) ){ 58734acd754cSdrh if( pParse->nErr ) goto select_end; 58744490c40bSdrh /* This subquery can be absorbed into its parent. */ 58754490c40bSdrh i = -1; 58764490c40bSdrh } 58774490c40bSdrh pTabList = p->pSrc; 58784490c40bSdrh if( db->mallocFailed ) goto select_end; 58794490c40bSdrh if( !IgnorableOrderby(pDest) ){ 58804490c40bSdrh sSort.pOrderBy = p->pOrderBy; 58814490c40bSdrh } 58824490c40bSdrh } 58834490c40bSdrh #endif 58844490c40bSdrh 58854490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 58864490c40bSdrh /* Handle compound SELECT statements using the separate multiSelect() 58874490c40bSdrh ** procedure. 58884490c40bSdrh */ 58894490c40bSdrh if( p->pPrior ){ 58904490c40bSdrh rc = multiSelect(pParse, p, pDest); 58914490c40bSdrh #if SELECTTRACE_ENABLED 5892f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end compound-select processing\n")); 5893e2ca99c9Sdrh if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 5894f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 5895f20609d1Sdrh } 58964490c40bSdrh #endif 5897c631ded5Sdrh if( p->pNext==0 ) ExplainQueryPlanPop(pParse); 58984490c40bSdrh return rc; 58994490c40bSdrh } 59004490c40bSdrh #endif 59014490c40bSdrh 59027810ab64Sdrh /* Do the WHERE-clause constant propagation optimization if this is 59037810ab64Sdrh ** a join. No need to speed time on this operation for non-join queries 59047810ab64Sdrh ** as the equivalent optimization will be handled by query planner in 59057810ab64Sdrh ** sqlite3WhereBegin(). 59067810ab64Sdrh */ 59077810ab64Sdrh if( pTabList->nSrc>1 59087810ab64Sdrh && OptimizationEnabled(db, SQLITE_PropagateConst) 590924e1116eSdrh && propagateConstants(pParse, p) 591024e1116eSdrh ){ 591124e1116eSdrh #if SELECTTRACE_ENABLED 591224e1116eSdrh if( sqlite3SelectTrace & 0x100 ){ 591324e1116eSdrh SELECTTRACE(0x100,pParse,p,("After constant propagation:\n")); 591424e1116eSdrh sqlite3TreeViewSelect(0, p, 0); 591524e1116eSdrh } 591624e1116eSdrh #endif 591724e1116eSdrh }else{ 59187810ab64Sdrh SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n")); 591924e1116eSdrh } 592024e1116eSdrh 5921a4b5fb55Sdan #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5922a4b5fb55Sdan if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) 5923a4b5fb55Sdan && countOfViewOptimization(pParse, p) 5924a4b5fb55Sdan ){ 5925a4b5fb55Sdan if( db->mallocFailed ) goto select_end; 5926a4b5fb55Sdan pEList = p->pEList; 5927a4b5fb55Sdan pTabList = p->pSrc; 5928a4b5fb55Sdan } 5929a4b5fb55Sdan #endif 5930a4b5fb55Sdan 5931701caf1eSdrh /* For each term in the FROM clause, do two things: 5932701caf1eSdrh ** (1) Authorized unreferenced tables 5933701caf1eSdrh ** (2) Generate code for all sub-queries 5934d820cb1bSdrh */ 59354490c40bSdrh for(i=0; i<pTabList->nSrc; i++){ 5936742f947bSdanielk1977 struct SrcList_item *pItem = &pTabList->a[i]; 5937c31c2eb8Sdrh SelectDest dest; 5938701caf1eSdrh Select *pSub; 5939824d21afSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5940824d21afSdrh const char *zSavedAuthContext; 5941824d21afSdrh #endif 5942701caf1eSdrh 59433d240d21Sdrh /* Issue SQLITE_READ authorizations with a fake column name for any 59443d240d21Sdrh ** tables that are referenced but from which no values are extracted. 59453d240d21Sdrh ** Examples of where these kinds of null SQLITE_READ authorizations 59463d240d21Sdrh ** would occur: 5947701caf1eSdrh ** 59482336c935Sdrh ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" 59492336c935Sdrh ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" 59502336c935Sdrh ** 59512336c935Sdrh ** The fake column name is an empty string. It is possible for a table to 59522336c935Sdrh ** have a column named by the empty string, in which case there is no way to 59532336c935Sdrh ** distinguish between an unreferenced table and an actual reference to the 59542336c935Sdrh ** "" column. The original design was for the fake column name to be a NULL, 59552336c935Sdrh ** which would be unambiguous. But legacy authorization callbacks might 59563d240d21Sdrh ** assume the column name is non-NULL and segfault. The use of an empty 59573d240d21Sdrh ** string for the fake column name seems safer. 5958701caf1eSdrh */ 595974c490e0Sdrh if( pItem->colUsed==0 && pItem->zName!=0 ){ 59602336c935Sdrh sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); 5961701caf1eSdrh } 5962701caf1eSdrh 5963701caf1eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5964701caf1eSdrh /* Generate code for all sub-queries in the FROM clause 5965701caf1eSdrh */ 5966701caf1eSdrh pSub = pItem->pSelect; 59675b6a9ed4Sdrh if( pSub==0 ) continue; 596821172c4cSdrh 5969d471bcb3Sdrh /* The code for a subquery should only be generated once, though it is 5970d471bcb3Sdrh ** technically harmless for it to be generated multiple times. The 5971d471bcb3Sdrh ** following assert() will detect if something changes to cause 5972d471bcb3Sdrh ** the same subquery to be coded multiple times, as a signal to the 597300c12a51Sdrh ** developers to try to optimize the situation. 597400c12a51Sdrh ** 597500c12a51Sdrh ** Update 2019-07-24: 597600c12a51Sdrh ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40. 597700c12a51Sdrh ** The dbsqlfuzz fuzzer found a case where the same subquery gets 597800c12a51Sdrh ** coded twice. So this assert() now becomes a testcase(). It should 597900c12a51Sdrh ** be very rare, though. 598000c12a51Sdrh */ 598100c12a51Sdrh testcase( pItem->addrFillSub!=0 ); 5982daf79acbSdanielk1977 5983fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 5984f7b5496eSdrh ** tree referred to by this, the parent select. The child select 5985fc976065Sdanielk1977 ** may contain expression trees of at most 5986fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 5987fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 5988fc976065Sdanielk1977 ** an exact limit. 5989fc976065Sdanielk1977 */ 5990fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 5991daf79acbSdanielk1977 5992adc57f68Sdrh /* Make copies of constant WHERE-clause terms in the outer query down 5993adc57f68Sdrh ** inside the subquery. This can help the subquery to run more efficiently. 5994adc57f68Sdrh */ 59957fbb101cSdrh if( OptimizationEnabled(db, SQLITE_PushDown) 59966a9b9527Sdrh && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, 59976a9b9527Sdrh (pItem->fg.jointype & JT_OUTER)!=0) 599869b72d5aSdrh ){ 599969b72d5aSdrh #if SELECTTRACE_ENABLED 600069b72d5aSdrh if( sqlite3SelectTrace & 0x100 ){ 6001d2a4401cSdrh SELECTTRACE(0x100,pParse,p, 6002d2a4401cSdrh ("After WHERE-clause push-down into subquery %d:\n", pSub->selId)); 600369b72d5aSdrh sqlite3TreeViewSelect(0, p, 0); 6004daf79acbSdanielk1977 } 600569b72d5aSdrh #endif 60062d277bb5Sdrh }else{ 60072d277bb5Sdrh SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); 600869b72d5aSdrh } 6009adc57f68Sdrh 6010824d21afSdrh zSavedAuthContext = pParse->zAuthContext; 6011824d21afSdrh pParse->zAuthContext = pItem->zName; 6012824d21afSdrh 6013adc57f68Sdrh /* Generate code to implement the subquery 60140ff47e9eSdrh ** 601525c221ebSdrh ** The subquery is implemented as a co-routine if the subquery is 601625c221ebSdrh ** guaranteed to be the outer loop (so that it does not need to be 601725c221ebSdrh ** computed more than once) 60180ff47e9eSdrh ** 60190ff47e9eSdrh ** TODO: Are there other reasons beside (1) to use a co-routine 60200ff47e9eSdrh ** implementation? 6021adc57f68Sdrh */ 60220ff47e9eSdrh if( i==0 60230ff47e9eSdrh && (pTabList->nSrc==1 60240ff47e9eSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ 6025a5759677Sdrh ){ 602621172c4cSdrh /* Implement a co-routine that will return a single row of the result 602721172c4cSdrh ** set on each invocation. 602821172c4cSdrh */ 6029725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 6030824d21afSdrh 603121172c4cSdrh pItem->regReturn = ++pParse->nMem; 6032725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 6033725de29aSdrh VdbeComment((v, "%s", pItem->pTab->zName)); 603421172c4cSdrh pItem->addrFillSub = addrTop; 603521172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 6036fef37760Sdrh ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId)); 603721172c4cSdrh sqlite3Select(pParse, pSub, &dest); 6038c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 60398a48b9c0Sdrh pItem->fg.viaCoroutine = 1; 60405f612295Sdrh pItem->regResult = dest.iSdst; 60412fade2f7Sdrh sqlite3VdbeEndCoroutine(v, pItem->regReturn); 604221172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 604321172c4cSdrh sqlite3ClearTempRegCache(pParse); 6044daf79acbSdanielk1977 }else{ 60455b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 60465b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 60475b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 60485b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 60495b6a9ed4Sdrh */ 60507157e8eaSdrh int topAddr; 605148f2d3b1Sdrh int onceAddr = 0; 60527157e8eaSdrh int retAddr; 6053e08e8d6bSdrh struct SrcList_item *pPrior; 6054e08e8d6bSdrh 605500c12a51Sdrh testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */ 60565b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 60577157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 60587157e8eaSdrh pItem->addrFillSub = topAddr+1; 60598a48b9c0Sdrh if( pItem->fg.isCorrelated==0 ){ 6060ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 60615b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 60625b6a9ed4Sdrh ** once. */ 6063511f9e8dSdrh onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 6064725de29aSdrh VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 6065725de29aSdrh }else{ 6066725de29aSdrh VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 60675b6a9ed4Sdrh } 6068e08e8d6bSdrh pPrior = isSelfJoinView(pTabList, pItem); 6069e08e8d6bSdrh if( pPrior ){ 6070e08e8d6bSdrh sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); 6071eafc6dfeSdrh assert( pPrior->pSelect!=0 ); 6072eafc6dfeSdrh pSub->nSelectRow = pPrior->pSelect->nSelectRow; 6073e08e8d6bSdrh }else{ 60741013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 6075fef37760Sdrh ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId)); 60767d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 6077e08e8d6bSdrh } 6078c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 607948f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 60807157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 60817157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 60827157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 6083cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 6084daf79acbSdanielk1977 } 6085adc57f68Sdrh if( db->mallocFailed ) goto select_end; 6086fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 6087824d21afSdrh pParse->zAuthContext = zSavedAuthContext; 6088daf79acbSdanielk1977 #endif 6089701caf1eSdrh } 6090adc57f68Sdrh 609138b4149cSdrh /* Various elements of the SELECT copied into local variables for 609238b4149cSdrh ** convenience */ 6093adc57f68Sdrh pEList = p->pEList; 6094daf79acbSdanielk1977 pWhere = p->pWhere; 6095832508b7Sdrh pGroupBy = p->pGroupBy; 6096832508b7Sdrh pHaving = p->pHaving; 6097e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 6098832508b7Sdrh 6099bc8edba1Sdrh #if SELECTTRACE_ENABLED 6100bc8edba1Sdrh if( sqlite3SelectTrace & 0x400 ){ 6101bc8edba1Sdrh SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); 6102bc8edba1Sdrh sqlite3TreeViewSelect(0, p, 0); 6103f23329a2Sdanielk1977 } 6104f23329a2Sdanielk1977 #endif 6105f23329a2Sdanielk1977 610650118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 610750118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 610850118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 610950118cdfSdan ** 611050118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 611150118cdfSdan ** 611250118cdfSdan ** is transformed to: 611350118cdfSdan ** 6114dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 611550118cdfSdan ** 611650118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 611750118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 611850118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 611950118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 612050118cdfSdan */ 612150118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 6122adc57f68Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 6123ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 6124e59c562bSdan && p->pWin==0 6125ef9f719dSdrh #endif 612650118cdfSdan ){ 612750118cdfSdan p->selFlags &= ~SF_Distinct; 6128adc57f68Sdrh pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); 61299e10f9abSdan p->selFlags |= SF_Aggregate; 6130e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 6131e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 6132e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 6133e8e4af76Sdrh assert( sDistinct.isTnct ); 61347512cb47Sdrh 61357512cb47Sdrh #if SELECTTRACE_ENABLED 61367512cb47Sdrh if( sqlite3SelectTrace & 0x400 ){ 61377512cb47Sdrh SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); 61387512cb47Sdrh sqlite3TreeViewSelect(0, p, 0); 61397512cb47Sdrh } 61407512cb47Sdrh #endif 614150118cdfSdan } 614250118cdfSdan 6143adc57f68Sdrh /* If there is an ORDER BY clause, then create an ephemeral index to 6144adc57f68Sdrh ** do the sorting. But this sorting ephemeral index might end up 6145adc57f68Sdrh ** being unused if the data can be extracted in pre-sorted order. 6146adc57f68Sdrh ** If that is the case, then the OP_OpenEphemeral instruction will be 6147adc57f68Sdrh ** changed to an OP_Noop once we figure out that the sorting index is 6148adc57f68Sdrh ** not needed. The sSort.addrSortIndex variable is used to facilitate 6149adc57f68Sdrh ** that change. 61507cedc8d4Sdanielk1977 */ 6151079a3072Sdrh if( sSort.pOrderBy ){ 61520342b1f5Sdrh KeyInfo *pKeyInfo; 6153f9eae18bSdan pKeyInfo = sqlite3KeyInfoFromExprList( 6154f9eae18bSdan pParse, sSort.pOrderBy, 0, pEList->nExpr); 6155079a3072Sdrh sSort.iECursor = pParse->nTab++; 6156079a3072Sdrh sSort.addrSortIndex = 615766a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 6158f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 6159f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 6160f45f2326Sdrh ); 61619d2985c7Sdrh }else{ 6162079a3072Sdrh sSort.addrSortIndex = -1; 61637cedc8d4Sdanielk1977 } 61647cedc8d4Sdanielk1977 61652d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 61662d0794e3Sdrh */ 61676c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 61682b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 61692d0794e3Sdrh } 61702d0794e3Sdrh 6171f42bacc2Sdrh /* Set the limiter. 6172f42bacc2Sdrh */ 6173ec4ccdbcSdrh iEnd = sqlite3VdbeMakeLabel(pParse); 617469b9383eSdan if( (p->selFlags & SF_FixedLimit)==0 ){ 6175c3489bbfSdrh p->nSelectRow = 320; /* 4 billion rows */ 617669b9383eSdan } 6177f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 6178079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 61790ff287fbSdrh sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); 6180079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 6181c6aff30cSdrh } 6182f42bacc2Sdrh 6183adc57f68Sdrh /* Open an ephemeral index to use for the distinct set. 6184cce7d176Sdrh */ 61852ce22453Sdan if( p->selFlags & SF_Distinct ){ 6186e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 6187e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 6188e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 6189f9eae18bSdan (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0), 61902ec2fb22Sdrh P4_KEYINFO); 6191d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 6192e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 6193832508b7Sdrh }else{ 6194e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 6195efb7251dSdrh } 6196832508b7Sdrh 619713449892Sdrh if( !isAgg && pGroupBy==0 ){ 6198e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 619967a9b8edSdan u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0) 620067a9b8edSdan | (p->selFlags & SF_FixedLimit); 620167a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 620267a9b8edSdan Window *pWin = p->pWin; /* Master window object (or NULL) */ 6203f9eae18bSdan if( pWin ){ 62044ea562eeSdan sqlite3WindowCodeInit(pParse, p); 620586fb6e17Sdan } 620667a9b8edSdan #endif 620767a9b8edSdan assert( WHERE_USE_LIMIT==SF_FixedLimit ); 620867a9b8edSdan 620986fb6e17Sdan 621038cc40c2Sdan /* Begin the database scan. */ 6211cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 6212079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 6213c3489bbfSdrh p->pEList, wctrlFlags, p->nSelectRow); 62141d83f052Sdrh if( pWInfo==0 ) goto select_end; 62156f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 62166f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 62176f32848dSdrh } 62186457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 62196f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 62206f32848dSdrh } 6221079a3072Sdrh if( sSort.pOrderBy ){ 6222079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 62236ee5a7b4Sdrh sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo); 6224079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 6225079a3072Sdrh sSort.pOrderBy = 0; 6226079a3072Sdrh } 6227079a3072Sdrh } 6228cce7d176Sdrh 6229b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 6230b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 62319d2985c7Sdrh ** into an OP_Noop. 62329d2985c7Sdrh */ 6233079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 6234079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 62359d2985c7Sdrh } 62369d2985c7Sdrh 62372def2f7eSdrh assert( p->pEList==pEList ); 623867a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 6239f9eae18bSdan if( pWin ){ 6240ec4ccdbcSdrh int addrGosub = sqlite3VdbeMakeLabel(pParse); 6241ec4ccdbcSdrh int iCont = sqlite3VdbeMakeLabel(pParse); 6242ec4ccdbcSdrh int iBreak = sqlite3VdbeMakeLabel(pParse); 6243f9eae18bSdan int regGosub = ++pParse->nMem; 624486fb6e17Sdan 6245dacf1de9Sdan sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub); 624686fb6e17Sdan 6247efa3a3c9Sdan sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 6248f9eae18bSdan sqlite3VdbeResolveLabel(v, addrGosub); 6249b0225bc5Sdrh VdbeNoopComment((v, "inner-loop subroutine")); 6250d4cb09e3Sdrh sSort.labelOBLopt = 0; 6251efa3a3c9Sdan selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak); 6252dacf1de9Sdan sqlite3VdbeResolveLabel(v, iCont); 625386fb6e17Sdan sqlite3VdbeAddOp1(v, OP_Return, regGosub); 62540b3b0dd1Sdrh VdbeComment((v, "end inner-loop subroutine")); 6255efa3a3c9Sdan sqlite3VdbeResolveLabel(v, iBreak); 625667a9b8edSdan }else 625767a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 625867a9b8edSdan { 625986fb6e17Sdan /* Use the standard inner loop. */ 62602def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, 62616f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 62626f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 62632282792aSdrh 6264cce7d176Sdrh /* End the database scan loop. 6265cce7d176Sdrh */ 62664adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 626786fb6e17Sdan } 626813449892Sdrh }else{ 6269e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 6270e8e4af76Sdrh ** or both */ 627113449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 627213449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 627313449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 627413449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 627513449892Sdrh ** one row of the input to the aggregator has been 627613449892Sdrh ** processed */ 627713449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 627813449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 6279d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 62801c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 62811c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 6282374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 6283d176611bSdrh 6284d176611bSdrh /* Remove any and all aliases between the result set and the 6285d176611bSdrh ** GROUP BY clause. 6286d176611bSdrh */ 6287d176611bSdrh if( pGroupBy ){ 6288dc5ea5c7Sdrh int k; /* Loop counter */ 6289d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 6290d176611bSdrh 6291dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 6292c2acc4e4Sdrh pItem->u.x.iAlias = 0; 6293d176611bSdrh } 6294dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 6295c2acc4e4Sdrh pItem->u.x.iAlias = 0; 6296d176611bSdrh } 6297c3489bbfSdrh assert( 66==sqlite3LogEst(100) ); 6298c3489bbfSdrh if( p->nSelectRow>66 ) p->nSelectRow = 66; 6299cce7d176Sdrh 6300374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 6301374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 6302374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 6303adc57f68Sdrh ** in the correct order. It also may not - the GROUP BY might use a 6304374cd78cSdan ** database index that causes rows to be grouped together as required 6305374cd78cSdan ** but not actually sorted. Either way, record the fact that the 6306374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 6307374cd78cSdan ** variable. */ 63088c9bcb23Sdan if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){ 6309e39f388eSdrh int ii; 63108c9bcb23Sdan /* The GROUP BY processing doesn't care whether rows are delivered in 63118c9bcb23Sdan ** ASC or DESC order - only that each group is returned contiguously. 63128c9bcb23Sdan ** So set the ASC/DESC flags in the GROUP BY to match those in the 63138c9bcb23Sdan ** ORDER BY to maximize the chances of rows being delivered in an 63148c9bcb23Sdan ** order that makes the ORDER BY redundant. */ 6315e39f388eSdrh for(ii=0; ii<pGroupBy->nExpr; ii++){ 6316e39f388eSdrh u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC; 6317e39f388eSdrh pGroupBy->a[ii].sortFlags = sortFlags; 63188c9bcb23Sdan } 6319374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 6320374cd78cSdan orderByGrp = 1; 6321374cd78cSdan } 63228c9bcb23Sdan } 63238c9bcb23Sdan }else{ 63248c9bcb23Sdan assert( 0==sqlite3LogEst(1) ); 63258c9bcb23Sdan p->nSelectRow = 0; 63268c9bcb23Sdan } 632713449892Sdrh 6328d176611bSdrh /* Create a label to jump to when we want to abort the query */ 6329ec4ccdbcSdrh addrEnd = sqlite3VdbeMakeLabel(pParse); 633013449892Sdrh 633113449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 633213449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 633313449892Sdrh ** SELECT statement. 63342282792aSdrh */ 633513449892Sdrh memset(&sNC, 0, sizeof(sNC)); 633613449892Sdrh sNC.pParse = pParse; 633713449892Sdrh sNC.pSrcList = pTabList; 633825c3b8caSdrh sNC.uNC.pAggInfo = &sAggInfo; 633925c3b8caSdrh VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) 63407e61d18eSdrh sAggInfo.mnReg = pParse->nMem+1; 6341dd23c6bfSdan sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 63429d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 6343d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 6344079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 6345d2b3e23bSdrh if( pHaving ){ 6346ab31a845Sdan if( pGroupBy ){ 6347ab31a845Sdan assert( pWhere==p->pWhere ); 6348cd0abc24Sdrh assert( pHaving==p->pHaving ); 6349cd0abc24Sdrh assert( pGroupBy==p->pGroupBy ); 6350cd0abc24Sdrh havingToWhere(pParse, p); 6351ab31a845Sdan pWhere = p->pWhere; 6352ab31a845Sdan } 6353d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 635413449892Sdrh } 635513449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 635647d9f839Sdrh if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){ 635747d9f839Sdrh minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy); 635847d9f839Sdrh }else{ 635947d9f839Sdrh minMaxFlag = WHERE_ORDERBY_NORMAL; 636047d9f839Sdrh } 636113449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 63626ba7ab0dSdan Expr *pExpr = sAggInfo.aFunc[i].pExpr; 63636ba7ab0dSdan assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 63643a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 63656ba7ab0dSdan sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList); 63666ba7ab0dSdan #ifndef SQLITE_OMIT_WINDOWFUNC 63674f9adee2Sdan assert( !IsWindowFunc(pExpr) ); 63684f9adee2Sdan if( ExprHasProperty(pExpr, EP_WinFunc) ){ 63694f9adee2Sdan sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter); 6370b28c4e56Sdan } 63716ba7ab0dSdan #endif 63723a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 637313449892Sdrh } 63747e61d18eSdrh sAggInfo.mxReg = pParse->nMem; 637517435752Sdrh if( db->mallocFailed ) goto select_end; 63767ea11066Sdrh #if SELECTTRACE_ENABLED 63777ea11066Sdrh if( sqlite3SelectTrace & 0x400 ){ 63787ea11066Sdrh int ii; 63797ea11066Sdrh SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n")); 63807ea11066Sdrh sqlite3TreeViewSelect(0, p, 0); 63817ea11066Sdrh for(ii=0; ii<sAggInfo.nColumn; ii++){ 63827ea11066Sdrh sqlite3DebugPrintf("agg-column[%d] iMem=%d\n", 63837ea11066Sdrh ii, sAggInfo.aCol[ii].iMem); 63847ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0); 63857ea11066Sdrh } 63867ea11066Sdrh for(ii=0; ii<sAggInfo.nFunc; ii++){ 63877ea11066Sdrh sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", 63887ea11066Sdrh ii, sAggInfo.aFunc[ii].iMem); 63897ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0); 63907ea11066Sdrh } 63917ea11066Sdrh } 63927ea11066Sdrh #endif 63937ea11066Sdrh 639413449892Sdrh 639513449892Sdrh /* Processing for aggregates with GROUP BY is very different and 63963c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 639713449892Sdrh */ 639813449892Sdrh if( pGroupBy ){ 639913449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 6400728e0f91Sdrh int addr1; /* A-vs-B comparision jump */ 6401d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 6402d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 6403d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 6404d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 6405d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 6406d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 6407d176611bSdrh int regReset; /* Return address register for reset subroutine */ 640813449892Sdrh 640913449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 641013449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 64111c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 641213449892Sdrh ** will be converted into a Noop. 641313449892Sdrh */ 641413449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 6415f9eae18bSdan pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn); 64161c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 6417cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 64182ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 641913449892Sdrh 642013449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 642113449892Sdrh */ 64220a07c107Sdrh iUseFlag = ++pParse->nMem; 64230a07c107Sdrh iAbortFlag = ++pParse->nMem; 6424d176611bSdrh regOutputRow = ++pParse->nMem; 6425ec4ccdbcSdrh addrOutputRow = sqlite3VdbeMakeLabel(pParse); 6426d176611bSdrh regReset = ++pParse->nMem; 6427ec4ccdbcSdrh addrReset = sqlite3VdbeMakeLabel(pParse); 64280a07c107Sdrh iAMem = pParse->nMem + 1; 642913449892Sdrh pParse->nMem += pGroupBy->nExpr; 64300a07c107Sdrh iBMem = pParse->nMem + 1; 643113449892Sdrh pParse->nMem += pGroupBy->nExpr; 64324c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 6433d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 6434b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 6435e313382eSdrh 643613449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 643713449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 643813449892Sdrh ** it might be a single loop that uses an index to extract information 643913449892Sdrh ** in the right order to begin with. 644013449892Sdrh */ 64412eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 6442cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 644393ec45d5Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 6444374cd78cSdan WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 6445374cd78cSdan ); 64465360ad34Sdrh if( pWInfo==0 ) goto select_end; 6447ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 644813449892Sdrh /* The optimizer is able to deliver rows in group by order so 6449b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 645013449892Sdrh ** cancelled later because we still need to use the pKeyInfo 645113449892Sdrh */ 645213449892Sdrh groupBySort = 0; 645313449892Sdrh }else{ 645413449892Sdrh /* Rows are coming out in undetermined order. We have to push 645513449892Sdrh ** each row into a sorting index, terminate the first loop, 645613449892Sdrh ** then loop over the sorting index in order to get the output 645713449892Sdrh ** in sorted order 645813449892Sdrh */ 6459892d3179Sdrh int regBase; 6460892d3179Sdrh int regRecord; 6461892d3179Sdrh int nCol; 6462892d3179Sdrh int nGroupBy; 6463892d3179Sdrh 64642ce22453Sdan explainTempTable(pParse, 6465e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 6466e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 64672ce22453Sdan 646813449892Sdrh groupBySort = 1; 6469892d3179Sdrh nGroupBy = pGroupBy->nExpr; 6470dd23c6bfSdan nCol = nGroupBy; 6471dd23c6bfSdan j = nGroupBy; 647213449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6473892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 6474892d3179Sdrh nCol++; 647513449892Sdrh j++; 647613449892Sdrh } 6477892d3179Sdrh } 6478892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 64795579d59fSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); 6480dd23c6bfSdan j = nGroupBy; 6481892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6482892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 6483892d3179Sdrh if( pCol->iSorterColumn>=j ){ 6484e55cbd72Sdrh int r1 = j + regBase; 64858c607191Sdrh sqlite3ExprCodeGetColumnOfTable(v, 64868c607191Sdrh pCol->pTab, pCol->iTable, pCol->iColumn, r1); 64876a012f04Sdrh j++; 6488892d3179Sdrh } 6489892d3179Sdrh } 6490892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 64911db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 64921c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 6493892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 6494892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 649513449892Sdrh sqlite3WhereEnd(pWInfo); 64965134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 64971c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 64981c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 64991c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 6500688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 650113449892Sdrh sAggInfo.useSortingIdx = 1; 6502374cd78cSdan } 6503374cd78cSdan 6504374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 6505374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 6506374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 6507374cd78cSdan ** 6508374cd78cSdan ** This is an optimization - the correct answer should result regardless. 6509374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 6510374cd78cSdan ** disable this optimization for testing purposes. */ 6511374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 6512374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 6513374cd78cSdan ){ 6514374cd78cSdan sSort.pOrderBy = 0; 6515374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 651613449892Sdrh } 651713449892Sdrh 651813449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 651913449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 652013449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 652113449892Sdrh ** from the previous row currently stored in a0, a1, a2... 652213449892Sdrh */ 652313449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 65241c9d835dSdrh if( groupBySort ){ 652538b4149cSdrh sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, 652638b4149cSdrh sortOut, sortPTab); 65271c9d835dSdrh } 652813449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 652913449892Sdrh if( groupBySort ){ 65301c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 653113449892Sdrh }else{ 653213449892Sdrh sAggInfo.directMode = 1; 65332dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 653413449892Sdrh } 653513449892Sdrh } 653616ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 65372ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 6538728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 6539728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); 654013449892Sdrh 654113449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 6542e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 654313449892Sdrh ** block. If there were no changes, this block is skipped. 654413449892Sdrh ** 654513449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 654613449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 654713449892Sdrh ** and resets the aggregate accumulator registers in preparation 654813449892Sdrh ** for the next GROUP BY batch. 654913449892Sdrh */ 6550b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 65512eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6552d4e70ebdSdrh VdbeComment((v, "output one row")); 6553688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 6554d4e70ebdSdrh VdbeComment((v, "check abort flag")); 65552eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 6556d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 655713449892Sdrh 655813449892Sdrh /* Update the aggregate accumulators based on the content of 655913449892Sdrh ** the current row 656013449892Sdrh */ 6561728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 6562280c894bSdan updateAccumulator(pParse, iUseFlag, &sAggInfo); 65634c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 6564d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 656513449892Sdrh 656613449892Sdrh /* End of the loop 656713449892Sdrh */ 656813449892Sdrh if( groupBySort ){ 65691c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 6570688852abSdrh VdbeCoverage(v); 657113449892Sdrh }else{ 657213449892Sdrh sqlite3WhereEnd(pWInfo); 657348f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 657413449892Sdrh } 657513449892Sdrh 657613449892Sdrh /* Output the final row of result 657713449892Sdrh */ 65782eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6579d4e70ebdSdrh VdbeComment((v, "output final row")); 658013449892Sdrh 6581d176611bSdrh /* Jump over the subroutines 6582d176611bSdrh */ 6583076e85f5Sdrh sqlite3VdbeGoto(v, addrEnd); 6584d176611bSdrh 6585d176611bSdrh /* Generate a subroutine that outputs a single row of the result 6586d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 6587d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 6588d176611bSdrh ** the processing calls for the query to abort, this subroutine 6589d176611bSdrh ** increments the iAbortFlag memory location before returning in 6590d176611bSdrh ** order to signal the caller to abort. 6591d176611bSdrh */ 6592d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 6593d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 6594d176611bSdrh VdbeComment((v, "set abort flag")); 6595d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6596d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 6597d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 6598d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 659938b4149cSdrh VdbeCoverage(v); 6600d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 6601d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6602d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 6603d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 66042def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, 6605e8e4af76Sdrh &sDistinct, pDest, 6606d176611bSdrh addrOutputRow+1, addrSetAbort); 6607d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6608d176611bSdrh VdbeComment((v, "end groupby result generator")); 6609d176611bSdrh 6610d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 6611d176611bSdrh */ 6612d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 6613d176611bSdrh resetAccumulator(pParse, &sAggInfo); 6614280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 6615280c894bSdan VdbeComment((v, "indicate accumulator empty")); 6616d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 6617d176611bSdrh 661843152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 661913449892Sdrh else { 6620a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 6621a5533162Sdanielk1977 Table *pTab; 6622a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 6623a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 6624a5533162Sdanielk1977 ** the SQL statement is of the form: 6625a5533162Sdanielk1977 ** 6626a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 6627a5533162Sdanielk1977 ** 6628a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 6629a5533162Sdanielk1977 ** 6630a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 6631a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 6632a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 6633a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 6634a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 6635a5533162Sdanielk1977 */ 6636a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 6637a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 6638a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 6639a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 6640a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 6641a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 6642a9d1ccb9Sdanielk1977 6643a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 6644a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 6645a5533162Sdanielk1977 6646d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 6647a5533162Sdanielk1977 ** 66483e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 66493e9548b3Sdrh ** 6650abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 66515f33f375Sdrh ** 6652a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 6653a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 6654a5533162Sdanielk1977 */ 66555c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 6656a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 6657d9e3cad2Sdrh if( pIdx->bUnordered==0 6658e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 6659d3037a41Sdrh && pIdx->pPartIdxWhere==0 6660e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 6661d9e3cad2Sdrh ){ 6662a5533162Sdanielk1977 pBest = pIdx; 6663a5533162Sdanielk1977 } 6664a5533162Sdanielk1977 } 6665d9e3cad2Sdrh if( pBest ){ 6666a5533162Sdanielk1977 iRoot = pBest->tnum; 66672ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 6668a5533162Sdanielk1977 } 6669a5533162Sdanielk1977 6670a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 6671261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); 6672a5533162Sdanielk1977 if( pKeyInfo ){ 66732ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 6674a5533162Sdanielk1977 } 6675a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 6676a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 6677ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 6678a5533162Sdanielk1977 }else 6679a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 6680a5533162Sdanielk1977 { 6681280c894bSdan int regAcc = 0; /* "populate accumulators" flag */ 6682280c894bSdan 6683ed09dddeSdan /* If there are accumulator registers but no min() or max() functions 6684ed09dddeSdan ** without FILTER clauses, allocate register regAcc. Register regAcc 6685ed09dddeSdan ** will contain 0 the first time the inner loop runs, and 1 thereafter. 6686ed09dddeSdan ** The code generated by updateAccumulator() uses this to ensure 6687ed09dddeSdan ** that the accumulator registers are (a) updated only once if 6688ed09dddeSdan ** there are no min() or max functions or (b) always updated for the 6689ed09dddeSdan ** first row visited by the aggregate, so that they are updated at 6690ed09dddeSdan ** least once even if the FILTER clause means the min() or max() 6691ed09dddeSdan ** function visits zero rows. */ 6692280c894bSdan if( sAggInfo.nAccumulator ){ 6693280c894bSdan for(i=0; i<sAggInfo.nFunc; i++){ 6694ed09dddeSdan if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue; 6695280c894bSdan if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break; 6696280c894bSdan } 6697280c894bSdan if( i==sAggInfo.nFunc ){ 6698280c894bSdan regAcc = ++pParse->nMem; 6699280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc); 6700280c894bSdan } 6701280c894bSdan } 6702280c894bSdan 670313449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 670413449892Sdrh ** processing is much simpler since there is only a single row 670513449892Sdrh ** of output. 670613449892Sdrh */ 670747d9f839Sdrh assert( p->pGroupBy==0 ); 670813449892Sdrh resetAccumulator(pParse, &sAggInfo); 670947d9f839Sdrh 671047d9f839Sdrh /* If this query is a candidate for the min/max optimization, then 671147d9f839Sdrh ** minMaxFlag will have been previously set to either 671247d9f839Sdrh ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will 671347d9f839Sdrh ** be an appropriate ORDER BY expression for the optimization. 671447d9f839Sdrh */ 671547d9f839Sdrh assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); 671647d9f839Sdrh assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); 671747d9f839Sdrh 6718cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 671947d9f839Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, 672047d9f839Sdrh 0, minMaxFlag, 0); 6721dba0137eSdanielk1977 if( pWInfo==0 ){ 6722dba0137eSdanielk1977 goto select_end; 6723dba0137eSdanielk1977 } 6724280c894bSdan updateAccumulator(pParse, regAcc, &sAggInfo); 6725280c894bSdan if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc); 6726ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 6727076e85f5Sdrh sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); 6728a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 672947d9f839Sdrh (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max"))); 6730a9d1ccb9Sdanielk1977 } 673113449892Sdrh sqlite3WhereEnd(pWInfo); 673213449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 67337a895a80Sdanielk1977 } 67347a895a80Sdanielk1977 6735079a3072Sdrh sSort.pOrderBy = 0; 673635573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 67372def2f7eSdrh selectInnerLoop(pParse, p, -1, 0, 0, 6738a9671a22Sdrh pDest, addrEnd, addrEnd); 673913449892Sdrh } 674013449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 674113449892Sdrh 674213449892Sdrh } /* endif aggregate query */ 67432282792aSdrh 6744e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 67452ce22453Sdan explainTempTable(pParse, "DISTINCT"); 67462ce22453Sdan } 67472ce22453Sdan 6748cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 6749cce7d176Sdrh ** and send them to the callback one by one. 6750cce7d176Sdrh */ 6751079a3072Sdrh if( sSort.pOrderBy ){ 675238b4149cSdrh explainTempTable(pParse, 675338b4149cSdrh sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 675424e25d32Sdan assert( p->pEList==pEList ); 6755079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 6756cce7d176Sdrh } 67576a535340Sdrh 6758ec7429aeSdrh /* Jump here to skip this query 6759ec7429aeSdrh */ 6760ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 6761ec7429aeSdrh 67625b1c07e7Sdan /* The SELECT has been coded. If there is an error in the Parse structure, 67635b1c07e7Sdan ** set the return code to 1. Otherwise 0. */ 67645b1c07e7Sdan rc = (pParse->nErr>0); 67651d83f052Sdrh 67661d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 67671d83f052Sdrh ** successful coding of the SELECT. 67681d83f052Sdrh */ 67691d83f052Sdrh select_end: 677047d9f839Sdrh sqlite3ExprListDelete(db, pMinMaxOrderBy); 6771633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 6772633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 6773eb9b884cSdrh #if SELECTTRACE_ENABLED 6774f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end processing\n")); 6775e2ca99c9Sdrh if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 6776f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 6777f20609d1Sdrh } 6778eb9b884cSdrh #endif 6779e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 67801d83f052Sdrh return rc; 6781cce7d176Sdrh } 6782