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 */ 71079a3072Sdrh u8 sortFlags; /* Zero or more SORTFLAG_* bits */ 72a536df4eSdrh u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */ 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 87b87fbed5Sdrh ** itself only if bFree is true. 88eda639e1Sdrh */ 89b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){ 90b87fbed5Sdrh while( p ){ 91b87fbed5Sdrh Select *pPrior = p->pPrior; 92633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 93633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 94633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 95633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 96633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 97633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 98633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 9967a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 100e3bf632cSdan if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){ 101e3bf632cSdan sqlite3WindowListDelete(db, p->pWinDefn); 102e3bf632cSdan } 10367a9b8edSdan #endif 1048906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith); 105dbd6a7dcSdrh if( bFree ) sqlite3DbFreeNN(db, p); 106b87fbed5Sdrh p = pPrior; 107b87fbed5Sdrh bFree = 1; 108b87fbed5Sdrh } 109eda639e1Sdrh } 110eda639e1Sdrh 1111013c932Sdrh /* 1121013c932Sdrh ** Initialize a SelectDest structure. 1131013c932Sdrh */ 1141013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 115ea678832Sdrh pDest->eDest = (u8)eDest; 1162b596da8Sdrh pDest->iSDParm = iParm; 11771c57db0Sdan pDest->zAffSdst = 0; 1182b596da8Sdrh pDest->iSdst = 0; 1192b596da8Sdrh pDest->nSdst = 0; 1201013c932Sdrh } 1211013c932Sdrh 122eda639e1Sdrh 123eda639e1Sdrh /* 1249bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 1259bb61fe7Sdrh ** structure. 126cce7d176Sdrh */ 1274adee20fSdanielk1977 Select *sqlite3SelectNew( 12817435752Sdrh Parse *pParse, /* Parsing context */ 129daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 130ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 131daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 132daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 133daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 134daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 135c3489bbfSdrh u32 selFlags, /* Flag parameters, such as SF_Distinct */ 1368c0833fbSdrh Expr *pLimit /* LIMIT value. NULL means not used */ 1379bb61fe7Sdrh ){ 1389bb61fe7Sdrh Select *pNew; 139eda639e1Sdrh Select standin; 140ef90a6b8Sdrh pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); 141daffd0e5Sdrh if( pNew==0 ){ 142ef90a6b8Sdrh assert( pParse->db->mallocFailed ); 143eda639e1Sdrh pNew = &standin; 144eda639e1Sdrh } 145b733d037Sdrh if( pEList==0 ){ 1463d240d21Sdrh pEList = sqlite3ExprListAppend(pParse, 0, 1473d240d21Sdrh sqlite3Expr(pParse->db,TK_ASTERISK,0)); 148b733d037Sdrh } 1499bb61fe7Sdrh pNew->pEList = pEList; 150ca3862dcSdrh pNew->op = TK_SELECT; 151ca3862dcSdrh pNew->selFlags = selFlags; 152ca3862dcSdrh pNew->iLimit = 0; 153ca3862dcSdrh pNew->iOffset = 0; 154fef37760Sdrh pNew->selId = ++pParse->nSelect; 155ca3862dcSdrh pNew->addrOpenEphm[0] = -1; 156ca3862dcSdrh pNew->addrOpenEphm[1] = -1; 157ca3862dcSdrh pNew->nSelectRow = 0; 158ef90a6b8Sdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); 1599bb61fe7Sdrh pNew->pSrc = pSrc; 1609bb61fe7Sdrh pNew->pWhere = pWhere; 1619bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 1629bb61fe7Sdrh pNew->pHaving = pHaving; 1639bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 164ca3862dcSdrh pNew->pPrior = 0; 165ca3862dcSdrh pNew->pNext = 0; 166a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 167ca3862dcSdrh pNew->pWith = 0; 16867a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 16986fb6e17Sdan pNew->pWin = 0; 170e3bf632cSdan pNew->pWinDefn = 0; 17167a9b8edSdan #endif 172ef90a6b8Sdrh if( pParse->db->mallocFailed ) { 173ef90a6b8Sdrh clearSelect(pParse->db, pNew, pNew!=&standin); 174eda639e1Sdrh pNew = 0; 175a464c234Sdrh }else{ 176a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 177daffd0e5Sdrh } 178338ec3e1Sdrh assert( pNew!=&standin ); 1799bb61fe7Sdrh return pNew; 1809bb61fe7Sdrh } 1819bb61fe7Sdrh 182eb9b884cSdrh 1839bb61fe7Sdrh /* 184eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 185eda639e1Sdrh */ 186633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 1878906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); 188eda639e1Sdrh } 189eda639e1Sdrh 190eda639e1Sdrh /* 191d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound. 192d227a291Sdrh */ 193d227a291Sdrh static Select *findRightmost(Select *p){ 194d227a291Sdrh while( p->pNext ) p = p->pNext; 195d227a291Sdrh return p; 1969bb61fe7Sdrh } 1979bb61fe7Sdrh 1989bb61fe7Sdrh /* 199f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the 20001f3f253Sdrh ** type of join. Return an integer constant that expresses that type 20101f3f253Sdrh ** in terms of the following bit values: 20201f3f253Sdrh ** 20301f3f253Sdrh ** JT_INNER 2043dec223cSdrh ** JT_CROSS 20501f3f253Sdrh ** JT_OUTER 20601f3f253Sdrh ** JT_NATURAL 20701f3f253Sdrh ** JT_LEFT 20801f3f253Sdrh ** JT_RIGHT 20901f3f253Sdrh ** 21001f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 21101f3f253Sdrh ** 21201f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 21301f3f253Sdrh ** a join type, but put an error in the pParse structure. 21401f3f253Sdrh */ 2154adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 21601f3f253Sdrh int jointype = 0; 21701f3f253Sdrh Token *apAll[3]; 21801f3f253Sdrh Token *p; 219373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 220373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 2215719628aSdrh static const struct { 222373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 223373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 224373cc2ddSdrh u8 code; /* Join type mask */ 225373cc2ddSdrh } aKeyword[] = { 226373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 227373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 228373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 229373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 230373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 231373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 232373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 23301f3f253Sdrh }; 23401f3f253Sdrh int i, j; 23501f3f253Sdrh apAll[0] = pA; 23601f3f253Sdrh apAll[1] = pB; 23701f3f253Sdrh apAll[2] = pC; 238195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 23901f3f253Sdrh p = apAll[i]; 240373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 241373cc2ddSdrh if( p->n==aKeyword[j].nChar 242373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 243373cc2ddSdrh jointype |= aKeyword[j].code; 24401f3f253Sdrh break; 24501f3f253Sdrh } 24601f3f253Sdrh } 247373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 248373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 24901f3f253Sdrh jointype |= JT_ERROR; 25001f3f253Sdrh break; 25101f3f253Sdrh } 25201f3f253Sdrh } 253ad2d8307Sdrh if( 254ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 255195e6967Sdrh (jointype & JT_ERROR)!=0 256ad2d8307Sdrh ){ 257a9671a22Sdrh const char *zSp = " "; 258a9671a22Sdrh assert( pB!=0 ); 259a9671a22Sdrh if( pC==0 ){ zSp++; } 260ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 261a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 26201f3f253Sdrh jointype = JT_INNER; 263373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 264373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 2654adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 266da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 267195e6967Sdrh jointype = JT_INNER; 26801f3f253Sdrh } 26901f3f253Sdrh return jointype; 27001f3f253Sdrh } 27101f3f253Sdrh 27201f3f253Sdrh /* 273ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 274ad2d8307Sdrh ** is not contained in the table. 275ad2d8307Sdrh */ 276ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 277ad2d8307Sdrh int i; 278ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 2794adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 280ad2d8307Sdrh } 281ad2d8307Sdrh return -1; 282ad2d8307Sdrh } 283ad2d8307Sdrh 284ad2d8307Sdrh /* 2852179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 2862179b434Sdrh ** table that has a column named zCol. 2872179b434Sdrh ** 2882179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 2892179b434Sdrh ** of the matching column and return TRUE. 2902179b434Sdrh ** 2912179b434Sdrh ** If not found, return FALSE. 2922179b434Sdrh */ 2932179b434Sdrh static int tableAndColumnIndex( 2942179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 2952179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 2962179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 2972179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 2982179b434Sdrh int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 2992179b434Sdrh ){ 3002179b434Sdrh int i; /* For looping over tables in pSrc */ 3012179b434Sdrh int iCol; /* Index of column matching zCol */ 3022179b434Sdrh 3032179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 3042179b434Sdrh for(i=0; i<N; i++){ 3052179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 3062179b434Sdrh if( iCol>=0 ){ 3072179b434Sdrh if( piTab ){ 3082179b434Sdrh *piTab = i; 3092179b434Sdrh *piCol = iCol; 3102179b434Sdrh } 3112179b434Sdrh return 1; 3122179b434Sdrh } 3132179b434Sdrh } 3142179b434Sdrh return 0; 3152179b434Sdrh } 3162179b434Sdrh 3172179b434Sdrh /* 318f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 319f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 320f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 321f7b0b0adSdan ** 322f7b0b0adSdan ** (tab1.col1 = tab2.col2) 323f7b0b0adSdan ** 324f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 325f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 326f7b0b0adSdan ** column iColRight of tab2. 327ad2d8307Sdrh */ 328ad2d8307Sdrh static void addWhereTerm( 32917435752Sdrh Parse *pParse, /* Parsing context */ 330f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 3312179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 332f7b0b0adSdan int iColLeft, /* Index of column in first table */ 3332179b434Sdrh int iRight, /* Index of second table in pSrc */ 334f7b0b0adSdan int iColRight, /* Index of column in second table */ 335f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 336f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 337ad2d8307Sdrh ){ 338f7b0b0adSdan sqlite3 *db = pParse->db; 339f7b0b0adSdan Expr *pE1; 340f7b0b0adSdan Expr *pE2; 341f7b0b0adSdan Expr *pEq; 342ad2d8307Sdrh 3432179b434Sdrh assert( iLeft<iRight ); 3442179b434Sdrh assert( pSrc->nSrc>iRight ); 3452179b434Sdrh assert( pSrc->a[iLeft].pTab ); 3462179b434Sdrh assert( pSrc->a[iRight].pTab ); 347f7b0b0adSdan 3482179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 3492179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 350f7b0b0adSdan 351abfd35eaSdrh pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); 352f7b0b0adSdan if( pEq && isOuterJoin ){ 353f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 354c5cd1249Sdrh assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); 355ebb6a65dSdrh ExprSetVVAProperty(pEq, EP_NoReduce); 356f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 357030530deSdrh } 358f7b0b0adSdan *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); 359ad2d8307Sdrh } 360ad2d8307Sdrh 361ad2d8307Sdrh /* 3621f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 36322d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 36422d6a53aSdrh ** expression. 3651cc093c2Sdrh ** 366e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 3671cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 3681f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 3691f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 3701f16230bSdrh ** WHERE clause during join processing but we need to remember that they 3711f16230bSdrh ** originated in the ON or USING clause. 37222d6a53aSdrh ** 37322d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 37422d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 37522d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 37622d6a53aSdrh ** for cases like this: 37722d6a53aSdrh ** 37822d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 37922d6a53aSdrh ** 38022d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 38122d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 38222d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 38322d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 38422d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 38522d6a53aSdrh ** the output, which is incorrect. 3861cc093c2Sdrh */ 38722d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 3881cc093c2Sdrh while( p ){ 3891f16230bSdrh ExprSetProperty(p, EP_FromJoin); 390c5cd1249Sdrh assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 391ebb6a65dSdrh ExprSetVVAProperty(p, EP_NoReduce); 392cf697396Sshane p->iRightJoinTable = (i16)iTable; 393606f2344Sdrh if( p->op==TK_FUNCTION && p->x.pList ){ 394606f2344Sdrh int i; 395606f2344Sdrh for(i=0; i<p->x.pList->nExpr; i++){ 396606f2344Sdrh setJoinExpr(p->x.pList->a[i].pExpr, iTable); 397606f2344Sdrh } 398606f2344Sdrh } 39922d6a53aSdrh setJoinExpr(p->pLeft, iTable); 4001cc093c2Sdrh p = p->pRight; 4011cc093c2Sdrh } 4021cc093c2Sdrh } 4031cc093c2Sdrh 4042589787cSdrh /* Undo the work of setJoinExpr(). In the expression tree p, convert every 4052589787cSdrh ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into 4062589787cSdrh ** an ordinary term that omits the EP_FromJoin mark. 4072589787cSdrh ** 4082589787cSdrh ** This happens when a LEFT JOIN is simplified into an ordinary JOIN. 4092589787cSdrh */ 4102589787cSdrh static void unsetJoinExpr(Expr *p, int iTable){ 4112589787cSdrh while( p ){ 4127fbb101cSdrh if( ExprHasProperty(p, EP_FromJoin) 4137fbb101cSdrh && (iTable<0 || p->iRightJoinTable==iTable) ){ 4142589787cSdrh ExprClearProperty(p, EP_FromJoin); 4152589787cSdrh } 4162589787cSdrh if( p->op==TK_FUNCTION && p->x.pList ){ 4172589787cSdrh int i; 4182589787cSdrh for(i=0; i<p->x.pList->nExpr; i++){ 4192589787cSdrh unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); 4202589787cSdrh } 4212589787cSdrh } 4222589787cSdrh unsetJoinExpr(p->pLeft, iTable); 4232589787cSdrh p = p->pRight; 4242589787cSdrh } 4252589787cSdrh } 4262589787cSdrh 4271cc093c2Sdrh /* 428ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 429ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 430ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 431ad2d8307Sdrh ** 43291bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 43391bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 43491bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 43591bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 43691bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 43791bb0eedSdrh ** also attached to the left entry. 43891bb0eedSdrh ** 439ad2d8307Sdrh ** This routine returns the number of errors encountered. 440ad2d8307Sdrh */ 441ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 44291bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 44391bb0eedSdrh int i, j; /* Loop counters */ 44491bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 44591bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 446ad2d8307Sdrh 44791bb0eedSdrh pSrc = p->pSrc; 44891bb0eedSdrh pLeft = &pSrc->a[0]; 44991bb0eedSdrh pRight = &pLeft[1]; 45091bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 45191bb0eedSdrh Table *pRightTab = pRight->pTab; 452ad27e761Sdrh int isOuter; 45391bb0eedSdrh 454ce2c482eSdrh if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; 4558a48b9c0Sdrh isOuter = (pRight->fg.jointype & JT_OUTER)!=0; 456ad2d8307Sdrh 457ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 458ad2d8307Sdrh ** every column that the two tables have in common. 459ad2d8307Sdrh */ 4608a48b9c0Sdrh if( pRight->fg.jointype & JT_NATURAL ){ 46161dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 4624adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 463ad2d8307Sdrh "an ON or USING clause", 0); 464ad2d8307Sdrh return 1; 465ad2d8307Sdrh } 4662179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4672179b434Sdrh char *zName; /* Name of column in the right table */ 4682179b434Sdrh int iLeft; /* Matching left table */ 4692179b434Sdrh int iLeftCol; /* Matching column in the left table */ 4702179b434Sdrh 4712179b434Sdrh zName = pRightTab->aCol[j].zName; 4722179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 4732179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 4742179b434Sdrh isOuter, &p->pWhere); 475ad2d8307Sdrh } 476ad2d8307Sdrh } 477ad2d8307Sdrh } 478ad2d8307Sdrh 479ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 480ad2d8307Sdrh */ 48161dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 4824adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 483da93d238Sdrh "clauses in the same join"); 484ad2d8307Sdrh return 1; 485ad2d8307Sdrh } 486ad2d8307Sdrh 487ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 48891bb0eedSdrh ** an AND operator. 489ad2d8307Sdrh */ 49061dfc31dSdrh if( pRight->pOn ){ 491ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 49217435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 49361dfc31dSdrh pRight->pOn = 0; 494ad2d8307Sdrh } 495ad2d8307Sdrh 496ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 497ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 498ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 499ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 500ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 501ad2d8307Sdrh ** not contained in both tables to be joined. 502ad2d8307Sdrh */ 50361dfc31dSdrh if( pRight->pUsing ){ 50461dfc31dSdrh IdList *pList = pRight->pUsing; 505ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 5062179b434Sdrh char *zName; /* Name of the term in the USING clause */ 5072179b434Sdrh int iLeft; /* Table on the left with matching column name */ 5082179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 5092179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 5102179b434Sdrh 5112179b434Sdrh zName = pList->a[j].zName; 5122179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 5132179b434Sdrh if( iRightCol<0 5142179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 5152179b434Sdrh ){ 5164adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 51791bb0eedSdrh "not present in both tables", zName); 518ad2d8307Sdrh return 1; 519ad2d8307Sdrh } 5202179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 5212179b434Sdrh isOuter, &p->pWhere); 522ad2d8307Sdrh } 523ad2d8307Sdrh } 524ad2d8307Sdrh } 525ad2d8307Sdrh return 0; 526ad2d8307Sdrh } 527ad2d8307Sdrh 528ad2d8307Sdrh /* 529bbd4ae5aSdrh ** An instance of this object holds information (beyond pParse and pSelect) 530bbd4ae5aSdrh ** needed to load the next result row that is to be added to the sorter. 531bbd4ae5aSdrh */ 532bbd4ae5aSdrh typedef struct RowLoadInfo RowLoadInfo; 533bbd4ae5aSdrh struct RowLoadInfo { 534bbd4ae5aSdrh int regResult; /* Store results in array of registers here */ 535bbd4ae5aSdrh u8 ecelFlags; /* Flag argument to ExprCodeExprList() */ 536bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 537bbd4ae5aSdrh ExprList *pExtra; /* Extra columns needed by sorter refs */ 538bbd4ae5aSdrh int regExtraResult; /* Where to load the extra columns */ 539bbd4ae5aSdrh #endif 540bbd4ae5aSdrh }; 541bbd4ae5aSdrh 542bbd4ae5aSdrh /* 543bbd4ae5aSdrh ** This routine does the work of loading query data into an array of 544bbd4ae5aSdrh ** registers so that it can be added to the sorter. 545bbd4ae5aSdrh */ 546bbd4ae5aSdrh static void innerLoopLoadRow( 547bbd4ae5aSdrh Parse *pParse, /* Statement under construction */ 548bbd4ae5aSdrh Select *pSelect, /* The query being coded */ 549bbd4ae5aSdrh RowLoadInfo *pInfo /* Info needed to complete the row load */ 550bbd4ae5aSdrh ){ 551bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult, 552bbd4ae5aSdrh 0, pInfo->ecelFlags); 553bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 554bbd4ae5aSdrh if( pInfo->pExtra ){ 555bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0); 556bbd4ae5aSdrh sqlite3ExprListDelete(pParse->db, pInfo->pExtra); 557bbd4ae5aSdrh } 558bbd4ae5aSdrh #endif 559bbd4ae5aSdrh } 560bbd4ae5aSdrh 561bbd4ae5aSdrh /* 562bbd4ae5aSdrh ** Code the OP_MakeRecord instruction that generates the entry to be 563bbd4ae5aSdrh ** added into the sorter. 564bbd4ae5aSdrh ** 565bbd4ae5aSdrh ** Return the register in which the result is stored. 566bbd4ae5aSdrh */ 567bbd4ae5aSdrh static int makeSorterRecord( 568bbd4ae5aSdrh Parse *pParse, 569bbd4ae5aSdrh SortCtx *pSort, 570bbd4ae5aSdrh Select *pSelect, 571bbd4ae5aSdrh int regBase, 572bbd4ae5aSdrh int nBase 573bbd4ae5aSdrh ){ 574bbd4ae5aSdrh int nOBSat = pSort->nOBSat; 575bbd4ae5aSdrh Vdbe *v = pParse->pVdbe; 576bbd4ae5aSdrh int regOut = ++pParse->nMem; 577bbd4ae5aSdrh if( pSort->pDeferredRowLoad ){ 578bbd4ae5aSdrh innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad); 579bbd4ae5aSdrh } 580bbd4ae5aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut); 581bbd4ae5aSdrh return regOut; 582bbd4ae5aSdrh } 583bbd4ae5aSdrh 584bbd4ae5aSdrh /* 585f45f2326Sdrh ** Generate code that will push the record in registers regData 586f45f2326Sdrh ** through regData+nData-1 onto the sorter. 587c926afbcSdrh */ 588d59ba6ceSdrh static void pushOntoSorter( 589d59ba6ceSdrh Parse *pParse, /* Parser context */ 590079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 591b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 592f45f2326Sdrh int regData, /* First register holding data to be sorted */ 5935579d59fSdrh int regOrigData, /* First register holding data before packing */ 594bbd4ae5aSdrh int nData, /* Number of elements in the regData data array */ 595fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 596d59ba6ceSdrh ){ 597f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 59878d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 599f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 60078d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 601fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 602bbd4ae5aSdrh int regRecord = 0; /* Assembled sorter record */ 60378d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 604f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 605a04a8be2Sdrh int iLimit; /* LIMIT counter */ 606bbd4ae5aSdrh int iSkip = 0; /* End of the sorter insert loop */ 607f45f2326Sdrh 60878d58432Sdan assert( bSeq==0 || bSeq==1 ); 609bbd4ae5aSdrh 610bbd4ae5aSdrh /* Three cases: 611bbd4ae5aSdrh ** (1) The data to be sorted has already been packed into a Record 612bbd4ae5aSdrh ** by a prior OP_MakeRecord. In this case nData==1 and regData 613bbd4ae5aSdrh ** will be completely unrelated to regOrigData. 614bbd4ae5aSdrh ** (2) All output columns are included in the sort record. In that 615bbd4ae5aSdrh ** case regData==regOrigData. 616bbd4ae5aSdrh ** (3) Some output columns are omitted from the sort record due to 617bbd4ae5aSdrh ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the 618c6f36fa3Sdrh ** SQLITE_ECEL_OMITREF optimization, or due to the 619c6f36fa3Sdrh ** SortCtx.pDeferredRowLoad optimiation. In any of these cases 620c6f36fa3Sdrh ** regOrigData is 0 to prevent this routine from trying to copy 621c6f36fa3Sdrh ** values that might not yet exist. 622bbd4ae5aSdrh */ 6239af90b72Sdan assert( nData==1 || regData==regOrigData || regOrigData==0 ); 624bbd4ae5aSdrh 625fd0a2f97Sdrh if( nPrefixReg ){ 62678d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 627bbd4ae5aSdrh regBase = regData - nPrefixReg; 628fd0a2f97Sdrh }else{ 629fb0d6e56Sdrh regBase = pParse->nMem + 1; 630fb0d6e56Sdrh pParse->nMem += nBase; 631fd0a2f97Sdrh } 632a04a8be2Sdrh assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); 633a04a8be2Sdrh iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; 634a04a8be2Sdrh pSort->labelDone = sqlite3VdbeMakeLabel(v); 6355579d59fSdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, 6369af90b72Sdan SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); 63778d58432Sdan if( bSeq ){ 638079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 639fd0a2f97Sdrh } 640257c13faSdan if( nPrefixReg==0 && nData>0 ){ 641236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 64278d58432Sdan } 643079a3072Sdrh if( nOBSat>0 ){ 644079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 645079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 646079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 647079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 648079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 649dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 650079a3072Sdrh 651bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 65226d7e7c6Sdrh regPrevKey = pParse->nMem+1; 65326d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 65478d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 65578d58432Sdan if( bSeq ){ 65678d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 65778d58432Sdan }else{ 65878d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 65978d58432Sdan } 66078d58432Sdan VdbeCoverage(v); 66126d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 662079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 66359b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 664fb0d6e56Sdrh pOp->p2 = nKey + nData; 665dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 666a485ad19Sdrh memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */ 667dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 668a485ad19Sdrh testcase( pKI->nAllField > pKI->nKeyField+2 ); 669f9eae18bSdan pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat, 670a485ad19Sdrh pKI->nAllField-pKI->nKeyField-1); 671079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 672079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 673079a3072Sdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(v); 674079a3072Sdrh pSort->regReturn = ++pParse->nMem; 675079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 67665ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 677a04a8be2Sdrh if( iLimit ){ 678a04a8be2Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); 679a04a8be2Sdrh VdbeCoverage(v); 680a04a8be2Sdrh } 681079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 682236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 683079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 684079a3072Sdrh } 685f226f03dSdan if( iLimit ){ 686f226f03dSdan /* At this point the values for the new sorter entry are stored 687f226f03dSdan ** in an array of registers. They need to be composed into a record 688f226f03dSdan ** and inserted into the sorter if either (a) there are currently 689f226f03dSdan ** less than LIMIT+OFFSET items or (b) the new record is smaller than 690f226f03dSdan ** the largest record currently in the sorter. If (b) is true and there 691f226f03dSdan ** are already LIMIT+OFFSET items in the sorter, delete the largest 692f226f03dSdan ** entry before inserting the new one. This way there are never more 693f226f03dSdan ** than LIMIT+OFFSET items in the sorter. 694f226f03dSdan ** 695f226f03dSdan ** If the new record does not need to be inserted into the sorter, 696f226f03dSdan ** jump to the next iteration of the loop. Or, if the 697f226f03dSdan ** pSort->bOrderedInnerLoop flag is set to indicate that the inner 698f226f03dSdan ** loop delivers items in sorted order, jump to the next iteration 699f226f03dSdan ** of the outer loop. 700f226f03dSdan */ 701f226f03dSdan int iCsr = pSort->iECursor; 702f226f03dSdan sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4); 703f226f03dSdan VdbeCoverage(v); 704f226f03dSdan sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0); 705bbd4ae5aSdrh iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE, 706bbd4ae5aSdrh iCsr, 0, regBase+nOBSat, nExpr-nOBSat); 707f226f03dSdan VdbeCoverage(v); 708f226f03dSdan sqlite3VdbeAddOp1(v, OP_Delete, iCsr); 709f226f03dSdan } 710bbd4ae5aSdrh if( regRecord==0 ){ 711bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 712f226f03dSdan } 713079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 714c6aff30cSdrh op = OP_SorterInsert; 715c6aff30cSdrh }else{ 716c6aff30cSdrh op = OP_IdxInsert; 717c6aff30cSdrh } 7184a8b013eSdrh sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, 7194a8b013eSdrh regBase+nOBSat, nBase-nOBSat); 720bbd4ae5aSdrh if( iSkip ){ 721bbd4ae5aSdrh assert( pSort->bOrderedInnerLoop==0 || pSort->bOrderedInnerLoop==1 ); 722bbd4ae5aSdrh sqlite3VdbeChangeP2(v, iSkip, 723bbd4ae5aSdrh sqlite3VdbeCurrentAddr(v) + pSort->bOrderedInnerLoop); 724bbd4ae5aSdrh } 725c926afbcSdrh } 726c926afbcSdrh 727c926afbcSdrh /* 728ec7429aeSdrh ** Add code to implement the OFFSET 729ea48eb2eSdrh */ 730ec7429aeSdrh static void codeOffset( 731bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 732aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 733b7654111Sdrh int iContinue /* Jump here to skip the current record */ 734ea48eb2eSdrh ){ 735a22a75e5Sdrh if( iOffset>0 ){ 7368b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); 7378b0cf38aSdrh VdbeComment((v, "OFFSET")); 738ea48eb2eSdrh } 739ea48eb2eSdrh } 740ea48eb2eSdrh 741ea48eb2eSdrh /* 74298757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 74398757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 744a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 745a2a49dc9Sdrh ** if the current N values are new. 746a2a49dc9Sdrh ** 747a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 748a2a49dc9Sdrh ** stack if the top N elements are not distinct. 749a2a49dc9Sdrh */ 750a2a49dc9Sdrh static void codeDistinct( 7512dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 752a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 753a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 754477df4b3Sdrh int N, /* Number of elements */ 755a2a49dc9Sdrh int iMem /* First element */ 756a2a49dc9Sdrh ){ 7572dcef11bSdrh Vdbe *v; 7582dcef11bSdrh int r1; 7592dcef11bSdrh 7602dcef11bSdrh v = pParse->pVdbe; 7612dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 762688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); 7631db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 7649b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); 765a67b5cb6Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 7662dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 767a2a49dc9Sdrh } 768a2a49dc9Sdrh 76924e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 77024e25d32Sdan /* 77124e25d32Sdan ** This function is called as part of inner-loop generation for a SELECT 77224e25d32Sdan ** statement with an ORDER BY that is not optimized by an index. It 77324e25d32Sdan ** determines the expressions, if any, that the sorter-reference 77424e25d32Sdan ** optimization should be used for. The sorter-reference optimization 77524e25d32Sdan ** is used for SELECT queries like: 77624e25d32Sdan ** 77724e25d32Sdan ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 77824e25d32Sdan ** 77924e25d32Sdan ** If the optimization is used for expression "bigblob", then instead of 78024e25d32Sdan ** storing values read from that column in the sorter records, the PK of 78124e25d32Sdan ** the row from table t1 is stored instead. Then, as records are extracted from 78224e25d32Sdan ** the sorter to return to the user, the required value of bigblob is 78324e25d32Sdan ** retrieved directly from table t1. If the values are very large, this 78424e25d32Sdan ** can be more efficient than storing them directly in the sorter records. 78524e25d32Sdan ** 78624e25d32Sdan ** The ExprList_item.bSorterRef flag is set for each expression in pEList 78724e25d32Sdan ** for which the sorter-reference optimization should be enabled. 78824e25d32Sdan ** Additionally, the pSort->aDefer[] array is populated with entries 78924e25d32Sdan ** for all cursors required to evaluate all selected expressions. Finally. 79024e25d32Sdan ** output variable (*ppExtra) is set to an expression list containing 79124e25d32Sdan ** expressions for all extra PK values that should be stored in the 79224e25d32Sdan ** sorter records. 79324e25d32Sdan */ 79424e25d32Sdan static void selectExprDefer( 79524e25d32Sdan Parse *pParse, /* Leave any error here */ 79624e25d32Sdan SortCtx *pSort, /* Sorter context */ 79724e25d32Sdan ExprList *pEList, /* Expressions destined for sorter */ 79824e25d32Sdan ExprList **ppExtra /* Expressions to append to sorter record */ 79924e25d32Sdan ){ 80024e25d32Sdan int i; 80124e25d32Sdan int nDefer = 0; 80224e25d32Sdan ExprList *pExtra = 0; 80324e25d32Sdan for(i=0; i<pEList->nExpr; i++){ 80424e25d32Sdan struct ExprList_item *pItem = &pEList->a[i]; 80524e25d32Sdan if( pItem->u.x.iOrderByCol==0 ){ 80624e25d32Sdan Expr *pExpr = pItem->pExpr; 80724e25d32Sdan Table *pTab = pExpr->pTab; 8080f86c9d8Sdan if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab) 8092e3a5a81Sdan && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF) 81024e25d32Sdan ){ 81124e25d32Sdan int j; 81224e25d32Sdan for(j=0; j<nDefer; j++){ 81324e25d32Sdan if( pSort->aDefer[j].iCsr==pExpr->iTable ) break; 81424e25d32Sdan } 81524e25d32Sdan if( j==nDefer ){ 81624e25d32Sdan if( nDefer==ArraySize(pSort->aDefer) ){ 81724e25d32Sdan continue; 81824e25d32Sdan }else{ 81924e25d32Sdan int nKey = 1; 82024e25d32Sdan int k; 82124e25d32Sdan Index *pPk = 0; 82224e25d32Sdan if( !HasRowid(pTab) ){ 82324e25d32Sdan pPk = sqlite3PrimaryKeyIndex(pTab); 82424e25d32Sdan nKey = pPk->nKeyCol; 82524e25d32Sdan } 82624e25d32Sdan for(k=0; k<nKey; k++){ 82724e25d32Sdan Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0); 82824e25d32Sdan if( pNew ){ 82924e25d32Sdan pNew->iTable = pExpr->iTable; 83024e25d32Sdan pNew->pTab = pExpr->pTab; 83124e25d32Sdan pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; 83224e25d32Sdan pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew); 83324e25d32Sdan } 83424e25d32Sdan } 83524e25d32Sdan pSort->aDefer[nDefer].pTab = pExpr->pTab; 83624e25d32Sdan pSort->aDefer[nDefer].iCsr = pExpr->iTable; 83724e25d32Sdan pSort->aDefer[nDefer].nKey = nKey; 83824e25d32Sdan nDefer++; 83924e25d32Sdan } 84024e25d32Sdan } 84124e25d32Sdan pItem->bSorterRef = 1; 84224e25d32Sdan } 84324e25d32Sdan } 84424e25d32Sdan } 84524e25d32Sdan pSort->nDefer = (u8)nDefer; 84624e25d32Sdan *ppExtra = pExtra; 84724e25d32Sdan } 84824e25d32Sdan #endif 84924e25d32Sdan 850c99130fdSdrh /* 8512282792aSdrh ** This routine generates the code for the inside of the inner loop 8522282792aSdrh ** of a SELECT. 85382c3d636Sdrh ** 8542def2f7eSdrh ** If srcTab is negative, then the p->pEList expressions 855340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 8562def2f7eSdrh ** zero or more, then data is pulled from srcTab and p->pEList is used only 857257c13faSdan ** to get the number of columns and the collation sequence for each column. 8582282792aSdrh */ 859d2b3e23bSdrh static void selectInnerLoop( 8602282792aSdrh Parse *pParse, /* The parser context */ 861df199a25Sdrh Select *p, /* The complete select statement being coded */ 8622def2f7eSdrh int srcTab, /* Pull data from this table if non-negative */ 863079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 864e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 8656c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 8662282792aSdrh int iContinue, /* Jump here to continue with next row */ 867a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 8682282792aSdrh ){ 8692282792aSdrh Vdbe *v = pParse->pVdbe; 870d847eaadSdrh int i; 871ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 872d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 8732b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 874d847eaadSdrh int nResultCol; /* Number of result columns */ 875fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 876bbd4ae5aSdrh RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */ 87738640e15Sdrh 8789af90b72Sdan /* Usually, regResult is the first cell in an array of memory cells 8799af90b72Sdan ** containing the current result row. In this case regOrig is set to the 8809af90b72Sdan ** same value. However, if the results are being sent to the sorter, the 8819af90b72Sdan ** values for any expressions that are also part of the sort-key are omitted 8829af90b72Sdan ** from this array. In this case regOrig is set to zero. */ 8839af90b72Sdan int regResult; /* Start of memory holding current results */ 8849af90b72Sdan int regOrig; /* Start of memory holding full result (or 0) */ 8859af90b72Sdan 8861c767f0dSdrh assert( v ); 8872def2f7eSdrh assert( p->pEList!=0 ); 888e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 889079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 890079a3072Sdrh if( pSort==0 && !hasDistinct ){ 891a22a75e5Sdrh assert( iContinue!=0 ); 892aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 893df199a25Sdrh } 894df199a25Sdrh 895967e8b73Sdrh /* Pull the requested columns. 8962282792aSdrh */ 8972def2f7eSdrh nResultCol = p->pEList->nExpr; 89805a86c5cSdrh 8992b596da8Sdrh if( pDest->iSdst==0 ){ 900fd0a2f97Sdrh if( pSort ){ 90178d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 90278d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 903fd0a2f97Sdrh pParse->nMem += nPrefixReg; 9041013c932Sdrh } 905a2a49dc9Sdrh pDest->iSdst = pParse->nMem+1; 906477df4b3Sdrh pParse->nMem += nResultCol; 90705a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 90805a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 90905a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 91005a86c5cSdrh ** there are columns in the table on the left. The error will be caught 91105a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 91205a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 91305a86c5cSdrh pParse->nMem += nResultCol; 9144c583128Sdrh } 91505a86c5cSdrh pDest->nSdst = nResultCol; 9169af90b72Sdan regOrig = regResult = pDest->iSdst; 917340309fdSdrh if( srcTab>=0 ){ 918340309fdSdrh for(i=0; i<nResultCol; i++){ 919d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 9202def2f7eSdrh VdbeComment((v, "%s", p->pEList->a[i].zName)); 92182c3d636Sdrh } 9229ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 92324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 92424e25d32Sdan ExprList *pExtra = 0; 92524e25d32Sdan #endif 9269ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 9279ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 9289ed1dfa8Sdanielk1977 */ 929bbd4ae5aSdrh u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */ 930bbd4ae5aSdrh ExprList *pEList; 931df553659Sdrh if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ 932df553659Sdrh ecelFlags = SQLITE_ECEL_DUP; 933df553659Sdrh }else{ 934df553659Sdrh ecelFlags = 0; 935a2a49dc9Sdrh } 936ac56ab7eSdan if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ 9372def2f7eSdrh /* For each expression in p->pEList that is a copy of an expression in 938257c13faSdan ** the ORDER BY clause (pSort->pOrderBy), set the associated 939257c13faSdan ** iOrderByCol value to one more than the index of the ORDER BY 940257c13faSdan ** expression within the sort-key that pushOntoSorter() will generate. 9412def2f7eSdrh ** This allows the p->pEList field to be omitted from the sorted record, 942257c13faSdan ** saving space and CPU cycles. */ 943257c13faSdan ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); 944bbd4ae5aSdrh 945257c13faSdan for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ 946257c13faSdan int j; 947257c13faSdan if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ 9482def2f7eSdrh p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; 949257c13faSdan } 950257c13faSdan } 95124e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 95224e25d32Sdan selectExprDefer(pParse, pSort, p->pEList, &pExtra); 9535a2e65edSdrh if( pExtra && pParse->db->mallocFailed==0 ){ 95424e25d32Sdan /* If there are any extra PK columns to add to the sorter records, 95524e25d32Sdan ** allocate extra memory cells and adjust the OpenEphemeral 95624e25d32Sdan ** instruction to account for the larger records. This is only 95724e25d32Sdan ** required if there are one or more WITHOUT ROWID tables with 95824e25d32Sdan ** composite primary keys in the SortCtx.aDefer[] array. */ 95924e25d32Sdan VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 96024e25d32Sdan pOp->p2 += (pExtra->nExpr - pSort->nDefer); 96124e25d32Sdan pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); 96224e25d32Sdan pParse->nMem += pExtra->nExpr; 96324e25d32Sdan } 96424e25d32Sdan #endif 965bbd4ae5aSdrh 966bbd4ae5aSdrh /* Adjust nResultCol to account for columns that are omitted 967bbd4ae5aSdrh ** from the sorter by the optimizations in this branch */ 968bbd4ae5aSdrh pEList = p->pEList; 969bbd4ae5aSdrh for(i=0; i<pEList->nExpr; i++){ 970bbd4ae5aSdrh if( pEList->a[i].u.x.iOrderByCol>0 971bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 972bbd4ae5aSdrh || pEList->a[i].bSorterRef 973bbd4ae5aSdrh #endif 974bbd4ae5aSdrh ){ 975bbd4ae5aSdrh nResultCol--; 9769af90b72Sdan regOrig = 0; 977bbd4ae5aSdrh } 978bbd4ae5aSdrh } 979bbd4ae5aSdrh 980bbd4ae5aSdrh testcase( regOrig ); 981bbd4ae5aSdrh testcase( eDest==SRT_Set ); 982bbd4ae5aSdrh testcase( eDest==SRT_Mem ); 983bbd4ae5aSdrh testcase( eDest==SRT_Coroutine ); 984bbd4ae5aSdrh testcase( eDest==SRT_Output ); 985257c13faSdan assert( eDest==SRT_Set || eDest==SRT_Mem 986257c13faSdan || eDest==SRT_Coroutine || eDest==SRT_Output ); 987257c13faSdan } 988bbd4ae5aSdrh sRowLoadInfo.regResult = regResult; 989bbd4ae5aSdrh sRowLoadInfo.ecelFlags = ecelFlags; 99024e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 991bbd4ae5aSdrh sRowLoadInfo.pExtra = pExtra; 992bbd4ae5aSdrh sRowLoadInfo.regExtraResult = regResult + nResultCol; 993bbd4ae5aSdrh if( pExtra ) nResultCol += pExtra->nExpr; 99424e25d32Sdan #endif 995bbd4ae5aSdrh if( p->iLimit 996bbd4ae5aSdrh && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 997bbd4ae5aSdrh && nPrefixReg>0 998bbd4ae5aSdrh ){ 999bbd4ae5aSdrh assert( pSort!=0 ); 1000bbd4ae5aSdrh assert( hasDistinct==0 ); 1001bbd4ae5aSdrh pSort->pDeferredRowLoad = &sRowLoadInfo; 1002c6f36fa3Sdrh regOrig = 0; 1003bbd4ae5aSdrh }else{ 1004bbd4ae5aSdrh innerLoopLoadRow(pParse, p, &sRowLoadInfo); 1005bbd4ae5aSdrh } 1006a2a49dc9Sdrh } 10072282792aSdrh 1008daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 1009daffd0e5Sdrh ** and this row has been seen before, then do not make this row 1010daffd0e5Sdrh ** part of the result. 10112282792aSdrh */ 1012ea48eb2eSdrh if( hasDistinct ){ 1013e8e4af76Sdrh switch( pDistinct->eTnctType ){ 1014e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 1015e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 1016e8e4af76Sdrh int iJump; /* Jump destination */ 1017e8e4af76Sdrh int regPrev; /* Previous row content */ 1018e8e4af76Sdrh 1019e8e4af76Sdrh /* Allocate space for the previous row */ 1020e8e4af76Sdrh regPrev = pParse->nMem+1; 1021340309fdSdrh pParse->nMem += nResultCol; 1022e8e4af76Sdrh 1023e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 1024e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 1025e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 1026e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 1027e8e4af76Sdrh ** row is all NULLs. 1028e8e4af76Sdrh */ 1029e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 1030e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 1031e8e4af76Sdrh pOp->opcode = OP_Null; 1032e8e4af76Sdrh pOp->p1 = 1; 1033e8e4af76Sdrh pOp->p2 = regPrev; 1034e8e4af76Sdrh 1035340309fdSdrh iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 1036340309fdSdrh for(i=0; i<nResultCol; i++){ 10372def2f7eSdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr); 1038340309fdSdrh if( i<nResultCol-1 ){ 1039e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 1040688852abSdrh VdbeCoverage(v); 1041e8e4af76Sdrh }else{ 1042e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 1043688852abSdrh VdbeCoverage(v); 1044e8e4af76Sdrh } 1045e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 1046e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 1047e8e4af76Sdrh } 1048fcf2a775Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 1049340309fdSdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); 1050e8e4af76Sdrh break; 1051e8e4af76Sdrh } 1052e8e4af76Sdrh 1053e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 1054e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 1055e8e4af76Sdrh break; 1056e8e4af76Sdrh } 1057e8e4af76Sdrh 1058e8e4af76Sdrh default: { 1059e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 106038b4149cSdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, 106138b4149cSdrh regResult); 1062e8e4af76Sdrh break; 1063e8e4af76Sdrh } 1064e8e4af76Sdrh } 1065079a3072Sdrh if( pSort==0 ){ 1066aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 1067ea48eb2eSdrh } 10682282792aSdrh } 106982c3d636Sdrh 1070c926afbcSdrh switch( eDest ){ 107182c3d636Sdrh /* In this mode, write each query result to the key of the temporary 107282c3d636Sdrh ** table iParm. 10732282792aSdrh */ 107413449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1075c926afbcSdrh case SRT_Union: { 10769cbf3425Sdrh int r1; 10779cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 1078340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 10799b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 10809cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1081c926afbcSdrh break; 1082c926afbcSdrh } 108382c3d636Sdrh 108482c3d636Sdrh /* Construct a record from the query result, but instead of 108582c3d636Sdrh ** saving that record, use it as a key to delete elements from 108682c3d636Sdrh ** the temporary table iParm. 108782c3d636Sdrh */ 1088c926afbcSdrh case SRT_Except: { 1089340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 1090c926afbcSdrh break; 1091c926afbcSdrh } 1092781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 10935338a5f7Sdanielk1977 10945338a5f7Sdanielk1977 /* Store the result as data using a unique key. 10955338a5f7Sdanielk1977 */ 10968e1ee88cSdrh case SRT_Fifo: 10978e1ee88cSdrh case SRT_DistFifo: 10985338a5f7Sdanielk1977 case SRT_Table: 1099b9bb7c18Sdrh case SRT_EphemTab: { 1100fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 1101373cc2ddSdrh testcase( eDest==SRT_Table ); 1102373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 1103e2248cfdSdrh testcase( eDest==SRT_Fifo ); 1104e2248cfdSdrh testcase( eDest==SRT_DistFifo ); 1105fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 11068ce7184bSdan #ifndef SQLITE_OMIT_CTE 11078e1ee88cSdrh if( eDest==SRT_DistFifo ){ 11088e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 11098ce7184bSdan ** on an ephemeral index. If the current row is already present 11108ce7184bSdan ** in the index, do not write it to the output. If not, add the 11118ce7184bSdan ** current row to the index and proceed with writing it to the 11128ce7184bSdan ** output table as well. */ 11138ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 111438b4149cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); 111538b4149cSdrh VdbeCoverage(v); 11169b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); 1117079a3072Sdrh assert( pSort==0 ); 11188ce7184bSdan } 11198ce7184bSdan #endif 1120079a3072Sdrh if( pSort ){ 1121bbd4ae5aSdrh assert( regResult==regOrig ); 1122bbd4ae5aSdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg); 11235338a5f7Sdanielk1977 }else{ 1124b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 1125b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 1126b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 1127b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1128b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 11295338a5f7Sdanielk1977 } 1130fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 11315338a5f7Sdanielk1977 break; 11325338a5f7Sdanielk1977 } 11332282792aSdrh 113493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 11352282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 11362282792aSdrh ** then there should be a single item on the stack. Write this 11372282792aSdrh ** item into the set table with bogus data. 11382282792aSdrh */ 1139c926afbcSdrh case SRT_Set: { 1140079a3072Sdrh if( pSort ){ 1141de941c60Sdrh /* At first glance you would think we could optimize out the 1142de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 1143de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 1144de941c60Sdrh ** case the order does matter */ 114551d82d1dSdan pushOntoSorter( 11469af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1147c926afbcSdrh }else{ 1148b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 114971c57db0Sdan assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); 115071c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 1151553168c7Sdan r1, pDest->zAffSdst, nResultCol); 115271c57db0Sdan sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 11539b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 1154b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 1155c926afbcSdrh } 1156c926afbcSdrh break; 1157c926afbcSdrh } 115882c3d636Sdrh 1159504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 1160ec7429aeSdrh */ 1161ec7429aeSdrh case SRT_Exists: { 11624c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 1163ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1164ec7429aeSdrh break; 1165ec7429aeSdrh } 1166ec7429aeSdrh 11672282792aSdrh /* If this is a scalar select that is part of an expression, then 1168870a0705Sdan ** store the results in the appropriate memory cell or array of 1169870a0705Sdan ** memory cells and break out of the scan loop. 11702282792aSdrh */ 1171c926afbcSdrh case SRT_Mem: { 1172079a3072Sdrh if( pSort ){ 1173257c13faSdan assert( nResultCol<=pDest->nSdst ); 1174870a0705Sdan pushOntoSorter( 11759af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1176c926afbcSdrh }else{ 1177257c13faSdan assert( nResultCol==pDest->nSdst ); 117853932ce8Sdrh assert( regResult==iParm ); 1179ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 1180c926afbcSdrh } 1181c926afbcSdrh break; 1182c926afbcSdrh } 118393758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 11842282792aSdrh 118581cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 118681cf13ecSdrh case SRT_Output: { /* Return the results */ 1187373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 1188373cc2ddSdrh testcase( eDest==SRT_Output ); 1189079a3072Sdrh if( pSort ){ 11909af90b72Sdan pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, 11915579d59fSdrh nPrefixReg); 1192e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 11932b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1194c182d163Sdrh }else{ 1195340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 1196340309fdSdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 1197ac82fcf5Sdrh } 1198142e30dfSdrh break; 1199142e30dfSdrh } 1200142e30dfSdrh 1201fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 1202fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 1203fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 1204fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 1205fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 1206fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 1207fe1c6bb9Sdrh */ 1208fe1c6bb9Sdrh case SRT_DistQueue: 1209fe1c6bb9Sdrh case SRT_Queue: { 1210fe1c6bb9Sdrh int nKey; 1211fe1c6bb9Sdrh int r1, r2, r3; 1212fe1c6bb9Sdrh int addrTest = 0; 1213fe1c6bb9Sdrh ExprList *pSO; 1214fe1c6bb9Sdrh pSO = pDest->pOrderBy; 1215fe1c6bb9Sdrh assert( pSO ); 1216fe1c6bb9Sdrh nKey = pSO->nExpr; 1217fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 1218fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 1219fe1c6bb9Sdrh r3 = r2+nKey+1; 1220fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 1221fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 1222fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 12237e4efaecSdrh ** added to the queue. */ 12247e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 12257e4efaecSdrh regResult, nResultCol); 1226688852abSdrh VdbeCoverage(v); 12277e4efaecSdrh } 12287e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 12297e4efaecSdrh if( eDest==SRT_DistQueue ){ 1230fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 1231cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1232fe1c6bb9Sdrh } 1233fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 1234fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 1235fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 1236fe1c6bb9Sdrh r2+i); 1237fe1c6bb9Sdrh } 1238fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 1239fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 12409b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); 1241fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 1242fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 1243fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 1244fe1c6bb9Sdrh break; 1245fe1c6bb9Sdrh } 1246fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 1247fe1c6bb9Sdrh 1248fe1c6bb9Sdrh 1249fe1c6bb9Sdrh 12506a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 1251d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 1252d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 1253d7489c39Sdrh ** user-defined functions that have side effects. We do not care 1254d7489c39Sdrh ** about the actual results of the select. 1255d7489c39Sdrh */ 1256c926afbcSdrh default: { 1257f46f905aSdrh assert( eDest==SRT_Discard ); 1258c926afbcSdrh break; 1259c926afbcSdrh } 126093758c8dSdanielk1977 #endif 1261c926afbcSdrh } 1262ec7429aeSdrh 12635e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 12645e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 12655e87be87Sdrh ** the output for us. 1266ec7429aeSdrh */ 1267079a3072Sdrh if( pSort==0 && p->iLimit ){ 126816897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 1269ec7429aeSdrh } 127082c3d636Sdrh } 127182c3d636Sdrh 127282c3d636Sdrh /* 1273ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 1274ad124329Sdrh ** X extra columns. 1275323df790Sdrh */ 1276ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 1277d4ab003dSdrh int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); 1278d8e4b132Sdrh KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); 1279323df790Sdrh if( p ){ 1280ad124329Sdrh p->aSortOrder = (u8*)&p->aColl[N+X]; 1281a485ad19Sdrh p->nKeyField = (u16)N; 1282a485ad19Sdrh p->nAllField = (u16)(N+X); 1283323df790Sdrh p->enc = ENC(db); 1284323df790Sdrh p->db = db; 12852ec2fb22Sdrh p->nRef = 1; 1286c263f7c4Sdrh memset(&p[1], 0, nExtra); 12872ec2fb22Sdrh }else{ 12884a642b60Sdrh sqlite3OomFault(db); 1289323df790Sdrh } 1290323df790Sdrh return p; 1291323df790Sdrh } 1292323df790Sdrh 1293323df790Sdrh /* 12942ec2fb22Sdrh ** Deallocate a KeyInfo object 12952ec2fb22Sdrh */ 12962ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 12972ec2fb22Sdrh if( p ){ 12982ec2fb22Sdrh assert( p->nRef>0 ); 12992ec2fb22Sdrh p->nRef--; 1300dbd6a7dcSdrh if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); 13012ec2fb22Sdrh } 13022ec2fb22Sdrh } 13032ec2fb22Sdrh 13042ec2fb22Sdrh /* 13052ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 13062ec2fb22Sdrh */ 13072ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 13082ec2fb22Sdrh if( p ){ 13092ec2fb22Sdrh assert( p->nRef>0 ); 13102ec2fb22Sdrh p->nRef++; 13112ec2fb22Sdrh } 13122ec2fb22Sdrh return p; 13132ec2fb22Sdrh } 13142ec2fb22Sdrh 13152ec2fb22Sdrh #ifdef SQLITE_DEBUG 13162ec2fb22Sdrh /* 13172ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 13182ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 13192ec2fb22Sdrh ** 13202ec2fb22Sdrh ** This routine is used only inside of assert() statements. 13212ec2fb22Sdrh */ 13222ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 13232ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 13242ec2fb22Sdrh 13252ec2fb22Sdrh /* 1326dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1327dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1328dece1a84Sdrh ** 13290342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 13300342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 13310342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 13320342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 13330342b1f5Sdrh ** index to implement a DISTINCT test. 13340342b1f5Sdrh ** 133560ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1336dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 13372ec2fb22Sdrh ** freed. 1338dece1a84Sdrh */ 1339f9eae18bSdan KeyInfo *sqlite3KeyInfoFromExprList( 1340079a3072Sdrh Parse *pParse, /* Parsing context */ 1341079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1342079a3072Sdrh int iStart, /* Begin with this column of pList */ 1343079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1344079a3072Sdrh ){ 1345dece1a84Sdrh int nExpr; 1346dece1a84Sdrh KeyInfo *pInfo; 1347dece1a84Sdrh struct ExprList_item *pItem; 1348323df790Sdrh sqlite3 *db = pParse->db; 1349dece1a84Sdrh int i; 1350dece1a84Sdrh 1351dece1a84Sdrh nExpr = pList->nExpr; 13523f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1353dece1a84Sdrh if( pInfo ){ 13542ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 13556284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 135670efa84dSdrh pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr); 13576284db90Sdrh pInfo->aSortOrder[i-iStart] = pItem->sortOrder; 1358dece1a84Sdrh } 1359dece1a84Sdrh } 1360dece1a84Sdrh return pInfo; 1361dece1a84Sdrh } 1362dece1a84Sdrh 13637f61e92cSdan /* 13647f61e92cSdan ** Name of the connection operator, used for error messages. 13657f61e92cSdan */ 13667f61e92cSdan static const char *selectOpName(int id){ 13677f61e92cSdan char *z; 13687f61e92cSdan switch( id ){ 13697f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 13707f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 13717f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 13727f61e92cSdan default: z = "UNION"; break; 13737f61e92cSdan } 13747f61e92cSdan return z; 13757f61e92cSdan } 13767f61e92cSdan 13772ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 137817c0bc0cSdan /* 137917c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 138017c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 138117c0bc0cSdan ** where the caption is of the form: 138217c0bc0cSdan ** 138317c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 138417c0bc0cSdan ** 138517c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 138617c0bc0cSdan ** is determined by the zUsage argument. 138717c0bc0cSdan */ 13882ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 1389e2ca99c9Sdrh ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage)); 13902ce22453Sdan } 139117c0bc0cSdan 139217c0bc0cSdan /* 1393bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1394bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1395bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1396bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1397bb2b4418Sdan ** code with #ifndef directives. 1398bb2b4418Sdan */ 1399bb2b4418Sdan # define explainSetInteger(a, b) a = b 1400bb2b4418Sdan 1401bb2b4418Sdan #else 1402bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1403bb2b4418Sdan # define explainTempTable(y,z) 1404bb2b4418Sdan # define explainSetInteger(y,z) 1405bb2b4418Sdan #endif 1406bb2b4418Sdan 1407dece1a84Sdrh 1408dece1a84Sdrh /* 1409d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1410d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1411d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1412d8bc7086Sdrh ** routine generates the code needed to do that. 1413d8bc7086Sdrh */ 1414c926afbcSdrh static void generateSortTail( 1415cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1416c926afbcSdrh Select *p, /* The SELECT statement */ 1417079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1418c926afbcSdrh int nColumn, /* Number of columns of data */ 14196c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1420c926afbcSdrh ){ 1421ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1422a04a8be2Sdrh int addrBreak = pSort->labelDone; /* Jump here to exit loop */ 1423dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 142424e25d32Sdan int addr; /* Top of output loop. Jump for Next. */ 1425079a3072Sdrh int addrOnce = 0; 14260342b1f5Sdrh int iTab; 1427079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 14286c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 14292b596da8Sdrh int iParm = pDest->iSDParm; 14302d401ab8Sdrh int regRow; 14312d401ab8Sdrh int regRowid; 1432257c13faSdan int iCol; 143324e25d32Sdan int nKey; /* Number of key columns in sorter record */ 1434f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1435f45f2326Sdrh int i; 143678d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 143724e25d32Sdan int nRefKey = 0; 143870f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 14392d401ab8Sdrh 1440a04a8be2Sdrh assert( addrBreak<0 ); 1441079a3072Sdrh if( pSort->labelBkOut ){ 1442079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1443076e85f5Sdrh sqlite3VdbeGoto(v, addrBreak); 1444079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1445079a3072Sdrh } 144624e25d32Sdan 144724e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 144824e25d32Sdan /* Open any cursors needed for sorter-reference expressions */ 144924e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 145024e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 145124e25d32Sdan int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 145224e25d32Sdan sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); 145324e25d32Sdan nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); 145424e25d32Sdan } 145524e25d32Sdan #endif 145624e25d32Sdan 1457079a3072Sdrh iTab = pSort->iECursor; 145871c57db0Sdan if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ 14593e9ca094Sdrh regRowid = 0; 1460f45f2326Sdrh regRow = pDest->iSdst; 1461ed24da4bSdrh }else{ 146251d82d1dSdan regRowid = sqlite3GetTempReg(pParse); 146351d82d1dSdan regRow = sqlite3GetTempRange(pParse, nColumn); 1464cdd536f0Sdrh } 1465079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1466079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1467c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1468f45f2326Sdrh iSortTab = pParse->nTab++; 146983553eefSdrh if( pSort->labelBkOut ){ 1470511f9e8dSdrh addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 147183553eefSdrh } 147224e25d32Sdan sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, 147324e25d32Sdan nKey+1+nColumn+nRefKey); 1474079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1475c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1476688852abSdrh VdbeCoverage(v); 1477aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 14786cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 147978d58432Sdan bSeq = 0; 1480c6aff30cSdrh }else{ 1481688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1482aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1483f45f2326Sdrh iSortTab = iTab; 148478d58432Sdan bSeq = 1; 1485f45f2326Sdrh } 1486d6189eafSdan for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){ 148724e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 148824e25d32Sdan if( aOutEx[i].bSorterRef ) continue; 148924e25d32Sdan #endif 14909f895239Sdrh if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++; 14919f895239Sdrh } 149224e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 149324e25d32Sdan if( pSort->nDefer ){ 149424e25d32Sdan int iKey = iCol+1; 149524e25d32Sdan int regKey = sqlite3GetTempRange(pParse, nRefKey); 149624e25d32Sdan 149724e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 149824e25d32Sdan int iCsr = pSort->aDefer[i].iCsr; 149924e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 150024e25d32Sdan int nKey = pSort->aDefer[i].nKey; 150124e25d32Sdan 150224e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 150324e25d32Sdan if( HasRowid(pTab) ){ 150424e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); 150524e25d32Sdan sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, 150624e25d32Sdan sqlite3VdbeCurrentAddr(v)+1, regKey); 150724e25d32Sdan }else{ 150824e25d32Sdan int k; 150924e25d32Sdan int iJmp; 15107590d093Sdrh assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); 151124e25d32Sdan for(k=0; k<nKey; k++){ 151224e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k); 151324e25d32Sdan } 151424e25d32Sdan iJmp = sqlite3VdbeCurrentAddr(v); 151524e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey); 151624e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey); 151724e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 151824e25d32Sdan } 151924e25d32Sdan } 152024e25d32Sdan sqlite3ReleaseTempRange(pParse, regKey, nRefKey); 152124e25d32Sdan } 152224e25d32Sdan #endif 1523d6189eafSdan for(i=nColumn-1; i>=0; i--){ 152424e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 152524e25d32Sdan if( aOutEx[i].bSorterRef ){ 152624e25d32Sdan sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); 152724e25d32Sdan }else 152824e25d32Sdan #endif 152924e25d32Sdan { 1530257c13faSdan int iRead; 1531257c13faSdan if( aOutEx[i].u.x.iOrderByCol ){ 1532257c13faSdan iRead = aOutEx[i].u.x.iOrderByCol-1; 1533257c13faSdan }else{ 15349f895239Sdrh iRead = iCol--; 1535257c13faSdan } 1536257c13faSdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); 153770f624c3Sdrh VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan)); 1538c6aff30cSdrh } 153924e25d32Sdan } 1540c926afbcSdrh switch( eDest ){ 1541ac56ab7eSdan case SRT_Table: 1542b9bb7c18Sdrh case SRT_EphemTab: { 15432d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 15442d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 15452d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1546c926afbcSdrh break; 1547c926afbcSdrh } 154893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1549c926afbcSdrh case SRT_Set: { 155071c57db0Sdan assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); 155171c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, 1552553168c7Sdan pDest->zAffSdst, nColumn); 155371c57db0Sdan sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn); 15549b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); 1555c926afbcSdrh break; 1556c926afbcSdrh } 1557c926afbcSdrh case SRT_Mem: { 1558ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1559c926afbcSdrh break; 1560c926afbcSdrh } 156193758c8dSdanielk1977 #endif 1562373cc2ddSdrh default: { 1563373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 15641c767f0dSdrh testcase( eDest==SRT_Output ); 15651c767f0dSdrh testcase( eDest==SRT_Coroutine ); 15667d10d5a6Sdrh if( eDest==SRT_Output ){ 15672b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 15682b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); 1569a9671a22Sdrh }else{ 15702b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1571ce665cf6Sdrh } 1572ac82fcf5Sdrh break; 1573ac82fcf5Sdrh } 1574c926afbcSdrh } 1575f45f2326Sdrh if( regRowid ){ 157651d82d1dSdan if( eDest==SRT_Set ){ 157751d82d1dSdan sqlite3ReleaseTempRange(pParse, regRow, nColumn); 157851d82d1dSdan }else{ 15792d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 158051d82d1dSdan } 15812d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1582f45f2326Sdrh } 1583ec7429aeSdrh /* The bottom of the loop 1584ec7429aeSdrh */ 1585dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1586079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1587688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1588c6aff30cSdrh }else{ 1589688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1590c6aff30cSdrh } 1591079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1592dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1593d8bc7086Sdrh } 1594d8bc7086Sdrh 1595d8bc7086Sdrh /* 1596517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1597517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1598e78e8284Sdrh ** 15995f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 16005f3e5e74Sdrh ** result in *pEstWidth. 16015f3e5e74Sdrh ** 1602955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1603955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1604955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1605955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1606955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1607955de52cSdanielk1977 ** considered a column by this function. 1608e78e8284Sdrh ** 1609955de52cSdanielk1977 ** SELECT col FROM tbl; 1610955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1611955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1612955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1613955de52cSdanielk1977 ** 1614955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 16155f3e5e74Sdrh ** 16165f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 16175f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1618fcb78a49Sdrh */ 16195f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1620cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) 1621b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1622cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B) 1623b121dd14Sdrh #endif 16245f3e5e74Sdrh static const char *columnTypeImpl( 1625955de52cSdanielk1977 NameContext *pNC, 1626cafc2f7bSdrh #ifndef SQLITE_ENABLE_COLUMN_METADATA 1627cafc2f7bSdrh Expr *pExpr 1628cafc2f7bSdrh #else 1629955de52cSdanielk1977 Expr *pExpr, 16305f3e5e74Sdrh const char **pzOrigDb, 16315f3e5e74Sdrh const char **pzOrigTab, 1632cafc2f7bSdrh const char **pzOrigCol 1633b121dd14Sdrh #endif 1634955de52cSdanielk1977 ){ 1635955de52cSdanielk1977 char const *zType = 0; 1636517eb646Sdanielk1977 int j; 1637b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1638b121dd14Sdrh char const *zOrigDb = 0; 1639b121dd14Sdrh char const *zOrigTab = 0; 1640b121dd14Sdrh char const *zOrigCol = 0; 1641b121dd14Sdrh #endif 16425338a5f7Sdanielk1977 1643f7ce4291Sdrh assert( pExpr!=0 ); 1644f7ce4291Sdrh assert( pNC->pSrcList!=0 ); 1645755b0fd3Sdrh assert( pExpr->op!=TK_AGG_COLUMN ); /* This routine runes before aggregates 1646755b0fd3Sdrh ** are processed */ 164700e279d9Sdanielk1977 switch( pExpr->op ){ 164800e279d9Sdanielk1977 case TK_COLUMN: { 1649955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1650955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1651955de52cSdanielk1977 ** database table or a subquery. 1652955de52cSdanielk1977 */ 1653955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1654955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1655955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 165643bc88bbSdan while( pNC && !pTab ){ 1657b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1658b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1659b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 16606a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1661955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1662b3bce662Sdanielk1977 }else{ 1663b3bce662Sdanielk1977 pNC = pNC->pNext; 1664b3bce662Sdanielk1977 } 1665b3bce662Sdanielk1977 } 1666955de52cSdanielk1977 166743bc88bbSdan if( pTab==0 ){ 1668417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1669417168adSdrh ** cause this condition to run. Since then, we have restructured how 1670417168adSdrh ** trigger code is generated and so this condition is no longer 167143bc88bbSdan ** possible. However, it can still be true for statements like 167243bc88bbSdan ** the following: 167343bc88bbSdan ** 167443bc88bbSdan ** CREATE TABLE t1(col INTEGER); 167543bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 167643bc88bbSdan ** 167743bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 167843bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 167943bc88bbSdan ** though it should really be "INTEGER". 168043bc88bbSdan ** 168143bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 168243bc88bbSdan ** used. When columnType() is called on the expression 168343bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 168443bc88bbSdan ** branch below. */ 16857e62779aSdrh break; 16867e62779aSdrh } 1687955de52cSdanielk1977 168843bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1689955de52cSdanielk1977 if( pS ){ 1690955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1691955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1692955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1693955de52cSdanielk1977 */ 1694f35f2f92Sdrh if( iCol>=0 && iCol<pS->pEList->nExpr ){ 1695955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1696955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1697955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1698955de52cSdanielk1977 */ 1699955de52cSdanielk1977 NameContext sNC; 1700955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1701955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 170243bc88bbSdan sNC.pNext = pNC; 1703955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1704cafc2f7bSdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 1705955de52cSdanielk1977 } 1706a78d757cSdrh }else{ 1707a78d757cSdrh /* A real table or a CTE table */ 1708955de52cSdanielk1977 assert( !pS ); 17095f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1710a78d757cSdrh if( iCol<0 ) iCol = pTab->iPKey; 1711a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 1712fcb78a49Sdrh if( iCol<0 ){ 1713fcb78a49Sdrh zType = "INTEGER"; 17145f3e5e74Sdrh zOrigCol = "rowid"; 1715fcb78a49Sdrh }else{ 17165f3e5e74Sdrh zOrigCol = pTab->aCol[iCol].zName; 1717d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 1718955de52cSdanielk1977 } 17195f3e5e74Sdrh zOrigTab = pTab->zName; 1720a78d757cSdrh if( pNC->pParse && pTab->pSchema ){ 1721955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1722e59be010Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; 1723955de52cSdanielk1977 } 17245f3e5e74Sdrh #else 1725a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 17265f3e5e74Sdrh if( iCol<0 ){ 17275f3e5e74Sdrh zType = "INTEGER"; 17285f3e5e74Sdrh }else{ 1729d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 17305f3e5e74Sdrh } 17315f3e5e74Sdrh #endif 1732fcb78a49Sdrh } 173300e279d9Sdanielk1977 break; 1734736c22b8Sdrh } 173593758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 173600e279d9Sdanielk1977 case TK_SELECT: { 1737955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1738955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1739955de52cSdanielk1977 ** statement. 1740955de52cSdanielk1977 */ 1741b3bce662Sdanielk1977 NameContext sNC; 17426ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1743955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 17446ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1745955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1746b3bce662Sdanielk1977 sNC.pNext = pNC; 1747955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1748cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 174900e279d9Sdanielk1977 break; 1750fcb78a49Sdrh } 175193758c8dSdanielk1977 #endif 175200e279d9Sdanielk1977 } 175300e279d9Sdanielk1977 17545f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 17555f3e5e74Sdrh if( pzOrigDb ){ 17565f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 17575f3e5e74Sdrh *pzOrigDb = zOrigDb; 17585f3e5e74Sdrh *pzOrigTab = zOrigTab; 17595f3e5e74Sdrh *pzOrigCol = zOrigCol; 1760955de52cSdanielk1977 } 17615f3e5e74Sdrh #endif 1762517eb646Sdanielk1977 return zType; 1763517eb646Sdanielk1977 } 1764517eb646Sdanielk1977 1765517eb646Sdanielk1977 /* 1766517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1767517eb646Sdanielk1977 ** in the result set. 1768517eb646Sdanielk1977 */ 1769517eb646Sdanielk1977 static void generateColumnTypes( 1770517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1771517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1772517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1773517eb646Sdanielk1977 ){ 17743f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1775517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1776517eb646Sdanielk1977 int i; 1777b3bce662Sdanielk1977 NameContext sNC; 1778b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1779955de52cSdanielk1977 sNC.pParse = pParse; 1780eac5fc04Sdrh sNC.pNext = 0; 1781517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1782517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 17833f913576Sdrh const char *zType; 17843f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1785955de52cSdanielk1977 const char *zOrigDb = 0; 1786955de52cSdanielk1977 const char *zOrigTab = 0; 1787955de52cSdanielk1977 const char *zOrigCol = 0; 1788cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1789955de52cSdanielk1977 179085b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 17914b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 17924b1ae99dSdanielk1977 ** virtual machine is deleted. 1793fbcd585fSdanielk1977 */ 179410fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 179510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 179610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 17973f913576Sdrh #else 1798cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 17993f913576Sdrh #endif 180010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1801fcb78a49Sdrh } 18025f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1803fcb78a49Sdrh } 1804fcb78a49Sdrh 1805eac5fc04Sdrh 1806eac5fc04Sdrh /* 1807ec360a8dSdrh ** Compute the column names for a SELECT statement. 1808ec360a8dSdrh ** 1809ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1810ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1811ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1812ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1813ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1814ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1815ec360a8dSdrh ** 1816ec360a8dSdrh ** See Also: sqlite3ColumnsFromExprList() 1817ec360a8dSdrh ** 1818ec360a8dSdrh ** The PRAGMA short_column_names and PRAGMA full_column_names settings are 1819ec360a8dSdrh ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all 1820ec360a8dSdrh ** applications should operate this way. Nevertheless, we need to support the 1821ec360a8dSdrh ** other modes for legacy: 1822ec360a8dSdrh ** 1823ec360a8dSdrh ** short=OFF, full=OFF: Column name is the text of the expression has it 1824ec360a8dSdrh ** originally appears in the SELECT statement. In 1825ec360a8dSdrh ** other words, the zSpan of the result expression. 1826ec360a8dSdrh ** 1827ec360a8dSdrh ** short=ON, full=OFF: (This is the default setting). If the result 18283d240d21Sdrh ** refers directly to a table column, then the 18293d240d21Sdrh ** result column name is just the table column 18303d240d21Sdrh ** name: COLUMN. Otherwise use zSpan. 1831ec360a8dSdrh ** 1832ec360a8dSdrh ** full=ON, short=ANY: If the result refers directly to a table column, 1833ec360a8dSdrh ** then the result column name with the table name 1834ec360a8dSdrh ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. 183582c3d636Sdrh */ 1836832508b7Sdrh static void generateColumnNames( 1837832508b7Sdrh Parse *pParse, /* Parser context */ 1838f35f2f92Sdrh Select *pSelect /* Generate column names for this SELECT statement */ 1839832508b7Sdrh ){ 1840d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1841eac5fc04Sdrh int i; 1842eac5fc04Sdrh Table *pTab; 1843f35f2f92Sdrh SrcList *pTabList; 1844f35f2f92Sdrh ExprList *pEList; 18459bb575fdSdrh sqlite3 *db = pParse->db; 1846ec360a8dSdrh int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ 1847ec360a8dSdrh int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ 1848fcabd464Sdrh 1849fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 18503cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 18513cf86063Sdanielk1977 if( pParse->explain ){ 185261de0d1bSdanielk1977 return; 18533cf86063Sdanielk1977 } 18545338a5f7Sdanielk1977 #endif 18553cf86063Sdanielk1977 18565e8b9853Sdrh if( pParse->colNamesSet ) return; 1857f35f2f92Sdrh /* Column names are determined by the left-most term of a compound select */ 1858f35f2f92Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 185907859486Sdrh SELECTTRACE(1,pParse,pSelect,("generating column names\n")); 1860f35f2f92Sdrh pTabList = pSelect->pSrc; 1861f35f2f92Sdrh pEList = pSelect->pEList; 18629802947fSdrh assert( v!=0 ); 1863f7ce4291Sdrh assert( pTabList!=0 ); 1864d8bc7086Sdrh pParse->colNamesSet = 1; 1865ec360a8dSdrh fullName = (db->flags & SQLITE_FullColNames)!=0; 1866ec360a8dSdrh srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; 186722322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 186882c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 1869ec360a8dSdrh Expr *p = pEList->a[i].pExpr; 1870ec360a8dSdrh 1871ec360a8dSdrh assert( p!=0 ); 18724dd89d5aSdrh assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ 18733d240d21Sdrh assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */ 187482c3d636Sdrh if( pEList->a[i].zName ){ 1875ec360a8dSdrh /* An AS clause always takes first priority */ 187682c3d636Sdrh char *zName = pEList->a[i].zName; 187710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1878f35f2f92Sdrh }else if( srcName && p->op==TK_COLUMN ){ 187997665873Sdrh char *zCol; 18808aff1015Sdrh int iCol = p->iColumn; 1881f35f2f92Sdrh pTab = p->pTab; 1882f35f2f92Sdrh assert( pTab!=0 ); 18838aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 188497665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1885b1363206Sdrh if( iCol<0 ){ 188647a6db2bSdrh zCol = "rowid"; 1887b1363206Sdrh }else{ 1888b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1889b1363206Sdrh } 1890ec360a8dSdrh if( fullName ){ 189182c3d636Sdrh char *zName = 0; 18921c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 189310fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 189482c3d636Sdrh }else{ 189510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 189682c3d636Sdrh } 18971bee3d7bSdrh }else{ 1898859bc542Sdrh const char *z = pEList->a[i].zSpan; 1899859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 1900859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 190182c3d636Sdrh } 190282c3d636Sdrh } 190376d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 19045080aaa7Sdrh } 190582c3d636Sdrh 1906d8bc7086Sdrh /* 190760ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 19087d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 19097d10d5a6Sdrh ** column names for a table that would hold the expression list. 19107d10d5a6Sdrh ** 19117d10d5a6Sdrh ** All column names will be unique. 19127d10d5a6Sdrh ** 19137d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 19147d10d5a6Sdrh ** and other fields of Column are zeroed. 19157d10d5a6Sdrh ** 19167d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 19177d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1918ec360a8dSdrh ** 1919ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1920ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1921ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1922ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1923ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1924ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1925ec360a8dSdrh ** 1926ec360a8dSdrh ** See Also: generateColumnNames() 1927315555caSdrh */ 19288981b904Sdrh int sqlite3ColumnsFromExprList( 19297d10d5a6Sdrh Parse *pParse, /* Parsing context */ 19307d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1931d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 19327d10d5a6Sdrh Column **paCol /* Write the new column list here */ 19337d10d5a6Sdrh ){ 1934dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1935dc5ea5c7Sdrh int i, j; /* Loop counters */ 1936ebed3fa3Sdrh u32 cnt; /* Index added to make the name unique */ 1937dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1938dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1939dc5ea5c7Sdrh char *zName; /* Column name */ 1940dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 19410315e3ccSdrh Hash ht; /* Hash table of column names */ 194279d5f63fSdrh 19430315e3ccSdrh sqlite3HashInit(&ht); 19448c2e0f02Sdan if( pEList ){ 19458c2e0f02Sdan nCol = pEList->nExpr; 19468c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 19478c2e0f02Sdan testcase( aCol==0 ); 19486fe3733bSdrh if( nCol>32767 ) nCol = 32767; 19498c2e0f02Sdan }else{ 19508c2e0f02Sdan nCol = 0; 19518c2e0f02Sdan aCol = 0; 19528c2e0f02Sdan } 19538836cbbcSdan assert( nCol==(i16)nCol ); 19548c2e0f02Sdan *pnCol = nCol; 19558c2e0f02Sdan *paCol = aCol; 19568c2e0f02Sdan 19570315e3ccSdrh for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ 195879d5f63fSdrh /* Get an appropriate name for the column 195979d5f63fSdrh */ 196091bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 196179d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 19627d10d5a6Sdrh }else{ 1963ec360a8dSdrh Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr); 1964b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1965b07028f7Sdrh pColExpr = pColExpr->pRight; 1966b07028f7Sdrh assert( pColExpr!=0 ); 1967b07028f7Sdrh } 1968755b0fd3Sdrh assert( pColExpr->op!=TK_AGG_COLUMN ); 1969755b0fd3Sdrh if( pColExpr->op==TK_COLUMN ){ 197093a960a0Sdrh /* For columns use the column name name */ 1971dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1972ec360a8dSdrh Table *pTab = pColExpr->pTab; 1973755b0fd3Sdrh assert( pTab!=0 ); 1974f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 197596ceaf86Sdrh zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; 1976b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 197733e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 197896ceaf86Sdrh zName = pColExpr->u.zToken; 197993a960a0Sdrh }else{ 198079d5f63fSdrh /* Use the original text of the column expression as its name */ 198196ceaf86Sdrh zName = pEList->a[i].zSpan; 19827d10d5a6Sdrh } 198322f70c32Sdrh } 1984d7ca600eSdrh if( zName ){ 1985d7ca600eSdrh zName = sqlite3DbStrDup(db, zName); 1986d7ca600eSdrh }else{ 1987155507b3Sdrh zName = sqlite3MPrintf(db,"column%d",i+1); 1988d7ca600eSdrh } 198979d5f63fSdrh 199079d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 199160ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 199279d5f63fSdrh */ 19930315e3ccSdrh cnt = 0; 19940315e3ccSdrh while( zName && sqlite3HashFind(&ht, zName)!=0 ){ 19950315e3ccSdrh nName = sqlite3Strlen30(zName); 1996f7ee8965Sdrh if( nName>0 ){ 19970315e3ccSdrh for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} 19980315e3ccSdrh if( zName[j]==':' ) nName = j; 1999f7ee8965Sdrh } 200096ceaf86Sdrh zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); 2001ebed3fa3Sdrh if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); 200279d5f63fSdrh } 200391bb0eedSdrh pCol->zName = zName; 2004ba68f8f3Sdan sqlite3ColumnPropertiesFromName(0, pCol); 200503d69a68Sdrh if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ 20064a642b60Sdrh sqlite3OomFault(db); 20077d10d5a6Sdrh } 20080315e3ccSdrh } 20090315e3ccSdrh sqlite3HashClear(&ht); 20107d10d5a6Sdrh if( db->mallocFailed ){ 20117d10d5a6Sdrh for(j=0; j<i; j++){ 20127d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 20137d10d5a6Sdrh } 20147d10d5a6Sdrh sqlite3DbFree(db, aCol); 20157d10d5a6Sdrh *paCol = 0; 20167d10d5a6Sdrh *pnCol = 0; 2017fad3039cSmistachkin return SQLITE_NOMEM_BKPT; 20187d10d5a6Sdrh } 20197d10d5a6Sdrh return SQLITE_OK; 20207d10d5a6Sdrh } 2021e014a838Sdanielk1977 20227d10d5a6Sdrh /* 20237d10d5a6Sdrh ** Add type and collation information to a column list based on 20247d10d5a6Sdrh ** a SELECT statement. 20257d10d5a6Sdrh ** 20267d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 20277d10d5a6Sdrh ** The column list has only names, not types or collations. This 20287d10d5a6Sdrh ** routine goes through and adds the types and collations. 20297d10d5a6Sdrh ** 2030b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 20317d10d5a6Sdrh ** statement be resolved. 203279d5f63fSdrh */ 2033ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation( 20347d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 2035186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 20367d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 20377d10d5a6Sdrh ){ 20387d10d5a6Sdrh sqlite3 *db = pParse->db; 20397d10d5a6Sdrh NameContext sNC; 20407d10d5a6Sdrh Column *pCol; 20417d10d5a6Sdrh CollSeq *pColl; 20427d10d5a6Sdrh int i; 20437d10d5a6Sdrh Expr *p; 20447d10d5a6Sdrh struct ExprList_item *a; 20457d10d5a6Sdrh 20467d10d5a6Sdrh assert( pSelect!=0 ); 20477d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 2048186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 20497d10d5a6Sdrh if( db->mallocFailed ) return; 2050c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 2051b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 20527d10d5a6Sdrh a = pSelect->pEList->a; 2053186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 2054ed06a131Sdrh const char *zType; 2055ed06a131Sdrh int n, m; 20567d10d5a6Sdrh p = a[i].pExpr; 2057cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 2058cafc2f7bSdrh /* pCol->szEst = ... // Column size est for SELECT tables never used */ 2059c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 20600c4db034Sdrh if( zType ){ 20610c4db034Sdrh m = sqlite3Strlen30(zType); 2062ed06a131Sdrh n = sqlite3Strlen30(pCol->zName); 2063ed06a131Sdrh pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); 2064ed06a131Sdrh if( pCol->zName ){ 2065ed06a131Sdrh memcpy(&pCol->zName[n+1], zType, m+1); 2066ed06a131Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 2067ed06a131Sdrh } 2068ed06a131Sdrh } 206905883a34Sdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB; 2070b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 20711cb50c88Sdrh if( pColl && pCol->zColl==0 ){ 207217435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 20730202b29eSdanielk1977 } 207422f70c32Sdrh } 2075cafc2f7bSdrh pTab->szTabRow = 1; /* Any non-zero value works */ 20767d10d5a6Sdrh } 20777d10d5a6Sdrh 20787d10d5a6Sdrh /* 20797d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 20807d10d5a6Sdrh ** the result set of that SELECT. 20817d10d5a6Sdrh */ 20827d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 20837d10d5a6Sdrh Table *pTab; 20847d10d5a6Sdrh sqlite3 *db = pParse->db; 20857d10d5a6Sdrh int savedFlags; 20867d10d5a6Sdrh 20877d10d5a6Sdrh savedFlags = db->flags; 20887d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 20897d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 20907d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 20917d10d5a6Sdrh if( pParse->nErr ) return 0; 20927d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 20937d10d5a6Sdrh db->flags = savedFlags; 20947d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 20957d10d5a6Sdrh if( pTab==0 ){ 20967d10d5a6Sdrh return 0; 20977d10d5a6Sdrh } 2098373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 2099b2468954Sdrh ** is disabled */ 21004a642b60Sdrh assert( db->lookaside.bDisable ); 210179df7782Sdrh pTab->nTabRef = 1; 21027d10d5a6Sdrh pTab->zName = 0; 2103cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 21048981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 2105ed06a131Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect); 210622f70c32Sdrh pTab->iPKey = -1; 21077ce72f69Sdrh if( db->mallocFailed ){ 21081feeaed2Sdan sqlite3DeleteTable(db, pTab); 21097ce72f69Sdrh return 0; 21107ce72f69Sdrh } 211122f70c32Sdrh return pTab; 211222f70c32Sdrh } 211322f70c32Sdrh 211422f70c32Sdrh /* 2115d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 2116d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 2117d8bc7086Sdrh */ 211855965619Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){ 211955965619Sdrh if( pParse->pVdbe ){ 212055965619Sdrh return pParse->pVdbe; 212155965619Sdrh } 2122e0e261a4Sdrh if( pParse->pToplevel==0 2123e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 2124e0e261a4Sdrh ){ 2125e0e261a4Sdrh pParse->okConstFactor = 1; 2126949f9cd5Sdrh } 212755965619Sdrh return sqlite3VdbeCreate(pParse); 21286f077343Sdrh } 2129d8bc7086Sdrh 213015007a99Sdrh 2131d8bc7086Sdrh /* 21327b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 21338c0833fbSdrh ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions 21347b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 2135a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 2136a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 2137a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 2138a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 21397b58daeaSdrh ** 2140d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 21418c0833fbSdrh ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit 21428c0833fbSdrh ** and iOffset should have been preset to appropriate default values (zero) 2143aa9ce707Sdrh ** prior to calling this routine. 2144aa9ce707Sdrh ** 2145aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 2146aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 2147aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 2148aa9ce707Sdrh ** 21498c0833fbSdrh ** Only if pLimit->pLeft!=0 do the limit registers get 21507b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 21517b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 21527b58daeaSdrh ** SELECT statements. 21537b58daeaSdrh */ 2154ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 215502afc861Sdrh Vdbe *v = 0; 215602afc861Sdrh int iLimit = 0; 215715007a99Sdrh int iOffset; 21588b0cf38aSdrh int n; 21598c0833fbSdrh Expr *pLimit = p->pLimit; 21608c0833fbSdrh 21610acb7e48Sdrh if( p->iLimit ) return; 216215007a99Sdrh 21637b58daeaSdrh /* 21647b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 2165f7b5496eSdrh ** controversy about what the correct behavior should be. 21667b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 21677b58daeaSdrh ** no rows. 21687b58daeaSdrh */ 2169ceea3321Sdrh sqlite3ExprCacheClear(pParse); 21708c0833fbSdrh if( pLimit ){ 21718c0833fbSdrh assert( pLimit->op==TK_LIMIT ); 21728c0833fbSdrh assert( pLimit->pLeft!=0 ); 21730a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 217415007a99Sdrh v = sqlite3GetVdbe(pParse); 2175aa9ce707Sdrh assert( v!=0 ); 21768c0833fbSdrh if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){ 21779b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 21789b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 2179456e4e4fSdrh if( n==0 ){ 2180076e85f5Sdrh sqlite3VdbeGoto(v, iBreak); 2181c3489bbfSdrh }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ 2182c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)n); 2183c3489bbfSdrh p->selFlags |= SF_FixedLimit; 21849b918ed1Sdrh } 21859b918ed1Sdrh }else{ 21868c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); 2187688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 2188d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 218916897072Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); 21909b918ed1Sdrh } 21918c0833fbSdrh if( pLimit->pRight ){ 21920a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 2193b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 21948c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pRight, iOffset); 2195688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 2196d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 2197cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); 2198d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 2199b7654111Sdrh } 2200d59ba6ceSdrh } 22017b58daeaSdrh } 22027b58daeaSdrh 2203b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 2204fbc4ee7bSdrh /* 2205fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 2206fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 2207fbc4ee7bSdrh ** the column has no default collating sequence. 2208fbc4ee7bSdrh ** 2209fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 2210fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 2211fbc4ee7bSdrh */ 2212dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 2213fbc4ee7bSdrh CollSeq *pRet; 2214dc1bdc4fSdanielk1977 if( p->pPrior ){ 2215dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 2216fbc4ee7bSdrh }else{ 2217fbc4ee7bSdrh pRet = 0; 2218dc1bdc4fSdanielk1977 } 221910c081adSdrh assert( iCol>=0 ); 22202ec18a3cSdrh /* iCol must be less than p->pEList->nExpr. Otherwise an error would 22212ec18a3cSdrh ** have been thrown during name resolution and we would not have gotten 22222ec18a3cSdrh ** this far */ 22232ec18a3cSdrh if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ 2224dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 2225dc1bdc4fSdanielk1977 } 2226dc1bdc4fSdanielk1977 return pRet; 2227d3d39e93Sdrh } 2228d3d39e93Sdrh 222953bed45eSdan /* 223053bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 223153bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 223253bed45eSdan ** structure suitable for implementing the ORDER BY. 223353bed45eSdan ** 223453bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 223553bed45eSdan ** function is responsible for ensuring that this structure is eventually 223653bed45eSdan ** freed. 223753bed45eSdan */ 223853bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 223953bed45eSdan ExprList *pOrderBy = p->pOrderBy; 224053bed45eSdan int nOrderBy = p->pOrderBy->nExpr; 224153bed45eSdan sqlite3 *db = pParse->db; 224253bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 224353bed45eSdan if( pRet ){ 224453bed45eSdan int i; 224553bed45eSdan for(i=0; i<nOrderBy; i++){ 224653bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 224753bed45eSdan Expr *pTerm = pItem->pExpr; 224853bed45eSdan CollSeq *pColl; 224953bed45eSdan 225053bed45eSdan if( pTerm->flags & EP_Collate ){ 225153bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 225253bed45eSdan }else{ 225353bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 225453bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 225553bed45eSdan pOrderBy->a[i].pExpr = 225653bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 225753bed45eSdan } 225853bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 225953bed45eSdan pRet->aColl[i] = pColl; 226053bed45eSdan pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; 226153bed45eSdan } 226253bed45eSdan } 226353bed45eSdan 226453bed45eSdan return pRet; 226553bed45eSdan } 2266d3d39e93Sdrh 2267781def29Sdrh #ifndef SQLITE_OMIT_CTE 2268781def29Sdrh /* 2269781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 2270781def29Sdrh ** query of the form: 2271781def29Sdrh ** 2272781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 2273781def29Sdrh ** \___________/ \_______________/ 2274781def29Sdrh ** p->pPrior p 2275781def29Sdrh ** 2276781def29Sdrh ** 2277781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 22788a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. 2279781def29Sdrh ** 2280781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 2281781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 2282fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 2283fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 2284fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 2285781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 2286781def29Sdrh ** and the iteration continues until the Queue table is empty. 2287781def29Sdrh ** 2288781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 2289781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 2290781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 2291781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 2292781def29Sdrh ** 2293781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 2294781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 2295781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 2296781def29Sdrh ** 2297781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 2298781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 2299781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 2300781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 2301781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 2302781def29Sdrh ** rows have been skipped. 2303781def29Sdrh */ 2304781def29Sdrh static void generateWithRecursiveQuery( 2305781def29Sdrh Parse *pParse, /* Parsing context */ 2306781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 2307781def29Sdrh SelectDest *pDest /* What to do with query results */ 2308781def29Sdrh ){ 2309781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 2310781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 2311781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 2312781def29Sdrh Select *pSetup = p->pPrior; /* The setup query */ 2313781def29Sdrh int addrTop; /* Top of the loop */ 2314781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 2315edf83d1eSdrh int iCurrent = 0; /* The Current table */ 2316781def29Sdrh int regCurrent; /* Register holding Current table */ 2317781def29Sdrh int iQueue; /* The Queue table */ 2318781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 23198e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 2320781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 2321781def29Sdrh int i; /* Loop counter */ 2322781def29Sdrh int rc; /* Result code */ 2323fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 23248c0833fbSdrh Expr *pLimit; /* Saved LIMIT and OFFSET */ 2325aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 2326781def29Sdrh 2327781def29Sdrh /* Obtain authorization to do a recursive query */ 2328781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 2329781def29Sdrh 2330aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 2331aa9ce707Sdrh addrBreak = sqlite3VdbeMakeLabel(v); 233269b9383eSdan p->nSelectRow = 320; /* 4 billion rows */ 2333aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 2334aa9ce707Sdrh pLimit = p->pLimit; 2335aa9ce707Sdrh regLimit = p->iLimit; 2336aa9ce707Sdrh regOffset = p->iOffset; 23378c0833fbSdrh p->pLimit = 0; 2338aa9ce707Sdrh p->iLimit = p->iOffset = 0; 233953bed45eSdan pOrderBy = p->pOrderBy; 2340781def29Sdrh 2341781def29Sdrh /* Locate the cursor number of the Current table */ 2342781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 23438a48b9c0Sdrh if( pSrc->a[i].fg.isRecursive ){ 2344781def29Sdrh iCurrent = pSrc->a[i].iCursor; 2345781def29Sdrh break; 2346781def29Sdrh } 2347781def29Sdrh } 2348781def29Sdrh 2349fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2350781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 23518e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2352781def29Sdrh iQueue = pParse->nTab++; 2353781def29Sdrh if( p->op==TK_UNION ){ 23548e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 2355781def29Sdrh iDistinct = pParse->nTab++; 2356fe1c6bb9Sdrh }else{ 23578e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2358781def29Sdrh } 2359781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2360781def29Sdrh 2361781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2362781def29Sdrh regCurrent = ++pParse->nMem; 2363781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2364fe1c6bb9Sdrh if( pOrderBy ){ 236553bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2366fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2367fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2368fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2369fe1c6bb9Sdrh }else{ 2370781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2371fe1c6bb9Sdrh } 2372fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2373781def29Sdrh if( iDistinct ){ 2374781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2375781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2376781def29Sdrh } 2377781def29Sdrh 237853bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 237953bed45eSdan p->pOrderBy = 0; 238053bed45eSdan 2381781def29Sdrh /* Store the results of the setup-query in Queue. */ 2382d227a291Sdrh pSetup->pNext = 0; 238384a01debSdrh ExplainQueryPlan((pParse, 1, "SETUP")); 2384781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2385d227a291Sdrh pSetup->pNext = p; 2386fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2387781def29Sdrh 2388781def29Sdrh /* Find the next row in the Queue and output that row */ 2389688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2390781def29Sdrh 2391781def29Sdrh /* Transfer the next row in Queue over to Current */ 2392781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2393fe1c6bb9Sdrh if( pOrderBy ){ 2394fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2395fe1c6bb9Sdrh }else{ 2396781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2397fe1c6bb9Sdrh } 2398781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2399781def29Sdrh 2400fe1c6bb9Sdrh /* Output the single row in Current */ 2401fe1c6bb9Sdrh addrCont = sqlite3VdbeMakeLabel(v); 2402aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 24032def2f7eSdrh selectInnerLoop(pParse, p, iCurrent, 2404079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2405688852abSdrh if( regLimit ){ 240616897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); 2407688852abSdrh VdbeCoverage(v); 2408688852abSdrh } 2409fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2410fe1c6bb9Sdrh 2411781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2412781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2413781def29Sdrh */ 2414b63ce02fSdrh if( p->selFlags & SF_Aggregate ){ 2415b63ce02fSdrh sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); 2416b63ce02fSdrh }else{ 2417781def29Sdrh p->pPrior = 0; 241884a01debSdrh ExplainQueryPlan((pParse, 1, "RECURSIVE STEP")); 2419781def29Sdrh sqlite3Select(pParse, p, &destQueue); 2420781def29Sdrh assert( p->pPrior==0 ); 2421781def29Sdrh p->pPrior = pSetup; 2422b63ce02fSdrh } 2423781def29Sdrh 2424781def29Sdrh /* Keep running the loop until the Queue is empty */ 2425076e85f5Sdrh sqlite3VdbeGoto(v, addrTop); 2426781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2427fe1c6bb9Sdrh 2428fe1c6bb9Sdrh end_of_recursive_query: 24299afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2430fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2431aa9ce707Sdrh p->pLimit = pLimit; 2432fe1c6bb9Sdrh return; 2433781def29Sdrh } 2434b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2435781def29Sdrh 2436781def29Sdrh /* Forward references */ 2437b21e7c70Sdrh static int multiSelectOrderBy( 2438b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2439b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2440a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2441b21e7c70Sdrh ); 2442b21e7c70Sdrh 244345f54a57Sdrh /* 244445f54a57Sdrh ** Handle the special case of a compound-select that originates from a 244545f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 244645f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 244745f54a57Sdrh ** on a VALUES clause. 244845f54a57Sdrh ** 244945f54a57Sdrh ** Because the Select object originates from a VALUES clause: 2450b058d054Sdrh ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 245145f54a57Sdrh ** (2) All terms are UNION ALL 245245f54a57Sdrh ** (3) There is no ORDER BY clause 2453b058d054Sdrh ** 2454b058d054Sdrh ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES 2455b058d054Sdrh ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). 2456b058d054Sdrh ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. 2457b058d054Sdrh ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES. 245845f54a57Sdrh */ 245945f54a57Sdrh static int multiSelectValues( 246045f54a57Sdrh Parse *pParse, /* Parsing context */ 246145f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 246245f54a57Sdrh SelectDest *pDest /* What to do with query results */ 246345f54a57Sdrh ){ 246445f54a57Sdrh int nRow = 1; 246545f54a57Sdrh int rc = 0; 2466fa16f5d9Sdrh int bShowAll = p->pLimit==0; 2467772460fdSdrh assert( p->selFlags & SF_MultiValue ); 246845f54a57Sdrh do{ 246945f54a57Sdrh assert( p->selFlags & SF_Values ); 247045f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 2471923cadb1Sdan assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); 247245f54a57Sdrh if( p->pPrior==0 ) break; 247345f54a57Sdrh assert( p->pPrior->pNext==p ); 247445f54a57Sdrh p = p->pPrior; 2475fa16f5d9Sdrh nRow += bShowAll; 247645f54a57Sdrh }while(1); 2477fa16f5d9Sdrh ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow, 2478fa16f5d9Sdrh nRow==1 ? "" : "S")); 247945f54a57Sdrh while( p ){ 2480fa16f5d9Sdrh selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1); 2481fa16f5d9Sdrh if( !bShowAll ) break; 248245f54a57Sdrh p->nSelectRow = nRow; 248345f54a57Sdrh p = p->pNext; 248445f54a57Sdrh } 248545f54a57Sdrh return rc; 248645f54a57Sdrh } 2487b21e7c70Sdrh 2488d3d39e93Sdrh /* 248916ee60ffSdrh ** This routine is called to process a compound query form from 249016ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 249116ee60ffSdrh ** INTERSECT 2492c926afbcSdrh ** 2493e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2494e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2495e78e8284Sdrh ** in which case this routine will be called recursively. 2496e78e8284Sdrh ** 2497e78e8284Sdrh ** The results of the total query are to be written into a destination 2498e78e8284Sdrh ** of type eDest with parameter iParm. 2499e78e8284Sdrh ** 2500e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2501e78e8284Sdrh ** 2502e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2503e78e8284Sdrh ** 2504e78e8284Sdrh ** This statement is parsed up as follows: 2505e78e8284Sdrh ** 2506e78e8284Sdrh ** SELECT c FROM t3 2507e78e8284Sdrh ** | 2508e78e8284Sdrh ** `-----> SELECT b FROM t2 2509e78e8284Sdrh ** | 25104b11c6d3Sjplyon ** `------> SELECT a FROM t1 2511e78e8284Sdrh ** 2512e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2513e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2514e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2515e78e8284Sdrh ** 2516e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2517e78e8284Sdrh ** individual selects always group from left to right. 251882c3d636Sdrh */ 251984ac9d02Sdanielk1977 static int multiSelect( 2520fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2521fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2522a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 252384ac9d02Sdanielk1977 ){ 252484ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 252510e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 252610e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 25271013c932Sdrh SelectDest dest; /* Alternative data destination */ 2528eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2529633e6d57Sdrh sqlite3 *db; /* Database connection */ 253082c3d636Sdrh 25317b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2532fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 253382c3d636Sdrh */ 2534701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2535eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2536633e6d57Sdrh db = pParse->db; 2537d8bc7086Sdrh pPrior = p->pPrior; 2538bc10377aSdrh dest = *pDest; 253963347e7dSdrh if( pPrior->pOrderBy || pPrior->pLimit ){ 254063347e7dSdrh sqlite3ErrorMsg(pParse,"%s clause should come after %s not before", 254163347e7dSdrh pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op)); 254284ac9d02Sdanielk1977 rc = 1; 254384ac9d02Sdanielk1977 goto multi_select_end; 25447b58daeaSdrh } 254582c3d636Sdrh 25464adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2547701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2548d8bc7086Sdrh 25491cc3d75fSdrh /* Create the destination temporary table if necessary 25501cc3d75fSdrh */ 25516c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2552b4964b72Sdanielk1977 assert( p->pEList ); 25532b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 25546c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 25551cc3d75fSdrh } 25561cc3d75fSdrh 255745f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 255845f54a57Sdrh */ 2559772460fdSdrh if( p->selFlags & SF_MultiValue ){ 256045f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 256145f54a57Sdrh goto multi_select_end; 256245f54a57Sdrh } 256345f54a57Sdrh 2564f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2565f6e369a1Sdrh ** in their result sets. 2566f6e369a1Sdrh */ 2567f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2568923cadb1Sdan assert( p->pEList->nExpr==pPrior->pEList->nExpr ); 2569f6e369a1Sdrh 2570eede6a53Sdan #ifndef SQLITE_OMIT_CTE 2571eae73fbfSdan if( p->selFlags & SF_Recursive ){ 2572781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 25738ce7184bSdan }else 25748ce7184bSdan #endif 2575f6e369a1Sdrh 2576a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2577a9671a22Sdrh */ 2578f6e369a1Sdrh if( p->pOrderBy ){ 2579a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 258003c3905fSdrh }else{ 2581f6e369a1Sdrh 2582c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN 258303c3905fSdrh if( pPrior->pPrior==0 ){ 25844d79983cSdrh ExplainQueryPlan((pParse, 1, "COMPOUND QUERY")); 2585c631ded5Sdrh ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); 2586c631ded5Sdrh } 2587c631ded5Sdrh #endif 2588c631ded5Sdrh 2589f46f905aSdrh /* Generate code for the left and right SELECT statements. 2590d8bc7086Sdrh */ 259182c3d636Sdrh switch( p->op ){ 2592f46f905aSdrh case TK_ALL: { 2593ec7429aeSdrh int addr = 0; 259495aa47b1Sdrh int nLimit; 2595a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2596547180baSdrh pPrior->iLimit = p->iLimit; 2597547180baSdrh pPrior->iOffset = p->iOffset; 2598a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 25997d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2600ad68cb6bSdanielk1977 p->pLimit = 0; 260184ac9d02Sdanielk1977 if( rc ){ 260284ac9d02Sdanielk1977 goto multi_select_end; 260384ac9d02Sdanielk1977 } 2604f46f905aSdrh p->pPrior = 0; 26057b58daeaSdrh p->iLimit = pPrior->iLimit; 26067b58daeaSdrh p->iOffset = pPrior->iOffset; 260792b01d53Sdrh if( p->iLimit ){ 260816897072Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); 2609d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 26109f1ef45fSdrh if( p->iOffset ){ 2611cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, 2612cc2fa4cfSdrh p->iLimit, p->iOffset+1, p->iOffset); 26139f1ef45fSdrh } 2614ec7429aeSdrh } 2615c631ded5Sdrh ExplainQueryPlan((pParse, 1, "UNION ALL")); 26167d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2617373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2618eca7e01aSdanielk1977 pDelete = p->pPrior; 2619f46f905aSdrh p->pPrior = pPrior; 2620c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 262195aa47b1Sdrh if( pPrior->pLimit 26228c0833fbSdrh && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) 2623c3489bbfSdrh && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 262495aa47b1Sdrh ){ 2625c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)nLimit); 262695aa47b1Sdrh } 2627ec7429aeSdrh if( addr ){ 2628ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2629ec7429aeSdrh } 2630f46f905aSdrh break; 2631f46f905aSdrh } 263282c3d636Sdrh case TK_EXCEPT: 263382c3d636Sdrh case TK_UNION: { 263403c3905fSdrh int unionTab; /* Cursor number of the temp table holding result */ 2635ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2636d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 26378c0833fbSdrh Expr *pLimit; /* Saved values of p->nLimit */ 2638dc1bdc4fSdanielk1977 int addr; 26396c8c8ce0Sdanielk1977 SelectDest uniondest; 264082c3d636Sdrh 2641373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2642373cc2ddSdrh testcase( p->op==TK_UNION ); 264393a960a0Sdrh priorOp = SRT_Union; 2644d227a291Sdrh if( dest.eDest==priorOp ){ 2645d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2646c926afbcSdrh ** right. 2647d8bc7086Sdrh */ 2648e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 26492b596da8Sdrh unionTab = dest.iSDParm; 265082c3d636Sdrh }else{ 2651d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2652d8bc7086Sdrh ** intermediate results. 2653d8bc7086Sdrh */ 265482c3d636Sdrh unionTab = pParse->nTab++; 265593a960a0Sdrh assert( p->pOrderBy==0 ); 265666a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2657b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2658b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2659d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 266084ac9d02Sdanielk1977 assert( p->pEList ); 2661d8bc7086Sdrh } 2662d8bc7086Sdrh 2663d8bc7086Sdrh /* Code the SELECT statements to our left 2664d8bc7086Sdrh */ 2665b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 26661013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 26677d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 266884ac9d02Sdanielk1977 if( rc ){ 266984ac9d02Sdanielk1977 goto multi_select_end; 267084ac9d02Sdanielk1977 } 2671d8bc7086Sdrh 2672d8bc7086Sdrh /* Code the current SELECT statement 2673d8bc7086Sdrh */ 26744cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 26754cfb22f7Sdrh op = SRT_Except; 26764cfb22f7Sdrh }else{ 26774cfb22f7Sdrh assert( p->op==TK_UNION ); 26784cfb22f7Sdrh op = SRT_Union; 2679d8bc7086Sdrh } 268082c3d636Sdrh p->pPrior = 0; 2681a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2682a2dc3b1aSdanielk1977 p->pLimit = 0; 26836c8c8ce0Sdanielk1977 uniondest.eDest = op; 2684c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2685c631ded5Sdrh selectOpName(p->op))); 26867d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2687373cc2ddSdrh testcase( rc!=SQLITE_OK ); 26885bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 26895bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2690633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 2691eca7e01aSdanielk1977 pDelete = p->pPrior; 269282c3d636Sdrh p->pPrior = pPrior; 2693a9671a22Sdrh p->pOrderBy = 0; 2694c3489bbfSdrh if( p->op==TK_UNION ){ 2695c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 2696c3489bbfSdrh } 2697633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2698a2dc3b1aSdanielk1977 p->pLimit = pLimit; 269992b01d53Sdrh p->iLimit = 0; 270092b01d53Sdrh p->iOffset = 0; 2701d8bc7086Sdrh 2702d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2703d8bc7086Sdrh ** it is that we currently need. 2704d8bc7086Sdrh */ 27052b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2706373cc2ddSdrh if( dest.eDest!=priorOp ){ 27076b56344dSdrh int iCont, iBreak, iStart; 270882c3d636Sdrh assert( p->pEList ); 27094adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 27104adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2711ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2712688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 27134adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 27142def2f7eSdrh selectInnerLoop(pParse, p, unionTab, 2715e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 27164adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2717688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 27184adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 271966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 272082c3d636Sdrh } 272182c3d636Sdrh break; 272282c3d636Sdrh } 2723373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 272482c3d636Sdrh int tab1, tab2; 27256b56344dSdrh int iCont, iBreak, iStart; 27268c0833fbSdrh Expr *pLimit; 2727dc1bdc4fSdanielk1977 int addr; 27281013c932Sdrh SelectDest intersectdest; 27299cbf3425Sdrh int r1; 273082c3d636Sdrh 2731d8bc7086Sdrh /* INTERSECT is different from the others since it requires 27326206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2733d8bc7086Sdrh ** by allocating the tables we will need. 2734d8bc7086Sdrh */ 273582c3d636Sdrh tab1 = pParse->nTab++; 273682c3d636Sdrh tab2 = pParse->nTab++; 273793a960a0Sdrh assert( p->pOrderBy==0 ); 2738dc1bdc4fSdanielk1977 273966a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2740b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2741b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2742d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 274384ac9d02Sdanielk1977 assert( p->pEList ); 2744d8bc7086Sdrh 2745d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2746d8bc7086Sdrh */ 27471013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 27487d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 274984ac9d02Sdanielk1977 if( rc ){ 275084ac9d02Sdanielk1977 goto multi_select_end; 275184ac9d02Sdanielk1977 } 2752d8bc7086Sdrh 2753d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2754d8bc7086Sdrh */ 275566a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2756b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2757b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 275882c3d636Sdrh p->pPrior = 0; 2759a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2760a2dc3b1aSdanielk1977 p->pLimit = 0; 27612b596da8Sdrh intersectdest.iSDParm = tab2; 2762c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2763c631ded5Sdrh selectOpName(p->op))); 27647d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 2765373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2766eca7e01aSdanielk1977 pDelete = p->pPrior; 276782c3d636Sdrh p->pPrior = pPrior; 276803c3905fSdrh if( p->nSelectRow>pPrior->nSelectRow ){ 276903c3905fSdrh p->nSelectRow = pPrior->nSelectRow; 277003c3905fSdrh } 2771633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2772a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2773d8bc7086Sdrh 2774d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2775d8bc7086Sdrh ** tables. 2776d8bc7086Sdrh */ 277782c3d636Sdrh assert( p->pEList ); 27784adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 27794adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2780ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2781688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 27829cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 27839057fc7cSdrh iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); 278403c3905fSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); 278503c3905fSdrh VdbeCoverage(v); 27869cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 27872def2f7eSdrh selectInnerLoop(pParse, p, tab1, 2788e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 27894adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2790688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); 27914adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 279266a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 279366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 279482c3d636Sdrh break; 279582c3d636Sdrh } 279682c3d636Sdrh } 27978cdbf836Sdrh 2798c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN 2799c631ded5Sdrh if( p->pNext==0 ){ 2800e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 2801c631ded5Sdrh } 2802c631ded5Sdrh #endif 280303c3905fSdrh } 28047f61e92cSdan 2805a9671a22Sdrh /* Compute collating sequences used by 2806a9671a22Sdrh ** temporary tables needed to implement the compound select. 2807a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 28088cdbf836Sdrh ** 28098cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 28108cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 28118cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 28128cdbf836Sdrh ** no temp tables are required. 2813fbc4ee7bSdrh */ 28147d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 2815fbc4ee7bSdrh int i; /* Loop counter */ 2816fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 28170342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 2818f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 281993a960a0Sdrh int nCol; /* Number of columns in result set */ 2820fbc4ee7bSdrh 2821d227a291Sdrh assert( p->pNext==0 ); 282293a960a0Sdrh nCol = p->pEList->nExpr; 2823ad124329Sdrh pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); 2824dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 2825fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT; 2826dc1bdc4fSdanielk1977 goto multi_select_end; 2827dc1bdc4fSdanielk1977 } 28280342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 28290342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 28300342b1f5Sdrh if( 0==*apColl ){ 2831633e6d57Sdrh *apColl = db->pDfltColl; 2832dc1bdc4fSdanielk1977 } 2833dc1bdc4fSdanielk1977 } 2834dc1bdc4fSdanielk1977 28350342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 28360342b1f5Sdrh for(i=0; i<2; i++){ 2837b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 28380342b1f5Sdrh if( addr<0 ){ 28390342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 28400342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 2841b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 28420342b1f5Sdrh break; 28430342b1f5Sdrh } 28440342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 28452ec2fb22Sdrh sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), 28462ec2fb22Sdrh P4_KEYINFO); 28470ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 28480342b1f5Sdrh } 2849dc1bdc4fSdanielk1977 } 28502ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyInfo); 2851dc1bdc4fSdanielk1977 } 2852dc1bdc4fSdanielk1977 2853dc1bdc4fSdanielk1977 multi_select_end: 28542b596da8Sdrh pDest->iSdst = dest.iSdst; 28552b596da8Sdrh pDest->nSdst = dest.nSdst; 2856633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 285784ac9d02Sdanielk1977 return rc; 28582282792aSdrh } 2859b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 28602282792aSdrh 2861b21e7c70Sdrh /* 286289b31d73Smistachkin ** Error message for when two or more terms of a compound select have different 286389b31d73Smistachkin ** size result sets. 286489b31d73Smistachkin */ 286589b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ 286689b31d73Smistachkin if( p->selFlags & SF_Values ){ 286789b31d73Smistachkin sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 286889b31d73Smistachkin }else{ 286989b31d73Smistachkin sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 287089b31d73Smistachkin " do not have the same number of result columns", selectOpName(p->op)); 287189b31d73Smistachkin } 287289b31d73Smistachkin } 287389b31d73Smistachkin 287489b31d73Smistachkin /* 2875b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 2876b21e7c70Sdrh ** SELECT statment. 28770acb7e48Sdrh ** 28782b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 28792b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 28800acb7e48Sdrh ** be sent. 28810acb7e48Sdrh ** 28820acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 28830acb7e48Sdrh ** return address. 28840acb7e48Sdrh ** 2885f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 28860acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 28870acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 28880acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 28890acb7e48Sdrh ** keys. 28900acb7e48Sdrh ** 28910acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 28920acb7e48Sdrh ** iBreak. 2893b21e7c70Sdrh */ 28940acb7e48Sdrh static int generateOutputSubroutine( 289592b01d53Sdrh Parse *pParse, /* Parsing context */ 289692b01d53Sdrh Select *p, /* The SELECT statement */ 289792b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 289892b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 289992b01d53Sdrh int regReturn, /* The return address register */ 29000acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 29010acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 290292b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 2903b21e7c70Sdrh ){ 2904b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 290592b01d53Sdrh int iContinue; 290692b01d53Sdrh int addr; 2907b21e7c70Sdrh 290892b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 290992b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 29100acb7e48Sdrh 29110acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 29120acb7e48Sdrh */ 29130acb7e48Sdrh if( regPrev ){ 2914728e0f91Sdrh int addr1, addr2; 2915728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 2916728e0f91Sdrh addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 29172ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 2918728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); 2919728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 2920e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2921ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 29220acb7e48Sdrh } 29231f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 29240acb7e48Sdrh 2925d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 29260acb7e48Sdrh */ 2927aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 2928b21e7c70Sdrh 2929e2248cfdSdrh assert( pDest->eDest!=SRT_Exists ); 2930e2248cfdSdrh assert( pDest->eDest!=SRT_Table ); 2931b21e7c70Sdrh switch( pDest->eDest ){ 2932b21e7c70Sdrh /* Store the result as data using a unique key. 2933b21e7c70Sdrh */ 2934b21e7c70Sdrh case SRT_EphemTab: { 2935b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 2936b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 29372b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 29382b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 29392b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2940b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2941b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 2942b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2943b21e7c70Sdrh break; 2944b21e7c70Sdrh } 2945b21e7c70Sdrh 2946b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 29471431807aSdrh /* If we are creating a set for an "expr IN (SELECT ...)". 2948b21e7c70Sdrh */ 2949b21e7c70Sdrh case SRT_Set: { 29506fccc35aSdrh int r1; 295163cecc41Sdrh testcase( pIn->nSdst>1 ); 2952b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 295371c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 29541431807aSdrh r1, pDest->zAffSdst, pIn->nSdst); 29551431807aSdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 29569b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, 29579b4eaebcSdrh pIn->iSdst, pIn->nSdst); 2958b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2959b21e7c70Sdrh break; 2960b21e7c70Sdrh } 2961b21e7c70Sdrh 2962b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2963b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2964b21e7c70Sdrh ** of the scan loop. 2965b21e7c70Sdrh */ 2966b21e7c70Sdrh case SRT_Mem: { 2967a276e3fdSdrh assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); 29682b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); 2969b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2970b21e7c70Sdrh break; 2971b21e7c70Sdrh } 2972b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2973b21e7c70Sdrh 29747d10d5a6Sdrh /* The results are stored in a sequence of registers 29752b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 2976b21e7c70Sdrh */ 297792b01d53Sdrh case SRT_Coroutine: { 29782b596da8Sdrh if( pDest->iSdst==0 ){ 29792b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 29802b596da8Sdrh pDest->nSdst = pIn->nSdst; 2981b21e7c70Sdrh } 29824b79bde7Sdan sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); 29832b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 298492b01d53Sdrh break; 298592b01d53Sdrh } 298692b01d53Sdrh 2987ccfcbceaSdrh /* If none of the above, then the result destination must be 2988ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2989ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2990ccfcbceaSdrh ** 2991ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2992ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2993ccfcbceaSdrh ** return the next row of result. 29947d10d5a6Sdrh */ 2995ccfcbceaSdrh default: { 2996ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 29972b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 29982b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 2999b21e7c70Sdrh break; 3000b21e7c70Sdrh } 3001b21e7c70Sdrh } 300292b01d53Sdrh 300392b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 300492b01d53Sdrh */ 300592b01d53Sdrh if( p->iLimit ){ 300616897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 300792b01d53Sdrh } 300892b01d53Sdrh 300992b01d53Sdrh /* Generate the subroutine return 301092b01d53Sdrh */ 30110acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 301292b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 301392b01d53Sdrh 301492b01d53Sdrh return addr; 3015b21e7c70Sdrh } 3016b21e7c70Sdrh 3017b21e7c70Sdrh /* 3018b21e7c70Sdrh ** Alternative compound select code generator for cases when there 3019b21e7c70Sdrh ** is an ORDER BY clause. 3020b21e7c70Sdrh ** 3021b21e7c70Sdrh ** We assume a query of the following form: 3022b21e7c70Sdrh ** 3023b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 3024b21e7c70Sdrh ** 3025b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 3026b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 3027b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 3028b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 3029b21e7c70Sdrh ** selectB) there are 7 subroutines: 3030b21e7c70Sdrh ** 3031b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 3032b21e7c70Sdrh ** of the compound query. 3033b21e7c70Sdrh ** 3034b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 3035b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 3036b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 3037b21e7c70Sdrh ** appears only in B.) 3038b21e7c70Sdrh ** 3039b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 3040b21e7c70Sdrh ** 3041b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 3042b21e7c70Sdrh ** 3043b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 3044b21e7c70Sdrh ** 3045b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 3046b21e7c70Sdrh ** 3047b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 3048b21e7c70Sdrh ** 3049b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 3050b21e7c70Sdrh ** <operator> is used: 3051b21e7c70Sdrh ** 3052b21e7c70Sdrh ** 3053b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 3054b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 3055b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 3056b21e7c70Sdrh ** 30570acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 3058b21e7c70Sdrh ** 3059b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 3060b21e7c70Sdrh ** 30610acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 3062b21e7c70Sdrh ** 30630acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 30640acb7e48Sdrh ** 30650acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 30660acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 30670acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 30680acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 30690acb7e48Sdrh ** 30700acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 30710acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 30720acb7e48Sdrh ** output value. A comparison is made against this value and the output 30730acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 3074b21e7c70Sdrh ** 3075b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 3076b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 3077b21e7c70Sdrh ** 3078b21e7c70Sdrh ** goto Init 3079b21e7c70Sdrh ** coA: coroutine for left query (A) 3080b21e7c70Sdrh ** coB: coroutine for right query (B) 3081b21e7c70Sdrh ** outA: output one row of A 3082b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 3083b21e7c70Sdrh ** EofA: ... 3084b21e7c70Sdrh ** EofB: ... 3085b21e7c70Sdrh ** AltB: ... 3086b21e7c70Sdrh ** AeqB: ... 3087b21e7c70Sdrh ** AgtB: ... 3088b21e7c70Sdrh ** Init: initialize coroutine registers 3089b21e7c70Sdrh ** yield coA 3090b21e7c70Sdrh ** if eof(A) goto EofA 3091b21e7c70Sdrh ** yield coB 3092b21e7c70Sdrh ** if eof(B) goto EofB 3093b21e7c70Sdrh ** Cmpr: Compare A, B 3094b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 3095b21e7c70Sdrh ** End: ... 3096b21e7c70Sdrh ** 3097b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 3098b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 3099b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 3100b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 3101b21e7c70Sdrh */ 3102de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3103b21e7c70Sdrh static int multiSelectOrderBy( 3104b21e7c70Sdrh Parse *pParse, /* Parsing context */ 3105b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 3106a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 3107b21e7c70Sdrh ){ 31080acb7e48Sdrh int i, j; /* Loop counters */ 3109b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 3110b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 3111b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 3112b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 311392b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 311492b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 311592b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 311692b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 311792b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 311892b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 311992b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 3120b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 312192b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 312281cf13ecSdrh int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ 312392b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 312492b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 312592b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 312692b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 312792b01d53Sdrh int regLimitA; /* Limit register for select-A */ 312892b01d53Sdrh int regLimitB; /* Limit register for select-A */ 31290acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 313092b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 313192b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 313292b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 313392b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 3134728e0f91Sdrh int addr1; /* Jump instructions that get retargetted */ 313592b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 313696067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 31370acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 31380acb7e48Sdrh sqlite3 *db; /* Database connection */ 31390acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 31400acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 31410acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 3142b21e7c70Sdrh 314392b01d53Sdrh assert( p->pOrderBy!=0 ); 314496067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 31450acb7e48Sdrh db = pParse->db; 314692b01d53Sdrh v = pParse->pVdbe; 3147ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 314892b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 314992b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 31500acb7e48Sdrh 3151b21e7c70Sdrh 315292b01d53Sdrh /* Patch up the ORDER BY clause 315392b01d53Sdrh */ 315492b01d53Sdrh op = p->op; 3155b21e7c70Sdrh pPrior = p->pPrior; 315692b01d53Sdrh assert( pPrior->pOrderBy==0 ); 31570acb7e48Sdrh pOrderBy = p->pOrderBy; 315893a960a0Sdrh assert( pOrderBy ); 31590acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 316093a960a0Sdrh 31610acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 31620acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 31630acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 31640acb7e48Sdrh */ 31650acb7e48Sdrh if( op!=TK_ALL ){ 31660acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 31677d10d5a6Sdrh struct ExprList_item *pItem; 31687d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 3169c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 ); 3170c2acc4e4Sdrh if( pItem->u.x.iOrderByCol==i ) break; 31710acb7e48Sdrh } 31720acb7e48Sdrh if( j==nOrderBy ){ 3173b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 3174fad3039cSmistachkin if( pNew==0 ) return SQLITE_NOMEM_BKPT; 31750acb7e48Sdrh pNew->flags |= EP_IntValue; 317633e619fcSdrh pNew->u.iValue = i; 317743606175Sdrh p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 3178c2acc4e4Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; 31790acb7e48Sdrh } 31800acb7e48Sdrh } 31810acb7e48Sdrh } 31820acb7e48Sdrh 31830acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 318410c081adSdrh ** the permutation used to determine if the next 31850acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 31860acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 31870acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 31880acb7e48Sdrh ** collation. 31890acb7e48Sdrh */ 3190575fad65Sdrh aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); 31910acb7e48Sdrh if( aPermute ){ 31927d10d5a6Sdrh struct ExprList_item *pItem; 3193b1702026Sdrh aPermute[0] = nOrderBy; 3194b1702026Sdrh for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ 31956736618aSdrh assert( pItem->u.x.iOrderByCol>0 ); 31962ec18a3cSdrh assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 3197c2acc4e4Sdrh aPermute[i] = pItem->u.x.iOrderByCol - 1; 31980acb7e48Sdrh } 319953bed45eSdan pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 32000acb7e48Sdrh }else{ 32010acb7e48Sdrh pKeyMerge = 0; 32020acb7e48Sdrh } 32030acb7e48Sdrh 32040acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 32050acb7e48Sdrh */ 32060acb7e48Sdrh p->pOrderBy = pOrderBy; 32076ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 32080acb7e48Sdrh 32090acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 32100acb7e48Sdrh ** for the logic that removes duplicate result rows when the 32110acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 32120acb7e48Sdrh */ 32130acb7e48Sdrh if( op==TK_ALL ){ 32140acb7e48Sdrh regPrev = 0; 32150acb7e48Sdrh }else{ 32160acb7e48Sdrh int nExpr = p->pEList->nExpr; 32171c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 3218c8ac0d16Sdrh regPrev = pParse->nMem+1; 3219c8ac0d16Sdrh pParse->nMem += nExpr+1; 32200acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 3221ad124329Sdrh pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); 32220acb7e48Sdrh if( pKeyDup ){ 32232ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); 32240acb7e48Sdrh for(i=0; i<nExpr; i++){ 32250acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 32260acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 32270acb7e48Sdrh } 32280acb7e48Sdrh } 32290acb7e48Sdrh } 323092b01d53Sdrh 323192b01d53Sdrh /* Separate the left and the right query from one another 323292b01d53Sdrh */ 323392b01d53Sdrh p->pPrior = 0; 3234d227a291Sdrh pPrior->pNext = 0; 32357d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 32360acb7e48Sdrh if( pPrior->pPrior==0 ){ 32377d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 32380acb7e48Sdrh } 323992b01d53Sdrh 324092b01d53Sdrh /* Compute the limit registers */ 324192b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 32420acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 324392b01d53Sdrh regLimitA = ++pParse->nMem; 324492b01d53Sdrh regLimitB = ++pParse->nMem; 324592b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 324692b01d53Sdrh regLimitA); 324792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 324892b01d53Sdrh }else{ 324992b01d53Sdrh regLimitA = regLimitB = 0; 325092b01d53Sdrh } 3251633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 32520acb7e48Sdrh p->pLimit = 0; 325392b01d53Sdrh 3254b21e7c70Sdrh regAddrA = ++pParse->nMem; 3255b21e7c70Sdrh regAddrB = ++pParse->nMem; 3256b21e7c70Sdrh regOutA = ++pParse->nMem; 3257b21e7c70Sdrh regOutB = ++pParse->nMem; 3258b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 3259b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 3260e2ca99c9Sdrh 3261c631ded5Sdrh ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op))); 3262b21e7c70Sdrh 326392b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 32640acb7e48Sdrh ** left of the compound operator - the "A" select. 32650acb7e48Sdrh */ 3266ed71a839Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 3267728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 3268ed71a839Sdrh VdbeComment((v, "left SELECT")); 326992b01d53Sdrh pPrior->iLimit = regLimitA; 3270c631ded5Sdrh ExplainQueryPlan((pParse, 1, "LEFT")); 32717d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 32722fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrA); 3273728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3274b21e7c70Sdrh 327592b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 327692b01d53Sdrh ** the right - the "B" select 327792b01d53Sdrh */ 3278ed71a839Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 3279728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 3280ed71a839Sdrh VdbeComment((v, "right SELECT")); 328192b01d53Sdrh savedLimit = p->iLimit; 328292b01d53Sdrh savedOffset = p->iOffset; 328392b01d53Sdrh p->iLimit = regLimitB; 328492b01d53Sdrh p->iOffset = 0; 3285c631ded5Sdrh ExplainQueryPlan((pParse, 1, "RIGHT")); 32867d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 328792b01d53Sdrh p->iLimit = savedLimit; 328892b01d53Sdrh p->iOffset = savedOffset; 32892fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrB); 3290b21e7c70Sdrh 329192b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 32920acb7e48Sdrh ** select as the next output row of the compound select. 329392b01d53Sdrh */ 3294b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 32950acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 32960acb7e48Sdrh p, &destA, pDest, regOutA, 32972ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 3298b21e7c70Sdrh 329992b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 33000acb7e48Sdrh ** select as the next output row of the compound select. 330192b01d53Sdrh */ 33020acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 3303b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 33040acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 33050acb7e48Sdrh p, &destB, pDest, regOutB, 33062ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 33070acb7e48Sdrh } 33082ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyDup); 3309b21e7c70Sdrh 331092b01d53Sdrh /* Generate a subroutine to run when the results from select A 331192b01d53Sdrh ** are exhausted and only data in select B remains. 331292b01d53Sdrh */ 331392b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 331481cf13ecSdrh addrEofA_noB = addrEofA = labelEnd; 331592b01d53Sdrh }else{ 331681cf13ecSdrh VdbeNoopComment((v, "eof-A subroutine")); 331781cf13ecSdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 331881cf13ecSdrh addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 3319688852abSdrh VdbeCoverage(v); 3320076e85f5Sdrh sqlite3VdbeGoto(v, addrEofA); 3321c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 3322b21e7c70Sdrh } 3323b21e7c70Sdrh 332492b01d53Sdrh /* Generate a subroutine to run when the results from select B 332592b01d53Sdrh ** are exhausted and only data in select A remains. 332692b01d53Sdrh */ 3327b21e7c70Sdrh if( op==TK_INTERSECT ){ 332892b01d53Sdrh addrEofB = addrEofA; 332995aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3330b21e7c70Sdrh }else{ 333192b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 333281cf13ecSdrh addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3333688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 3334076e85f5Sdrh sqlite3VdbeGoto(v, addrEofB); 3335b21e7c70Sdrh } 3336b21e7c70Sdrh 333792b01d53Sdrh /* Generate code to handle the case of A<B 333892b01d53Sdrh */ 3339b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 33400acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3341688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3342076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3343b21e7c70Sdrh 334492b01d53Sdrh /* Generate code to handle the case of A==B 334592b01d53Sdrh */ 3346b21e7c70Sdrh if( op==TK_ALL ){ 3347b21e7c70Sdrh addrAeqB = addrAltB; 33480acb7e48Sdrh }else if( op==TK_INTERSECT ){ 33490acb7e48Sdrh addrAeqB = addrAltB; 33500acb7e48Sdrh addrAltB++; 335192b01d53Sdrh }else{ 3352b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 33530acb7e48Sdrh addrAeqB = 3354688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3355076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 335692b01d53Sdrh } 3357b21e7c70Sdrh 335892b01d53Sdrh /* Generate code to handle the case of A>B 335992b01d53Sdrh */ 3360b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 3361b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 3362b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 3363b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 336492b01d53Sdrh } 3365688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3366076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3367b21e7c70Sdrh 336892b01d53Sdrh /* This code runs once to initialize everything. 336992b01d53Sdrh */ 3370728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3371688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3372688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 337392b01d53Sdrh 337492b01d53Sdrh /* Implement the main merge loop 337592b01d53Sdrh */ 337692b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 33770acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 33782b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 33792ec2fb22Sdrh (char*)pKeyMerge, P4_KEYINFO); 3380953f7611Sdrh sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3381688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 338292b01d53Sdrh 338392b01d53Sdrh /* Jump to the this point in order to terminate the query. 338492b01d53Sdrh */ 3385b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 3386b21e7c70Sdrh 33870acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 33880acb7e48Sdrh ** by the calling function */ 33895e7ad508Sdanielk1977 if( p->pPrior ){ 3390633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 33915e7ad508Sdanielk1977 } 33920acb7e48Sdrh p->pPrior = pPrior; 3393d227a291Sdrh pPrior->pNext = p; 339492b01d53Sdrh 339592b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 339692b01d53Sdrh **** subqueries ****/ 3397e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 33983dc4cc66Sdrh return pParse->nErr!=0; 339992b01d53Sdrh } 3400de3e41e3Sdanielk1977 #endif 3401b21e7c70Sdrh 34023514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 340346967de2Sdrh 340446967de2Sdrh /* An instance of the SubstContext object describes an substitution edit 340546967de2Sdrh ** to be performed on a parse tree. 340646967de2Sdrh ** 340746967de2Sdrh ** All references to columns in table iTable are to be replaced by corresponding 340846967de2Sdrh ** expressions in pEList. 340946967de2Sdrh */ 341046967de2Sdrh typedef struct SubstContext { 341146967de2Sdrh Parse *pParse; /* The parsing context */ 341246967de2Sdrh int iTable; /* Replace references to this table */ 341331d6fd55Sdrh int iNewTable; /* New table number */ 341431d6fd55Sdrh int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ 341546967de2Sdrh ExprList *pEList; /* Replacement expressions */ 341646967de2Sdrh } SubstContext; 341746967de2Sdrh 341817435752Sdrh /* Forward Declarations */ 341946967de2Sdrh static void substExprList(SubstContext*, ExprList*); 342046967de2Sdrh static void substSelect(SubstContext*, Select*, int); 342117435752Sdrh 34222282792aSdrh /* 3423832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 34246a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 342584e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 34266a3ea0e6Sdrh ** unchanged.) 3427832508b7Sdrh ** 3428832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 3429832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 3430832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3431aca19e19Sdrh ** FORM clause entry is iTable. This routine makes the necessary 3432832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 3433832508b7Sdrh ** of the subquery rather the result set of the subquery. 3434832508b7Sdrh */ 3435b7916a78Sdrh static Expr *substExpr( 343646967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 343746967de2Sdrh Expr *pExpr /* Expr in which substitution occurs */ 343817435752Sdrh ){ 3439b7916a78Sdrh if( pExpr==0 ) return 0; 34403d240d21Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) 34413d240d21Sdrh && pExpr->iRightJoinTable==pSubst->iTable 34423d240d21Sdrh ){ 3443399c7e21Sdrh pExpr->iRightJoinTable = pSubst->iNewTable; 3444399c7e21Sdrh } 344546967de2Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){ 344650350a15Sdrh if( pExpr->iColumn<0 ){ 344750350a15Sdrh pExpr->op = TK_NULL; 344850350a15Sdrh }else{ 3449832508b7Sdrh Expr *pNew; 345046967de2Sdrh Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; 345131d6fd55Sdrh Expr ifNullRow; 345246967de2Sdrh assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr ); 3453*1fd4e7bbSdrh assert( pExpr->pRight==0 ); 345444c5604cSdan if( sqlite3ExprIsVector(pCopy) ){ 345546967de2Sdrh sqlite3VectorErrorMsg(pSubst->pParse, pCopy); 345644c5604cSdan }else{ 345746967de2Sdrh sqlite3 *db = pSubst->pParse->db; 345831d6fd55Sdrh if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){ 345931d6fd55Sdrh memset(&ifNullRow, 0, sizeof(ifNullRow)); 346031d6fd55Sdrh ifNullRow.op = TK_IF_NULL_ROW; 346131d6fd55Sdrh ifNullRow.pLeft = pCopy; 346231d6fd55Sdrh ifNullRow.iTable = pSubst->iNewTable; 346331d6fd55Sdrh pCopy = &ifNullRow; 346431d6fd55Sdrh } 346544c5604cSdan pNew = sqlite3ExprDup(db, pCopy, 0); 3466bd11a2acSdan if( pNew && pSubst->isLeftJoin ){ 3467bd11a2acSdan ExprSetProperty(pNew, EP_CanBeNull); 3468bd11a2acSdan } 3469bd11a2acSdan if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){ 347092ddb3bdSdan pNew->iRightJoinTable = pExpr->iRightJoinTable; 3471bd11a2acSdan ExprSetProperty(pNew, EP_FromJoin); 347292ddb3bdSdan } 3473b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 3474b7916a78Sdrh pExpr = pNew; 347550350a15Sdrh } 347644c5604cSdan } 3477832508b7Sdrh }else{ 34787c1544e0Sdrh if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ 34797c1544e0Sdrh pExpr->iTable = pSubst->iNewTable; 34807c1544e0Sdrh } 348146967de2Sdrh pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); 348246967de2Sdrh pExpr->pRight = substExpr(pSubst, pExpr->pRight); 34836ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 348446967de2Sdrh substSelect(pSubst, pExpr->x.pSelect, 1); 34856ab3a2ecSdanielk1977 }else{ 348646967de2Sdrh substExprList(pSubst, pExpr->x.pList); 34876ab3a2ecSdanielk1977 } 3488832508b7Sdrh } 3489b7916a78Sdrh return pExpr; 3490832508b7Sdrh } 349117435752Sdrh static void substExprList( 349246967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 349346967de2Sdrh ExprList *pList /* List to scan and in which to make substitutes */ 349417435752Sdrh ){ 3495832508b7Sdrh int i; 3496832508b7Sdrh if( pList==0 ) return; 3497832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 349846967de2Sdrh pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); 3499832508b7Sdrh } 3500832508b7Sdrh } 350117435752Sdrh static void substSelect( 350246967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 350317435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 3504d12b6363Sdrh int doPrior /* Do substitutes on p->pPrior too */ 350517435752Sdrh ){ 3506588a9a1aSdrh SrcList *pSrc; 3507588a9a1aSdrh struct SrcList_item *pItem; 3508588a9a1aSdrh int i; 3509b3bce662Sdanielk1977 if( !p ) return; 3510d12b6363Sdrh do{ 351146967de2Sdrh substExprList(pSubst, p->pEList); 351246967de2Sdrh substExprList(pSubst, p->pGroupBy); 351346967de2Sdrh substExprList(pSubst, p->pOrderBy); 351446967de2Sdrh p->pHaving = substExpr(pSubst, p->pHaving); 351546967de2Sdrh p->pWhere = substExpr(pSubst, p->pWhere); 3516588a9a1aSdrh pSrc = p->pSrc; 35172906490bSdrh assert( pSrc!=0 ); 3518588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 351946967de2Sdrh substSelect(pSubst, pItem->pSelect, 1); 3520d12b6363Sdrh if( pItem->fg.isTabFunc ){ 352146967de2Sdrh substExprList(pSubst, pItem->u1.pFuncArg); 3522588a9a1aSdrh } 3523588a9a1aSdrh } 3524d12b6363Sdrh }while( doPrior && (p = p->pPrior)!=0 ); 3525b3bce662Sdanielk1977 } 35263514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3527832508b7Sdrh 35283514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3529832508b7Sdrh /* 3530630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3531630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 35321350b030Sdrh ** 35331350b030Sdrh ** To understand the concept of flattening, consider the following 35341350b030Sdrh ** query: 35351350b030Sdrh ** 35361350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 35371350b030Sdrh ** 35381350b030Sdrh ** The default way of implementing this query is to execute the 35391350b030Sdrh ** subquery first and store the results in a temporary table, then 35401350b030Sdrh ** run the outer query on that temporary table. This requires two 35411350b030Sdrh ** passes over the data. Furthermore, because the temporary table 35421350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3543832508b7Sdrh ** optimized. 35441350b030Sdrh ** 3545832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 35461350b030Sdrh ** a single flat select, like this: 35471350b030Sdrh ** 35481350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 35491350b030Sdrh ** 355060ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 3551832508b7Sdrh ** but only has to scan the data once. And because indices might 3552832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 3553832508b7Sdrh ** avoided. 35541350b030Sdrh ** 3555d981e828Sdrh ** Flattening is subject to the following constraints: 35561350b030Sdrh ** 355725c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 355825c221ebSdrh ** The subquery and the outer query cannot both be aggregates. 35591350b030Sdrh ** 356025c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3561d981e828Sdrh ** (2) If the subquery is an aggregate then 3562d981e828Sdrh ** (2a) the outer query must not be a join and 3563d981e828Sdrh ** (2b) the outer query must not use subqueries 3564d981e828Sdrh ** other than the one FROM-clause subquery that is a candidate 3565d981e828Sdrh ** for flattening. (This is due to ticket [2f7170d73bf9abf80] 3566d981e828Sdrh ** from 2015-02-09.) 3567832508b7Sdrh ** 3568d981e828Sdrh ** (3) If the subquery is the right operand of a LEFT JOIN then 3569d981e828Sdrh ** (3a) the subquery may not be a join and 3570d981e828Sdrh ** (3b) the FROM clause of the subquery may not contain a virtual 3571d981e828Sdrh ** table and 3572d981e828Sdrh ** (3c) the outer query may not be an aggregate. 3573832508b7Sdrh ** 3574d981e828Sdrh ** (4) The subquery can not be DISTINCT. 3575832508b7Sdrh ** 357649ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 357749ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 357849ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 3579832508b7Sdrh ** 358025c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 358125c221ebSdrh ** If the subquery is aggregate, the outer query may not be DISTINCT. 3582832508b7Sdrh ** 3583d981e828Sdrh ** (7) The subquery must have a FROM clause. TODO: For subqueries without 358431d6fd55Sdrh ** A FROM clause, consider adding a FROM clause with the special 3585630d296cSdrh ** table sqlite_once that consists of a single row containing a 3586630d296cSdrh ** single NULL. 358708192d5fSdrh ** 3588d981e828Sdrh ** (8) If the subquery uses LIMIT then the outer query may not be a join. 3589df199a25Sdrh ** 3590d981e828Sdrh ** (9) If the subquery uses LIMIT then the outer query may not be aggregate. 3591df199a25Sdrh ** 35926092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 35936092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 3594d981e828Sdrh ** constraint: "If the subquery is aggregate then the outer query 3595d981e828Sdrh ** may not use LIMIT." 3596df199a25Sdrh ** 3597d981e828Sdrh ** (11) The subquery and the outer query may not both have ORDER BY clauses. 3598174b6195Sdrh ** 35997b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 36002b300d5dSdrh ** a separate restriction deriving from ticket #350. 36013fc673e6Sdrh ** 3602d981e828Sdrh ** (13) The subquery and outer query may not both use LIMIT. 3603ac83963aSdrh ** 3604d981e828Sdrh ** (14) The subquery may not use OFFSET. 3605ac83963aSdrh ** 3606d981e828Sdrh ** (15) If the outer query is part of a compound select, then the 3607d981e828Sdrh ** subquery may not use LIMIT. 3608f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 3609ad91c6cdSdrh ** 3610d981e828Sdrh ** (16) If the outer query is aggregate, then the subquery may not 3611d981e828Sdrh ** use ORDER BY. (Ticket #2942) This used to not matter 3612c52e355dSdrh ** until we introduced the group_concat() function. 3613c52e355dSdrh ** 3614d981e828Sdrh ** (17) If the subquery is a compound select, then 3615d981e828Sdrh ** (17a) all compound operators must be a UNION ALL, and 3616d981e828Sdrh ** (17b) no terms within the subquery compound may be aggregate 3617e76acc65Sdrh ** or DISTINCT, and 3618d981e828Sdrh ** (17c) every term within the subquery compound must have a FROM clause 3619d981e828Sdrh ** (17d) the outer query may not be 3620d981e828Sdrh ** (17d1) aggregate, or 3621d981e828Sdrh ** (17d2) DISTINCT, or 3622d981e828Sdrh ** (17d3) a join. 3623f23329a2Sdanielk1977 ** 36244914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 36254914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 3626630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 3627630d296cSdrh ** operator other than UNION ALL because all the other compound 3628630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 3629630d296cSdrh ** restriction (4). 3630f23329a2Sdanielk1977 ** 363167c70142Sdan ** Also, each component of the sub-query must return the same number 363267c70142Sdan ** of result columns. This is actually a requirement for any compound 363367c70142Sdan ** SELECT statement, but all the code here does is make sure that no 363467c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 363567c70142Sdan ** syntax error and return a detailed message. 363667c70142Sdan ** 363749fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 3638d981e828Sdrh ** ORDER BY clause of the parent must be simple references to 363949fc1f60Sdanielk1977 ** columns of the sub-query. 364049fc1f60Sdanielk1977 ** 3641d981e828Sdrh ** (19) If the subquery uses LIMIT then the outer query may not 3642229cf702Sdrh ** have a WHERE clause. 3643229cf702Sdrh ** 3644fca23557Sdrh ** (20) If the sub-query is a compound select, then it must not use 3645fca23557Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 3646fca23557Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 3647fca23557Sdrh ** appear as unmodified result columns in the outer query. But we 3648fca23557Sdrh ** have other optimizations in mind to deal with that case. 3649e8902a70Sdrh ** 3650d981e828Sdrh ** (21) If the subquery uses LIMIT then the outer query may not be 3651a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 3652a91491e5Sshaneh ** 3653d981e828Sdrh ** (22) The subquery may not be a recursive CTE. 36548290c2adSdan ** 3655cdb2f607Sdrh ** (**) Subsumed into restriction (17d3). Was: If the outer query is 3656cdb2f607Sdrh ** a recursive CTE, then the sub-query may not be a compound query. 3657cdb2f607Sdrh ** This restriction is because transforming the 36588290c2adSdan ** parent to a compound query confuses the code that handles 36598290c2adSdan ** recursive queries in multiSelect(). 36608290c2adSdan ** 3661508e2d00Sdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3662508e2d00Sdrh ** The subquery may not be an aggregate that uses the built-in min() or 36639588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 36649588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 36659588ad95Sdrh ** return the value X for which Y was maximal.) 36669588ad95Sdrh ** 36679a94722dSdan ** (25) If either the subquery or the parent query contains a window 36689a94722dSdan ** function in the select list or ORDER BY clause, flattening 36699a94722dSdan ** is not attempted. 36709a94722dSdan ** 36718290c2adSdan ** 3672832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 3673832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 367425c221ebSdrh ** uses aggregates. 3675832508b7Sdrh ** 3676665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 3677832508b7Sdrh ** If flattening is attempted this routine returns 1. 3678832508b7Sdrh ** 3679832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 3680832508b7Sdrh ** the subquery before this routine runs. 36811350b030Sdrh */ 36828c74a8caSdrh static int flattenSubquery( 3683524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 36848c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 36858c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 368625c221ebSdrh int isAgg /* True if outer SELECT uses aggregate functions */ 36878c74a8caSdrh ){ 3688524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 3689d12b6363Sdrh Select *pParent; /* Current UNION ALL term of the other query */ 36900bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 3691f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3692ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 3693ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 36946a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 3695399c7e21Sdrh int iNewParent = -1;/* Replacement table for iParent */ 3696399c7e21Sdrh int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ 369791bb0eedSdrh int i; /* Loop counter */ 369891bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 369991bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 3700524cc21eSdanielk1977 sqlite3 *db = pParse->db; 37011350b030Sdrh 3702832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 3703832508b7Sdrh */ 3704a78c22c4Sdrh assert( p!=0 ); 3705d981e828Sdrh assert( p->pPrior==0 ); 37067e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3707832508b7Sdrh pSrc = p->pSrc; 3708ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 370991bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 371049fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 371191bb0eedSdrh pSub = pSubitem->pSelect; 3712832508b7Sdrh assert( pSub!=0 ); 3713885a5b03Sdrh 371467a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 37159a94722dSdan if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ 371667a9b8edSdan #endif 371786fb6e17Sdan 3718832508b7Sdrh pSubSrc = pSub->pSrc; 3719832508b7Sdrh assert( pSubSrc ); 3720ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 372160ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3722ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 3723ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 3724ac83963aSdrh ** and (14). */ 3725ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 37268c0833fbSdrh if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ 3727d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3728ad91c6cdSdrh return 0; /* Restriction (15) */ 3729ad91c6cdSdrh } 3730ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 3731d981e828Sdrh if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ 373249ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 373349ad330dSdan return 0; /* Restrictions (8)(9) */ 3734df199a25Sdrh } 37357d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 3736ac83963aSdrh return 0; /* Restriction (11) */ 3737ac83963aSdrh } 3738c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 3739229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 3740a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 3741a91491e5Sshaneh return 0; /* Restriction (21) */ 3742a91491e5Sshaneh } 3743508e2d00Sdrh if( pSub->selFlags & (SF_Recursive) ){ 3744508e2d00Sdrh return 0; /* Restrictions (22) */ 37459588ad95Sdrh } 3746832508b7Sdrh 3747399c7e21Sdrh /* 3748399c7e21Sdrh ** If the subquery is the right operand of a LEFT JOIN, then the 3749d981e828Sdrh ** subquery may not be a join itself (3a). Example of why this is not 3750d981e828Sdrh ** allowed: 37518af4d3acSdrh ** 37528af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 37538af4d3acSdrh ** 37548af4d3acSdrh ** If we flatten the above, we would get 37558af4d3acSdrh ** 37568af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 37578af4d3acSdrh ** 37588af4d3acSdrh ** which is not at all the same thing. 37592b300d5dSdrh ** 37603c790f2aSdrh ** If the subquery is the right operand of a LEFT JOIN, then the outer 3761d981e828Sdrh ** query cannot be an aggregate. (3c) This is an artifact of the way 3762d981e828Sdrh ** aggregates are processed - there is no mechanism to determine if 3763d981e828Sdrh ** the LEFT JOIN table should be all-NULL. 37643c790f2aSdrh ** 376531d6fd55Sdrh ** See also tickets #306, #350, and #3300. 37663fc673e6Sdrh */ 37678a48b9c0Sdrh if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ 3768399c7e21Sdrh isLeftJoin = 1; 376946133d98Sdan if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){ 3770d981e828Sdrh /* (3a) (3c) (3b) */ 3771d981e828Sdrh return 0; 3772399c7e21Sdrh } 37733fc673e6Sdrh } 3774dc6de479Sdrh #ifdef SQLITE_EXTRA_IFNULLROW 3775dc6de479Sdrh else if( iFrom>0 && !isAgg ){ 3776dc6de479Sdrh /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for 37773d240d21Sdrh ** every reference to any result column from subquery in a join, even 37783d240d21Sdrh ** though they are not necessary. This will stress-test the OP_IfNullRow 37793d240d21Sdrh ** opcode. */ 3780dc6de479Sdrh isLeftJoin = -1; 3781dc6de479Sdrh } 3782dc6de479Sdrh #endif 37833fc673e6Sdrh 3784d981e828Sdrh /* Restriction (17): If the sub-query is a compound SELECT, then it must 3785f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 3786f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 3787f23329a2Sdanielk1977 ** queries. 3788f23329a2Sdanielk1977 */ 3789f23329a2Sdanielk1977 if( pSub->pPrior ){ 3790fca23557Sdrh if( pSub->pOrderBy ){ 3791fca23557Sdrh return 0; /* Restriction (20) */ 3792fca23557Sdrh } 3793e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3794d981e828Sdrh return 0; /* (17d1), (17d2), or (17d3) */ 3795f23329a2Sdanielk1977 } 3796f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3797ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3798ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 37994b3ac73cSdrh assert( pSub->pSrc!=0 ); 38002ec18a3cSdrh assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); 3801d981e828Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ 3802d981e828Sdrh || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ 3803d981e828Sdrh || pSub1->pSrc->nSrc<1 /* (17c) */ 380480b3c548Sdanielk1977 ){ 3805f23329a2Sdanielk1977 return 0; 3806f23329a2Sdanielk1977 } 38074b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 3808f23329a2Sdanielk1977 } 380949fc1f60Sdanielk1977 3810d981e828Sdrh /* Restriction (18). */ 381149fc1f60Sdanielk1977 if( p->pOrderBy ){ 381249fc1f60Sdanielk1977 int ii; 381349fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3814c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 381549fc1f60Sdanielk1977 } 381649fc1f60Sdanielk1977 } 3817f23329a2Sdanielk1977 } 3818f23329a2Sdanielk1977 3819cdb2f607Sdrh /* Ex-restriction (23): 3820cdb2f607Sdrh ** The only way that the recursive part of a CTE can contain a compound 3821cdb2f607Sdrh ** subquery is for the subquery to be one term of a join. But if the 3822cdb2f607Sdrh ** subquery is a join, then the flattening has already been stopped by 3823cdb2f607Sdrh ** restriction (17d3) 3824cdb2f607Sdrh */ 3825cdb2f607Sdrh assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); 3826cdb2f607Sdrh 38277d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 3828fef37760Sdrh SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n", 3829fef37760Sdrh pSub->selId, pSub, iFrom)); 38307d10d5a6Sdrh 38317d10d5a6Sdrh /* Authorize the subquery */ 3832524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 3833a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 3834a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 3835524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 3836524cc21eSdanielk1977 38377d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 38387d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 38397d10d5a6Sdrh ** be of the form: 3840f23329a2Sdanielk1977 ** 3841f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 3842f23329a2Sdanielk1977 ** 3843f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 3844a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 3845f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 3846f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 3847f23329a2Sdanielk1977 ** select statements in the compound sub-query. 3848a78c22c4Sdrh ** 3849a78c22c4Sdrh ** Example: 3850a78c22c4Sdrh ** 3851a78c22c4Sdrh ** SELECT a+1 FROM ( 3852a78c22c4Sdrh ** SELECT x FROM tab 3853a78c22c4Sdrh ** UNION ALL 3854a78c22c4Sdrh ** SELECT y FROM tab 3855a78c22c4Sdrh ** UNION ALL 3856a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 3857a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 3858a78c22c4Sdrh ** 3859a78c22c4Sdrh ** Transformed into: 3860a78c22c4Sdrh ** 3861a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 3862a78c22c4Sdrh ** UNION ALL 3863a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 3864a78c22c4Sdrh ** UNION ALL 3865a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 3866a78c22c4Sdrh ** ORDER BY 1 3867a78c22c4Sdrh ** 3868a78c22c4Sdrh ** We call this the "compound-subquery flattening". 3869f23329a2Sdanielk1977 */ 3870f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 3871f23329a2Sdanielk1977 Select *pNew; 3872f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 38734b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 3874f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 3875f23329a2Sdanielk1977 p->pOrderBy = 0; 3876f23329a2Sdanielk1977 p->pSrc = 0; 3877f23329a2Sdanielk1977 p->pPrior = 0; 38784b86ef1dSdanielk1977 p->pLimit = 0; 38796ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 38804b86ef1dSdanielk1977 p->pLimit = pLimit; 3881a78c22c4Sdrh p->pOrderBy = pOrderBy; 3882a78c22c4Sdrh p->pSrc = pSrc; 3883a78c22c4Sdrh p->op = TK_ALL; 3884a78c22c4Sdrh if( pNew==0 ){ 3885d227a291Sdrh p->pPrior = pPrior; 3886a78c22c4Sdrh }else{ 3887a78c22c4Sdrh pNew->pPrior = pPrior; 3888d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 3889d227a291Sdrh pNew->pNext = p; 3890a78c22c4Sdrh p->pPrior = pNew; 3891e2243d26Sdrh SELECTTRACE(2,pParse,p,("compound-subquery flattener" 3892fef37760Sdrh " creates %u as peer\n",pNew->selId)); 3893d227a291Sdrh } 3894a78c22c4Sdrh if( db->mallocFailed ) return 1; 3895a78c22c4Sdrh } 3896f23329a2Sdanielk1977 38977d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 38987d10d5a6Sdrh ** in the outer query. 3899832508b7Sdrh */ 3900f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 3901c31c2eb8Sdrh 3902a78c22c4Sdrh /* Delete the transient table structure associated with the 3903a78c22c4Sdrh ** subquery 3904a78c22c4Sdrh */ 3905a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 3906a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 3907a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 3908a78c22c4Sdrh pSubitem->zDatabase = 0; 3909a78c22c4Sdrh pSubitem->zName = 0; 3910a78c22c4Sdrh pSubitem->zAlias = 0; 3911a78c22c4Sdrh pSubitem->pSelect = 0; 3912a78c22c4Sdrh 3913a78c22c4Sdrh /* Defer deleting the Table object associated with the 3914a78c22c4Sdrh ** subquery until code generation is 3915a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 3916a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 3917ccfcbceaSdrh ** 3918ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 3919a78c22c4Sdrh */ 3920ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 3921a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 392279df7782Sdrh if( pTabToDel->nTabRef==1 ){ 392365a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 392465a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 392565a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 3926a78c22c4Sdrh }else{ 392779df7782Sdrh pTabToDel->nTabRef--; 3928a78c22c4Sdrh } 3929a78c22c4Sdrh pSubitem->pTab = 0; 3930a78c22c4Sdrh } 3931a78c22c4Sdrh 3932a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 3933a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 3934a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 3935a78c22c4Sdrh ** then this loop only runs once. 3936a78c22c4Sdrh ** 3937a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 3938c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 3939c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 3940c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 3941c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 3942c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 3943c31c2eb8Sdrh ** elements we are now copying in. 3944c31c2eb8Sdrh */ 3945a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 3946a78c22c4Sdrh int nSubSrc; 3947ea678832Sdrh u8 jointype = 0; 3948a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 3949a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 3950a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 3951588a9a1aSdrh 3952a78c22c4Sdrh if( pSrc ){ 3953a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 39548a48b9c0Sdrh jointype = pSubitem->fg.jointype; 3955588a9a1aSdrh }else{ 3956a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 3957a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 3958cfa063b3Sdrh if( pSrc==0 ){ 3959a78c22c4Sdrh assert( db->mallocFailed ); 3960a78c22c4Sdrh break; 3961cfa063b3Sdrh } 3962c31c2eb8Sdrh } 3963a78c22c4Sdrh 3964a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 3965a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 3966a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 3967a78c22c4Sdrh ** of the subquery. 3968a78c22c4Sdrh ** 3969a78c22c4Sdrh ** Example: 3970a78c22c4Sdrh ** 3971a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 3972a78c22c4Sdrh ** 3973a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 3974a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 3975d12b6363Sdrh ** block of code will expand the outer query FROM clause to 4 slots. 3976d12b6363Sdrh ** The middle slot is expanded to two slots in order to make space 3977d12b6363Sdrh ** for the two elements in the FROM clause of the subquery. 3978a78c22c4Sdrh */ 3979a78c22c4Sdrh if( nSubSrc>1 ){ 3980a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 3981a78c22c4Sdrh if( db->mallocFailed ){ 3982a78c22c4Sdrh break; 3983c31c2eb8Sdrh } 3984c31c2eb8Sdrh } 3985a78c22c4Sdrh 3986a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 3987a78c22c4Sdrh ** outer query. 3988a78c22c4Sdrh */ 3989c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 3990c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 399120292310Sdrh assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); 3992c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 3993399c7e21Sdrh iNewParent = pSubSrc->a[i].iCursor; 3994c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3995c31c2eb8Sdrh } 39968a48b9c0Sdrh pSrc->a[iFrom].fg.jointype = jointype; 3997c31c2eb8Sdrh 3998c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 3999c31c2eb8Sdrh ** references to the iParent in the outer query. 4000c31c2eb8Sdrh ** 4001c31c2eb8Sdrh ** Example: 4002c31c2eb8Sdrh ** 4003c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 4004c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 4005c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 4006c31c2eb8Sdrh ** 4007c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 4008c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 4009c31c2eb8Sdrh */ 4010174b6195Sdrh if( pSub->pOrderBy ){ 40117c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 40127c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 40137c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 40147c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 40157c0a4720Sdan ** zero them before transfering the ORDER BY clause. 40167c0a4720Sdan ** 40177c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 40187c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 40197c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 40207c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 40217c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 40227c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 40237c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 40247c0a4720Sdan } 4025f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 40267c0a4720Sdan pParent->pOrderBy = pOrderBy; 4027174b6195Sdrh pSub->pOrderBy = 0; 4028174b6195Sdrh } 40296ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 4030dc6de479Sdrh if( isLeftJoin>0 ){ 4031399c7e21Sdrh setJoinExpr(pWhere, iNewParent); 4032399c7e21Sdrh } 40334c5ebee0Sdan pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere); 4034c3becddbSdan if( db->mallocFailed==0 ){ 403546967de2Sdrh SubstContext x; 403646967de2Sdrh x.pParse = pParse; 403746967de2Sdrh x.iTable = iParent; 4038399c7e21Sdrh x.iNewTable = iNewParent; 403931d6fd55Sdrh x.isLeftJoin = isLeftJoin; 404046967de2Sdrh x.pEList = pSub->pEList; 404146967de2Sdrh substSelect(&x, pParent, 0); 4042c3becddbSdan } 4043c31c2eb8Sdrh 4044c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 4045c31c2eb8Sdrh ** outer query is distinct. 4046c31c2eb8Sdrh */ 40477d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 40488c74a8caSdrh 4049a58fdfb1Sdanielk1977 /* 4050a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 4051ac83963aSdrh ** 4052ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 4053ac83963aSdrh ** does not work if either limit is negative. 4054a58fdfb1Sdanielk1977 */ 4055a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 4056f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 4057a2dc3b1aSdanielk1977 pSub->pLimit = 0; 4058df199a25Sdrh } 4059f23329a2Sdanielk1977 } 40608c74a8caSdrh 4061c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 4062c31c2eb8Sdrh ** success. 4063c31c2eb8Sdrh */ 4064633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 4065f23329a2Sdanielk1977 4066c90713d3Sdrh #if SELECTTRACE_ENABLED 4067c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 4068bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After flattening:\n")); 4069c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4070c90713d3Sdrh } 4071c90713d3Sdrh #endif 4072c90713d3Sdrh 4073832508b7Sdrh return 1; 40741350b030Sdrh } 40753514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 40761350b030Sdrh 4077660ee556Sdrh /* 4078efad2e23Sdrh ** A structure to keep track of all of the column values that fixed to 4079efad2e23Sdrh ** a known value due to WHERE clause constraints of the form COLUMN=VALUE. 4080660ee556Sdrh */ 4081660ee556Sdrh typedef struct WhereConst WhereConst; 4082660ee556Sdrh struct WhereConst { 4083efad2e23Sdrh Parse *pParse; /* Parsing context */ 4084660ee556Sdrh int nConst; /* Number for COLUMN=CONSTANT terms */ 4085660ee556Sdrh int nChng; /* Number of times a constant is propagated */ 4086efad2e23Sdrh Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */ 4087660ee556Sdrh }; 408869b72d5aSdrh 4089660ee556Sdrh /* 4090660ee556Sdrh ** Add a new entry to the pConst object 4091660ee556Sdrh */ 4092660ee556Sdrh static void constInsert( 4093660ee556Sdrh WhereConst *pConst, 4094660ee556Sdrh Expr *pColumn, 4095660ee556Sdrh Expr *pValue 4096660ee556Sdrh ){ 40979cbf4f35Sdrh 4098660ee556Sdrh pConst->nConst++; 4099efad2e23Sdrh pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr, 4100660ee556Sdrh pConst->nConst*2*sizeof(Expr*)); 4101660ee556Sdrh if( pConst->apExpr==0 ){ 4102660ee556Sdrh pConst->nConst = 0; 4103660ee556Sdrh }else{ 4104efad2e23Sdrh if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft; 4105660ee556Sdrh pConst->apExpr[pConst->nConst*2-2] = pColumn; 4106660ee556Sdrh pConst->apExpr[pConst->nConst*2-1] = pValue; 4107660ee556Sdrh } 4108660ee556Sdrh } 4109660ee556Sdrh 4110660ee556Sdrh /* 4111efad2e23Sdrh ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE 4112efad2e23Sdrh ** is a constant expression and where the term must be true because it 4113efad2e23Sdrh ** is part of the AND-connected terms of the expression. For each term 4114efad2e23Sdrh ** found, add it to the pConst structure. 4115660ee556Sdrh */ 4116660ee556Sdrh static void findConstInWhere(WhereConst *pConst, Expr *pExpr){ 4117efad2e23Sdrh Expr *pRight, *pLeft; 4118660ee556Sdrh if( pExpr==0 ) return; 4119660ee556Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) ) return; 4120660ee556Sdrh if( pExpr->op==TK_AND ){ 4121660ee556Sdrh findConstInWhere(pConst, pExpr->pRight); 4122660ee556Sdrh findConstInWhere(pConst, pExpr->pLeft); 4123660ee556Sdrh return; 4124660ee556Sdrh } 4125660ee556Sdrh if( pExpr->op!=TK_EQ ) return; 4126efad2e23Sdrh pRight = pExpr->pRight; 4127efad2e23Sdrh pLeft = pExpr->pLeft; 4128efad2e23Sdrh assert( pRight!=0 ); 4129efad2e23Sdrh assert( pLeft!=0 ); 4130efad2e23Sdrh if( pRight->op==TK_COLUMN 4131efad2e23Sdrh && !ExprHasProperty(pRight, EP_FixedCol) 4132efad2e23Sdrh && sqlite3ExprIsConstant(pLeft) 41339cbf4f35Sdrh && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight)) 4134efad2e23Sdrh ){ 4135efad2e23Sdrh constInsert(pConst, pRight, pLeft); 4136660ee556Sdrh }else 4137efad2e23Sdrh if( pLeft->op==TK_COLUMN 4138efad2e23Sdrh && !ExprHasProperty(pLeft, EP_FixedCol) 41399cbf4f35Sdrh && sqlite3ExprIsConstant(pRight) 41409cbf4f35Sdrh && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight)) 41419cbf4f35Sdrh ){ 4142efad2e23Sdrh constInsert(pConst, pLeft, pRight); 4143660ee556Sdrh } 4144660ee556Sdrh } 4145660ee556Sdrh 4146660ee556Sdrh /* 4147660ee556Sdrh ** This is a Walker expression callback. pExpr is a candidate expression 4148660ee556Sdrh ** to be replaced by a value. If pExpr is equivalent to one of the 4149660ee556Sdrh ** columns named in pWalker->u.pConst, then overwrite it with its 4150660ee556Sdrh ** corresponding value. 4151660ee556Sdrh */ 4152660ee556Sdrh static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ 4153660ee556Sdrh int i; 4154660ee556Sdrh WhereConst *pConst; 4155660ee556Sdrh if( pExpr->op!=TK_COLUMN ) return WRC_Continue; 4156efad2e23Sdrh if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue; 4157660ee556Sdrh pConst = pWalker->u.pConst; 4158660ee556Sdrh for(i=0; i<pConst->nConst; i++){ 4159660ee556Sdrh Expr *pColumn = pConst->apExpr[i*2]; 4160660ee556Sdrh if( pColumn==pExpr ) continue; 4161660ee556Sdrh if( pColumn->iTable!=pExpr->iTable ) continue; 4162660ee556Sdrh if( pColumn->iColumn!=pExpr->iColumn ) continue; 4163efad2e23Sdrh /* A match is found. Add the EP_FixedCol property */ 4164660ee556Sdrh pConst->nChng++; 4165660ee556Sdrh ExprClearProperty(pExpr, EP_Leaf); 4166efad2e23Sdrh ExprSetProperty(pExpr, EP_FixedCol); 4167efad2e23Sdrh assert( pExpr->pLeft==0 ); 4168efad2e23Sdrh pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); 4169660ee556Sdrh break; 4170660ee556Sdrh } 4171660ee556Sdrh return WRC_Prune; 4172660ee556Sdrh } 4173660ee556Sdrh 4174660ee556Sdrh /* 4175660ee556Sdrh ** The WHERE-clause constant propagation optimization. 4176660ee556Sdrh ** 4177660ee556Sdrh ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or 4178660ee556Sdrh ** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level 4179660ee556Sdrh ** AND-connected terms that are not part of a ON clause from a LEFT JOIN) 4180660ee556Sdrh ** then throughout the query replace all other occurrences of COLUMN 4181efad2e23Sdrh ** with CONSTANT within the WHERE clause. 4182660ee556Sdrh ** 4183660ee556Sdrh ** For example, the query: 4184660ee556Sdrh ** 4185660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b 4186660ee556Sdrh ** 4187660ee556Sdrh ** Is transformed into 4188660ee556Sdrh ** 4189660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39 4190660ee556Sdrh ** 4191660ee556Sdrh ** Return true if any transformations where made and false if not. 4192efad2e23Sdrh ** 4193efad2e23Sdrh ** Implementation note: Constant propagation is tricky due to affinity 4194efad2e23Sdrh ** and collating sequence interactions. Consider this example: 4195efad2e23Sdrh ** 4196efad2e23Sdrh ** CREATE TABLE t1(a INT,b TEXT); 4197efad2e23Sdrh ** INSERT INTO t1 VALUES(123,'0123'); 4198efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=a; 4199efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=123; 4200efad2e23Sdrh ** 4201efad2e23Sdrh ** The two SELECT statements above should return different answers. b=a 4202efad2e23Sdrh ** is alway true because the comparison uses numeric affinity, but b=123 4203efad2e23Sdrh ** is false because it uses text affinity and '0123' is not the same as '123'. 4204efad2e23Sdrh ** To work around this, the expression tree is not actually changed from 4205efad2e23Sdrh ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol 4206efad2e23Sdrh ** and the "123" value is hung off of the pLeft pointer. Code generator 4207efad2e23Sdrh ** routines know to generate the constant "123" instead of looking up the 4208efad2e23Sdrh ** column value. Also, to avoid collation problems, this optimization is 4209efad2e23Sdrh ** only attempted if the "a=123" term uses the default BINARY collation. 4210660ee556Sdrh */ 4211660ee556Sdrh static int propagateConstants( 4212660ee556Sdrh Parse *pParse, /* The parsing context */ 4213660ee556Sdrh Select *p /* The query in which to propagate constants */ 4214660ee556Sdrh ){ 4215660ee556Sdrh WhereConst x; 4216660ee556Sdrh Walker w; 4217660ee556Sdrh int nChng = 0; 4218efad2e23Sdrh x.pParse = pParse; 4219660ee556Sdrh do{ 4220660ee556Sdrh x.nConst = 0; 4221660ee556Sdrh x.nChng = 0; 4222660ee556Sdrh x.apExpr = 0; 4223660ee556Sdrh findConstInWhere(&x, p->pWhere); 4224660ee556Sdrh if( x.nConst ){ 4225660ee556Sdrh memset(&w, 0, sizeof(w)); 4226660ee556Sdrh w.pParse = pParse; 4227660ee556Sdrh w.xExprCallback = propagateConstantExprRewrite; 4228660ee556Sdrh w.xSelectCallback = sqlite3SelectWalkNoop; 4229660ee556Sdrh w.xSelectCallback2 = 0; 4230660ee556Sdrh w.walkerDepth = 0; 4231660ee556Sdrh w.u.pConst = &x; 4232efad2e23Sdrh sqlite3WalkExpr(&w, p->pWhere); 4233efad2e23Sdrh sqlite3DbFree(x.pParse->db, x.apExpr); 4234660ee556Sdrh nChng += x.nChng; 4235660ee556Sdrh } 4236660ee556Sdrh }while( x.nChng ); 4237660ee556Sdrh return nChng; 4238660ee556Sdrh } 423969b72d5aSdrh 424069b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 424169b72d5aSdrh /* 424269b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into 424369b72d5aSdrh ** the WHERE clause of subquery. Example: 424469b72d5aSdrh ** 424569b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; 424669b72d5aSdrh ** 424769b72d5aSdrh ** Transformed into: 424869b72d5aSdrh ** 424969b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) 425069b72d5aSdrh ** WHERE x=5 AND y=10; 425169b72d5aSdrh ** 425269b72d5aSdrh ** The hope is that the terms added to the inner query will make it more 425369b72d5aSdrh ** efficient. 425469b72d5aSdrh ** 425569b72d5aSdrh ** Do not attempt this optimization if: 425669b72d5aSdrh ** 425725c221ebSdrh ** (1) (** This restriction was removed on 2017-09-29. We used to 425825c221ebSdrh ** disallow this optimization for aggregate subqueries, but now 425967cc51a4Sdrh ** it is allowed by putting the extra terms on the HAVING clause. 426067cc51a4Sdrh ** The added HAVING clause is pointless if the subquery lacks 426167cc51a4Sdrh ** a GROUP BY clause. But such a HAVING clause is also harmless 426267cc51a4Sdrh ** so there does not appear to be any reason to add extra logic 426367cc51a4Sdrh ** to suppress it. **) 426469b72d5aSdrh ** 426569b72d5aSdrh ** (2) The inner query is the recursive part of a common table expression. 426669b72d5aSdrh ** 426769b72d5aSdrh ** (3) The inner query has a LIMIT clause (since the changes to the WHERE 4268ce103735Sdan ** clause would change the meaning of the LIMIT). 426969b72d5aSdrh ** 42706a9b9527Sdrh ** (4) The inner query is the right operand of a LEFT JOIN and the 42716a9b9527Sdrh ** expression to be pushed down does not come from the ON clause 42726a9b9527Sdrh ** on that LEFT JOIN. 427369b72d5aSdrh ** 427438978dd4Sdrh ** (5) The WHERE clause expression originates in the ON or USING clause 42757fbb101cSdrh ** of a LEFT JOIN where iCursor is not the right-hand table of that 42767fbb101cSdrh ** left join. An example: 42777fbb101cSdrh ** 42787fbb101cSdrh ** SELECT * 42797fbb101cSdrh ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa 42807fbb101cSdrh ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) 42817fbb101cSdrh ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); 42827fbb101cSdrh ** 42837fbb101cSdrh ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). 42847fbb101cSdrh ** But if the (b2=2) term were to be pushed down into the bb subquery, 42857fbb101cSdrh ** then the (1,1,NULL) row would be suppressed. 428638978dd4Sdrh ** 4287ce103735Sdan ** (6) The inner query features one or more window-functions (since 4288ce103735Sdan ** changes to the WHERE clause of the inner query could change the 4289ce103735Sdan ** window over which window functions are calculated). 4290ce103735Sdan ** 429169b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause 429269b72d5aSdrh ** terms are duplicated into the subquery. 429369b72d5aSdrh */ 429469b72d5aSdrh static int pushDownWhereTerms( 429544c5604cSdan Parse *pParse, /* Parse context (for malloc() and error reporting) */ 429669b72d5aSdrh Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ 429769b72d5aSdrh Expr *pWhere, /* The WHERE clause of the outer query */ 42986a9b9527Sdrh int iCursor, /* Cursor number of the subquery */ 42996a9b9527Sdrh int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ 430069b72d5aSdrh ){ 430169b72d5aSdrh Expr *pNew; 430269b72d5aSdrh int nChng = 0; 430369b72d5aSdrh if( pWhere==0 ) return 0; 4304508e2d00Sdrh if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ 4305508e2d00Sdrh 4306ce103735Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 4307142066d4Sdrh if( pSubq->pWin ) return 0; /* restriction (6) */ 4308ce103735Sdan #endif 4309ce103735Sdan 4310508e2d00Sdrh #ifdef SQLITE_DEBUG 4311508e2d00Sdrh /* Only the first term of a compound can have a WITH clause. But make 4312508e2d00Sdrh ** sure no other terms are marked SF_Recursive in case something changes 4313508e2d00Sdrh ** in the future. 4314508e2d00Sdrh */ 4315508e2d00Sdrh { 4316508e2d00Sdrh Select *pX; 4317b1ec87afSdrh for(pX=pSubq; pX; pX=pX->pPrior){ 4318508e2d00Sdrh assert( (pX->selFlags & (SF_Recursive))==0 ); 431969b72d5aSdrh } 4320b1ec87afSdrh } 4321508e2d00Sdrh #endif 4322508e2d00Sdrh 432369b72d5aSdrh if( pSubq->pLimit!=0 ){ 432469b72d5aSdrh return 0; /* restriction (3) */ 432569b72d5aSdrh } 432669b72d5aSdrh while( pWhere->op==TK_AND ){ 43276a9b9527Sdrh nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, 43286a9b9527Sdrh iCursor, isLeftJoin); 432969b72d5aSdrh pWhere = pWhere->pLeft; 433069b72d5aSdrh } 43316a9b9527Sdrh if( isLeftJoin 43326a9b9527Sdrh && (ExprHasProperty(pWhere,EP_FromJoin)==0 43336a9b9527Sdrh || pWhere->iRightJoinTable!=iCursor) 43346a9b9527Sdrh ){ 43356a9b9527Sdrh return 0; /* restriction (4) */ 43366a9b9527Sdrh } 43377fbb101cSdrh if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){ 43387fbb101cSdrh return 0; /* restriction (5) */ 43397fbb101cSdrh } 434069b72d5aSdrh if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ 434169b72d5aSdrh nChng++; 434269b72d5aSdrh while( pSubq ){ 434346967de2Sdrh SubstContext x; 434444c5604cSdan pNew = sqlite3ExprDup(pParse->db, pWhere, 0); 43457fbb101cSdrh unsetJoinExpr(pNew, -1); 434646967de2Sdrh x.pParse = pParse; 434746967de2Sdrh x.iTable = iCursor; 4348399c7e21Sdrh x.iNewTable = iCursor; 434931d6fd55Sdrh x.isLeftJoin = 0; 435046967de2Sdrh x.pEList = pSubq->pEList; 435146967de2Sdrh pNew = substExpr(&x, pNew); 435225c221ebSdrh if( pSubq->selFlags & SF_Aggregate ){ 435325c221ebSdrh pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew); 435425c221ebSdrh }else{ 435544c5604cSdan pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew); 435625c221ebSdrh } 435769b72d5aSdrh pSubq = pSubq->pPrior; 435869b72d5aSdrh } 435969b72d5aSdrh } 436069b72d5aSdrh return nChng; 436169b72d5aSdrh } 436269b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 436369b72d5aSdrh 43641350b030Sdrh /* 436547d9f839Sdrh ** The pFunc is the only aggregate function in the query. Check to see 436647d9f839Sdrh ** if the query is a candidate for the min/max optimization. 4367a9d1ccb9Sdanielk1977 ** 436847d9f839Sdrh ** If the query is a candidate for the min/max optimization, then set 436947d9f839Sdrh ** *ppMinMax to be an ORDER BY clause to be used for the optimization 437047d9f839Sdrh ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on 437147d9f839Sdrh ** whether pFunc is a min() or max() function. 4372738bdcfbSdanielk1977 ** 437347d9f839Sdrh ** If the query is not a candidate for the min/max optimization, return 437447d9f839Sdrh ** WHERE_ORDERBY_NORMAL (which must be zero). 43754ac391fcSdan ** 437647d9f839Sdrh ** This routine must be called after aggregate functions have been 437747d9f839Sdrh ** located but before their arguments have been subjected to aggregate 437847d9f839Sdrh ** analysis. 4379a9d1ccb9Sdanielk1977 */ 438047d9f839Sdrh static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ 43814ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 438247d9f839Sdrh ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */ 438347d9f839Sdrh const char *zFunc; /* Name of aggregate function pFunc */ 438447d9f839Sdrh ExprList *pOrderBy; 438547d9f839Sdrh u8 sortOrder; 4386a9d1ccb9Sdanielk1977 438747d9f839Sdrh assert( *ppMinMax==0 ); 438847d9f839Sdrh assert( pFunc->op==TK_AGG_FUNCTION ); 438947d9f839Sdrh if( pEList==0 || pEList->nExpr!=1 ) return eRet; 439047d9f839Sdrh zFunc = pFunc->u.zToken; 43914ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 43924ac391fcSdan eRet = WHERE_ORDERBY_MIN; 439347d9f839Sdrh sortOrder = SQLITE_SO_ASC; 43944ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 43954ac391fcSdan eRet = WHERE_ORDERBY_MAX; 439647d9f839Sdrh sortOrder = SQLITE_SO_DESC; 439747d9f839Sdrh }else{ 439847d9f839Sdrh return eRet; 4399a9d1ccb9Sdanielk1977 } 440047d9f839Sdrh *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0); 440147d9f839Sdrh assert( pOrderBy!=0 || db->mallocFailed ); 440247d9f839Sdrh if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder; 44034ac391fcSdan return eRet; 4404a9d1ccb9Sdanielk1977 } 4405a9d1ccb9Sdanielk1977 4406a9d1ccb9Sdanielk1977 /* 4407a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 440860ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 4409a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 4410a5533162Sdanielk1977 ** 4411a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4412a5533162Sdanielk1977 ** 4413a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 4414a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 4415a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 4416a5533162Sdanielk1977 */ 4417a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 4418a5533162Sdanielk1977 Table *pTab; 4419a5533162Sdanielk1977 Expr *pExpr; 4420a5533162Sdanielk1977 4421a5533162Sdanielk1977 assert( !p->pGroupBy ); 4422a5533162Sdanielk1977 44237a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 4424a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 4425a5533162Sdanielk1977 ){ 4426a5533162Sdanielk1977 return 0; 4427a5533162Sdanielk1977 } 4428a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 4429a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 443002f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 443102f33725Sdanielk1977 443202f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 4433a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 4434fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 4435d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 4436a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 4437a5533162Sdanielk1977 4438a5533162Sdanielk1977 return pTab; 4439a5533162Sdanielk1977 } 4440a5533162Sdanielk1977 4441a5533162Sdanielk1977 /* 4442b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 4443b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 4444b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 4445b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 4446b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 4447b1c685b0Sdanielk1977 */ 4448b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 44498a48b9c0Sdrh if( pFrom->pTab && pFrom->fg.isIndexedBy ){ 4450b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 44518a48b9c0Sdrh char *zIndexedBy = pFrom->u1.zIndexedBy; 4452b1c685b0Sdanielk1977 Index *pIdx; 4453b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 4454d62fbb50Sdrh pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 4455b1c685b0Sdanielk1977 pIdx=pIdx->pNext 4456b1c685b0Sdanielk1977 ); 4457b1c685b0Sdanielk1977 if( !pIdx ){ 4458d62fbb50Sdrh sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); 44591db95106Sdan pParse->checkSchema = 1; 4460b1c685b0Sdanielk1977 return SQLITE_ERROR; 4461b1c685b0Sdanielk1977 } 44628a48b9c0Sdrh pFrom->pIBIndex = pIdx; 4463b1c685b0Sdanielk1977 } 4464b1c685b0Sdanielk1977 return SQLITE_OK; 4465b1c685b0Sdanielk1977 } 4466c01b7306Sdrh /* 4467c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 4468c01b7306Sdrh ** an alternative collating sequence. 4469c01b7306Sdrh ** 4470c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 4471c01b7306Sdrh ** 4472c01b7306Sdrh ** These are rewritten as a subquery: 4473c01b7306Sdrh ** 4474c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 4475c01b7306Sdrh ** ORDER BY ... COLLATE ... 4476c01b7306Sdrh ** 4477c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 4478c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 4479c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 4480c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 4481c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 4482c01b7306Sdrh ** 4483c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 4484c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 4485c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 4486c01b7306Sdrh */ 4487c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 4488c01b7306Sdrh int i; 4489c01b7306Sdrh Select *pNew; 4490c01b7306Sdrh Select *pX; 4491c01b7306Sdrh sqlite3 *db; 4492c01b7306Sdrh struct ExprList_item *a; 4493c01b7306Sdrh SrcList *pNewSrc; 4494c01b7306Sdrh Parse *pParse; 4495c01b7306Sdrh Token dummy; 4496c01b7306Sdrh 4497c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 4498c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 4499c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 4500c01b7306Sdrh if( pX==0 ) return WRC_Continue; 4501c01b7306Sdrh a = p->pOrderBy->a; 4502c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 4503c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 4504c01b7306Sdrh } 4505c01b7306Sdrh if( i<0 ) return WRC_Continue; 4506c01b7306Sdrh 4507c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 4508c01b7306Sdrh 4509c01b7306Sdrh pParse = pWalker->pParse; 4510c01b7306Sdrh db = pParse->db; 4511c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 4512c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 4513c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 4514c01b7306Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 4515c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 4516c01b7306Sdrh *pNew = *p; 4517c01b7306Sdrh p->pSrc = pNewSrc; 45181a1d3cd2Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); 4519c01b7306Sdrh p->op = TK_SELECT; 4520c01b7306Sdrh p->pWhere = 0; 4521c01b7306Sdrh pNew->pGroupBy = 0; 4522c01b7306Sdrh pNew->pHaving = 0; 4523c01b7306Sdrh pNew->pOrderBy = 0; 4524c01b7306Sdrh p->pPrior = 0; 45258af9ad95Sdrh p->pNext = 0; 4526f932f714Sdrh p->pWith = 0; 45278af9ad95Sdrh p->selFlags &= ~SF_Compound; 4528b33c50f2Sdan assert( (p->selFlags & SF_Converted)==0 ); 4529b33c50f2Sdan p->selFlags |= SF_Converted; 4530a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 4531a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 4532c01b7306Sdrh pNew->pLimit = 0; 4533c01b7306Sdrh return WRC_Continue; 4534c01b7306Sdrh } 4535b1c685b0Sdanielk1977 453620292310Sdrh /* 453720292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function 453820292310Sdrh ** arguments. If it does, leave an error message in pParse and return 453920292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function. 454020292310Sdrh */ 454120292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ 454220292310Sdrh if( pFrom->fg.isTabFunc ){ 454320292310Sdrh sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); 454420292310Sdrh return 1; 454520292310Sdrh } 454620292310Sdrh return 0; 454720292310Sdrh } 454820292310Sdrh 4549eede6a53Sdan #ifndef SQLITE_OMIT_CTE 4550eede6a53Sdan /* 4551eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 4552eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 4553eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 4554eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 4555eede6a53Sdan ** return NULL. 455698f45e53Sdan ** 455798f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 455898f45e53Sdan ** object that the returned CTE belongs to. 455960c1a2f0Sdrh */ 456098f45e53Sdan static struct Cte *searchWith( 45612476a6f2Sdrh With *pWith, /* Current innermost WITH clause */ 456298f45e53Sdan struct SrcList_item *pItem, /* FROM clause element to resolve */ 456398f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 456498f45e53Sdan ){ 45657b19f252Sdrh const char *zName; 45667b19f252Sdrh if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 4567eede6a53Sdan With *p; 4568eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 45694e9119d9Sdan int i; 4570eede6a53Sdan for(i=0; i<p->nCte; i++){ 4571eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 457298f45e53Sdan *ppContext = p; 4573eede6a53Sdan return &p->a[i]; 45744e9119d9Sdan } 45754e9119d9Sdan } 45764e9119d9Sdan } 45774e9119d9Sdan } 45784e9119d9Sdan return 0; 45794e9119d9Sdan } 45804e9119d9Sdan 4581c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 4582c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 4583c49832c2Sdrh ** 4584b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 4585b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 4586b290f117Sdan ** WITH clause will never be popped from the stack. In this case it 4587b290f117Sdan ** should be freed along with the Parse object. In other cases, when 4588b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 4589b290f117Sdan ** statement with which it is associated. 4590c49832c2Sdrh */ 4591b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 45926e772266Sdrh assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); 45934e9119d9Sdan if( pWith ){ 45942476a6f2Sdrh assert( pParse->pWith!=pWith ); 45954e9119d9Sdan pWith->pOuter = pParse->pWith; 45964e9119d9Sdan pParse->pWith = pWith; 45976e772266Sdrh if( bFree ) pParse->pWithToFree = pWith; 45984e9119d9Sdan } 45994e9119d9Sdan } 46004e9119d9Sdan 4601eede6a53Sdan /* 4602eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 4603eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And, 4604eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive 4605eede6a53Sdan ** reference to the current CTE. 4606eede6a53Sdan ** 4607eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab 4608eede6a53Sdan ** and other fields are populated accordingly. The caller should check 4609eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match 4610eede6a53Sdan ** was found. 4611eede6a53Sdan ** 4612eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error 4613eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the 4614eede6a53Sdan ** parser and some error code other than SQLITE_OK returned. 4615eede6a53Sdan */ 46168ce7184bSdan static int withExpand( 46178ce7184bSdan Walker *pWalker, 4618eede6a53Sdan struct SrcList_item *pFrom 46198ce7184bSdan ){ 46208ce7184bSdan Parse *pParse = pWalker->pParse; 46218ce7184bSdan sqlite3 *db = pParse->db; 462298f45e53Sdan struct Cte *pCte; /* Matched CTE (or NULL if no match) */ 462398f45e53Sdan With *pWith; /* WITH clause that pCte belongs to */ 46248ce7184bSdan 46258ce7184bSdan assert( pFrom->pTab==0 ); 46268ce7184bSdan 462798f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 4628eae73fbfSdan if( pCte ){ 462998f45e53Sdan Table *pTab; 46308ce7184bSdan ExprList *pEList; 46318ce7184bSdan Select *pSel; 463260e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 4633f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 463498f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 4635f2655fe8Sdan 46360576bc59Sdrh /* If pCte->zCteErr is non-NULL at this point, then this is an illegal 4637f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 46380576bc59Sdrh ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. 4639f2655fe8Sdan ** In this case, proceed. */ 46400576bc59Sdrh if( pCte->zCteErr ){ 46410576bc59Sdrh sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); 464298f45e53Sdan return SQLITE_ERROR; 4643f2655fe8Sdan } 464420292310Sdrh if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; 46458ce7184bSdan 4646c25e2ebcSdrh assert( pFrom->pTab==0 ); 46478ce7184bSdan pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 46488ce7184bSdan if( pTab==0 ) return WRC_Abort; 464979df7782Sdrh pTab->nTabRef = 1; 46502d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 46518ce7184bSdan pTab->iPKey = -1; 4652cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4653fccda8a1Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 46548ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 4655fad3039cSmistachkin if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; 46568ce7184bSdan assert( pFrom->pSelect ); 46578ce7184bSdan 4658eae73fbfSdan /* Check if this is a recursive CTE. */ 46598ce7184bSdan pSel = pFrom->pSelect; 4660f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 4661f2655fe8Sdan if( bMayRecursive ){ 4662eae73fbfSdan int i; 4663eae73fbfSdan SrcList *pSrc = pFrom->pSelect->pSrc; 4664eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 4665eae73fbfSdan struct SrcList_item *pItem = &pSrc->a[i]; 4666eae73fbfSdan if( pItem->zDatabase==0 4667eae73fbfSdan && pItem->zName!=0 4668eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4669eae73fbfSdan ){ 4670eae73fbfSdan pItem->pTab = pTab; 46718a48b9c0Sdrh pItem->fg.isRecursive = 1; 467279df7782Sdrh pTab->nTabRef++; 4673eae73fbfSdan pSel->selFlags |= SF_Recursive; 46748ce7184bSdan } 4675eae73fbfSdan } 4676eae73fbfSdan } 4677eae73fbfSdan 4678eae73fbfSdan /* Only one recursive reference is permitted. */ 467979df7782Sdrh if( pTab->nTabRef>2 ){ 4680eae73fbfSdan sqlite3ErrorMsg( 4681727a99f1Sdrh pParse, "multiple references to recursive table: %s", pCte->zName 4682eae73fbfSdan ); 468398f45e53Sdan return SQLITE_ERROR; 4684eae73fbfSdan } 46853d240d21Sdrh assert( pTab->nTabRef==1 || 46863d240d21Sdrh ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); 4687eae73fbfSdan 46880576bc59Sdrh pCte->zCteErr = "circular reference: %s"; 468998f45e53Sdan pSavedWith = pParse->pWith; 469098f45e53Sdan pParse->pWith = pWith; 4691067cd837Sdan if( bMayRecursive ){ 4692067cd837Sdan Select *pPrior = pSel->pPrior; 4693067cd837Sdan assert( pPrior->pWith==0 ); 4694067cd837Sdan pPrior->pWith = pSel->pWith; 4695067cd837Sdan sqlite3WalkSelect(pWalker, pPrior); 4696067cd837Sdan pPrior->pWith = 0; 4697067cd837Sdan }else{ 4698067cd837Sdan sqlite3WalkSelect(pWalker, pSel); 4699067cd837Sdan } 47006e772266Sdrh pParse->pWith = pWith; 47018ce7184bSdan 47028ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 47038ce7184bSdan pEList = pLeft->pEList; 470460e7068dSdan if( pCte->pCols ){ 47058f9d0b2bSdrh if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ 4706727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 470760e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 470860e7068dSdan ); 470998f45e53Sdan pParse->pWith = pSavedWith; 471098f45e53Sdan return SQLITE_ERROR; 47118ce7184bSdan } 471260e7068dSdan pEList = pCte->pCols; 471360e7068dSdan } 47148ce7184bSdan 47158981b904Sdrh sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4716f2655fe8Sdan if( bMayRecursive ){ 4717f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 47180576bc59Sdrh pCte->zCteErr = "multiple recursive references: %s"; 4719f2655fe8Sdan }else{ 47200576bc59Sdrh pCte->zCteErr = "recursive reference in a subquery: %s"; 4721f2655fe8Sdan } 4722f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 4723f2655fe8Sdan } 47240576bc59Sdrh pCte->zCteErr = 0; 472598f45e53Sdan pParse->pWith = pSavedWith; 47268ce7184bSdan } 47278ce7184bSdan 47288ce7184bSdan return SQLITE_OK; 47298ce7184bSdan } 4730eede6a53Sdan #endif 47314e9119d9Sdan 4732b290f117Sdan #ifndef SQLITE_OMIT_CTE 473371856944Sdan /* 473471856944Sdan ** If the SELECT passed as the second argument has an associated WITH 473571856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 473671856944Sdan ** 473771856944Sdan ** This function is used as the xSelectCallback2() callback by 473871856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 473971856944Sdan ** names and other FROM clause elements. 474071856944Sdan */ 4741b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){ 4742b290f117Sdan Parse *pParse = pWalker->pParse; 47432f65b2f5Sdrh if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ 4744d227a291Sdrh With *pWith = findRightmost(p)->pWith; 4745d227a291Sdrh if( pWith!=0 ){ 4746d227a291Sdrh assert( pParse->pWith==pWith ); 4747d227a291Sdrh pParse->pWith = pWith->pOuter; 4748b290f117Sdan } 4749b290f117Sdan } 4750067cd837Sdan } 4751b290f117Sdan #else 4752b290f117Sdan #define selectPopWith 0 4753b290f117Sdan #endif 4754b290f117Sdan 47559a94722dSdan /* 47569a94722dSdan ** The SrcList_item structure passed as the second argument represents a 47579a94722dSdan ** sub-query in the FROM clause of a SELECT statement. This function 47589a94722dSdan ** allocates and populates the SrcList_item.pTab object. If successful, 47599a94722dSdan ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered, 47609a94722dSdan ** SQLITE_NOMEM. 47619a94722dSdan */ 4762dfa552f4Sdan int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){ 476386fb6e17Sdan Select *pSel = pFrom->pSelect; 476486fb6e17Sdan Table *pTab; 476586fb6e17Sdan 47669a94722dSdan assert( pSel ); 476786fb6e17Sdan pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table)); 47689a94722dSdan if( pTab==0 ) return SQLITE_NOMEM; 476986fb6e17Sdan pTab->nTabRef = 1; 477086fb6e17Sdan if( pFrom->zAlias ){ 477186fb6e17Sdan pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias); 477286fb6e17Sdan }else{ 4773fef37760Sdrh pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId); 477486fb6e17Sdan } 477586fb6e17Sdan while( pSel->pPrior ){ pSel = pSel->pPrior; } 477686fb6e17Sdan sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); 477786fb6e17Sdan pTab->iPKey = -1; 477886fb6e17Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 477986fb6e17Sdan pTab->tabFlags |= TF_Ephemeral; 478086fb6e17Sdan 47819a94722dSdan return SQLITE_OK; 478286fb6e17Sdan } 478386fb6e17Sdan 4784b1c685b0Sdanielk1977 /* 47857d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 47867d10d5a6Sdrh ** "Expanding" means to do the following: 47877d10d5a6Sdrh ** 47887d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 47897d10d5a6Sdrh ** element of the FROM clause. 47907d10d5a6Sdrh ** 47917d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 47927d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 47937d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 47947d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 47957d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 479660ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 47977d10d5a6Sdrh ** of the view. 47987d10d5a6Sdrh ** 479960ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 48007d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 48017d10d5a6Sdrh ** 48027d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 48037d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 48047d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 48057d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 48067d10d5a6Sdrh ** 4807b3bce662Sdanielk1977 */ 48087d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 48097d10d5a6Sdrh Parse *pParse = pWalker->pParse; 48107d10d5a6Sdrh int i, j, k; 48117d10d5a6Sdrh SrcList *pTabList; 48127d10d5a6Sdrh ExprList *pEList; 48137d10d5a6Sdrh struct SrcList_item *pFrom; 48147d10d5a6Sdrh sqlite3 *db = pParse->db; 48153e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 4816785097daSdrh u16 selFlags = p->selFlags; 4817fca23557Sdrh u32 elistFlags = 0; 48187d10d5a6Sdrh 4819785097daSdrh p->selFlags |= SF_Expanded; 48207d10d5a6Sdrh if( db->mallocFailed ){ 48217d10d5a6Sdrh return WRC_Abort; 48227d10d5a6Sdrh } 48239d9c41e2Sdrh assert( p->pSrc!=0 ); 48249d9c41e2Sdrh if( (selFlags & SF_Expanded)!=0 ){ 48257d10d5a6Sdrh return WRC_Prune; 48267d10d5a6Sdrh } 48277d10d5a6Sdrh pTabList = p->pSrc; 48287d10d5a6Sdrh pEList = p->pEList; 4829067cd837Sdan sqlite3WithPush(pParse, p->pWith, 0); 48307d10d5a6Sdrh 48317d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 48327d10d5a6Sdrh ** the FROM clause of the SELECT statement. 48337d10d5a6Sdrh */ 48347d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 48357d10d5a6Sdrh 48367d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 48377d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 48387d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 48397d10d5a6Sdrh */ 48407d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 48417d10d5a6Sdrh Table *pTab; 4842e2b7d7a0Sdrh assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); 48438a48b9c0Sdrh if( pFrom->fg.isRecursive ) continue; 4844e2b7d7a0Sdrh assert( pFrom->pTab==0 ); 48454e9119d9Sdan #ifndef SQLITE_OMIT_CTE 4846eede6a53Sdan if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4847eede6a53Sdan if( pFrom->pTab ) {} else 48484e9119d9Sdan #endif 48497d10d5a6Sdrh if( pFrom->zName==0 ){ 48507d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 48517d10d5a6Sdrh Select *pSel = pFrom->pSelect; 48527d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 48537d10d5a6Sdrh assert( pSel!=0 ); 48547d10d5a6Sdrh assert( pFrom->pTab==0 ); 48552b8c5a00Sdrh if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; 4856dfa552f4Sdan if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort; 485786fb6e17Sdan #endif 48587d10d5a6Sdrh }else{ 48597d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 48607d10d5a6Sdrh assert( pFrom->pTab==0 ); 486141fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 48627d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 486379df7782Sdrh if( pTab->nTabRef>=0xffff ){ 4864d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 4865d2a56238Sdrh pTab->zName); 4866d2a56238Sdrh pFrom->pTab = 0; 4867d2a56238Sdrh return WRC_Abort; 4868d2a56238Sdrh } 486979df7782Sdrh pTab->nTabRef++; 487020292310Sdrh if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ 487120292310Sdrh return WRC_Abort; 487220292310Sdrh } 48737d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 487420292310Sdrh if( IsVirtual(pTab) || pTab->pSelect ){ 4875bfad7be7Sdrh i16 nCol; 48767d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 487743152cf8Sdrh assert( pFrom->pSelect==0 ); 48786ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 4879bfad7be7Sdrh nCol = pTab->nCol; 4880bfad7be7Sdrh pTab->nCol = -1; 48817d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 4882bfad7be7Sdrh pTab->nCol = nCol; 48837d10d5a6Sdrh } 48847d10d5a6Sdrh #endif 48857d10d5a6Sdrh } 488685574e31Sdanielk1977 488785574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 4888b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 488985574e31Sdanielk1977 return WRC_Abort; 489085574e31Sdanielk1977 } 48917d10d5a6Sdrh } 48927d10d5a6Sdrh 48937d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 48947d10d5a6Sdrh */ 48957d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 48967d10d5a6Sdrh return WRC_Abort; 48977d10d5a6Sdrh } 48987d10d5a6Sdrh 48997d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 49007d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 49017d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 49021a1d3cd2Sdrh ** with the TK_ASTERISK operator for each "*" that it found in the column 49031a1d3cd2Sdrh ** list. The following code just has to locate the TK_ASTERISK 49041a1d3cd2Sdrh ** expressions and expand each one to the list of all columns in 49051a1d3cd2Sdrh ** all tables. 49067d10d5a6Sdrh ** 49077d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 49087d10d5a6Sdrh ** that need expanding. 49097d10d5a6Sdrh */ 49107d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 49113e3f1a5bSdrh pE = pEList->a[k].pExpr; 49121a1d3cd2Sdrh if( pE->op==TK_ASTERISK ) break; 491343152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 491443152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 49151a1d3cd2Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; 4916fca23557Sdrh elistFlags |= pE->flags; 49177d10d5a6Sdrh } 49187d10d5a6Sdrh if( k<pEList->nExpr ){ 49197d10d5a6Sdrh /* 49207d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 49217d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 49227d10d5a6Sdrh ** in the result set and expand them one by one. 49237d10d5a6Sdrh */ 49247d10d5a6Sdrh struct ExprList_item *a = pEList->a; 49257d10d5a6Sdrh ExprList *pNew = 0; 49267d10d5a6Sdrh int flags = pParse->db->flags; 49277d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 492838b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 492938b384a0Sdrh 49307d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 49313e3f1a5bSdrh pE = a[k].pExpr; 4932fca23557Sdrh elistFlags |= pE->flags; 49333e3f1a5bSdrh pRight = pE->pRight; 49343e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 49351a1d3cd2Sdrh if( pE->op!=TK_ASTERISK 49361a1d3cd2Sdrh && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) 49371a1d3cd2Sdrh ){ 49387d10d5a6Sdrh /* This particular expression does not need to be expanded. 49397d10d5a6Sdrh */ 4940b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 49417d10d5a6Sdrh if( pNew ){ 49427d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 4943b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 4944b7916a78Sdrh a[k].zName = 0; 4945b7916a78Sdrh a[k].zSpan = 0; 49467d10d5a6Sdrh } 49477d10d5a6Sdrh a[k].pExpr = 0; 49487d10d5a6Sdrh }else{ 49497d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 49507d10d5a6Sdrh ** expanded. */ 49517d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 49523e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 495343152cf8Sdrh if( pE->op==TK_DOT ){ 495443152cf8Sdrh assert( pE->pLeft!=0 ); 495533e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 495633e619fcSdrh zTName = pE->pLeft->u.zToken; 49577d10d5a6Sdrh } 49587d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 49597d10d5a6Sdrh Table *pTab = pFrom->pTab; 49603e3f1a5bSdrh Select *pSub = pFrom->pSelect; 49617d10d5a6Sdrh char *zTabName = pFrom->zAlias; 49623e3f1a5bSdrh const char *zSchemaName = 0; 4963c75e09c7Sdrh int iDb; 496443152cf8Sdrh if( zTabName==0 ){ 49657d10d5a6Sdrh zTabName = pTab->zName; 49667d10d5a6Sdrh } 49677d10d5a6Sdrh if( db->mallocFailed ) break; 49683e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 49693e3f1a5bSdrh pSub = 0; 49707d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 49717d10d5a6Sdrh continue; 49727d10d5a6Sdrh } 49733e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 497469c33826Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; 49753e3f1a5bSdrh } 49767d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 49777d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 4978b7916a78Sdrh char *zColname; /* The computed column name */ 4979b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 4980b7916a78Sdrh Token sColname; /* Computed column name as a token */ 49817d10d5a6Sdrh 4982c75e09c7Sdrh assert( zName ); 49833e3f1a5bSdrh if( zTName && pSub 49843e3f1a5bSdrh && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 49853e3f1a5bSdrh ){ 49863e3f1a5bSdrh continue; 49873e3f1a5bSdrh } 49883e3f1a5bSdrh 498980090f92Sdrh /* If a column is marked as 'hidden', omit it from the expanded 499080090f92Sdrh ** result-set list unless the SELECT has the SF_IncludeHidden 499180090f92Sdrh ** bit set. 49927d10d5a6Sdrh */ 499380090f92Sdrh if( (p->selFlags & SF_IncludeHidden)==0 499480090f92Sdrh && IsHiddenColumn(&pTab->aCol[j]) 499580090f92Sdrh ){ 49967d10d5a6Sdrh continue; 49977d10d5a6Sdrh } 49983e3f1a5bSdrh tableSeen = 1; 49997d10d5a6Sdrh 5000da55c48aSdrh if( i>0 && zTName==0 ){ 50018a48b9c0Sdrh if( (pFrom->fg.jointype & JT_NATURAL)!=0 50022179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 50032179b434Sdrh ){ 50047d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 50052179b434Sdrh ** table to the right of the join */ 50067d10d5a6Sdrh continue; 50077d10d5a6Sdrh } 50082179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 50097d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 50107d10d5a6Sdrh ** using clause from the table on the right. */ 50117d10d5a6Sdrh continue; 50127d10d5a6Sdrh } 50137d10d5a6Sdrh } 5014b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 5015b7916a78Sdrh zColname = zName; 5016b7916a78Sdrh zToFree = 0; 50177d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 5018b7916a78Sdrh Expr *pLeft; 5019b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 5020abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); 502138b384a0Sdrh if( zSchemaName ){ 5022c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 5023abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); 5024c75e09c7Sdrh } 5025b7916a78Sdrh if( longNames ){ 5026b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 5027b7916a78Sdrh zToFree = zColname; 5028b7916a78Sdrh } 50297d10d5a6Sdrh }else{ 50307d10d5a6Sdrh pExpr = pRight; 50317d10d5a6Sdrh } 5032b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 503340aced5cSdrh sqlite3TokenInit(&sColname, zColname); 5034b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 50358f25d18bSdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ 50363e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 50373e3f1a5bSdrh if( pSub ){ 50383e3f1a5bSdrh pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); 5039c75e09c7Sdrh testcase( pX->zSpan==0 ); 50403e3f1a5bSdrh }else{ 50413e3f1a5bSdrh pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", 50423e3f1a5bSdrh zSchemaName, zTabName, zColname); 5043c75e09c7Sdrh testcase( pX->zSpan==0 ); 50443e3f1a5bSdrh } 50453e3f1a5bSdrh pX->bSpanIsTab = 1; 50468f25d18bSdrh } 5047b7916a78Sdrh sqlite3DbFree(db, zToFree); 50487d10d5a6Sdrh } 50497d10d5a6Sdrh } 50507d10d5a6Sdrh if( !tableSeen ){ 50517d10d5a6Sdrh if( zTName ){ 50527d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 50537d10d5a6Sdrh }else{ 50547d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 50557d10d5a6Sdrh } 50567d10d5a6Sdrh } 50577d10d5a6Sdrh } 50587d10d5a6Sdrh } 50597d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 50607d10d5a6Sdrh p->pEList = pNew; 50617d10d5a6Sdrh } 5062fca23557Sdrh if( p->pEList ){ 5063fca23557Sdrh if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 50647d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 50658836cbbcSdan return WRC_Abort; 50667d10d5a6Sdrh } 5067fca23557Sdrh if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ 5068fca23557Sdrh p->selFlags |= SF_ComplexResult; 5069fca23557Sdrh } 5070fca23557Sdrh } 50717d10d5a6Sdrh return WRC_Continue; 50727d10d5a6Sdrh } 50737d10d5a6Sdrh 50747d10d5a6Sdrh /* 50757d10d5a6Sdrh ** No-op routine for the parse-tree walker. 50767d10d5a6Sdrh ** 50777d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 50787d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 50797d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 50807d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 50817d10d5a6Sdrh ** subquery in the parser tree. 50827d10d5a6Sdrh */ 50835b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 508462c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 50857d10d5a6Sdrh return WRC_Continue; 50867d10d5a6Sdrh } 50877d10d5a6Sdrh 50887d10d5a6Sdrh /* 5089979dd1beSdrh ** No-op routine for the parse-tree walker for SELECT statements. 5090979dd1beSdrh ** subquery in the parser tree. 5091979dd1beSdrh */ 5092979dd1beSdrh int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ 5093979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 5094979dd1beSdrh return WRC_Continue; 5095979dd1beSdrh } 5096979dd1beSdrh 5097979dd1beSdrh #if SQLITE_DEBUG 5098979dd1beSdrh /* 5099979dd1beSdrh ** Always assert. This xSelectCallback2 implementation proves that the 5100979dd1beSdrh ** xSelectCallback2 is never invoked. 5101979dd1beSdrh */ 5102979dd1beSdrh void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ 5103979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 5104979dd1beSdrh assert( 0 ); 5105979dd1beSdrh } 5106979dd1beSdrh #endif 5107979dd1beSdrh /* 51087d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 51097d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 51107d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 51117d10d5a6Sdrh ** 51127d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 51137d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 51147d10d5a6Sdrh ** name resolution is performed. 51157d10d5a6Sdrh ** 51167d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 51177d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 51187d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 51197d10d5a6Sdrh */ 51207d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 51217d10d5a6Sdrh Walker w; 51225b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 51237d10d5a6Sdrh w.pParse = pParse; 5124878fcf9dSdrh if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ 5125d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 5126979dd1beSdrh w.xSelectCallback2 = 0; 51277d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 5128d58d3278Sdrh } 5129c01b7306Sdrh w.xSelectCallback = selectExpander; 5130b290f117Sdan w.xSelectCallback2 = selectPopWith; 5131c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 51327d10d5a6Sdrh } 51337d10d5a6Sdrh 51347d10d5a6Sdrh 51357d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 51367d10d5a6Sdrh /* 51377d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 51387d10d5a6Sdrh ** interface. 51397d10d5a6Sdrh ** 51407d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 51417d10d5a6Sdrh ** information to the Table structure that represents the result set 51427d10d5a6Sdrh ** of that subquery. 51437d10d5a6Sdrh ** 51447d10d5a6Sdrh ** The Table structure that represents the result set was constructed 51457d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 51467d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 51477d10d5a6Sdrh ** routine is called after identifier resolution. 51487d10d5a6Sdrh */ 5149b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 51507d10d5a6Sdrh Parse *pParse; 51517d10d5a6Sdrh int i; 51527d10d5a6Sdrh SrcList *pTabList; 51537d10d5a6Sdrh struct SrcList_item *pFrom; 51547d10d5a6Sdrh 51559d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 5156cc464418Sdan if( p->selFlags & SF_HasTypeInfo ) return; 51577d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 51587d10d5a6Sdrh pParse = pWalker->pParse; 51597d10d5a6Sdrh pTabList = p->pSrc; 51607d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 51617d10d5a6Sdrh Table *pTab = pFrom->pTab; 5162e2b7d7a0Sdrh assert( pTab!=0 ); 5163e2b7d7a0Sdrh if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ 51647d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 51657d10d5a6Sdrh Select *pSel = pFrom->pSelect; 51668ce7184bSdan if( pSel ){ 51677d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 5168ed06a131Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel); 51697d10d5a6Sdrh } 51707d10d5a6Sdrh } 51715a29d9cbSdrh } 51728ce7184bSdan } 51737d10d5a6Sdrh #endif 51747d10d5a6Sdrh 51757d10d5a6Sdrh 51767d10d5a6Sdrh /* 51777d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 51787d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 51797d10d5a6Sdrh ** SELECT statement. 51807d10d5a6Sdrh ** 51817d10d5a6Sdrh ** Use this routine after name resolution. 51827d10d5a6Sdrh */ 51837d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 51847d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 51857d10d5a6Sdrh Walker w; 5186979dd1beSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 5187b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 51885b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 51897d10d5a6Sdrh w.pParse = pParse; 51907d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 51917d10d5a6Sdrh #endif 51927d10d5a6Sdrh } 51937d10d5a6Sdrh 51947d10d5a6Sdrh 51957d10d5a6Sdrh /* 5196030796dfSdrh ** This routine sets up a SELECT statement for processing. The 51977d10d5a6Sdrh ** following is accomplished: 51987d10d5a6Sdrh ** 51997d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 52007d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 52017d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 52027d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 52037d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 52047d10d5a6Sdrh ** 52057d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 52067d10d5a6Sdrh */ 52077d10d5a6Sdrh void sqlite3SelectPrep( 5208b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 5209b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 52107d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 5211b3bce662Sdanielk1977 ){ 5212e2463398Sdrh assert( p!=0 || pParse->db->mallocFailed ); 5213e2463398Sdrh if( pParse->db->mallocFailed ) return; 52147d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 52157d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 5216b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 52177d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 5218b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 52197d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 5220f6bbe022Sdrh } 5221b3bce662Sdanielk1977 5222b3bce662Sdanielk1977 /* 522313449892Sdrh ** Reset the aggregate accumulator. 522413449892Sdrh ** 522513449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 522613449892Sdrh ** intermediate results while calculating an aggregate. This 5227030796dfSdrh ** routine generates code that stores NULLs in all of those memory 5228030796dfSdrh ** cells. 5229b3bce662Sdanielk1977 */ 523013449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 523113449892Sdrh Vdbe *v = pParse->pVdbe; 523213449892Sdrh int i; 5233c99130fdSdrh struct AggInfo_func *pFunc; 52347e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 52357e61d18eSdrh if( nReg==0 ) return; 52367e61d18eSdrh #ifdef SQLITE_DEBUG 52377e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 52387e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 52397e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 524013449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 52417e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 52427e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 524313449892Sdrh } 52447e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 52457e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 52467e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 52477e61d18eSdrh } 52487e61d18eSdrh #endif 52497e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 5250c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 5251c99130fdSdrh if( pFunc->iDistinct>=0 ){ 5252c99130fdSdrh Expr *pE = pFunc->pExpr; 52536ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 52546ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 52550daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 52560daa002cSdrh "argument"); 5257c99130fdSdrh pFunc->iDistinct = -1; 5258c99130fdSdrh }else{ 5259f9eae18bSdan KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0); 526066a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 52612ec2fb22Sdrh (char*)pKeyInfo, P4_KEYINFO); 5262c99130fdSdrh } 5263c99130fdSdrh } 526413449892Sdrh } 5265b3bce662Sdanielk1977 } 5266b3bce662Sdanielk1977 5267b3bce662Sdanielk1977 /* 526813449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 526913449892Sdrh ** in the AggInfo structure. 5270b3bce662Sdanielk1977 */ 527113449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 527213449892Sdrh Vdbe *v = pParse->pVdbe; 527313449892Sdrh int i; 527413449892Sdrh struct AggInfo_func *pF; 527513449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 52766ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 52776ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 52782700acaaSdrh sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); 52792700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5280b3bce662Sdanielk1977 } 528113449892Sdrh } 528213449892Sdrh 5283280c894bSdan 528413449892Sdrh /* 528513449892Sdrh ** Update the accumulator memory cells for an aggregate based on 528613449892Sdrh ** the current cursor position. 5287280c894bSdan ** 5288280c894bSdan ** If regAcc is non-zero and there are no min() or max() aggregates 5289280c894bSdan ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator 5290280c894bSdan ** registers i register regAcc contains 0. The caller will take care 5291280c894bSdan ** of setting and clearing regAcc. 529213449892Sdrh */ 5293280c894bSdan static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){ 529413449892Sdrh Vdbe *v = pParse->pVdbe; 529513449892Sdrh int i; 52967a95789cSdrh int regHit = 0; 52977a95789cSdrh int addrHitTest = 0; 529813449892Sdrh struct AggInfo_func *pF; 529913449892Sdrh struct AggInfo_col *pC; 530013449892Sdrh 530113449892Sdrh pAggInfo->directMode = 1; 530213449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 530313449892Sdrh int nArg; 5304c99130fdSdrh int addrNext = 0; 530598757157Sdrh int regAgg; 53066ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 53076ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 530813449892Sdrh if( pList ){ 530913449892Sdrh nArg = pList->nExpr; 5310892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 53115579d59fSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); 531213449892Sdrh }else{ 531313449892Sdrh nArg = 0; 531498757157Sdrh regAgg = 0; 531513449892Sdrh } 5316c99130fdSdrh if( pF->iDistinct>=0 ){ 5317c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 53187c052da5Sdrh testcase( nArg==0 ); /* Error condition */ 53197c052da5Sdrh testcase( nArg>1 ); /* Also an error */ 53202dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 5321c99130fdSdrh } 5322d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 532313449892Sdrh CollSeq *pColl = 0; 532413449892Sdrh struct ExprList_item *pItem; 532513449892Sdrh int j; 5326e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 532743617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 532813449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 532913449892Sdrh } 533013449892Sdrh if( !pColl ){ 533113449892Sdrh pColl = pParse->db->pDfltColl; 533213449892Sdrh } 53337a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 53347a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 533513449892Sdrh } 53368f26da6cSdrh sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem); 53372700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5338ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 5339da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 5340f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 5341c99130fdSdrh if( addrNext ){ 5342c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 5343ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5344c99130fdSdrh } 534513449892Sdrh } 534667a6a40cSdan 534767a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 534867a6a40cSdan ** Otherwise, if any of the required column values are already present 534967a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 535067a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 535167a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 535267a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 535367a6a40cSdan ** 535467a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 535567a6a40cSdan ** values to an OP_Copy. 535667a6a40cSdan */ 5357280c894bSdan if( regHit==0 && pAggInfo->nAccumulator ){ 5358280c894bSdan regHit = regAcc; 5359280c894bSdan } 53607a95789cSdrh if( regHit ){ 5361688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 53627a95789cSdrh } 536367a6a40cSdan sqlite3ExprCacheClear(pParse); 536413449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 5365389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 536613449892Sdrh } 536713449892Sdrh pAggInfo->directMode = 0; 5368ceea3321Sdrh sqlite3ExprCacheClear(pParse); 53697a95789cSdrh if( addrHitTest ){ 53707a95789cSdrh sqlite3VdbeJumpHere(v, addrHitTest); 53717a95789cSdrh } 537213449892Sdrh } 537313449892Sdrh 5374b3bce662Sdanielk1977 /* 5375ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 5376ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 5377ef7075deSdan */ 5378ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 5379ef7075deSdan static void explainSimpleCount( 5380ef7075deSdan Parse *pParse, /* Parse context */ 5381ef7075deSdan Table *pTab, /* Table being queried */ 5382ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 5383ef7075deSdan ){ 5384ef7075deSdan if( pParse->explain==2 ){ 538548dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 5386e2ca99c9Sdrh sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s", 5387ef7075deSdan pTab->zName, 5388e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 5389e96f2df3Sdan bCover ? pIdx->zName : "" 5390ef7075deSdan ); 5391ef7075deSdan } 5392ef7075deSdan } 5393ef7075deSdan #else 5394ef7075deSdan # define explainSimpleCount(a,b,c) 5395ef7075deSdan #endif 5396ef7075deSdan 5397ef7075deSdan /* 5398ab31a845Sdan ** sqlite3WalkExpr() callback used by havingToWhere(). 5399ab31a845Sdan ** 5400ab31a845Sdan ** If the node passed to the callback is a TK_AND node, return 5401ab31a845Sdan ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes. 5402ab31a845Sdan ** 5403ab31a845Sdan ** Otherwise, return WRC_Prune. In this case, also check if the 5404ab31a845Sdan ** sub-expression matches the criteria for being moved to the WHERE 5405ab31a845Sdan ** clause. If so, add it to the WHERE clause and replace the sub-expression 5406ab31a845Sdan ** within the HAVING expression with a constant "1". 5407ab31a845Sdan */ 5408ab31a845Sdan static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ 5409ab31a845Sdan if( pExpr->op!=TK_AND ){ 5410cd0abc24Sdrh Select *pS = pWalker->u.pSelect; 5411cd0abc24Sdrh if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){ 5412ab31a845Sdan sqlite3 *db = pWalker->pParse->db; 5413ab31a845Sdan Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0); 5414ab31a845Sdan if( pNew ){ 5415cd0abc24Sdrh Expr *pWhere = pS->pWhere; 5416ab31a845Sdan SWAP(Expr, *pNew, *pExpr); 5417ab31a845Sdan pNew = sqlite3ExprAnd(db, pWhere, pNew); 5418cd0abc24Sdrh pS->pWhere = pNew; 5419cd0abc24Sdrh pWalker->eCode = 1; 5420ab31a845Sdan } 5421ab31a845Sdan } 5422ab31a845Sdan return WRC_Prune; 5423ab31a845Sdan } 5424ab31a845Sdan return WRC_Continue; 5425ab31a845Sdan } 5426ab31a845Sdan 5427ab31a845Sdan /* 5428ab31a845Sdan ** Transfer eligible terms from the HAVING clause of a query, which is 5429ab31a845Sdan ** processed after grouping, to the WHERE clause, which is processed before 5430ab31a845Sdan ** grouping. For example, the query: 5431ab31a845Sdan ** 5432ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=? 5433ab31a845Sdan ** 5434ab31a845Sdan ** can be rewritten as: 5435ab31a845Sdan ** 5436ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=? 5437ab31a845Sdan ** 5438ab31a845Sdan ** A term of the HAVING expression is eligible for transfer if it consists 5439ab31a845Sdan ** entirely of constants and expressions that are also GROUP BY terms that 5440ab31a845Sdan ** use the "BINARY" collation sequence. 5441ab31a845Sdan */ 5442cd0abc24Sdrh static void havingToWhere(Parse *pParse, Select *p){ 5443ab31a845Sdan Walker sWalker; 5444ab31a845Sdan memset(&sWalker, 0, sizeof(sWalker)); 5445ab31a845Sdan sWalker.pParse = pParse; 5446ab31a845Sdan sWalker.xExprCallback = havingToWhereExprCb; 5447cd0abc24Sdrh sWalker.u.pSelect = p; 5448cd0abc24Sdrh sqlite3WalkExpr(&sWalker, p->pHaving); 5449cd0abc24Sdrh #if SELECTTRACE_ENABLED 5450cd0abc24Sdrh if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){ 5451cd0abc24Sdrh SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); 5452cd0abc24Sdrh sqlite3TreeViewSelect(0, p, 0); 5453cd0abc24Sdrh } 5454cd0abc24Sdrh #endif 5455ab31a845Sdan } 5456ab31a845Sdan 5457ab31a845Sdan /* 5458e08e8d6bSdrh ** Check to see if the pThis entry of pTabList is a self-join of a prior view. 5459e08e8d6bSdrh ** If it is, then return the SrcList_item for the prior view. If it is not, 5460e08e8d6bSdrh ** then return 0. 5461e08e8d6bSdrh */ 5462e08e8d6bSdrh static struct SrcList_item *isSelfJoinView( 5463e08e8d6bSdrh SrcList *pTabList, /* Search for self-joins in this FROM clause */ 5464e08e8d6bSdrh struct SrcList_item *pThis /* Search for prior reference to this subquery */ 5465e08e8d6bSdrh ){ 5466e08e8d6bSdrh struct SrcList_item *pItem; 5467e08e8d6bSdrh for(pItem = pTabList->a; pItem<pThis; pItem++){ 5468e08e8d6bSdrh if( pItem->pSelect==0 ) continue; 5469e08e8d6bSdrh if( pItem->fg.viaCoroutine ) continue; 547033543c23Sdrh if( pItem->zName==0 ) continue; 547133543c23Sdrh if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue; 5472ed712980Sdrh if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; 54735aa550cfSdan if( sqlite3ExprCompare(0, 54745aa550cfSdan pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1) 54755aa550cfSdan ){ 5476ed712980Sdrh /* The view was modified by some other optimization such as 5477ed712980Sdrh ** pushDownWhereTerms() */ 5478ed712980Sdrh continue; 5479ed712980Sdrh } 5480ed712980Sdrh return pItem; 5481e08e8d6bSdrh } 5482e08e8d6bSdrh return 0; 5483e08e8d6bSdrh } 5484e08e8d6bSdrh 5485269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5486269ba804Sdrh /* 5487269ba804Sdrh ** Attempt to transform a query of the form 5488269ba804Sdrh ** 5489269ba804Sdrh ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) 5490269ba804Sdrh ** 5491269ba804Sdrh ** Into this: 5492269ba804Sdrh ** 5493269ba804Sdrh ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) 5494269ba804Sdrh ** 5495269ba804Sdrh ** The transformation only works if all of the following are true: 5496269ba804Sdrh ** 5497269ba804Sdrh ** * The subquery is a UNION ALL of two or more terms 5498269ba804Sdrh ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries 5499269ba804Sdrh ** * The outer query is a simple count(*) 5500269ba804Sdrh ** 5501269ba804Sdrh ** Return TRUE if the optimization is undertaken. 5502269ba804Sdrh */ 5503269ba804Sdrh static int countOfViewOptimization(Parse *pParse, Select *p){ 5504269ba804Sdrh Select *pSub, *pPrior; 5505269ba804Sdrh Expr *pExpr; 5506269ba804Sdrh Expr *pCount; 5507269ba804Sdrh sqlite3 *db; 55083d240d21Sdrh if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ 5509269ba804Sdrh if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ 5510269ba804Sdrh pExpr = p->pEList->a[0].pExpr; 5511269ba804Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ 55123d240d21Sdrh if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ 5513269ba804Sdrh if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ 55143d240d21Sdrh if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ 5515269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5516269ba804Sdrh if( pSub==0 ) return 0; /* The FROM is a subquery */ 55173d240d21Sdrh if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ 5518269ba804Sdrh do{ 5519269ba804Sdrh if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ 5520269ba804Sdrh if( pSub->pWhere ) return 0; /* No WHERE clause */ 5521269ba804Sdrh if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ 55223d240d21Sdrh pSub = pSub->pPrior; /* Repeat over compound */ 5523269ba804Sdrh }while( pSub ); 5524269ba804Sdrh 55253d240d21Sdrh /* If we reach this point then it is OK to perform the transformation */ 5526269ba804Sdrh 5527269ba804Sdrh db = pParse->db; 5528269ba804Sdrh pCount = pExpr; 5529269ba804Sdrh pExpr = 0; 5530269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5531269ba804Sdrh p->pSrc->a[0].pSelect = 0; 5532269ba804Sdrh sqlite3SrcListDelete(db, p->pSrc); 5533269ba804Sdrh p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); 5534269ba804Sdrh while( pSub ){ 5535269ba804Sdrh Expr *pTerm; 5536269ba804Sdrh pPrior = pSub->pPrior; 5537269ba804Sdrh pSub->pPrior = 0; 5538269ba804Sdrh pSub->pNext = 0; 5539269ba804Sdrh pSub->selFlags |= SF_Aggregate; 5540269ba804Sdrh pSub->selFlags &= ~SF_Compound; 5541269ba804Sdrh pSub->nSelectRow = 0; 5542269ba804Sdrh sqlite3ExprListDelete(db, pSub->pEList); 5543269ba804Sdrh pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; 5544269ba804Sdrh pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm); 5545269ba804Sdrh pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0); 5546269ba804Sdrh sqlite3PExprAddSelect(pParse, pTerm, pSub); 5547269ba804Sdrh if( pExpr==0 ){ 5548269ba804Sdrh pExpr = pTerm; 5549269ba804Sdrh }else{ 5550269ba804Sdrh pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); 5551269ba804Sdrh } 5552269ba804Sdrh pSub = pPrior; 5553269ba804Sdrh } 5554269ba804Sdrh p->pEList->a[0].pExpr = pExpr; 5555269ba804Sdrh p->selFlags &= ~SF_Aggregate; 5556269ba804Sdrh 5557269ba804Sdrh #if SELECTTRACE_ENABLED 5558269ba804Sdrh if( sqlite3SelectTrace & 0x400 ){ 5559269ba804Sdrh SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); 5560269ba804Sdrh sqlite3TreeViewSelect(0, p, 0); 5561269ba804Sdrh } 5562269ba804Sdrh #endif 5563269ba804Sdrh return 1; 5564269ba804Sdrh } 5565269ba804Sdrh #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ 5566269ba804Sdrh 5567e08e8d6bSdrh /* 55687d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 55699bb61fe7Sdrh ** 5570340309fdSdrh ** The results are returned according to the SelectDest structure. 5571340309fdSdrh ** See comments in sqliteInt.h for further information. 5572e78e8284Sdrh ** 55739bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 55749bb61fe7Sdrh ** encountered, then an appropriate error message is left in 55759bb61fe7Sdrh ** pParse->zErrMsg. 55769bb61fe7Sdrh ** 55779bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 55789bb61fe7Sdrh ** calling function needs to do that. 55799bb61fe7Sdrh */ 55804adee20fSdanielk1977 int sqlite3Select( 5581cce7d176Sdrh Parse *pParse, /* The parser context */ 55829bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 55837d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 5584cce7d176Sdrh ){ 558513449892Sdrh int i, j; /* Loop counters */ 558613449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 558713449892Sdrh Vdbe *v; /* The virtual machine under construction */ 5588b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 5589c29cbb0bSmistachkin ExprList *pEList = 0; /* List of columns to extract. */ 5590ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 55919bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 55922282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 55932282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 55941d83f052Sdrh int rc = 1; /* Value to return from this function */ 5595e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 5596079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 559713449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 5598ec7429aeSdrh int iEnd; /* Address of the end of the query */ 559917435752Sdrh sqlite3 *db; /* The database connection */ 560047d9f839Sdrh ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ 560147d9f839Sdrh u8 minMaxFlag; /* Flag for min/max queries */ 56029bb61fe7Sdrh 560317435752Sdrh db = pParse->db; 5604e2ca99c9Sdrh v = sqlite3GetVdbe(pParse); 560517435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 56066f7adc8aSdrh return 1; 56076f7adc8aSdrh } 56084adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 560913449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 5610e2ca99c9Sdrh #if SELECTTRACE_ENABLED 5611e2ca99c9Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain)); 5612c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 5613c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 5614c90713d3Sdrh } 5615eb9b884cSdrh #endif 5616daffd0e5Sdrh 56178e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 56188e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 56199afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 56209afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 56216c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 56229ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 56239afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 56248e1ee88cSdrh pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || 56258e1ee88cSdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); 5626ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 5627ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 5628ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 5629ccfcbceaSdrh p->pOrderBy = 0; 56307d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 56319a99334dSdrh } 56327d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 5633956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 56349a99334dSdrh goto select_end; 56359a99334dSdrh } 5636adc57f68Sdrh assert( p->pEList!=0 ); 563717645f5eSdrh #if SELECTTRACE_ENABLED 5638e2243d26Sdrh if( sqlite3SelectTrace & 0x104 ){ 5639e2243d26Sdrh SELECTTRACE(0x104,pParse,p, ("after name resolution:\n")); 564017645f5eSdrh sqlite3TreeViewSelect(0, p, 0); 564117645f5eSdrh } 564217645f5eSdrh #endif 5643cce7d176Sdrh 5644f35f2f92Sdrh if( pDest->eDest==SRT_Output ){ 5645f35f2f92Sdrh generateColumnNames(pParse, p); 5646f35f2f92Sdrh } 5647f35f2f92Sdrh 564867a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 564967a9b8edSdan if( sqlite3WindowRewrite(pParse, p) ){ 565086fb6e17Sdan goto select_end; 565186fb6e17Sdan } 5652dfa552f4Sdan #if SELECTTRACE_ENABLED 5653dfa552f4Sdan if( sqlite3SelectTrace & 0x108 ){ 5654dfa552f4Sdan SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n")); 5655dfa552f4Sdan sqlite3TreeViewSelect(0, p, 0); 5656dfa552f4Sdan } 5657dfa552f4Sdan #endif 565867a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 565986fb6e17Sdan pTabList = p->pSrc; 56607392569fSdan isAgg = (p->selFlags & SF_Aggregate)!=0; 5661f02cdd37Sdan memset(&sSort, 0, sizeof(sSort)); 5662f02cdd37Sdan sSort.pOrderBy = p->pOrderBy; 566386fb6e17Sdan 56642589787cSdrh /* Try to various optimizations (flattening subqueries, and strength 56652589787cSdrh ** reduction of join operators) in the FROM clause up into the main query 5666d820cb1bSdrh */ 566751522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5668f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 566913449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 5670daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 56712679f14fSdrh Table *pTab = pItem->pTab; 56722589787cSdrh 56732589787cSdrh /* Convert LEFT JOIN into JOIN if there are terms of the right table 56742589787cSdrh ** of the LEFT JOIN used in the WHERE clause. 56752589787cSdrh */ 56762589787cSdrh if( (pItem->fg.jointype & JT_LEFT)!=0 56772589787cSdrh && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) 56782589787cSdrh && OptimizationEnabled(db, SQLITE_SimplifyJoin) 56792589787cSdrh ){ 56802589787cSdrh SELECTTRACE(0x100,pParse,p, 56812589787cSdrh ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); 5682efce69deSdrh pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); 56832589787cSdrh unsetJoinExpr(p->pWhere, pItem->iCursor); 56842589787cSdrh } 56852589787cSdrh 56862589787cSdrh /* No futher action if this term of the FROM clause is no a subquery */ 56874490c40bSdrh if( pSub==0 ) continue; 56882679f14fSdrh 56892679f14fSdrh /* Catch mismatch in the declared columns of a view and the number of 56902679f14fSdrh ** columns in the SELECT on the RHS */ 56912679f14fSdrh if( pTab->nCol!=pSub->pEList->nExpr ){ 56922679f14fSdrh sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", 56932679f14fSdrh pTab->nCol, pTab->zName, pSub->pEList->nExpr); 56942679f14fSdrh goto select_end; 56952679f14fSdrh } 56962679f14fSdrh 569725c221ebSdrh /* Do not try to flatten an aggregate subquery. 569825c221ebSdrh ** 569925c221ebSdrh ** Flattening an aggregate subquery is only possible if the outer query 570025c221ebSdrh ** is not a join. But if the outer query is not a join, then the subquery 570125c221ebSdrh ** will be implemented as a co-routine and there is no advantage to 570225c221ebSdrh ** flattening in that case. 570325c221ebSdrh */ 570425c221ebSdrh if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; 570525c221ebSdrh assert( pSub->pGroupBy==0 ); 570625c221ebSdrh 5707fca23557Sdrh /* If the outer query contains a "complex" result set (that is, 5708fca23557Sdrh ** if the result set of the outer query uses functions or subqueries) 5709fca23557Sdrh ** and if the subquery contains an ORDER BY clause and if 5710648fe49fSdrh ** it will be implemented as a co-routine, then do not flatten. This 5711648fe49fSdrh ** restriction allows SQL constructs like this: 5712648fe49fSdrh ** 5713648fe49fSdrh ** SELECT expensive_function(x) 5714648fe49fSdrh ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5715648fe49fSdrh ** 5716648fe49fSdrh ** The expensive_function() is only computed on the 10 rows that 5717648fe49fSdrh ** are output, rather than every row of the table. 5718fca23557Sdrh ** 5719fca23557Sdrh ** The requirement that the outer query have a complex result set 5720fca23557Sdrh ** means that flattening does occur on simpler SQL constraints without 5721fca23557Sdrh ** the expensive_function() like: 5722fca23557Sdrh ** 5723fca23557Sdrh ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5724648fe49fSdrh */ 572525c221ebSdrh if( pSub->pOrderBy!=0 5726648fe49fSdrh && i==0 5727fca23557Sdrh && (p->selFlags & SF_ComplexResult)!=0 5728648fe49fSdrh && (pTabList->nSrc==1 5729648fe49fSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) 5730648fe49fSdrh ){ 5731648fe49fSdrh continue; 5732648fe49fSdrh } 5733648fe49fSdrh 573425c221ebSdrh if( flattenSubquery(pParse, p, i, isAgg) ){ 57354490c40bSdrh /* This subquery can be absorbed into its parent. */ 57364490c40bSdrh i = -1; 57374490c40bSdrh } 57384490c40bSdrh pTabList = p->pSrc; 57394490c40bSdrh if( db->mallocFailed ) goto select_end; 57404490c40bSdrh if( !IgnorableOrderby(pDest) ){ 57414490c40bSdrh sSort.pOrderBy = p->pOrderBy; 57424490c40bSdrh } 57434490c40bSdrh } 57444490c40bSdrh #endif 57454490c40bSdrh 57464490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 57474490c40bSdrh /* Handle compound SELECT statements using the separate multiSelect() 57484490c40bSdrh ** procedure. 57494490c40bSdrh */ 57504490c40bSdrh if( p->pPrior ){ 57514490c40bSdrh rc = multiSelect(pParse, p, pDest); 57524490c40bSdrh #if SELECTTRACE_ENABLED 5753f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end compound-select processing\n")); 5754e2ca99c9Sdrh if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 5755f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 5756f20609d1Sdrh } 57574490c40bSdrh #endif 5758c631ded5Sdrh if( p->pNext==0 ) ExplainQueryPlanPop(pParse); 57594490c40bSdrh return rc; 57604490c40bSdrh } 57614490c40bSdrh #endif 57624490c40bSdrh 57637810ab64Sdrh /* Do the WHERE-clause constant propagation optimization if this is 57647810ab64Sdrh ** a join. No need to speed time on this operation for non-join queries 57657810ab64Sdrh ** as the equivalent optimization will be handled by query planner in 57667810ab64Sdrh ** sqlite3WhereBegin(). 57677810ab64Sdrh */ 57687810ab64Sdrh if( pTabList->nSrc>1 57697810ab64Sdrh && OptimizationEnabled(db, SQLITE_PropagateConst) 577024e1116eSdrh && propagateConstants(pParse, p) 577124e1116eSdrh ){ 577224e1116eSdrh #if SELECTTRACE_ENABLED 577324e1116eSdrh if( sqlite3SelectTrace & 0x100 ){ 577424e1116eSdrh SELECTTRACE(0x100,pParse,p,("After constant propagation:\n")); 577524e1116eSdrh sqlite3TreeViewSelect(0, p, 0); 577624e1116eSdrh } 577724e1116eSdrh #endif 577824e1116eSdrh }else{ 57797810ab64Sdrh SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n")); 578024e1116eSdrh } 578124e1116eSdrh 5782701caf1eSdrh /* For each term in the FROM clause, do two things: 5783701caf1eSdrh ** (1) Authorized unreferenced tables 5784701caf1eSdrh ** (2) Generate code for all sub-queries 5785d820cb1bSdrh */ 57864490c40bSdrh for(i=0; i<pTabList->nSrc; i++){ 5787742f947bSdanielk1977 struct SrcList_item *pItem = &pTabList->a[i]; 5788c31c2eb8Sdrh SelectDest dest; 5789701caf1eSdrh Select *pSub; 5790824d21afSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5791824d21afSdrh const char *zSavedAuthContext; 5792824d21afSdrh #endif 5793701caf1eSdrh 57943d240d21Sdrh /* Issue SQLITE_READ authorizations with a fake column name for any 57953d240d21Sdrh ** tables that are referenced but from which no values are extracted. 57963d240d21Sdrh ** Examples of where these kinds of null SQLITE_READ authorizations 57973d240d21Sdrh ** would occur: 5798701caf1eSdrh ** 57992336c935Sdrh ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" 58002336c935Sdrh ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" 58012336c935Sdrh ** 58022336c935Sdrh ** The fake column name is an empty string. It is possible for a table to 58032336c935Sdrh ** have a column named by the empty string, in which case there is no way to 58042336c935Sdrh ** distinguish between an unreferenced table and an actual reference to the 58052336c935Sdrh ** "" column. The original design was for the fake column name to be a NULL, 58062336c935Sdrh ** which would be unambiguous. But legacy authorization callbacks might 58073d240d21Sdrh ** assume the column name is non-NULL and segfault. The use of an empty 58083d240d21Sdrh ** string for the fake column name seems safer. 5809701caf1eSdrh */ 5810701caf1eSdrh if( pItem->colUsed==0 ){ 58112336c935Sdrh sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); 5812701caf1eSdrh } 5813701caf1eSdrh 5814701caf1eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5815701caf1eSdrh /* Generate code for all sub-queries in the FROM clause 5816701caf1eSdrh */ 5817701caf1eSdrh pSub = pItem->pSelect; 58185b6a9ed4Sdrh if( pSub==0 ) continue; 581921172c4cSdrh 582021172c4cSdrh /* Sometimes the code for a subquery will be generated more than 582121172c4cSdrh ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, 582221172c4cSdrh ** for example. In that case, do not regenerate the code to manifest 582321172c4cSdrh ** a view or the co-routine to implement a view. The first instance 582421172c4cSdrh ** is sufficient, though the subroutine to manifest the view does need 582521172c4cSdrh ** to be invoked again. */ 5826ccb9eb78Sdan if( pItem->addrFillSub ){ 58278a48b9c0Sdrh if( pItem->fg.viaCoroutine==0 ){ 58287555581fSdrh /* The subroutine that manifests the view might be a one-time routine, 58297555581fSdrh ** or it might need to be rerun on each iteration because it 58307555581fSdrh ** encodes a correlated subquery. */ 58317555581fSdrh testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once ); 58325b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 583321172c4cSdrh } 58345b6a9ed4Sdrh continue; 58355b6a9ed4Sdrh } 5836daf79acbSdanielk1977 5837fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 5838f7b5496eSdrh ** tree referred to by this, the parent select. The child select 5839fc976065Sdanielk1977 ** may contain expression trees of at most 5840fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 5841fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 5842fc976065Sdanielk1977 ** an exact limit. 5843fc976065Sdanielk1977 */ 5844fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 5845daf79acbSdanielk1977 5846adc57f68Sdrh /* Make copies of constant WHERE-clause terms in the outer query down 5847adc57f68Sdrh ** inside the subquery. This can help the subquery to run more efficiently. 5848adc57f68Sdrh */ 58497fbb101cSdrh if( OptimizationEnabled(db, SQLITE_PushDown) 58506a9b9527Sdrh && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, 58516a9b9527Sdrh (pItem->fg.jointype & JT_OUTER)!=0) 585269b72d5aSdrh ){ 585369b72d5aSdrh #if SELECTTRACE_ENABLED 585469b72d5aSdrh if( sqlite3SelectTrace & 0x100 ){ 5855d2a4401cSdrh SELECTTRACE(0x100,pParse,p, 5856d2a4401cSdrh ("After WHERE-clause push-down into subquery %d:\n", pSub->selId)); 585769b72d5aSdrh sqlite3TreeViewSelect(0, p, 0); 5858daf79acbSdanielk1977 } 585969b72d5aSdrh #endif 58602d277bb5Sdrh }else{ 58612d277bb5Sdrh SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); 586269b72d5aSdrh } 5863adc57f68Sdrh 5864824d21afSdrh zSavedAuthContext = pParse->zAuthContext; 5865824d21afSdrh pParse->zAuthContext = pItem->zName; 5866824d21afSdrh 5867adc57f68Sdrh /* Generate code to implement the subquery 58680ff47e9eSdrh ** 586925c221ebSdrh ** The subquery is implemented as a co-routine if the subquery is 587025c221ebSdrh ** guaranteed to be the outer loop (so that it does not need to be 587125c221ebSdrh ** computed more than once) 58720ff47e9eSdrh ** 58730ff47e9eSdrh ** TODO: Are there other reasons beside (1) to use a co-routine 58740ff47e9eSdrh ** implementation? 5875adc57f68Sdrh */ 58760ff47e9eSdrh if( i==0 58770ff47e9eSdrh && (pTabList->nSrc==1 58780ff47e9eSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ 5879a5759677Sdrh ){ 588021172c4cSdrh /* Implement a co-routine that will return a single row of the result 588121172c4cSdrh ** set on each invocation. 588221172c4cSdrh */ 5883725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 5884824d21afSdrh 588521172c4cSdrh pItem->regReturn = ++pParse->nMem; 5886725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 5887725de29aSdrh VdbeComment((v, "%s", pItem->pTab->zName)); 588821172c4cSdrh pItem->addrFillSub = addrTop; 588921172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 5890fef37760Sdrh ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId)); 589121172c4cSdrh sqlite3Select(pParse, pSub, &dest); 5892c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 58938a48b9c0Sdrh pItem->fg.viaCoroutine = 1; 58945f612295Sdrh pItem->regResult = dest.iSdst; 58952fade2f7Sdrh sqlite3VdbeEndCoroutine(v, pItem->regReturn); 589621172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 589721172c4cSdrh sqlite3ClearTempRegCache(pParse); 5898daf79acbSdanielk1977 }else{ 58995b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 59005b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 59015b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 59025b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 59035b6a9ed4Sdrh */ 59047157e8eaSdrh int topAddr; 590548f2d3b1Sdrh int onceAddr = 0; 59067157e8eaSdrh int retAddr; 5907e08e8d6bSdrh struct SrcList_item *pPrior; 5908e08e8d6bSdrh 59095b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 59105b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 59117157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 59127157e8eaSdrh pItem->addrFillSub = topAddr+1; 59138a48b9c0Sdrh if( pItem->fg.isCorrelated==0 ){ 5914ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 59155b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 59165b6a9ed4Sdrh ** once. */ 5917511f9e8dSdrh onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 5918725de29aSdrh VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 5919725de29aSdrh }else{ 5920725de29aSdrh VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 59215b6a9ed4Sdrh } 5922e08e8d6bSdrh pPrior = isSelfJoinView(pTabList, pItem); 5923e08e8d6bSdrh if( pPrior ){ 5924e08e8d6bSdrh sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); 5925eafc6dfeSdrh assert( pPrior->pSelect!=0 ); 5926eafc6dfeSdrh pSub->nSelectRow = pPrior->pSelect->nSelectRow; 5927e08e8d6bSdrh }else{ 59281013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 5929fef37760Sdrh ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId)); 59307d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 5931e08e8d6bSdrh } 5932c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 593348f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 59347157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 59357157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 59367157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 5937cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 5938daf79acbSdanielk1977 } 5939adc57f68Sdrh if( db->mallocFailed ) goto select_end; 5940fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 5941824d21afSdrh pParse->zAuthContext = zSavedAuthContext; 5942daf79acbSdanielk1977 #endif 5943701caf1eSdrh } 5944adc57f68Sdrh 594538b4149cSdrh /* Various elements of the SELECT copied into local variables for 594638b4149cSdrh ** convenience */ 5947adc57f68Sdrh pEList = p->pEList; 5948daf79acbSdanielk1977 pWhere = p->pWhere; 5949832508b7Sdrh pGroupBy = p->pGroupBy; 5950832508b7Sdrh pHaving = p->pHaving; 5951e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 5952832508b7Sdrh 5953bc8edba1Sdrh #if SELECTTRACE_ENABLED 5954bc8edba1Sdrh if( sqlite3SelectTrace & 0x400 ){ 5955bc8edba1Sdrh SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); 5956bc8edba1Sdrh sqlite3TreeViewSelect(0, p, 0); 5957f23329a2Sdanielk1977 } 5958f23329a2Sdanielk1977 #endif 5959f23329a2Sdanielk1977 5960269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5961269ba804Sdrh if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) 5962269ba804Sdrh && countOfViewOptimization(pParse, p) 5963269ba804Sdrh ){ 5964269ba804Sdrh if( db->mallocFailed ) goto select_end; 5965269ba804Sdrh pEList = p->pEList; 5966269ba804Sdrh pTabList = p->pSrc; 5967269ba804Sdrh } 5968269ba804Sdrh #endif 5969269ba804Sdrh 597050118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 597150118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 597250118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 597350118cdfSdan ** 597450118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 597550118cdfSdan ** 597650118cdfSdan ** is transformed to: 597750118cdfSdan ** 5978dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 597950118cdfSdan ** 598050118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 598150118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 598250118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 598350118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 598450118cdfSdan */ 598550118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 5986adc57f68Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 598750118cdfSdan ){ 598850118cdfSdan p->selFlags &= ~SF_Distinct; 5989adc57f68Sdrh pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); 5990e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 5991e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 5992e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 5993e8e4af76Sdrh assert( sDistinct.isTnct ); 59947512cb47Sdrh 59957512cb47Sdrh #if SELECTTRACE_ENABLED 59967512cb47Sdrh if( sqlite3SelectTrace & 0x400 ){ 59977512cb47Sdrh SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); 59987512cb47Sdrh sqlite3TreeViewSelect(0, p, 0); 59997512cb47Sdrh } 60007512cb47Sdrh #endif 600150118cdfSdan } 600250118cdfSdan 6003adc57f68Sdrh /* If there is an ORDER BY clause, then create an ephemeral index to 6004adc57f68Sdrh ** do the sorting. But this sorting ephemeral index might end up 6005adc57f68Sdrh ** being unused if the data can be extracted in pre-sorted order. 6006adc57f68Sdrh ** If that is the case, then the OP_OpenEphemeral instruction will be 6007adc57f68Sdrh ** changed to an OP_Noop once we figure out that the sorting index is 6008adc57f68Sdrh ** not needed. The sSort.addrSortIndex variable is used to facilitate 6009adc57f68Sdrh ** that change. 60107cedc8d4Sdanielk1977 */ 6011079a3072Sdrh if( sSort.pOrderBy ){ 60120342b1f5Sdrh KeyInfo *pKeyInfo; 6013f9eae18bSdan pKeyInfo = sqlite3KeyInfoFromExprList( 6014f9eae18bSdan pParse, sSort.pOrderBy, 0, pEList->nExpr); 6015079a3072Sdrh sSort.iECursor = pParse->nTab++; 6016079a3072Sdrh sSort.addrSortIndex = 601766a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 6018f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 6019f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 6020f45f2326Sdrh ); 60219d2985c7Sdrh }else{ 6022079a3072Sdrh sSort.addrSortIndex = -1; 60237cedc8d4Sdanielk1977 } 60247cedc8d4Sdanielk1977 60252d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 60262d0794e3Sdrh */ 60276c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 60282b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 60292d0794e3Sdrh } 60302d0794e3Sdrh 6031f42bacc2Sdrh /* Set the limiter. 6032f42bacc2Sdrh */ 6033f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 603469b9383eSdan if( (p->selFlags & SF_FixedLimit)==0 ){ 6035c3489bbfSdrh p->nSelectRow = 320; /* 4 billion rows */ 603669b9383eSdan } 6037f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 6038079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 60390ff287fbSdrh sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); 6040079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 6041c6aff30cSdrh } 6042f42bacc2Sdrh 6043adc57f68Sdrh /* Open an ephemeral index to use for the distinct set. 6044cce7d176Sdrh */ 60452ce22453Sdan if( p->selFlags & SF_Distinct ){ 6046e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 6047e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 6048e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 6049f9eae18bSdan (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0), 60502ec2fb22Sdrh P4_KEYINFO); 6051d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 6052e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 6053832508b7Sdrh }else{ 6054e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 6055efb7251dSdrh } 6056832508b7Sdrh 605713449892Sdrh if( !isAgg && pGroupBy==0 ){ 6058e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 605967a9b8edSdan u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0) 606067a9b8edSdan | (p->selFlags & SF_FixedLimit); 606167a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 606267a9b8edSdan Window *pWin = p->pWin; /* Master window object (or NULL) */ 6063f9eae18bSdan if( pWin ){ 6064f9eae18bSdan sqlite3WindowCodeInit(pParse, pWin); 606586fb6e17Sdan } 606667a9b8edSdan #endif 606767a9b8edSdan assert( WHERE_USE_LIMIT==SF_FixedLimit ); 606867a9b8edSdan 606986fb6e17Sdan 607038cc40c2Sdan /* Begin the database scan. */ 6071cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 6072079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 6073c3489bbfSdrh p->pEList, wctrlFlags, p->nSelectRow); 60741d83f052Sdrh if( pWInfo==0 ) goto select_end; 60756f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 60766f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 60776f32848dSdrh } 60786457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 60796f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 60806f32848dSdrh } 6081079a3072Sdrh if( sSort.pOrderBy ){ 6082079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 6083a536df4eSdrh sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo); 6084079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 6085079a3072Sdrh sSort.pOrderBy = 0; 6086079a3072Sdrh } 6087079a3072Sdrh } 6088cce7d176Sdrh 6089b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 6090b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 60919d2985c7Sdrh ** into an OP_Noop. 60929d2985c7Sdrh */ 6093079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 6094079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 60959d2985c7Sdrh } 60969d2985c7Sdrh 60972def2f7eSdrh assert( p->pEList==pEList ); 609867a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 6099f9eae18bSdan if( pWin ){ 6100f9eae18bSdan int addrGosub = sqlite3VdbeMakeLabel(v); 6101dacf1de9Sdan int iCont = sqlite3VdbeMakeLabel(v); 6102efa3a3c9Sdan int iBreak = sqlite3VdbeMakeLabel(v); 6103f9eae18bSdan int regGosub = ++pParse->nMem; 610486fb6e17Sdan 6105dacf1de9Sdan sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub); 610686fb6e17Sdan 6107efa3a3c9Sdan sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 6108f9eae18bSdan sqlite3VdbeResolveLabel(v, addrGosub); 6109b0225bc5Sdrh VdbeNoopComment((v, "inner-loop subroutine")); 6110efa3a3c9Sdan selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak); 6111dacf1de9Sdan sqlite3VdbeResolveLabel(v, iCont); 611286fb6e17Sdan sqlite3VdbeAddOp1(v, OP_Return, regGosub); 61130b3b0dd1Sdrh VdbeComment((v, "end inner-loop subroutine")); 6114efa3a3c9Sdan sqlite3VdbeResolveLabel(v, iBreak); 611567a9b8edSdan }else 611667a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 611767a9b8edSdan { 611886fb6e17Sdan /* Use the standard inner loop. */ 61192def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, 61206f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 61216f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 61222282792aSdrh 6123cce7d176Sdrh /* End the database scan loop. 6124cce7d176Sdrh */ 61254adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 612686fb6e17Sdan } 612713449892Sdrh }else{ 6128e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 6129e8e4af76Sdrh ** or both */ 613013449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 613113449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 613213449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 613313449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 613413449892Sdrh ** one row of the input to the aggregator has been 613513449892Sdrh ** processed */ 613613449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 613713449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 6138d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 61391c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 61401c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 6141374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 6142d176611bSdrh 6143d176611bSdrh /* Remove any and all aliases between the result set and the 6144d176611bSdrh ** GROUP BY clause. 6145d176611bSdrh */ 6146d176611bSdrh if( pGroupBy ){ 6147dc5ea5c7Sdrh int k; /* Loop counter */ 6148d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 6149d176611bSdrh 6150dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 6151c2acc4e4Sdrh pItem->u.x.iAlias = 0; 6152d176611bSdrh } 6153dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 6154c2acc4e4Sdrh pItem->u.x.iAlias = 0; 6155d176611bSdrh } 6156c3489bbfSdrh assert( 66==sqlite3LogEst(100) ); 6157c3489bbfSdrh if( p->nSelectRow>66 ) p->nSelectRow = 66; 615895aa47b1Sdrh }else{ 6159c3489bbfSdrh assert( 0==sqlite3LogEst(1) ); 6160c3489bbfSdrh p->nSelectRow = 0; 6161d176611bSdrh } 6162cce7d176Sdrh 6163374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 6164374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 6165374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 6166adc57f68Sdrh ** in the correct order. It also may not - the GROUP BY might use a 6167374cd78cSdan ** database index that causes rows to be grouped together as required 6168374cd78cSdan ** but not actually sorted. Either way, record the fact that the 6169374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 6170374cd78cSdan ** variable. */ 6171374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 6172374cd78cSdan orderByGrp = 1; 6173374cd78cSdan } 617413449892Sdrh 6175d176611bSdrh /* Create a label to jump to when we want to abort the query */ 617613449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 617713449892Sdrh 617813449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 617913449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 618013449892Sdrh ** SELECT statement. 61812282792aSdrh */ 618213449892Sdrh memset(&sNC, 0, sizeof(sNC)); 618313449892Sdrh sNC.pParse = pParse; 618413449892Sdrh sNC.pSrcList = pTabList; 618525c3b8caSdrh sNC.uNC.pAggInfo = &sAggInfo; 618625c3b8caSdrh VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) 61877e61d18eSdrh sAggInfo.mnReg = pParse->nMem+1; 6188dd23c6bfSdan sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 61899d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 6190d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 6191079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 6192d2b3e23bSdrh if( pHaving ){ 6193ab31a845Sdan if( pGroupBy ){ 6194ab31a845Sdan assert( pWhere==p->pWhere ); 6195cd0abc24Sdrh assert( pHaving==p->pHaving ); 6196cd0abc24Sdrh assert( pGroupBy==p->pGroupBy ); 6197cd0abc24Sdrh havingToWhere(pParse, p); 6198ab31a845Sdan pWhere = p->pWhere; 6199ab31a845Sdan } 6200d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 620113449892Sdrh } 620213449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 620347d9f839Sdrh if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){ 620447d9f839Sdrh minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy); 620547d9f839Sdrh }else{ 620647d9f839Sdrh minMaxFlag = WHERE_ORDERBY_NORMAL; 620747d9f839Sdrh } 620813449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 62096ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 62103a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 62116ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 62123a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 621313449892Sdrh } 62147e61d18eSdrh sAggInfo.mxReg = pParse->nMem; 621517435752Sdrh if( db->mallocFailed ) goto select_end; 62167ea11066Sdrh #if SELECTTRACE_ENABLED 62177ea11066Sdrh if( sqlite3SelectTrace & 0x400 ){ 62187ea11066Sdrh int ii; 62197ea11066Sdrh SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n")); 62207ea11066Sdrh sqlite3TreeViewSelect(0, p, 0); 62217ea11066Sdrh for(ii=0; ii<sAggInfo.nColumn; ii++){ 62227ea11066Sdrh sqlite3DebugPrintf("agg-column[%d] iMem=%d\n", 62237ea11066Sdrh ii, sAggInfo.aCol[ii].iMem); 62247ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0); 62257ea11066Sdrh } 62267ea11066Sdrh for(ii=0; ii<sAggInfo.nFunc; ii++){ 62277ea11066Sdrh sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", 62287ea11066Sdrh ii, sAggInfo.aFunc[ii].iMem); 62297ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0); 62307ea11066Sdrh } 62317ea11066Sdrh } 62327ea11066Sdrh #endif 62337ea11066Sdrh 623413449892Sdrh 623513449892Sdrh /* Processing for aggregates with GROUP BY is very different and 62363c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 623713449892Sdrh */ 623813449892Sdrh if( pGroupBy ){ 623913449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 6240728e0f91Sdrh int addr1; /* A-vs-B comparision jump */ 6241d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 6242d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 6243d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 6244d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 6245d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 6246d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 6247d176611bSdrh int regReset; /* Return address register for reset subroutine */ 624813449892Sdrh 624913449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 625013449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 62511c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 625213449892Sdrh ** will be converted into a Noop. 625313449892Sdrh */ 625413449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 6255f9eae18bSdan pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn); 62561c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 6257cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 62582ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 625913449892Sdrh 626013449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 626113449892Sdrh */ 62620a07c107Sdrh iUseFlag = ++pParse->nMem; 62630a07c107Sdrh iAbortFlag = ++pParse->nMem; 6264d176611bSdrh regOutputRow = ++pParse->nMem; 6265d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 6266d176611bSdrh regReset = ++pParse->nMem; 6267d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 62680a07c107Sdrh iAMem = pParse->nMem + 1; 626913449892Sdrh pParse->nMem += pGroupBy->nExpr; 62700a07c107Sdrh iBMem = pParse->nMem + 1; 627113449892Sdrh pParse->nMem += pGroupBy->nExpr; 62724c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 6273d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 6274b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 6275e313382eSdrh 627613449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 627713449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 627813449892Sdrh ** it might be a single loop that uses an index to extract information 627913449892Sdrh ** in the right order to begin with. 628013449892Sdrh */ 62812eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 6282cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 628393ec45d5Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 6284374cd78cSdan WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 6285374cd78cSdan ); 62865360ad34Sdrh if( pWInfo==0 ) goto select_end; 6287ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 628813449892Sdrh /* The optimizer is able to deliver rows in group by order so 6289b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 629013449892Sdrh ** cancelled later because we still need to use the pKeyInfo 629113449892Sdrh */ 629213449892Sdrh groupBySort = 0; 629313449892Sdrh }else{ 629413449892Sdrh /* Rows are coming out in undetermined order. We have to push 629513449892Sdrh ** each row into a sorting index, terminate the first loop, 629613449892Sdrh ** then loop over the sorting index in order to get the output 629713449892Sdrh ** in sorted order 629813449892Sdrh */ 6299892d3179Sdrh int regBase; 6300892d3179Sdrh int regRecord; 6301892d3179Sdrh int nCol; 6302892d3179Sdrh int nGroupBy; 6303892d3179Sdrh 63042ce22453Sdan explainTempTable(pParse, 6305e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 6306e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 63072ce22453Sdan 630813449892Sdrh groupBySort = 1; 6309892d3179Sdrh nGroupBy = pGroupBy->nExpr; 6310dd23c6bfSdan nCol = nGroupBy; 6311dd23c6bfSdan j = nGroupBy; 631213449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6313892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 6314892d3179Sdrh nCol++; 631513449892Sdrh j++; 631613449892Sdrh } 6317892d3179Sdrh } 6318892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 6319ceea3321Sdrh sqlite3ExprCacheClear(pParse); 63205579d59fSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); 6321dd23c6bfSdan j = nGroupBy; 6322892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6323892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 6324892d3179Sdrh if( pCol->iSorterColumn>=j ){ 6325e55cbd72Sdrh int r1 = j + regBase; 6326ce78bc6eSdrh sqlite3ExprCodeGetColumnToReg(pParse, 6327ce78bc6eSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1); 63286a012f04Sdrh j++; 6329892d3179Sdrh } 6330892d3179Sdrh } 6331892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 63321db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 63331c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 6334892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 6335892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 633613449892Sdrh sqlite3WhereEnd(pWInfo); 63375134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 63381c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 63391c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 63401c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 6341688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 634213449892Sdrh sAggInfo.useSortingIdx = 1; 6343ceea3321Sdrh sqlite3ExprCacheClear(pParse); 6344374cd78cSdan 6345374cd78cSdan } 6346374cd78cSdan 6347374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 6348374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 6349374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 6350374cd78cSdan ** 6351374cd78cSdan ** This is an optimization - the correct answer should result regardless. 6352374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 6353374cd78cSdan ** disable this optimization for testing purposes. */ 6354374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 6355374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 6356374cd78cSdan ){ 6357374cd78cSdan sSort.pOrderBy = 0; 6358374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 635913449892Sdrh } 636013449892Sdrh 636113449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 636213449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 636313449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 636413449892Sdrh ** from the previous row currently stored in a0, a1, a2... 636513449892Sdrh */ 636613449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 6367ceea3321Sdrh sqlite3ExprCacheClear(pParse); 63681c9d835dSdrh if( groupBySort ){ 636938b4149cSdrh sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, 637038b4149cSdrh sortOut, sortPTab); 63711c9d835dSdrh } 637213449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 637313449892Sdrh if( groupBySort ){ 63741c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 637513449892Sdrh }else{ 637613449892Sdrh sAggInfo.directMode = 1; 63772dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 637813449892Sdrh } 637913449892Sdrh } 638016ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 63812ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 6382728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 6383728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); 638413449892Sdrh 638513449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 6386e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 638713449892Sdrh ** block. If there were no changes, this block is skipped. 638813449892Sdrh ** 638913449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 639013449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 639113449892Sdrh ** and resets the aggregate accumulator registers in preparation 639213449892Sdrh ** for the next GROUP BY batch. 639313449892Sdrh */ 6394b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 63952eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6396d4e70ebdSdrh VdbeComment((v, "output one row")); 6397688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 6398d4e70ebdSdrh VdbeComment((v, "check abort flag")); 63992eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 6400d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 640113449892Sdrh 640213449892Sdrh /* Update the aggregate accumulators based on the content of 640313449892Sdrh ** the current row 640413449892Sdrh */ 6405728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 6406280c894bSdan updateAccumulator(pParse, iUseFlag, &sAggInfo); 64074c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 6408d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 640913449892Sdrh 641013449892Sdrh /* End of the loop 641113449892Sdrh */ 641213449892Sdrh if( groupBySort ){ 64131c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 6414688852abSdrh VdbeCoverage(v); 641513449892Sdrh }else{ 641613449892Sdrh sqlite3WhereEnd(pWInfo); 641748f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 641813449892Sdrh } 641913449892Sdrh 642013449892Sdrh /* Output the final row of result 642113449892Sdrh */ 64222eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6423d4e70ebdSdrh VdbeComment((v, "output final row")); 642413449892Sdrh 6425d176611bSdrh /* Jump over the subroutines 6426d176611bSdrh */ 6427076e85f5Sdrh sqlite3VdbeGoto(v, addrEnd); 6428d176611bSdrh 6429d176611bSdrh /* Generate a subroutine that outputs a single row of the result 6430d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 6431d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 6432d176611bSdrh ** the processing calls for the query to abort, this subroutine 6433d176611bSdrh ** increments the iAbortFlag memory location before returning in 6434d176611bSdrh ** order to signal the caller to abort. 6435d176611bSdrh */ 6436d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 6437d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 6438d176611bSdrh VdbeComment((v, "set abort flag")); 6439d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6440d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 6441d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 6442d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 644338b4149cSdrh VdbeCoverage(v); 6444d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 6445d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6446d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 6447d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 64482def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, 6449e8e4af76Sdrh &sDistinct, pDest, 6450d176611bSdrh addrOutputRow+1, addrSetAbort); 6451d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6452d176611bSdrh VdbeComment((v, "end groupby result generator")); 6453d176611bSdrh 6454d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 6455d176611bSdrh */ 6456d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 6457d176611bSdrh resetAccumulator(pParse, &sAggInfo); 6458280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 6459280c894bSdan VdbeComment((v, "indicate accumulator empty")); 6460d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 6461d176611bSdrh 646243152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 646313449892Sdrh else { 6464a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 6465a5533162Sdanielk1977 Table *pTab; 6466a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 6467a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 6468a5533162Sdanielk1977 ** the SQL statement is of the form: 6469a5533162Sdanielk1977 ** 6470a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 6471a5533162Sdanielk1977 ** 6472a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 6473a5533162Sdanielk1977 ** 6474a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 6475a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 6476a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 6477a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 6478a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 6479a5533162Sdanielk1977 */ 6480a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 6481a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 6482a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 6483a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 6484a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 6485a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 6486a9d1ccb9Sdanielk1977 6487a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 6488a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 6489a5533162Sdanielk1977 6490d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 6491a5533162Sdanielk1977 ** 64923e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 64933e9548b3Sdrh ** 6494abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 64955f33f375Sdrh ** 6496a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 6497a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 6498a5533162Sdanielk1977 */ 64995c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 6500a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 6501d9e3cad2Sdrh if( pIdx->bUnordered==0 6502e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 6503d3037a41Sdrh && pIdx->pPartIdxWhere==0 6504e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 6505d9e3cad2Sdrh ){ 6506a5533162Sdanielk1977 pBest = pIdx; 6507a5533162Sdanielk1977 } 6508a5533162Sdanielk1977 } 6509d9e3cad2Sdrh if( pBest ){ 6510a5533162Sdanielk1977 iRoot = pBest->tnum; 65112ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 6512a5533162Sdanielk1977 } 6513a5533162Sdanielk1977 6514a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 6515261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); 6516a5533162Sdanielk1977 if( pKeyInfo ){ 65172ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 6518a5533162Sdanielk1977 } 6519a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 6520a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 6521ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 6522a5533162Sdanielk1977 }else 6523a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 6524a5533162Sdanielk1977 { 6525280c894bSdan int regAcc = 0; /* "populate accumulators" flag */ 6526280c894bSdan 6527280c894bSdan /* If there are accumulator registers but no min() or max() functions, 6528280c894bSdan ** allocate register regAcc. Register regAcc will contain 0 the first 6529280c894bSdan ** time the inner loop runs, and 1 thereafter. The code generated 6530280c894bSdan ** by updateAccumulator() only updates the accumulator registers if 6531280c894bSdan ** regAcc contains 0. */ 6532280c894bSdan if( sAggInfo.nAccumulator ){ 6533280c894bSdan for(i=0; i<sAggInfo.nFunc; i++){ 6534280c894bSdan if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break; 6535280c894bSdan } 6536280c894bSdan if( i==sAggInfo.nFunc ){ 6537280c894bSdan regAcc = ++pParse->nMem; 6538280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc); 6539280c894bSdan } 6540280c894bSdan } 6541280c894bSdan 654213449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 654313449892Sdrh ** processing is much simpler since there is only a single row 654413449892Sdrh ** of output. 654513449892Sdrh */ 654647d9f839Sdrh assert( p->pGroupBy==0 ); 654713449892Sdrh resetAccumulator(pParse, &sAggInfo); 654847d9f839Sdrh 654947d9f839Sdrh /* If this query is a candidate for the min/max optimization, then 655047d9f839Sdrh ** minMaxFlag will have been previously set to either 655147d9f839Sdrh ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will 655247d9f839Sdrh ** be an appropriate ORDER BY expression for the optimization. 655347d9f839Sdrh */ 655447d9f839Sdrh assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); 655547d9f839Sdrh assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); 655647d9f839Sdrh 6557cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 655847d9f839Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, 655947d9f839Sdrh 0, minMaxFlag, 0); 6560dba0137eSdanielk1977 if( pWInfo==0 ){ 6561dba0137eSdanielk1977 goto select_end; 6562dba0137eSdanielk1977 } 6563280c894bSdan updateAccumulator(pParse, regAcc, &sAggInfo); 6564280c894bSdan if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc); 6565ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 6566076e85f5Sdrh sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); 6567a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 656847d9f839Sdrh (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max"))); 6569a9d1ccb9Sdanielk1977 } 657013449892Sdrh sqlite3WhereEnd(pWInfo); 657113449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 65727a895a80Sdanielk1977 } 65737a895a80Sdanielk1977 6574079a3072Sdrh sSort.pOrderBy = 0; 657535573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 65762def2f7eSdrh selectInnerLoop(pParse, p, -1, 0, 0, 6577a9671a22Sdrh pDest, addrEnd, addrEnd); 657813449892Sdrh } 657913449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 658013449892Sdrh 658113449892Sdrh } /* endif aggregate query */ 65822282792aSdrh 6583e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 65842ce22453Sdan explainTempTable(pParse, "DISTINCT"); 65852ce22453Sdan } 65862ce22453Sdan 6587cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 6588cce7d176Sdrh ** and send them to the callback one by one. 6589cce7d176Sdrh */ 6590079a3072Sdrh if( sSort.pOrderBy ){ 659138b4149cSdrh explainTempTable(pParse, 659238b4149cSdrh sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 659324e25d32Sdan assert( p->pEList==pEList ); 6594079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 6595cce7d176Sdrh } 65966a535340Sdrh 6597ec7429aeSdrh /* Jump here to skip this query 6598ec7429aeSdrh */ 6599ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 6600ec7429aeSdrh 66015b1c07e7Sdan /* The SELECT has been coded. If there is an error in the Parse structure, 66025b1c07e7Sdan ** set the return code to 1. Otherwise 0. */ 66035b1c07e7Sdan rc = (pParse->nErr>0); 66041d83f052Sdrh 66051d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 66061d83f052Sdrh ** successful coding of the SELECT. 66071d83f052Sdrh */ 66081d83f052Sdrh select_end: 660947d9f839Sdrh sqlite3ExprListDelete(db, pMinMaxOrderBy); 6610633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 6611633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 6612eb9b884cSdrh #if SELECTTRACE_ENABLED 6613f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end processing\n")); 6614e2ca99c9Sdrh if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 6615f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 6616f20609d1Sdrh } 6617eb9b884cSdrh #endif 6618e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 66191d83f052Sdrh return rc; 6620cce7d176Sdrh } 6621