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)) \ 24b3b0d317Sdrh sqlite3DebugPrintf("%s/%d/%p: ",(S)->zSelName,(P)->iSelectId,(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 81079a3072Sdrh }; 82079a3072Sdrh #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ 83cce7d176Sdrh 84cce7d176Sdrh /* 85b87fbed5Sdrh ** Delete all the content of a Select structure. Deallocate the structure 86b87fbed5Sdrh ** itself only if bFree is true. 87eda639e1Sdrh */ 88b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){ 89b87fbed5Sdrh while( p ){ 90b87fbed5Sdrh Select *pPrior = p->pPrior; 91633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 92633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 93633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 94633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 95633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 96633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 97633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 988906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith); 99dbd6a7dcSdrh if( bFree ) sqlite3DbFreeNN(db, p); 100b87fbed5Sdrh p = pPrior; 101b87fbed5Sdrh bFree = 1; 102b87fbed5Sdrh } 103eda639e1Sdrh } 104eda639e1Sdrh 1051013c932Sdrh /* 1061013c932Sdrh ** Initialize a SelectDest structure. 1071013c932Sdrh */ 1081013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 109ea678832Sdrh pDest->eDest = (u8)eDest; 1102b596da8Sdrh pDest->iSDParm = iParm; 11171c57db0Sdan pDest->zAffSdst = 0; 1122b596da8Sdrh pDest->iSdst = 0; 1132b596da8Sdrh pDest->nSdst = 0; 1141013c932Sdrh } 1151013c932Sdrh 116eda639e1Sdrh 117eda639e1Sdrh /* 1189bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 1199bb61fe7Sdrh ** structure. 120cce7d176Sdrh */ 1214adee20fSdanielk1977 Select *sqlite3SelectNew( 12217435752Sdrh Parse *pParse, /* Parsing context */ 123daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 124ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 125daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 126daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 127daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 128daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 129c3489bbfSdrh u32 selFlags, /* Flag parameters, such as SF_Distinct */ 1308c0833fbSdrh Expr *pLimit /* LIMIT value. NULL means not used */ 1319bb61fe7Sdrh ){ 1329bb61fe7Sdrh Select *pNew; 133eda639e1Sdrh Select standin; 134ef90a6b8Sdrh pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); 135daffd0e5Sdrh if( pNew==0 ){ 136ef90a6b8Sdrh assert( pParse->db->mallocFailed ); 137eda639e1Sdrh pNew = &standin; 138eda639e1Sdrh } 139b733d037Sdrh if( pEList==0 ){ 1403d240d21Sdrh pEList = sqlite3ExprListAppend(pParse, 0, 1413d240d21Sdrh sqlite3Expr(pParse->db,TK_ASTERISK,0)); 142b733d037Sdrh } 1439bb61fe7Sdrh pNew->pEList = pEList; 144ca3862dcSdrh pNew->op = TK_SELECT; 145ca3862dcSdrh pNew->selFlags = selFlags; 146ca3862dcSdrh pNew->iLimit = 0; 147ca3862dcSdrh pNew->iOffset = 0; 1489ca33fa4Sdrh #if SELECTTRACE_ENABLED 1499ca33fa4Sdrh pNew->zSelName[0] = 0; 1509ca33fa4Sdrh #endif 151ca3862dcSdrh pNew->addrOpenEphm[0] = -1; 152ca3862dcSdrh pNew->addrOpenEphm[1] = -1; 153ca3862dcSdrh pNew->nSelectRow = 0; 154ef90a6b8Sdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); 1559bb61fe7Sdrh pNew->pSrc = pSrc; 1569bb61fe7Sdrh pNew->pWhere = pWhere; 1579bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 1589bb61fe7Sdrh pNew->pHaving = pHaving; 1599bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 160ca3862dcSdrh pNew->pPrior = 0; 161ca3862dcSdrh pNew->pNext = 0; 162a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 163ca3862dcSdrh pNew->pWith = 0; 164ef90a6b8Sdrh if( pParse->db->mallocFailed ) { 165ef90a6b8Sdrh clearSelect(pParse->db, pNew, pNew!=&standin); 166eda639e1Sdrh pNew = 0; 167a464c234Sdrh }else{ 168a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 169daffd0e5Sdrh } 170338ec3e1Sdrh assert( pNew!=&standin ); 1719bb61fe7Sdrh return pNew; 1729bb61fe7Sdrh } 1739bb61fe7Sdrh 174eb9b884cSdrh #if SELECTTRACE_ENABLED 175eb9b884cSdrh /* 176eb9b884cSdrh ** Set the name of a Select object 177eb9b884cSdrh */ 178eb9b884cSdrh void sqlite3SelectSetName(Select *p, const char *zName){ 179eb9b884cSdrh if( p && zName ){ 180eb9b884cSdrh sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); 181eb9b884cSdrh } 182eb9b884cSdrh } 183eb9b884cSdrh #endif 184eb9b884cSdrh 185eb9b884cSdrh 1869bb61fe7Sdrh /* 187eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 188eda639e1Sdrh */ 189633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 1908906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); 191eda639e1Sdrh } 192eda639e1Sdrh 193eda639e1Sdrh /* 194d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound. 195d227a291Sdrh */ 196d227a291Sdrh static Select *findRightmost(Select *p){ 197d227a291Sdrh while( p->pNext ) p = p->pNext; 198d227a291Sdrh return p; 1999bb61fe7Sdrh } 2009bb61fe7Sdrh 2019bb61fe7Sdrh /* 202f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the 20301f3f253Sdrh ** type of join. Return an integer constant that expresses that type 20401f3f253Sdrh ** in terms of the following bit values: 20501f3f253Sdrh ** 20601f3f253Sdrh ** JT_INNER 2073dec223cSdrh ** JT_CROSS 20801f3f253Sdrh ** JT_OUTER 20901f3f253Sdrh ** JT_NATURAL 21001f3f253Sdrh ** JT_LEFT 21101f3f253Sdrh ** JT_RIGHT 21201f3f253Sdrh ** 21301f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 21401f3f253Sdrh ** 21501f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 21601f3f253Sdrh ** a join type, but put an error in the pParse structure. 21701f3f253Sdrh */ 2184adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 21901f3f253Sdrh int jointype = 0; 22001f3f253Sdrh Token *apAll[3]; 22101f3f253Sdrh Token *p; 222373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 223373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 2245719628aSdrh static const struct { 225373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 226373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 227373cc2ddSdrh u8 code; /* Join type mask */ 228373cc2ddSdrh } aKeyword[] = { 229373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 230373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 231373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 232373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 233373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 234373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 235373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 23601f3f253Sdrh }; 23701f3f253Sdrh int i, j; 23801f3f253Sdrh apAll[0] = pA; 23901f3f253Sdrh apAll[1] = pB; 24001f3f253Sdrh apAll[2] = pC; 241195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 24201f3f253Sdrh p = apAll[i]; 243373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 244373cc2ddSdrh if( p->n==aKeyword[j].nChar 245373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 246373cc2ddSdrh jointype |= aKeyword[j].code; 24701f3f253Sdrh break; 24801f3f253Sdrh } 24901f3f253Sdrh } 250373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 251373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 25201f3f253Sdrh jointype |= JT_ERROR; 25301f3f253Sdrh break; 25401f3f253Sdrh } 25501f3f253Sdrh } 256ad2d8307Sdrh if( 257ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 258195e6967Sdrh (jointype & JT_ERROR)!=0 259ad2d8307Sdrh ){ 260a9671a22Sdrh const char *zSp = " "; 261a9671a22Sdrh assert( pB!=0 ); 262a9671a22Sdrh if( pC==0 ){ zSp++; } 263ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 264a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 26501f3f253Sdrh jointype = JT_INNER; 266373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 267373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 2684adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 269da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 270195e6967Sdrh jointype = JT_INNER; 27101f3f253Sdrh } 27201f3f253Sdrh return jointype; 27301f3f253Sdrh } 27401f3f253Sdrh 27501f3f253Sdrh /* 276ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 277ad2d8307Sdrh ** is not contained in the table. 278ad2d8307Sdrh */ 279ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 280ad2d8307Sdrh int i; 281ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 2824adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 283ad2d8307Sdrh } 284ad2d8307Sdrh return -1; 285ad2d8307Sdrh } 286ad2d8307Sdrh 287ad2d8307Sdrh /* 2882179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 2892179b434Sdrh ** table that has a column named zCol. 2902179b434Sdrh ** 2912179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 2922179b434Sdrh ** of the matching column and return TRUE. 2932179b434Sdrh ** 2942179b434Sdrh ** If not found, return FALSE. 2952179b434Sdrh */ 2962179b434Sdrh static int tableAndColumnIndex( 2972179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 2982179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 2992179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 3002179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 3012179b434Sdrh int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 3022179b434Sdrh ){ 3032179b434Sdrh int i; /* For looping over tables in pSrc */ 3042179b434Sdrh int iCol; /* Index of column matching zCol */ 3052179b434Sdrh 3062179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 3072179b434Sdrh for(i=0; i<N; i++){ 3082179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 3092179b434Sdrh if( iCol>=0 ){ 3102179b434Sdrh if( piTab ){ 3112179b434Sdrh *piTab = i; 3122179b434Sdrh *piCol = iCol; 3132179b434Sdrh } 3142179b434Sdrh return 1; 3152179b434Sdrh } 3162179b434Sdrh } 3172179b434Sdrh return 0; 3182179b434Sdrh } 3192179b434Sdrh 3202179b434Sdrh /* 321f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 322f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 323f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 324f7b0b0adSdan ** 325f7b0b0adSdan ** (tab1.col1 = tab2.col2) 326f7b0b0adSdan ** 327f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 328f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 329f7b0b0adSdan ** column iColRight of tab2. 330ad2d8307Sdrh */ 331ad2d8307Sdrh static void addWhereTerm( 33217435752Sdrh Parse *pParse, /* Parsing context */ 333f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 3342179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 335f7b0b0adSdan int iColLeft, /* Index of column in first table */ 3362179b434Sdrh int iRight, /* Index of second table in pSrc */ 337f7b0b0adSdan int iColRight, /* Index of column in second table */ 338f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 339f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 340ad2d8307Sdrh ){ 341f7b0b0adSdan sqlite3 *db = pParse->db; 342f7b0b0adSdan Expr *pE1; 343f7b0b0adSdan Expr *pE2; 344f7b0b0adSdan Expr *pEq; 345ad2d8307Sdrh 3462179b434Sdrh assert( iLeft<iRight ); 3472179b434Sdrh assert( pSrc->nSrc>iRight ); 3482179b434Sdrh assert( pSrc->a[iLeft].pTab ); 3492179b434Sdrh assert( pSrc->a[iRight].pTab ); 350f7b0b0adSdan 3512179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 3522179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 353f7b0b0adSdan 354abfd35eaSdrh pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); 355f7b0b0adSdan if( pEq && isOuterJoin ){ 356f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 357c5cd1249Sdrh assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); 358ebb6a65dSdrh ExprSetVVAProperty(pEq, EP_NoReduce); 359f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 360030530deSdrh } 361f7b0b0adSdan *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); 362ad2d8307Sdrh } 363ad2d8307Sdrh 364ad2d8307Sdrh /* 3651f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 36622d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 36722d6a53aSdrh ** expression. 3681cc093c2Sdrh ** 369e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 3701cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 3711f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 3721f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 3731f16230bSdrh ** WHERE clause during join processing but we need to remember that they 3741f16230bSdrh ** originated in the ON or USING clause. 37522d6a53aSdrh ** 37622d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 37722d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 37822d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 37922d6a53aSdrh ** for cases like this: 38022d6a53aSdrh ** 38122d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 38222d6a53aSdrh ** 38322d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 38422d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 38522d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 38622d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 38722d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 38822d6a53aSdrh ** the output, which is incorrect. 3891cc093c2Sdrh */ 39022d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 3911cc093c2Sdrh while( p ){ 3921f16230bSdrh ExprSetProperty(p, EP_FromJoin); 393c5cd1249Sdrh assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 394ebb6a65dSdrh ExprSetVVAProperty(p, EP_NoReduce); 395cf697396Sshane p->iRightJoinTable = (i16)iTable; 396606f2344Sdrh if( p->op==TK_FUNCTION && p->x.pList ){ 397606f2344Sdrh int i; 398606f2344Sdrh for(i=0; i<p->x.pList->nExpr; i++){ 399606f2344Sdrh setJoinExpr(p->x.pList->a[i].pExpr, iTable); 400606f2344Sdrh } 401606f2344Sdrh } 40222d6a53aSdrh setJoinExpr(p->pLeft, iTable); 4031cc093c2Sdrh p = p->pRight; 4041cc093c2Sdrh } 4051cc093c2Sdrh } 4061cc093c2Sdrh 4072589787cSdrh /* Undo the work of setJoinExpr(). In the expression tree p, convert every 4082589787cSdrh ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into 4092589787cSdrh ** an ordinary term that omits the EP_FromJoin mark. 4102589787cSdrh ** 4112589787cSdrh ** This happens when a LEFT JOIN is simplified into an ordinary JOIN. 4122589787cSdrh */ 4132589787cSdrh static void unsetJoinExpr(Expr *p, int iTable){ 4142589787cSdrh while( p ){ 4157fbb101cSdrh if( ExprHasProperty(p, EP_FromJoin) 4167fbb101cSdrh && (iTable<0 || p->iRightJoinTable==iTable) ){ 4172589787cSdrh ExprClearProperty(p, EP_FromJoin); 4182589787cSdrh } 4192589787cSdrh if( p->op==TK_FUNCTION && p->x.pList ){ 4202589787cSdrh int i; 4212589787cSdrh for(i=0; i<p->x.pList->nExpr; i++){ 4222589787cSdrh unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); 4232589787cSdrh } 4242589787cSdrh } 4252589787cSdrh unsetJoinExpr(p->pLeft, iTable); 4262589787cSdrh p = p->pRight; 4272589787cSdrh } 4282589787cSdrh } 4292589787cSdrh 4301cc093c2Sdrh /* 431ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 432ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 433ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 434ad2d8307Sdrh ** 43591bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 43691bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 43791bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 43891bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 43991bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 44091bb0eedSdrh ** also attached to the left entry. 44191bb0eedSdrh ** 442ad2d8307Sdrh ** This routine returns the number of errors encountered. 443ad2d8307Sdrh */ 444ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 44591bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 44691bb0eedSdrh int i, j; /* Loop counters */ 44791bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 44891bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 449ad2d8307Sdrh 45091bb0eedSdrh pSrc = p->pSrc; 45191bb0eedSdrh pLeft = &pSrc->a[0]; 45291bb0eedSdrh pRight = &pLeft[1]; 45391bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 45491bb0eedSdrh Table *pRightTab = pRight->pTab; 455ad27e761Sdrh int isOuter; 45691bb0eedSdrh 457ce2c482eSdrh if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; 4588a48b9c0Sdrh isOuter = (pRight->fg.jointype & JT_OUTER)!=0; 459ad2d8307Sdrh 460ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 461ad2d8307Sdrh ** every column that the two tables have in common. 462ad2d8307Sdrh */ 4638a48b9c0Sdrh if( pRight->fg.jointype & JT_NATURAL ){ 46461dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 4654adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 466ad2d8307Sdrh "an ON or USING clause", 0); 467ad2d8307Sdrh return 1; 468ad2d8307Sdrh } 4692179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4702179b434Sdrh char *zName; /* Name of column in the right table */ 4712179b434Sdrh int iLeft; /* Matching left table */ 4722179b434Sdrh int iLeftCol; /* Matching column in the left table */ 4732179b434Sdrh 4742179b434Sdrh zName = pRightTab->aCol[j].zName; 4752179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 4762179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 4772179b434Sdrh isOuter, &p->pWhere); 478ad2d8307Sdrh } 479ad2d8307Sdrh } 480ad2d8307Sdrh } 481ad2d8307Sdrh 482ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 483ad2d8307Sdrh */ 48461dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 4854adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 486da93d238Sdrh "clauses in the same join"); 487ad2d8307Sdrh return 1; 488ad2d8307Sdrh } 489ad2d8307Sdrh 490ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 49191bb0eedSdrh ** an AND operator. 492ad2d8307Sdrh */ 49361dfc31dSdrh if( pRight->pOn ){ 494ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 49517435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 49661dfc31dSdrh pRight->pOn = 0; 497ad2d8307Sdrh } 498ad2d8307Sdrh 499ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 500ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 501ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 502ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 503ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 504ad2d8307Sdrh ** not contained in both tables to be joined. 505ad2d8307Sdrh */ 50661dfc31dSdrh if( pRight->pUsing ){ 50761dfc31dSdrh IdList *pList = pRight->pUsing; 508ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 5092179b434Sdrh char *zName; /* Name of the term in the USING clause */ 5102179b434Sdrh int iLeft; /* Table on the left with matching column name */ 5112179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 5122179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 5132179b434Sdrh 5142179b434Sdrh zName = pList->a[j].zName; 5152179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 5162179b434Sdrh if( iRightCol<0 5172179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 5182179b434Sdrh ){ 5194adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 52091bb0eedSdrh "not present in both tables", zName); 521ad2d8307Sdrh return 1; 522ad2d8307Sdrh } 5232179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 5242179b434Sdrh isOuter, &p->pWhere); 525ad2d8307Sdrh } 526ad2d8307Sdrh } 527ad2d8307Sdrh } 528ad2d8307Sdrh return 0; 529ad2d8307Sdrh } 530ad2d8307Sdrh 531079a3072Sdrh /* Forward reference */ 532079a3072Sdrh static KeyInfo *keyInfoFromExprList( 533079a3072Sdrh Parse *pParse, /* Parsing context */ 534079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 535079a3072Sdrh int iStart, /* Begin with this column of pList */ 536079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 537079a3072Sdrh ); 538079a3072Sdrh 539ad2d8307Sdrh /* 540f45f2326Sdrh ** Generate code that will push the record in registers regData 541f45f2326Sdrh ** through regData+nData-1 onto the sorter. 542c926afbcSdrh */ 543d59ba6ceSdrh static void pushOntoSorter( 544d59ba6ceSdrh Parse *pParse, /* Parser context */ 545079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 546b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 547f45f2326Sdrh int regData, /* First register holding data to be sorted */ 5485579d59fSdrh int regOrigData, /* First register holding data before packing */ 549fd0a2f97Sdrh int nData, /* Number of elements in the data array */ 550fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 551d59ba6ceSdrh ){ 552f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 55378d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 554f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 55578d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 556fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 557fb0d6e56Sdrh int regRecord = ++pParse->nMem; /* Assembled sorter record */ 55878d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 559f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 560a04a8be2Sdrh int iLimit; /* LIMIT counter */ 561f45f2326Sdrh 56278d58432Sdan assert( bSeq==0 || bSeq==1 ); 5639af90b72Sdan assert( nData==1 || regData==regOrigData || regOrigData==0 ); 564fd0a2f97Sdrh if( nPrefixReg ){ 56578d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 56678d58432Sdan regBase = regData - nExpr - bSeq; 567fd0a2f97Sdrh }else{ 568fb0d6e56Sdrh regBase = pParse->nMem + 1; 569fb0d6e56Sdrh pParse->nMem += nBase; 570fd0a2f97Sdrh } 571a04a8be2Sdrh assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); 572a04a8be2Sdrh iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; 573a04a8be2Sdrh pSort->labelDone = sqlite3VdbeMakeLabel(v); 5745579d59fSdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, 5759af90b72Sdan SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); 57678d58432Sdan if( bSeq ){ 577079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 578fd0a2f97Sdrh } 579257c13faSdan if( nPrefixReg==0 && nData>0 ){ 580236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 58178d58432Sdan } 582f45f2326Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); 583079a3072Sdrh if( nOBSat>0 ){ 584079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 585079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 586079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 587079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 588079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 589dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 590079a3072Sdrh 59126d7e7c6Sdrh regPrevKey = pParse->nMem+1; 59226d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 59378d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 59478d58432Sdan if( bSeq ){ 59578d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 59678d58432Sdan }else{ 59778d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 59878d58432Sdan } 59978d58432Sdan VdbeCoverage(v); 60026d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 601079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 60259b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 603fb0d6e56Sdrh pOp->p2 = nKey + nData; 604dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 605a485ad19Sdrh memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */ 606dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 607a485ad19Sdrh testcase( pKI->nAllField > pKI->nKeyField+2 ); 608fe201effSdrh pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 609a485ad19Sdrh pKI->nAllField-pKI->nKeyField-1); 610079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 611079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 612079a3072Sdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(v); 613079a3072Sdrh pSort->regReturn = ++pParse->nMem; 614079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 61565ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 616a04a8be2Sdrh if( iLimit ){ 617a04a8be2Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); 618a04a8be2Sdrh VdbeCoverage(v); 619a04a8be2Sdrh } 620079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 621236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 622079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 623079a3072Sdrh } 624079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 625c6aff30cSdrh op = OP_SorterInsert; 626c6aff30cSdrh }else{ 627c6aff30cSdrh op = OP_IdxInsert; 628c6aff30cSdrh } 6294a8b013eSdrh sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, 6304a8b013eSdrh regBase+nOBSat, nBase-nOBSat); 631a04a8be2Sdrh if( iLimit ){ 63216897072Sdrh int addr; 633a536df4eSdrh int r1 = 0; 634a536df4eSdrh /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit 635a536df4eSdrh ** register is initialized with value of LIMIT+OFFSET.) After the sorter 636a536df4eSdrh ** fills up, delete the least entry in the sorter after each insert. 637a536df4eSdrh ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */ 638f99dd359Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v); 639079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); 640a536df4eSdrh if( pSort->bOrderedInnerLoop ){ 641a536df4eSdrh r1 = ++pParse->nMem; 642a536df4eSdrh sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1); 643a536df4eSdrh VdbeComment((v, "seq")); 644a536df4eSdrh } 645079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); 646a536df4eSdrh if( pSort->bOrderedInnerLoop ){ 647a536df4eSdrh /* If the inner loop is driven by an index such that values from 648a536df4eSdrh ** the same iteration of the inner loop are in sorted order, then 649a536df4eSdrh ** immediately jump to the next iteration of an inner loop if the 650a536df4eSdrh ** entry from the current iteration does not fit into the top 651a536df4eSdrh ** LIMIT+OFFSET entries of the sorter. */ 652a536df4eSdrh int iBrk = sqlite3VdbeCurrentAddr(v) + 2; 653a536df4eSdrh sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1); 6546326d9f6Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 655a536df4eSdrh VdbeCoverage(v); 656a536df4eSdrh } 65716897072Sdrh sqlite3VdbeJumpHere(v, addr); 658d59ba6ceSdrh } 659c926afbcSdrh } 660c926afbcSdrh 661c926afbcSdrh /* 662ec7429aeSdrh ** Add code to implement the OFFSET 663ea48eb2eSdrh */ 664ec7429aeSdrh static void codeOffset( 665bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 666aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 667b7654111Sdrh int iContinue /* Jump here to skip the current record */ 668ea48eb2eSdrh ){ 669a22a75e5Sdrh if( iOffset>0 ){ 6708b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); 6718b0cf38aSdrh VdbeComment((v, "OFFSET")); 672ea48eb2eSdrh } 673ea48eb2eSdrh } 674ea48eb2eSdrh 675ea48eb2eSdrh /* 67698757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 67798757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 678a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 679a2a49dc9Sdrh ** if the current N values are new. 680a2a49dc9Sdrh ** 681a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 682a2a49dc9Sdrh ** stack if the top N elements are not distinct. 683a2a49dc9Sdrh */ 684a2a49dc9Sdrh static void codeDistinct( 6852dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 686a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 687a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 688477df4b3Sdrh int N, /* Number of elements */ 689a2a49dc9Sdrh int iMem /* First element */ 690a2a49dc9Sdrh ){ 6912dcef11bSdrh Vdbe *v; 6922dcef11bSdrh int r1; 6932dcef11bSdrh 6942dcef11bSdrh v = pParse->pVdbe; 6952dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 696688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); 6971db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 6989b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); 699a67b5cb6Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 7002dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 701a2a49dc9Sdrh } 702a2a49dc9Sdrh 70324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 70424e25d32Sdan /* 70524e25d32Sdan ** This function is called as part of inner-loop generation for a SELECT 70624e25d32Sdan ** statement with an ORDER BY that is not optimized by an index. It 70724e25d32Sdan ** determines the expressions, if any, that the sorter-reference 70824e25d32Sdan ** optimization should be used for. The sorter-reference optimization 70924e25d32Sdan ** is used for SELECT queries like: 71024e25d32Sdan ** 71124e25d32Sdan ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 71224e25d32Sdan ** 71324e25d32Sdan ** If the optimization is used for expression "bigblob", then instead of 71424e25d32Sdan ** storing values read from that column in the sorter records, the PK of 71524e25d32Sdan ** the row from table t1 is stored instead. Then, as records are extracted from 71624e25d32Sdan ** the sorter to return to the user, the required value of bigblob is 71724e25d32Sdan ** retrieved directly from table t1. If the values are very large, this 71824e25d32Sdan ** can be more efficient than storing them directly in the sorter records. 71924e25d32Sdan ** 72024e25d32Sdan ** The ExprList_item.bSorterRef flag is set for each expression in pEList 72124e25d32Sdan ** for which the sorter-reference optimization should be enabled. 72224e25d32Sdan ** Additionally, the pSort->aDefer[] array is populated with entries 72324e25d32Sdan ** for all cursors required to evaluate all selected expressions. Finally. 72424e25d32Sdan ** output variable (*ppExtra) is set to an expression list containing 72524e25d32Sdan ** expressions for all extra PK values that should be stored in the 72624e25d32Sdan ** sorter records. 72724e25d32Sdan */ 72824e25d32Sdan static void selectExprDefer( 72924e25d32Sdan Parse *pParse, /* Leave any error here */ 73024e25d32Sdan SortCtx *pSort, /* Sorter context */ 73124e25d32Sdan ExprList *pEList, /* Expressions destined for sorter */ 73224e25d32Sdan ExprList **ppExtra /* Expressions to append to sorter record */ 73324e25d32Sdan ){ 73424e25d32Sdan int i; 73524e25d32Sdan int nDefer = 0; 73624e25d32Sdan ExprList *pExtra = 0; 73724e25d32Sdan for(i=0; i<pEList->nExpr; i++){ 73824e25d32Sdan struct ExprList_item *pItem = &pEList->a[i]; 73924e25d32Sdan if( pItem->u.x.iOrderByCol==0 ){ 74024e25d32Sdan Expr *pExpr = pItem->pExpr; 74124e25d32Sdan Table *pTab = pExpr->pTab; 7422e3a5a81Sdan if( pExpr->op==TK_COLUMN && pTab && !IsVirtual(pTab) 7432e3a5a81Sdan && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF) 7442e3a5a81Sdan #if 0 7452e3a5a81Sdan && pTab->pSchema && pTab->pSelect==0 && !IsVirtual(pTab) 7462e3a5a81Sdan #endif 74724e25d32Sdan ){ 74824e25d32Sdan int j; 74924e25d32Sdan for(j=0; j<nDefer; j++){ 75024e25d32Sdan if( pSort->aDefer[j].iCsr==pExpr->iTable ) break; 75124e25d32Sdan } 75224e25d32Sdan if( j==nDefer ){ 75324e25d32Sdan if( nDefer==ArraySize(pSort->aDefer) ){ 75424e25d32Sdan continue; 75524e25d32Sdan }else{ 75624e25d32Sdan int nKey = 1; 75724e25d32Sdan int k; 75824e25d32Sdan Index *pPk = 0; 75924e25d32Sdan if( !HasRowid(pTab) ){ 76024e25d32Sdan pPk = sqlite3PrimaryKeyIndex(pTab); 76124e25d32Sdan nKey = pPk->nKeyCol; 76224e25d32Sdan } 76324e25d32Sdan for(k=0; k<nKey; k++){ 76424e25d32Sdan Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0); 76524e25d32Sdan if( pNew ){ 76624e25d32Sdan pNew->iTable = pExpr->iTable; 76724e25d32Sdan pNew->pTab = pExpr->pTab; 76824e25d32Sdan pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; 76924e25d32Sdan pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew); 77024e25d32Sdan } 77124e25d32Sdan } 77224e25d32Sdan pSort->aDefer[nDefer].pTab = pExpr->pTab; 77324e25d32Sdan pSort->aDefer[nDefer].iCsr = pExpr->iTable; 77424e25d32Sdan pSort->aDefer[nDefer].nKey = nKey; 77524e25d32Sdan nDefer++; 77624e25d32Sdan } 77724e25d32Sdan } 77824e25d32Sdan pItem->bSorterRef = 1; 77924e25d32Sdan } 78024e25d32Sdan } 78124e25d32Sdan } 78224e25d32Sdan pSort->nDefer = (u8)nDefer; 78324e25d32Sdan *ppExtra = pExtra; 78424e25d32Sdan } 78524e25d32Sdan #endif 78624e25d32Sdan 787c99130fdSdrh /* 7882282792aSdrh ** This routine generates the code for the inside of the inner loop 7892282792aSdrh ** of a SELECT. 79082c3d636Sdrh ** 7912def2f7eSdrh ** If srcTab is negative, then the p->pEList expressions 792340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 7932def2f7eSdrh ** zero or more, then data is pulled from srcTab and p->pEList is used only 794257c13faSdan ** to get the number of columns and the collation sequence for each column. 7952282792aSdrh */ 796d2b3e23bSdrh static void selectInnerLoop( 7972282792aSdrh Parse *pParse, /* The parser context */ 798df199a25Sdrh Select *p, /* The complete select statement being coded */ 7992def2f7eSdrh int srcTab, /* Pull data from this table if non-negative */ 800079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 801e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 8026c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 8032282792aSdrh int iContinue, /* Jump here to continue with next row */ 804a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 8052282792aSdrh ){ 8062282792aSdrh Vdbe *v = pParse->pVdbe; 807d847eaadSdrh int i; 808ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 809d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 8102b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 811d847eaadSdrh int nResultCol; /* Number of result columns */ 812fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 81338640e15Sdrh 8149af90b72Sdan /* Usually, regResult is the first cell in an array of memory cells 8159af90b72Sdan ** containing the current result row. In this case regOrig is set to the 8169af90b72Sdan ** same value. However, if the results are being sent to the sorter, the 8179af90b72Sdan ** values for any expressions that are also part of the sort-key are omitted 8189af90b72Sdan ** from this array. In this case regOrig is set to zero. */ 8199af90b72Sdan int regResult; /* Start of memory holding current results */ 8209af90b72Sdan int regOrig; /* Start of memory holding full result (or 0) */ 8219af90b72Sdan 8221c767f0dSdrh assert( v ); 8232def2f7eSdrh assert( p->pEList!=0 ); 824e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 825079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 826079a3072Sdrh if( pSort==0 && !hasDistinct ){ 827a22a75e5Sdrh assert( iContinue!=0 ); 828aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 829df199a25Sdrh } 830df199a25Sdrh 831967e8b73Sdrh /* Pull the requested columns. 8322282792aSdrh */ 8332def2f7eSdrh nResultCol = p->pEList->nExpr; 83405a86c5cSdrh 8352b596da8Sdrh if( pDest->iSdst==0 ){ 836fd0a2f97Sdrh if( pSort ){ 83778d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 83878d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 839fd0a2f97Sdrh pParse->nMem += nPrefixReg; 8401013c932Sdrh } 841a2a49dc9Sdrh pDest->iSdst = pParse->nMem+1; 842477df4b3Sdrh pParse->nMem += nResultCol; 84305a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 84405a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 84505a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 84605a86c5cSdrh ** there are columns in the table on the left. The error will be caught 84705a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 84805a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 84905a86c5cSdrh pParse->nMem += nResultCol; 8504c583128Sdrh } 85105a86c5cSdrh pDest->nSdst = nResultCol; 8529af90b72Sdan regOrig = regResult = pDest->iSdst; 853340309fdSdrh if( srcTab>=0 ){ 854340309fdSdrh for(i=0; i<nResultCol; i++){ 855d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 8562def2f7eSdrh VdbeComment((v, "%s", p->pEList->a[i].zName)); 85782c3d636Sdrh } 8589ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 85924e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 86024e25d32Sdan ExprList *pExtra = 0; 86124e25d32Sdan #endif 8629ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 8639ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 8649ed1dfa8Sdanielk1977 */ 865df553659Sdrh u8 ecelFlags; 866df553659Sdrh if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ 867df553659Sdrh ecelFlags = SQLITE_ECEL_DUP; 868df553659Sdrh }else{ 869df553659Sdrh ecelFlags = 0; 870a2a49dc9Sdrh } 871ac56ab7eSdan if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ 8722def2f7eSdrh /* For each expression in p->pEList that is a copy of an expression in 873257c13faSdan ** the ORDER BY clause (pSort->pOrderBy), set the associated 874257c13faSdan ** iOrderByCol value to one more than the index of the ORDER BY 875257c13faSdan ** expression within the sort-key that pushOntoSorter() will generate. 8762def2f7eSdrh ** This allows the p->pEList field to be omitted from the sorted record, 877257c13faSdan ** saving space and CPU cycles. */ 878257c13faSdan ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); 879257c13faSdan for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ 880257c13faSdan int j; 881257c13faSdan if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ 8822def2f7eSdrh p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; 883257c13faSdan } 884257c13faSdan } 88524e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 88624e25d32Sdan selectExprDefer(pParse, pSort, p->pEList, &pExtra); 8875a2e65edSdrh if( pExtra && pParse->db->mallocFailed==0 ){ 88824e25d32Sdan /* If there are any extra PK columns to add to the sorter records, 88924e25d32Sdan ** allocate extra memory cells and adjust the OpenEphemeral 89024e25d32Sdan ** instruction to account for the larger records. This is only 89124e25d32Sdan ** required if there are one or more WITHOUT ROWID tables with 89224e25d32Sdan ** composite primary keys in the SortCtx.aDefer[] array. */ 89324e25d32Sdan VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 89424e25d32Sdan pOp->p2 += (pExtra->nExpr - pSort->nDefer); 89524e25d32Sdan pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); 89624e25d32Sdan pParse->nMem += pExtra->nExpr; 89724e25d32Sdan } 89824e25d32Sdan #endif 8999af90b72Sdan regOrig = 0; 900257c13faSdan assert( eDest==SRT_Set || eDest==SRT_Mem 901257c13faSdan || eDest==SRT_Coroutine || eDest==SRT_Output ); 902257c13faSdan } 9033d240d21Sdrh nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult, 9043d240d21Sdrh 0,ecelFlags); 90524e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 90624e25d32Sdan if( pExtra ){ 90724e25d32Sdan nResultCol += sqlite3ExprCodeExprList( 90824e25d32Sdan pParse, pExtra, regResult + nResultCol, 0, 0 90924e25d32Sdan ); 91024e25d32Sdan sqlite3ExprListDelete(pParse->db, pExtra); 91124e25d32Sdan } 91224e25d32Sdan #endif 913a2a49dc9Sdrh } 9142282792aSdrh 915daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 916daffd0e5Sdrh ** and this row has been seen before, then do not make this row 917daffd0e5Sdrh ** part of the result. 9182282792aSdrh */ 919ea48eb2eSdrh if( hasDistinct ){ 920e8e4af76Sdrh switch( pDistinct->eTnctType ){ 921e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 922e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 923e8e4af76Sdrh int iJump; /* Jump destination */ 924e8e4af76Sdrh int regPrev; /* Previous row content */ 925e8e4af76Sdrh 926e8e4af76Sdrh /* Allocate space for the previous row */ 927e8e4af76Sdrh regPrev = pParse->nMem+1; 928340309fdSdrh pParse->nMem += nResultCol; 929e8e4af76Sdrh 930e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 931e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 932e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 933e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 934e8e4af76Sdrh ** row is all NULLs. 935e8e4af76Sdrh */ 936e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 937e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 938e8e4af76Sdrh pOp->opcode = OP_Null; 939e8e4af76Sdrh pOp->p1 = 1; 940e8e4af76Sdrh pOp->p2 = regPrev; 941e8e4af76Sdrh 942340309fdSdrh iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 943340309fdSdrh for(i=0; i<nResultCol; i++){ 9442def2f7eSdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr); 945340309fdSdrh if( i<nResultCol-1 ){ 946e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 947688852abSdrh VdbeCoverage(v); 948e8e4af76Sdrh }else{ 949e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 950688852abSdrh VdbeCoverage(v); 951e8e4af76Sdrh } 952e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 953e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 954e8e4af76Sdrh } 955fcf2a775Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 956340309fdSdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); 957e8e4af76Sdrh break; 958e8e4af76Sdrh } 959e8e4af76Sdrh 960e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 961e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 962e8e4af76Sdrh break; 963e8e4af76Sdrh } 964e8e4af76Sdrh 965e8e4af76Sdrh default: { 966e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 96738b4149cSdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, 96838b4149cSdrh regResult); 969e8e4af76Sdrh break; 970e8e4af76Sdrh } 971e8e4af76Sdrh } 972079a3072Sdrh if( pSort==0 ){ 973aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 974ea48eb2eSdrh } 9752282792aSdrh } 97682c3d636Sdrh 977c926afbcSdrh switch( eDest ){ 97882c3d636Sdrh /* In this mode, write each query result to the key of the temporary 97982c3d636Sdrh ** table iParm. 9802282792aSdrh */ 98113449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 982c926afbcSdrh case SRT_Union: { 9839cbf3425Sdrh int r1; 9849cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 985340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 9869b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 9879cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 988c926afbcSdrh break; 989c926afbcSdrh } 99082c3d636Sdrh 99182c3d636Sdrh /* Construct a record from the query result, but instead of 99282c3d636Sdrh ** saving that record, use it as a key to delete elements from 99382c3d636Sdrh ** the temporary table iParm. 99482c3d636Sdrh */ 995c926afbcSdrh case SRT_Except: { 996340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 997c926afbcSdrh break; 998c926afbcSdrh } 999781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 10005338a5f7Sdanielk1977 10015338a5f7Sdanielk1977 /* Store the result as data using a unique key. 10025338a5f7Sdanielk1977 */ 10038e1ee88cSdrh case SRT_Fifo: 10048e1ee88cSdrh case SRT_DistFifo: 10055338a5f7Sdanielk1977 case SRT_Table: 1006b9bb7c18Sdrh case SRT_EphemTab: { 1007fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 1008373cc2ddSdrh testcase( eDest==SRT_Table ); 1009373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 1010e2248cfdSdrh testcase( eDest==SRT_Fifo ); 1011e2248cfdSdrh testcase( eDest==SRT_DistFifo ); 1012fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 10138ce7184bSdan #ifndef SQLITE_OMIT_CTE 10148e1ee88cSdrh if( eDest==SRT_DistFifo ){ 10158e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 10168ce7184bSdan ** on an ephemeral index. If the current row is already present 10178ce7184bSdan ** in the index, do not write it to the output. If not, add the 10188ce7184bSdan ** current row to the index and proceed with writing it to the 10198ce7184bSdan ** output table as well. */ 10208ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 102138b4149cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); 102238b4149cSdrh VdbeCoverage(v); 10239b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); 1024079a3072Sdrh assert( pSort==0 ); 10258ce7184bSdan } 10268ce7184bSdan #endif 1027079a3072Sdrh if( pSort ){ 10285579d59fSdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg); 10295338a5f7Sdanielk1977 }else{ 1030b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 1031b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 1032b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 1033b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1034b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 10355338a5f7Sdanielk1977 } 1036fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 10375338a5f7Sdanielk1977 break; 10385338a5f7Sdanielk1977 } 10392282792aSdrh 104093758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 10412282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 10422282792aSdrh ** then there should be a single item on the stack. Write this 10432282792aSdrh ** item into the set table with bogus data. 10442282792aSdrh */ 1045c926afbcSdrh case SRT_Set: { 1046079a3072Sdrh if( pSort ){ 1047de941c60Sdrh /* At first glance you would think we could optimize out the 1048de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 1049de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 1050de941c60Sdrh ** case the order does matter */ 105151d82d1dSdan pushOntoSorter( 10529af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1053c926afbcSdrh }else{ 1054b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 105571c57db0Sdan assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); 105671c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 1057553168c7Sdan r1, pDest->zAffSdst, nResultCol); 105871c57db0Sdan sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 10599b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 1060b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 1061c926afbcSdrh } 1062c926afbcSdrh break; 1063c926afbcSdrh } 106482c3d636Sdrh 1065504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 1066ec7429aeSdrh */ 1067ec7429aeSdrh case SRT_Exists: { 10684c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 1069ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1070ec7429aeSdrh break; 1071ec7429aeSdrh } 1072ec7429aeSdrh 10732282792aSdrh /* If this is a scalar select that is part of an expression, then 1074870a0705Sdan ** store the results in the appropriate memory cell or array of 1075870a0705Sdan ** memory cells and break out of the scan loop. 10762282792aSdrh */ 1077c926afbcSdrh case SRT_Mem: { 1078079a3072Sdrh if( pSort ){ 1079257c13faSdan assert( nResultCol<=pDest->nSdst ); 1080870a0705Sdan pushOntoSorter( 10819af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1082c926afbcSdrh }else{ 1083257c13faSdan assert( nResultCol==pDest->nSdst ); 108453932ce8Sdrh assert( regResult==iParm ); 1085ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 1086c926afbcSdrh } 1087c926afbcSdrh break; 1088c926afbcSdrh } 108993758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 10902282792aSdrh 109181cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 109281cf13ecSdrh case SRT_Output: { /* Return the results */ 1093373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 1094373cc2ddSdrh testcase( eDest==SRT_Output ); 1095079a3072Sdrh if( pSort ){ 10969af90b72Sdan pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, 10975579d59fSdrh nPrefixReg); 1098e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 10992b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1100c182d163Sdrh }else{ 1101340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 1102340309fdSdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 1103ac82fcf5Sdrh } 1104142e30dfSdrh break; 1105142e30dfSdrh } 1106142e30dfSdrh 1107fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 1108fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 1109fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 1110fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 1111fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 1112fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 1113fe1c6bb9Sdrh */ 1114fe1c6bb9Sdrh case SRT_DistQueue: 1115fe1c6bb9Sdrh case SRT_Queue: { 1116fe1c6bb9Sdrh int nKey; 1117fe1c6bb9Sdrh int r1, r2, r3; 1118fe1c6bb9Sdrh int addrTest = 0; 1119fe1c6bb9Sdrh ExprList *pSO; 1120fe1c6bb9Sdrh pSO = pDest->pOrderBy; 1121fe1c6bb9Sdrh assert( pSO ); 1122fe1c6bb9Sdrh nKey = pSO->nExpr; 1123fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 1124fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 1125fe1c6bb9Sdrh r3 = r2+nKey+1; 1126fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 1127fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 1128fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 11297e4efaecSdrh ** added to the queue. */ 11307e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 11317e4efaecSdrh regResult, nResultCol); 1132688852abSdrh VdbeCoverage(v); 11337e4efaecSdrh } 11347e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 11357e4efaecSdrh if( eDest==SRT_DistQueue ){ 1136fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 1137cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1138fe1c6bb9Sdrh } 1139fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 1140fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 1141fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 1142fe1c6bb9Sdrh r2+i); 1143fe1c6bb9Sdrh } 1144fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 1145fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 11469b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); 1147fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 1148fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 1149fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 1150fe1c6bb9Sdrh break; 1151fe1c6bb9Sdrh } 1152fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 1153fe1c6bb9Sdrh 1154fe1c6bb9Sdrh 1155fe1c6bb9Sdrh 11566a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 1157d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 1158d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 1159d7489c39Sdrh ** user-defined functions that have side effects. We do not care 1160d7489c39Sdrh ** about the actual results of the select. 1161d7489c39Sdrh */ 1162c926afbcSdrh default: { 1163f46f905aSdrh assert( eDest==SRT_Discard ); 1164c926afbcSdrh break; 1165c926afbcSdrh } 116693758c8dSdanielk1977 #endif 1167c926afbcSdrh } 1168ec7429aeSdrh 11695e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 11705e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 11715e87be87Sdrh ** the output for us. 1172ec7429aeSdrh */ 1173079a3072Sdrh if( pSort==0 && p->iLimit ){ 117416897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 1175ec7429aeSdrh } 117682c3d636Sdrh } 117782c3d636Sdrh 117882c3d636Sdrh /* 1179ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 1180ad124329Sdrh ** X extra columns. 1181323df790Sdrh */ 1182ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 1183d4ab003dSdrh int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); 1184d8e4b132Sdrh KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); 1185323df790Sdrh if( p ){ 1186ad124329Sdrh p->aSortOrder = (u8*)&p->aColl[N+X]; 1187a485ad19Sdrh p->nKeyField = (u16)N; 1188a485ad19Sdrh p->nAllField = (u16)(N+X); 1189323df790Sdrh p->enc = ENC(db); 1190323df790Sdrh p->db = db; 11912ec2fb22Sdrh p->nRef = 1; 1192c263f7c4Sdrh memset(&p[1], 0, nExtra); 11932ec2fb22Sdrh }else{ 11944a642b60Sdrh sqlite3OomFault(db); 1195323df790Sdrh } 1196323df790Sdrh return p; 1197323df790Sdrh } 1198323df790Sdrh 1199323df790Sdrh /* 12002ec2fb22Sdrh ** Deallocate a KeyInfo object 12012ec2fb22Sdrh */ 12022ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 12032ec2fb22Sdrh if( p ){ 12042ec2fb22Sdrh assert( p->nRef>0 ); 12052ec2fb22Sdrh p->nRef--; 1206dbd6a7dcSdrh if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); 12072ec2fb22Sdrh } 12082ec2fb22Sdrh } 12092ec2fb22Sdrh 12102ec2fb22Sdrh /* 12112ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 12122ec2fb22Sdrh */ 12132ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 12142ec2fb22Sdrh if( p ){ 12152ec2fb22Sdrh assert( p->nRef>0 ); 12162ec2fb22Sdrh p->nRef++; 12172ec2fb22Sdrh } 12182ec2fb22Sdrh return p; 12192ec2fb22Sdrh } 12202ec2fb22Sdrh 12212ec2fb22Sdrh #ifdef SQLITE_DEBUG 12222ec2fb22Sdrh /* 12232ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 12242ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 12252ec2fb22Sdrh ** 12262ec2fb22Sdrh ** This routine is used only inside of assert() statements. 12272ec2fb22Sdrh */ 12282ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 12292ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 12302ec2fb22Sdrh 12312ec2fb22Sdrh /* 1232dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1233dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1234dece1a84Sdrh ** 12350342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 12360342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 12370342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 12380342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 12390342b1f5Sdrh ** index to implement a DISTINCT test. 12400342b1f5Sdrh ** 124160ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1242dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 12432ec2fb22Sdrh ** freed. 1244dece1a84Sdrh */ 1245079a3072Sdrh static KeyInfo *keyInfoFromExprList( 1246079a3072Sdrh Parse *pParse, /* Parsing context */ 1247079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1248079a3072Sdrh int iStart, /* Begin with this column of pList */ 1249079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1250079a3072Sdrh ){ 1251dece1a84Sdrh int nExpr; 1252dece1a84Sdrh KeyInfo *pInfo; 1253dece1a84Sdrh struct ExprList_item *pItem; 1254323df790Sdrh sqlite3 *db = pParse->db; 1255dece1a84Sdrh int i; 1256dece1a84Sdrh 1257dece1a84Sdrh nExpr = pList->nExpr; 12583f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1259dece1a84Sdrh if( pInfo ){ 12602ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 12616284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 126270efa84dSdrh pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr); 12636284db90Sdrh pInfo->aSortOrder[i-iStart] = pItem->sortOrder; 1264dece1a84Sdrh } 1265dece1a84Sdrh } 1266dece1a84Sdrh return pInfo; 1267dece1a84Sdrh } 1268dece1a84Sdrh 12697f61e92cSdan /* 12707f61e92cSdan ** Name of the connection operator, used for error messages. 12717f61e92cSdan */ 12727f61e92cSdan static const char *selectOpName(int id){ 12737f61e92cSdan char *z; 12747f61e92cSdan switch( id ){ 12757f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 12767f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 12777f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 12787f61e92cSdan default: z = "UNION"; break; 12797f61e92cSdan } 12807f61e92cSdan return z; 12817f61e92cSdan } 12827f61e92cSdan 12832ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 128417c0bc0cSdan /* 128517c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 128617c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 128717c0bc0cSdan ** where the caption is of the form: 128817c0bc0cSdan ** 128917c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 129017c0bc0cSdan ** 129117c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 129217c0bc0cSdan ** is determined by the zUsage argument. 129317c0bc0cSdan */ 12942ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 12952ce22453Sdan if( pParse->explain==2 ){ 12962ce22453Sdan Vdbe *v = pParse->pVdbe; 12972ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 12982ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 12992ce22453Sdan } 13002ce22453Sdan } 130117c0bc0cSdan 130217c0bc0cSdan /* 1303bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1304bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1305bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1306bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1307bb2b4418Sdan ** code with #ifndef directives. 1308bb2b4418Sdan */ 1309bb2b4418Sdan # define explainSetInteger(a, b) a = b 1310bb2b4418Sdan 1311bb2b4418Sdan #else 1312bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1313bb2b4418Sdan # define explainTempTable(y,z) 1314bb2b4418Sdan # define explainSetInteger(y,z) 1315bb2b4418Sdan #endif 1316bb2b4418Sdan 1317bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 1318bb2b4418Sdan /* 13197f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 13207f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 13217f61e92cSdan ** where the caption is of one of the two forms: 13227f61e92cSdan ** 13237f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 13247f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 13257f61e92cSdan ** 13267f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 13277f61e92cSdan ** function parameters, and op is the text representation of the parameter 13287f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 13297f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 13307f61e92cSdan ** false, or the second form if it is true. 13317f61e92cSdan */ 13327f61e92cSdan static void explainComposite( 13337f61e92cSdan Parse *pParse, /* Parse context */ 13347f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 13357f61e92cSdan int iSub1, /* Subquery id 1 */ 13367f61e92cSdan int iSub2, /* Subquery id 2 */ 13377f61e92cSdan int bUseTmp /* True if a temp table was used */ 13387f61e92cSdan ){ 13397f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 13407f61e92cSdan if( pParse->explain==2 ){ 13417f61e92cSdan Vdbe *v = pParse->pVdbe; 13427f61e92cSdan char *zMsg = sqlite3MPrintf( 134330969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 13447f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 13457f61e92cSdan ); 13467f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 13477f61e92cSdan } 13487f61e92cSdan } 13492ce22453Sdan #else 135017c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 13517f61e92cSdan # define explainComposite(v,w,x,y,z) 13522ce22453Sdan #endif 1353dece1a84Sdrh 1354dece1a84Sdrh /* 1355d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1356d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1357d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1358d8bc7086Sdrh ** routine generates the code needed to do that. 1359d8bc7086Sdrh */ 1360c926afbcSdrh static void generateSortTail( 1361cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1362c926afbcSdrh Select *p, /* The SELECT statement */ 1363079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1364c926afbcSdrh int nColumn, /* Number of columns of data */ 13656c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1366c926afbcSdrh ){ 1367ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1368a04a8be2Sdrh int addrBreak = pSort->labelDone; /* Jump here to exit loop */ 1369dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 137024e25d32Sdan int addr; /* Top of output loop. Jump for Next. */ 1371079a3072Sdrh int addrOnce = 0; 13720342b1f5Sdrh int iTab; 1373079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 13746c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 13752b596da8Sdrh int iParm = pDest->iSDParm; 13762d401ab8Sdrh int regRow; 13772d401ab8Sdrh int regRowid; 1378257c13faSdan int iCol; 137924e25d32Sdan int nKey; /* Number of key columns in sorter record */ 1380f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1381f45f2326Sdrh int i; 138278d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 138324e25d32Sdan int nRefKey = 0; 138470f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 13852d401ab8Sdrh 1386a04a8be2Sdrh assert( addrBreak<0 ); 1387079a3072Sdrh if( pSort->labelBkOut ){ 1388079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1389076e85f5Sdrh sqlite3VdbeGoto(v, addrBreak); 1390079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1391079a3072Sdrh } 139224e25d32Sdan 139324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 139424e25d32Sdan /* Open any cursors needed for sorter-reference expressions */ 139524e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 139624e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 139724e25d32Sdan int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 139824e25d32Sdan sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); 139924e25d32Sdan nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); 140024e25d32Sdan } 140124e25d32Sdan #endif 140224e25d32Sdan 1403079a3072Sdrh iTab = pSort->iECursor; 140471c57db0Sdan if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ 14053e9ca094Sdrh regRowid = 0; 1406f45f2326Sdrh regRow = pDest->iSdst; 1407ed24da4bSdrh }else{ 140851d82d1dSdan regRowid = sqlite3GetTempReg(pParse); 140951d82d1dSdan regRow = sqlite3GetTempRange(pParse, nColumn); 1410cdd536f0Sdrh } 1411079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1412079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1413c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1414f45f2326Sdrh iSortTab = pParse->nTab++; 141583553eefSdrh if( pSort->labelBkOut ){ 1416511f9e8dSdrh addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 141783553eefSdrh } 141824e25d32Sdan sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, 141924e25d32Sdan nKey+1+nColumn+nRefKey); 1420079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1421c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1422688852abSdrh VdbeCoverage(v); 1423aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 14246cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 142578d58432Sdan bSeq = 0; 1426c6aff30cSdrh }else{ 1427688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1428aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1429f45f2326Sdrh iSortTab = iTab; 143078d58432Sdan bSeq = 1; 1431f45f2326Sdrh } 1432d6189eafSdan for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){ 143324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 143424e25d32Sdan if( aOutEx[i].bSorterRef ) continue; 143524e25d32Sdan #endif 14369f895239Sdrh if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++; 14379f895239Sdrh } 143824e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 143924e25d32Sdan if( pSort->nDefer ){ 144024e25d32Sdan int iKey = iCol+1; 144124e25d32Sdan int regKey = sqlite3GetTempRange(pParse, nRefKey); 144224e25d32Sdan 144324e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 144424e25d32Sdan int iCsr = pSort->aDefer[i].iCsr; 144524e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 144624e25d32Sdan int nKey = pSort->aDefer[i].nKey; 144724e25d32Sdan 144824e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 144924e25d32Sdan if( HasRowid(pTab) ){ 145024e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); 145124e25d32Sdan sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, 145224e25d32Sdan sqlite3VdbeCurrentAddr(v)+1, regKey); 145324e25d32Sdan }else{ 145424e25d32Sdan int k; 145524e25d32Sdan int iJmp; 14567590d093Sdrh assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); 145724e25d32Sdan for(k=0; k<nKey; k++){ 145824e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k); 145924e25d32Sdan } 146024e25d32Sdan iJmp = sqlite3VdbeCurrentAddr(v); 146124e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey); 146224e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey); 146324e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 146424e25d32Sdan } 146524e25d32Sdan } 146624e25d32Sdan sqlite3ReleaseTempRange(pParse, regKey, nRefKey); 146724e25d32Sdan } 146824e25d32Sdan #endif 1469d6189eafSdan for(i=nColumn-1; i>=0; i--){ 147024e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 147124e25d32Sdan if( aOutEx[i].bSorterRef ){ 147224e25d32Sdan sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); 147324e25d32Sdan }else 147424e25d32Sdan #endif 147524e25d32Sdan { 1476257c13faSdan int iRead; 1477257c13faSdan if( aOutEx[i].u.x.iOrderByCol ){ 1478257c13faSdan iRead = aOutEx[i].u.x.iOrderByCol-1; 1479257c13faSdan }else{ 14809f895239Sdrh iRead = iCol--; 1481257c13faSdan } 1482257c13faSdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); 148370f624c3Sdrh VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan)); 1484c6aff30cSdrh } 148524e25d32Sdan } 1486c926afbcSdrh switch( eDest ){ 1487ac56ab7eSdan case SRT_Table: 1488b9bb7c18Sdrh case SRT_EphemTab: { 14892d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 14902d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 14912d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1492c926afbcSdrh break; 1493c926afbcSdrh } 149493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1495c926afbcSdrh case SRT_Set: { 149671c57db0Sdan assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); 149771c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, 1498553168c7Sdan pDest->zAffSdst, nColumn); 149971c57db0Sdan sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn); 15009b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); 1501c926afbcSdrh break; 1502c926afbcSdrh } 1503c926afbcSdrh case SRT_Mem: { 1504ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1505c926afbcSdrh break; 1506c926afbcSdrh } 150793758c8dSdanielk1977 #endif 1508373cc2ddSdrh default: { 1509373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 15101c767f0dSdrh testcase( eDest==SRT_Output ); 15111c767f0dSdrh testcase( eDest==SRT_Coroutine ); 15127d10d5a6Sdrh if( eDest==SRT_Output ){ 15132b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 15142b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); 1515a9671a22Sdrh }else{ 15162b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1517ce665cf6Sdrh } 1518ac82fcf5Sdrh break; 1519ac82fcf5Sdrh } 1520c926afbcSdrh } 1521f45f2326Sdrh if( regRowid ){ 152251d82d1dSdan if( eDest==SRT_Set ){ 152351d82d1dSdan sqlite3ReleaseTempRange(pParse, regRow, nColumn); 152451d82d1dSdan }else{ 15252d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 152651d82d1dSdan } 15272d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1528f45f2326Sdrh } 1529ec7429aeSdrh /* The bottom of the loop 1530ec7429aeSdrh */ 1531dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1532079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1533688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1534c6aff30cSdrh }else{ 1535688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1536c6aff30cSdrh } 1537079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1538dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1539d8bc7086Sdrh } 1540d8bc7086Sdrh 1541d8bc7086Sdrh /* 1542517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1543517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1544e78e8284Sdrh ** 15455f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 15465f3e5e74Sdrh ** result in *pEstWidth. 15475f3e5e74Sdrh ** 1548955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1549955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1550955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1551955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1552955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1553955de52cSdanielk1977 ** considered a column by this function. 1554e78e8284Sdrh ** 1555955de52cSdanielk1977 ** SELECT col FROM tbl; 1556955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1557955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1558955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1559955de52cSdanielk1977 ** 1560955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 15615f3e5e74Sdrh ** 15625f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 15635f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1564fcb78a49Sdrh */ 15655f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1566cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) 1567b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1568cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B) 1569b121dd14Sdrh #endif 15705f3e5e74Sdrh static const char *columnTypeImpl( 1571955de52cSdanielk1977 NameContext *pNC, 1572cafc2f7bSdrh #ifndef SQLITE_ENABLE_COLUMN_METADATA 1573cafc2f7bSdrh Expr *pExpr 1574cafc2f7bSdrh #else 1575955de52cSdanielk1977 Expr *pExpr, 15765f3e5e74Sdrh const char **pzOrigDb, 15775f3e5e74Sdrh const char **pzOrigTab, 1578cafc2f7bSdrh const char **pzOrigCol 1579b121dd14Sdrh #endif 1580955de52cSdanielk1977 ){ 1581955de52cSdanielk1977 char const *zType = 0; 1582517eb646Sdanielk1977 int j; 1583b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1584b121dd14Sdrh char const *zOrigDb = 0; 1585b121dd14Sdrh char const *zOrigTab = 0; 1586b121dd14Sdrh char const *zOrigCol = 0; 1587b121dd14Sdrh #endif 15885338a5f7Sdanielk1977 1589f7ce4291Sdrh assert( pExpr!=0 ); 1590f7ce4291Sdrh assert( pNC->pSrcList!=0 ); 1591755b0fd3Sdrh assert( pExpr->op!=TK_AGG_COLUMN ); /* This routine runes before aggregates 1592755b0fd3Sdrh ** are processed */ 159300e279d9Sdanielk1977 switch( pExpr->op ){ 159400e279d9Sdanielk1977 case TK_COLUMN: { 1595955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1596955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1597955de52cSdanielk1977 ** database table or a subquery. 1598955de52cSdanielk1977 */ 1599955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1600955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1601955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 160243bc88bbSdan while( pNC && !pTab ){ 1603b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1604b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1605b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 16066a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1607955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1608b3bce662Sdanielk1977 }else{ 1609b3bce662Sdanielk1977 pNC = pNC->pNext; 1610b3bce662Sdanielk1977 } 1611b3bce662Sdanielk1977 } 1612955de52cSdanielk1977 161343bc88bbSdan if( pTab==0 ){ 1614417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1615417168adSdrh ** cause this condition to run. Since then, we have restructured how 1616417168adSdrh ** trigger code is generated and so this condition is no longer 161743bc88bbSdan ** possible. However, it can still be true for statements like 161843bc88bbSdan ** the following: 161943bc88bbSdan ** 162043bc88bbSdan ** CREATE TABLE t1(col INTEGER); 162143bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 162243bc88bbSdan ** 162343bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 162443bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 162543bc88bbSdan ** though it should really be "INTEGER". 162643bc88bbSdan ** 162743bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 162843bc88bbSdan ** used. When columnType() is called on the expression 162943bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 163043bc88bbSdan ** branch below. */ 16317e62779aSdrh break; 16327e62779aSdrh } 1633955de52cSdanielk1977 163443bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1635955de52cSdanielk1977 if( pS ){ 1636955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1637955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1638955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1639955de52cSdanielk1977 */ 1640f35f2f92Sdrh if( iCol>=0 && iCol<pS->pEList->nExpr ){ 1641955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1642955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1643955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1644955de52cSdanielk1977 */ 1645955de52cSdanielk1977 NameContext sNC; 1646955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1647955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 164843bc88bbSdan sNC.pNext = pNC; 1649955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1650cafc2f7bSdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 1651955de52cSdanielk1977 } 1652a78d757cSdrh }else{ 1653a78d757cSdrh /* A real table or a CTE table */ 1654955de52cSdanielk1977 assert( !pS ); 16555f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1656a78d757cSdrh if( iCol<0 ) iCol = pTab->iPKey; 1657a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 1658fcb78a49Sdrh if( iCol<0 ){ 1659fcb78a49Sdrh zType = "INTEGER"; 16605f3e5e74Sdrh zOrigCol = "rowid"; 1661fcb78a49Sdrh }else{ 16625f3e5e74Sdrh zOrigCol = pTab->aCol[iCol].zName; 1663d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 1664955de52cSdanielk1977 } 16655f3e5e74Sdrh zOrigTab = pTab->zName; 1666a78d757cSdrh if( pNC->pParse && pTab->pSchema ){ 1667955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1668e59be010Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; 1669955de52cSdanielk1977 } 16705f3e5e74Sdrh #else 1671a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 16725f3e5e74Sdrh if( iCol<0 ){ 16735f3e5e74Sdrh zType = "INTEGER"; 16745f3e5e74Sdrh }else{ 1675d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 16765f3e5e74Sdrh } 16775f3e5e74Sdrh #endif 1678fcb78a49Sdrh } 167900e279d9Sdanielk1977 break; 1680736c22b8Sdrh } 168193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 168200e279d9Sdanielk1977 case TK_SELECT: { 1683955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1684955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1685955de52cSdanielk1977 ** statement. 1686955de52cSdanielk1977 */ 1687b3bce662Sdanielk1977 NameContext sNC; 16886ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1689955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 16906ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1691955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1692b3bce662Sdanielk1977 sNC.pNext = pNC; 1693955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1694cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 169500e279d9Sdanielk1977 break; 1696fcb78a49Sdrh } 169793758c8dSdanielk1977 #endif 169800e279d9Sdanielk1977 } 169900e279d9Sdanielk1977 17005f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 17015f3e5e74Sdrh if( pzOrigDb ){ 17025f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 17035f3e5e74Sdrh *pzOrigDb = zOrigDb; 17045f3e5e74Sdrh *pzOrigTab = zOrigTab; 17055f3e5e74Sdrh *pzOrigCol = zOrigCol; 1706955de52cSdanielk1977 } 17075f3e5e74Sdrh #endif 1708517eb646Sdanielk1977 return zType; 1709517eb646Sdanielk1977 } 1710517eb646Sdanielk1977 1711517eb646Sdanielk1977 /* 1712517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1713517eb646Sdanielk1977 ** in the result set. 1714517eb646Sdanielk1977 */ 1715517eb646Sdanielk1977 static void generateColumnTypes( 1716517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1717517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1718517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1719517eb646Sdanielk1977 ){ 17203f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1721517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1722517eb646Sdanielk1977 int i; 1723b3bce662Sdanielk1977 NameContext sNC; 1724b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1725955de52cSdanielk1977 sNC.pParse = pParse; 1726eac5fc04Sdrh sNC.pNext = 0; 1727517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1728517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 17293f913576Sdrh const char *zType; 17303f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1731955de52cSdanielk1977 const char *zOrigDb = 0; 1732955de52cSdanielk1977 const char *zOrigTab = 0; 1733955de52cSdanielk1977 const char *zOrigCol = 0; 1734cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1735955de52cSdanielk1977 173685b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 17374b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 17384b1ae99dSdanielk1977 ** virtual machine is deleted. 1739fbcd585fSdanielk1977 */ 174010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 174110fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 174210fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 17433f913576Sdrh #else 1744cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 17453f913576Sdrh #endif 174610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1747fcb78a49Sdrh } 17485f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1749fcb78a49Sdrh } 1750fcb78a49Sdrh 1751eac5fc04Sdrh 1752eac5fc04Sdrh /* 1753ec360a8dSdrh ** Compute the column names for a SELECT statement. 1754ec360a8dSdrh ** 1755ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1756ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1757ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1758ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1759ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1760ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1761ec360a8dSdrh ** 1762ec360a8dSdrh ** See Also: sqlite3ColumnsFromExprList() 1763ec360a8dSdrh ** 1764ec360a8dSdrh ** The PRAGMA short_column_names and PRAGMA full_column_names settings are 1765ec360a8dSdrh ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all 1766ec360a8dSdrh ** applications should operate this way. Nevertheless, we need to support the 1767ec360a8dSdrh ** other modes for legacy: 1768ec360a8dSdrh ** 1769ec360a8dSdrh ** short=OFF, full=OFF: Column name is the text of the expression has it 1770ec360a8dSdrh ** originally appears in the SELECT statement. In 1771ec360a8dSdrh ** other words, the zSpan of the result expression. 1772ec360a8dSdrh ** 1773ec360a8dSdrh ** short=ON, full=OFF: (This is the default setting). If the result 17743d240d21Sdrh ** refers directly to a table column, then the 17753d240d21Sdrh ** result column name is just the table column 17763d240d21Sdrh ** name: COLUMN. Otherwise use zSpan. 1777ec360a8dSdrh ** 1778ec360a8dSdrh ** full=ON, short=ANY: If the result refers directly to a table column, 1779ec360a8dSdrh ** then the result column name with the table name 1780ec360a8dSdrh ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. 178182c3d636Sdrh */ 1782832508b7Sdrh static void generateColumnNames( 1783832508b7Sdrh Parse *pParse, /* Parser context */ 1784f35f2f92Sdrh Select *pSelect /* Generate column names for this SELECT statement */ 1785832508b7Sdrh ){ 1786d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1787eac5fc04Sdrh int i; 1788eac5fc04Sdrh Table *pTab; 1789f35f2f92Sdrh SrcList *pTabList; 1790f35f2f92Sdrh ExprList *pEList; 17919bb575fdSdrh sqlite3 *db = pParse->db; 1792ec360a8dSdrh int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ 1793ec360a8dSdrh int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ 1794fcabd464Sdrh 1795fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 17963cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 17973cf86063Sdanielk1977 if( pParse->explain ){ 179861de0d1bSdanielk1977 return; 17993cf86063Sdanielk1977 } 18005338a5f7Sdanielk1977 #endif 18013cf86063Sdanielk1977 18029802947fSdrh if( pParse->colNamesSet || db->mallocFailed ) return; 1803f35f2f92Sdrh /* Column names are determined by the left-most term of a compound select */ 1804f35f2f92Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 180507859486Sdrh SELECTTRACE(1,pParse,pSelect,("generating column names\n")); 1806f35f2f92Sdrh pTabList = pSelect->pSrc; 1807f35f2f92Sdrh pEList = pSelect->pEList; 18089802947fSdrh assert( v!=0 ); 1809f7ce4291Sdrh assert( pTabList!=0 ); 1810d8bc7086Sdrh pParse->colNamesSet = 1; 1811ec360a8dSdrh fullName = (db->flags & SQLITE_FullColNames)!=0; 1812ec360a8dSdrh srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; 181322322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 181482c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 1815ec360a8dSdrh Expr *p = pEList->a[i].pExpr; 1816ec360a8dSdrh 1817ec360a8dSdrh assert( p!=0 ); 18184dd89d5aSdrh assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ 18193d240d21Sdrh assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */ 182082c3d636Sdrh if( pEList->a[i].zName ){ 1821ec360a8dSdrh /* An AS clause always takes first priority */ 182282c3d636Sdrh char *zName = pEList->a[i].zName; 182310fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1824f35f2f92Sdrh }else if( srcName && p->op==TK_COLUMN ){ 182597665873Sdrh char *zCol; 18268aff1015Sdrh int iCol = p->iColumn; 1827f35f2f92Sdrh pTab = p->pTab; 1828f35f2f92Sdrh assert( pTab!=0 ); 18298aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 183097665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1831b1363206Sdrh if( iCol<0 ){ 183247a6db2bSdrh zCol = "rowid"; 1833b1363206Sdrh }else{ 1834b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1835b1363206Sdrh } 1836ec360a8dSdrh if( fullName ){ 183782c3d636Sdrh char *zName = 0; 18381c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 183910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 184082c3d636Sdrh }else{ 184110fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 184282c3d636Sdrh } 18431bee3d7bSdrh }else{ 1844859bc542Sdrh const char *z = pEList->a[i].zSpan; 1845859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 1846859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 184782c3d636Sdrh } 184882c3d636Sdrh } 184976d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 18505080aaa7Sdrh } 185182c3d636Sdrh 1852d8bc7086Sdrh /* 185360ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 18547d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 18557d10d5a6Sdrh ** column names for a table that would hold the expression list. 18567d10d5a6Sdrh ** 18577d10d5a6Sdrh ** All column names will be unique. 18587d10d5a6Sdrh ** 18597d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 18607d10d5a6Sdrh ** and other fields of Column are zeroed. 18617d10d5a6Sdrh ** 18627d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 18637d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1864ec360a8dSdrh ** 1865ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 1866ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 1867ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 1868ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 1869ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 1870ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 1871ec360a8dSdrh ** 1872ec360a8dSdrh ** See Also: generateColumnNames() 1873315555caSdrh */ 18748981b904Sdrh int sqlite3ColumnsFromExprList( 18757d10d5a6Sdrh Parse *pParse, /* Parsing context */ 18767d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1877d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 18787d10d5a6Sdrh Column **paCol /* Write the new column list here */ 18797d10d5a6Sdrh ){ 1880dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1881dc5ea5c7Sdrh int i, j; /* Loop counters */ 1882ebed3fa3Sdrh u32 cnt; /* Index added to make the name unique */ 1883dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1884dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1885dc5ea5c7Sdrh char *zName; /* Column name */ 1886dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 18870315e3ccSdrh Hash ht; /* Hash table of column names */ 188879d5f63fSdrh 18890315e3ccSdrh sqlite3HashInit(&ht); 18908c2e0f02Sdan if( pEList ){ 18918c2e0f02Sdan nCol = pEList->nExpr; 18928c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 18938c2e0f02Sdan testcase( aCol==0 ); 18946fe3733bSdrh if( nCol>32767 ) nCol = 32767; 18958c2e0f02Sdan }else{ 18968c2e0f02Sdan nCol = 0; 18978c2e0f02Sdan aCol = 0; 18988c2e0f02Sdan } 18998836cbbcSdan assert( nCol==(i16)nCol ); 19008c2e0f02Sdan *pnCol = nCol; 19018c2e0f02Sdan *paCol = aCol; 19028c2e0f02Sdan 19030315e3ccSdrh for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ 190479d5f63fSdrh /* Get an appropriate name for the column 190579d5f63fSdrh */ 190691bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 190779d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 19087d10d5a6Sdrh }else{ 1909ec360a8dSdrh Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr); 1910b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1911b07028f7Sdrh pColExpr = pColExpr->pRight; 1912b07028f7Sdrh assert( pColExpr!=0 ); 1913b07028f7Sdrh } 1914755b0fd3Sdrh assert( pColExpr->op!=TK_AGG_COLUMN ); 1915755b0fd3Sdrh if( pColExpr->op==TK_COLUMN ){ 191693a960a0Sdrh /* For columns use the column name name */ 1917dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1918ec360a8dSdrh Table *pTab = pColExpr->pTab; 1919755b0fd3Sdrh assert( pTab!=0 ); 1920f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 192196ceaf86Sdrh zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; 1922b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 192333e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 192496ceaf86Sdrh zName = pColExpr->u.zToken; 192593a960a0Sdrh }else{ 192679d5f63fSdrh /* Use the original text of the column expression as its name */ 192796ceaf86Sdrh zName = pEList->a[i].zSpan; 19287d10d5a6Sdrh } 192922f70c32Sdrh } 1930d7ca600eSdrh if( zName ){ 1931d7ca600eSdrh zName = sqlite3DbStrDup(db, zName); 1932d7ca600eSdrh }else{ 1933155507b3Sdrh zName = sqlite3MPrintf(db,"column%d",i+1); 1934d7ca600eSdrh } 193579d5f63fSdrh 193679d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 193760ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 193879d5f63fSdrh */ 19390315e3ccSdrh cnt = 0; 19400315e3ccSdrh while( zName && sqlite3HashFind(&ht, zName)!=0 ){ 19410315e3ccSdrh nName = sqlite3Strlen30(zName); 1942f7ee8965Sdrh if( nName>0 ){ 19430315e3ccSdrh for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} 19440315e3ccSdrh if( zName[j]==':' ) nName = j; 1945f7ee8965Sdrh } 194696ceaf86Sdrh zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); 1947ebed3fa3Sdrh if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); 194879d5f63fSdrh } 194991bb0eedSdrh pCol->zName = zName; 1950ba68f8f3Sdan sqlite3ColumnPropertiesFromName(0, pCol); 195103d69a68Sdrh if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ 19524a642b60Sdrh sqlite3OomFault(db); 19537d10d5a6Sdrh } 19540315e3ccSdrh } 19550315e3ccSdrh sqlite3HashClear(&ht); 19567d10d5a6Sdrh if( db->mallocFailed ){ 19577d10d5a6Sdrh for(j=0; j<i; j++){ 19587d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 19597d10d5a6Sdrh } 19607d10d5a6Sdrh sqlite3DbFree(db, aCol); 19617d10d5a6Sdrh *paCol = 0; 19627d10d5a6Sdrh *pnCol = 0; 1963fad3039cSmistachkin return SQLITE_NOMEM_BKPT; 19647d10d5a6Sdrh } 19657d10d5a6Sdrh return SQLITE_OK; 19667d10d5a6Sdrh } 1967e014a838Sdanielk1977 19687d10d5a6Sdrh /* 19697d10d5a6Sdrh ** Add type and collation information to a column list based on 19707d10d5a6Sdrh ** a SELECT statement. 19717d10d5a6Sdrh ** 19727d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 19737d10d5a6Sdrh ** The column list has only names, not types or collations. This 19747d10d5a6Sdrh ** routine goes through and adds the types and collations. 19757d10d5a6Sdrh ** 1976b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 19777d10d5a6Sdrh ** statement be resolved. 197879d5f63fSdrh */ 1979ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation( 19807d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 1981186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 19827d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 19837d10d5a6Sdrh ){ 19847d10d5a6Sdrh sqlite3 *db = pParse->db; 19857d10d5a6Sdrh NameContext sNC; 19867d10d5a6Sdrh Column *pCol; 19877d10d5a6Sdrh CollSeq *pColl; 19887d10d5a6Sdrh int i; 19897d10d5a6Sdrh Expr *p; 19907d10d5a6Sdrh struct ExprList_item *a; 19917d10d5a6Sdrh 19927d10d5a6Sdrh assert( pSelect!=0 ); 19937d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 1994186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 19957d10d5a6Sdrh if( db->mallocFailed ) return; 1996c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1997b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 19987d10d5a6Sdrh a = pSelect->pEList->a; 1999186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 2000ed06a131Sdrh const char *zType; 2001ed06a131Sdrh int n, m; 20027d10d5a6Sdrh p = a[i].pExpr; 2003cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 2004cafc2f7bSdrh /* pCol->szEst = ... // Column size est for SELECT tables never used */ 2005c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 20060c4db034Sdrh if( zType ){ 20070c4db034Sdrh m = sqlite3Strlen30(zType); 2008ed06a131Sdrh n = sqlite3Strlen30(pCol->zName); 2009ed06a131Sdrh pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); 2010ed06a131Sdrh if( pCol->zName ){ 2011ed06a131Sdrh memcpy(&pCol->zName[n+1], zType, m+1); 2012ed06a131Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 2013ed06a131Sdrh } 2014ed06a131Sdrh } 201505883a34Sdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB; 2016b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 20171cb50c88Sdrh if( pColl && pCol->zColl==0 ){ 201817435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 20190202b29eSdanielk1977 } 202022f70c32Sdrh } 2021cafc2f7bSdrh pTab->szTabRow = 1; /* Any non-zero value works */ 20227d10d5a6Sdrh } 20237d10d5a6Sdrh 20247d10d5a6Sdrh /* 20257d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 20267d10d5a6Sdrh ** the result set of that SELECT. 20277d10d5a6Sdrh */ 20287d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 20297d10d5a6Sdrh Table *pTab; 20307d10d5a6Sdrh sqlite3 *db = pParse->db; 20317d10d5a6Sdrh int savedFlags; 20327d10d5a6Sdrh 20337d10d5a6Sdrh savedFlags = db->flags; 20347d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 20357d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 20367d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 20377d10d5a6Sdrh if( pParse->nErr ) return 0; 20387d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 20397d10d5a6Sdrh db->flags = savedFlags; 20407d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 20417d10d5a6Sdrh if( pTab==0 ){ 20427d10d5a6Sdrh return 0; 20437d10d5a6Sdrh } 2044373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 2045b2468954Sdrh ** is disabled */ 20464a642b60Sdrh assert( db->lookaside.bDisable ); 204779df7782Sdrh pTab->nTabRef = 1; 20487d10d5a6Sdrh pTab->zName = 0; 2049cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 20508981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 2051ed06a131Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect); 205222f70c32Sdrh pTab->iPKey = -1; 20537ce72f69Sdrh if( db->mallocFailed ){ 20541feeaed2Sdan sqlite3DeleteTable(db, pTab); 20557ce72f69Sdrh return 0; 20567ce72f69Sdrh } 205722f70c32Sdrh return pTab; 205822f70c32Sdrh } 205922f70c32Sdrh 206022f70c32Sdrh /* 2061d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 2062d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 2063d8bc7086Sdrh */ 206455965619Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){ 206555965619Sdrh if( pParse->pVdbe ){ 206655965619Sdrh return pParse->pVdbe; 206755965619Sdrh } 2068e0e261a4Sdrh if( pParse->pToplevel==0 2069e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 2070e0e261a4Sdrh ){ 2071e0e261a4Sdrh pParse->okConstFactor = 1; 2072949f9cd5Sdrh } 207355965619Sdrh return sqlite3VdbeCreate(pParse); 20746f077343Sdrh } 2075d8bc7086Sdrh 207615007a99Sdrh 2077d8bc7086Sdrh /* 20787b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 20798c0833fbSdrh ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions 20807b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 2081a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 2082a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 2083a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 2084a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 20857b58daeaSdrh ** 2086d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 20878c0833fbSdrh ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit 20888c0833fbSdrh ** and iOffset should have been preset to appropriate default values (zero) 2089aa9ce707Sdrh ** prior to calling this routine. 2090aa9ce707Sdrh ** 2091aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 2092aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 2093aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 2094aa9ce707Sdrh ** 20958c0833fbSdrh ** Only if pLimit->pLeft!=0 do the limit registers get 20967b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 20977b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 20987b58daeaSdrh ** SELECT statements. 20997b58daeaSdrh */ 2100ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 210102afc861Sdrh Vdbe *v = 0; 210202afc861Sdrh int iLimit = 0; 210315007a99Sdrh int iOffset; 21048b0cf38aSdrh int n; 21058c0833fbSdrh Expr *pLimit = p->pLimit; 21068c0833fbSdrh 21070acb7e48Sdrh if( p->iLimit ) return; 210815007a99Sdrh 21097b58daeaSdrh /* 21107b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 2111f7b5496eSdrh ** controversy about what the correct behavior should be. 21127b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 21137b58daeaSdrh ** no rows. 21147b58daeaSdrh */ 2115ceea3321Sdrh sqlite3ExprCacheClear(pParse); 21168c0833fbSdrh if( pLimit ){ 21178c0833fbSdrh assert( pLimit->op==TK_LIMIT ); 21188c0833fbSdrh assert( pLimit->pLeft!=0 ); 21190a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 212015007a99Sdrh v = sqlite3GetVdbe(pParse); 2121aa9ce707Sdrh assert( v!=0 ); 21228c0833fbSdrh if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){ 21239b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 21249b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 2125456e4e4fSdrh if( n==0 ){ 2126076e85f5Sdrh sqlite3VdbeGoto(v, iBreak); 2127c3489bbfSdrh }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ 2128c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)n); 2129c3489bbfSdrh p->selFlags |= SF_FixedLimit; 21309b918ed1Sdrh } 21319b918ed1Sdrh }else{ 21328c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); 2133688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 2134d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 213516897072Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); 21369b918ed1Sdrh } 21378c0833fbSdrh if( pLimit->pRight ){ 21380a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 2139b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 21408c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pRight, iOffset); 2141688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 2142d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 2143cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); 2144d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 2145b7654111Sdrh } 2146d59ba6ceSdrh } 21477b58daeaSdrh } 21487b58daeaSdrh 2149b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 2150fbc4ee7bSdrh /* 2151fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 2152fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 2153fbc4ee7bSdrh ** the column has no default collating sequence. 2154fbc4ee7bSdrh ** 2155fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 2156fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 2157fbc4ee7bSdrh */ 2158dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 2159fbc4ee7bSdrh CollSeq *pRet; 2160dc1bdc4fSdanielk1977 if( p->pPrior ){ 2161dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 2162fbc4ee7bSdrh }else{ 2163fbc4ee7bSdrh pRet = 0; 2164dc1bdc4fSdanielk1977 } 216510c081adSdrh assert( iCol>=0 ); 21662ec18a3cSdrh /* iCol must be less than p->pEList->nExpr. Otherwise an error would 21672ec18a3cSdrh ** have been thrown during name resolution and we would not have gotten 21682ec18a3cSdrh ** this far */ 21692ec18a3cSdrh if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ 2170dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 2171dc1bdc4fSdanielk1977 } 2172dc1bdc4fSdanielk1977 return pRet; 2173d3d39e93Sdrh } 2174d3d39e93Sdrh 217553bed45eSdan /* 217653bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 217753bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 217853bed45eSdan ** structure suitable for implementing the ORDER BY. 217953bed45eSdan ** 218053bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 218153bed45eSdan ** function is responsible for ensuring that this structure is eventually 218253bed45eSdan ** freed. 218353bed45eSdan */ 218453bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 218553bed45eSdan ExprList *pOrderBy = p->pOrderBy; 218653bed45eSdan int nOrderBy = p->pOrderBy->nExpr; 218753bed45eSdan sqlite3 *db = pParse->db; 218853bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 218953bed45eSdan if( pRet ){ 219053bed45eSdan int i; 219153bed45eSdan for(i=0; i<nOrderBy; i++){ 219253bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 219353bed45eSdan Expr *pTerm = pItem->pExpr; 219453bed45eSdan CollSeq *pColl; 219553bed45eSdan 219653bed45eSdan if( pTerm->flags & EP_Collate ){ 219753bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 219853bed45eSdan }else{ 219953bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 220053bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 220153bed45eSdan pOrderBy->a[i].pExpr = 220253bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 220353bed45eSdan } 220453bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 220553bed45eSdan pRet->aColl[i] = pColl; 220653bed45eSdan pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; 220753bed45eSdan } 220853bed45eSdan } 220953bed45eSdan 221053bed45eSdan return pRet; 221153bed45eSdan } 2212d3d39e93Sdrh 2213781def29Sdrh #ifndef SQLITE_OMIT_CTE 2214781def29Sdrh /* 2215781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 2216781def29Sdrh ** query of the form: 2217781def29Sdrh ** 2218781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 2219781def29Sdrh ** \___________/ \_______________/ 2220781def29Sdrh ** p->pPrior p 2221781def29Sdrh ** 2222781def29Sdrh ** 2223781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 22248a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. 2225781def29Sdrh ** 2226781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 2227781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 2228fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 2229fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 2230fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 2231781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 2232781def29Sdrh ** and the iteration continues until the Queue table is empty. 2233781def29Sdrh ** 2234781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 2235781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 2236781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 2237781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 2238781def29Sdrh ** 2239781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 2240781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 2241781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 2242781def29Sdrh ** 2243781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 2244781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 2245781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 2246781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 2247781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 2248781def29Sdrh ** rows have been skipped. 2249781def29Sdrh */ 2250781def29Sdrh static void generateWithRecursiveQuery( 2251781def29Sdrh Parse *pParse, /* Parsing context */ 2252781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 2253781def29Sdrh SelectDest *pDest /* What to do with query results */ 2254781def29Sdrh ){ 2255781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 2256781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 2257781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 2258781def29Sdrh Select *pSetup = p->pPrior; /* The setup query */ 2259781def29Sdrh int addrTop; /* Top of the loop */ 2260781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 2261edf83d1eSdrh int iCurrent = 0; /* The Current table */ 2262781def29Sdrh int regCurrent; /* Register holding Current table */ 2263781def29Sdrh int iQueue; /* The Queue table */ 2264781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 22658e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 2266781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 2267781def29Sdrh int i; /* Loop counter */ 2268781def29Sdrh int rc; /* Result code */ 2269fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 22708c0833fbSdrh Expr *pLimit; /* Saved LIMIT and OFFSET */ 2271aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 2272781def29Sdrh 2273781def29Sdrh /* Obtain authorization to do a recursive query */ 2274781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 2275781def29Sdrh 2276aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 2277aa9ce707Sdrh addrBreak = sqlite3VdbeMakeLabel(v); 227869b9383eSdan p->nSelectRow = 320; /* 4 billion rows */ 2279aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 2280aa9ce707Sdrh pLimit = p->pLimit; 2281aa9ce707Sdrh regLimit = p->iLimit; 2282aa9ce707Sdrh regOffset = p->iOffset; 22838c0833fbSdrh p->pLimit = 0; 2284aa9ce707Sdrh p->iLimit = p->iOffset = 0; 228553bed45eSdan pOrderBy = p->pOrderBy; 2286781def29Sdrh 2287781def29Sdrh /* Locate the cursor number of the Current table */ 2288781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 22898a48b9c0Sdrh if( pSrc->a[i].fg.isRecursive ){ 2290781def29Sdrh iCurrent = pSrc->a[i].iCursor; 2291781def29Sdrh break; 2292781def29Sdrh } 2293781def29Sdrh } 2294781def29Sdrh 2295fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2296781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 22978e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2298781def29Sdrh iQueue = pParse->nTab++; 2299781def29Sdrh if( p->op==TK_UNION ){ 23008e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 2301781def29Sdrh iDistinct = pParse->nTab++; 2302fe1c6bb9Sdrh }else{ 23038e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2304781def29Sdrh } 2305781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2306781def29Sdrh 2307781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2308781def29Sdrh regCurrent = ++pParse->nMem; 2309781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2310fe1c6bb9Sdrh if( pOrderBy ){ 231153bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2312fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2313fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2314fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2315fe1c6bb9Sdrh }else{ 2316781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2317fe1c6bb9Sdrh } 2318fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2319781def29Sdrh if( iDistinct ){ 2320781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2321781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2322781def29Sdrh } 2323781def29Sdrh 232453bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 232553bed45eSdan p->pOrderBy = 0; 232653bed45eSdan 2327781def29Sdrh /* Store the results of the setup-query in Queue. */ 2328d227a291Sdrh pSetup->pNext = 0; 2329781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2330d227a291Sdrh pSetup->pNext = p; 2331fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2332781def29Sdrh 2333781def29Sdrh /* Find the next row in the Queue and output that row */ 2334688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2335781def29Sdrh 2336781def29Sdrh /* Transfer the next row in Queue over to Current */ 2337781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2338fe1c6bb9Sdrh if( pOrderBy ){ 2339fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2340fe1c6bb9Sdrh }else{ 2341781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2342fe1c6bb9Sdrh } 2343781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2344781def29Sdrh 2345fe1c6bb9Sdrh /* Output the single row in Current */ 2346fe1c6bb9Sdrh addrCont = sqlite3VdbeMakeLabel(v); 2347aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 23482def2f7eSdrh selectInnerLoop(pParse, p, iCurrent, 2349079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2350688852abSdrh if( regLimit ){ 235116897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); 2352688852abSdrh VdbeCoverage(v); 2353688852abSdrh } 2354fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2355fe1c6bb9Sdrh 2356781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2357781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2358781def29Sdrh */ 2359b63ce02fSdrh if( p->selFlags & SF_Aggregate ){ 2360b63ce02fSdrh sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); 2361b63ce02fSdrh }else{ 2362781def29Sdrh p->pPrior = 0; 2363781def29Sdrh sqlite3Select(pParse, p, &destQueue); 2364781def29Sdrh assert( p->pPrior==0 ); 2365781def29Sdrh p->pPrior = pSetup; 2366b63ce02fSdrh } 2367781def29Sdrh 2368781def29Sdrh /* Keep running the loop until the Queue is empty */ 2369076e85f5Sdrh sqlite3VdbeGoto(v, addrTop); 2370781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2371fe1c6bb9Sdrh 2372fe1c6bb9Sdrh end_of_recursive_query: 23739afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2374fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2375aa9ce707Sdrh p->pLimit = pLimit; 2376fe1c6bb9Sdrh return; 2377781def29Sdrh } 2378b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2379781def29Sdrh 2380781def29Sdrh /* Forward references */ 2381b21e7c70Sdrh static int multiSelectOrderBy( 2382b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2383b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2384a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2385b21e7c70Sdrh ); 2386b21e7c70Sdrh 238745f54a57Sdrh /* 238845f54a57Sdrh ** Handle the special case of a compound-select that originates from a 238945f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 239045f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 239145f54a57Sdrh ** on a VALUES clause. 239245f54a57Sdrh ** 239345f54a57Sdrh ** Because the Select object originates from a VALUES clause: 2394b058d054Sdrh ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 239545f54a57Sdrh ** (2) All terms are UNION ALL 239645f54a57Sdrh ** (3) There is no ORDER BY clause 2397b058d054Sdrh ** 2398b058d054Sdrh ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES 2399b058d054Sdrh ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). 2400b058d054Sdrh ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. 2401b058d054Sdrh ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES. 240245f54a57Sdrh */ 240345f54a57Sdrh static int multiSelectValues( 240445f54a57Sdrh Parse *pParse, /* Parsing context */ 240545f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 240645f54a57Sdrh SelectDest *pDest /* What to do with query results */ 240745f54a57Sdrh ){ 240845f54a57Sdrh Select *pPrior; 2409b058d054Sdrh Select *pRightmost = p; 241045f54a57Sdrh int nRow = 1; 241145f54a57Sdrh int rc = 0; 2412772460fdSdrh assert( p->selFlags & SF_MultiValue ); 241345f54a57Sdrh do{ 241445f54a57Sdrh assert( p->selFlags & SF_Values ); 241545f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 2416923cadb1Sdan assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); 241745f54a57Sdrh if( p->pPrior==0 ) break; 241845f54a57Sdrh assert( p->pPrior->pNext==p ); 241945f54a57Sdrh p = p->pPrior; 242045f54a57Sdrh nRow++; 242145f54a57Sdrh }while(1); 242245f54a57Sdrh while( p ){ 242345f54a57Sdrh pPrior = p->pPrior; 242445f54a57Sdrh p->pPrior = 0; 242545f54a57Sdrh rc = sqlite3Select(pParse, p, pDest); 242645f54a57Sdrh p->pPrior = pPrior; 2427b058d054Sdrh if( rc || pRightmost->pLimit ) break; 242845f54a57Sdrh p->nSelectRow = nRow; 242945f54a57Sdrh p = p->pNext; 243045f54a57Sdrh } 243145f54a57Sdrh return rc; 243245f54a57Sdrh } 2433b21e7c70Sdrh 2434d3d39e93Sdrh /* 243516ee60ffSdrh ** This routine is called to process a compound query form from 243616ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 243716ee60ffSdrh ** INTERSECT 2438c926afbcSdrh ** 2439e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2440e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2441e78e8284Sdrh ** in which case this routine will be called recursively. 2442e78e8284Sdrh ** 2443e78e8284Sdrh ** The results of the total query are to be written into a destination 2444e78e8284Sdrh ** of type eDest with parameter iParm. 2445e78e8284Sdrh ** 2446e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2447e78e8284Sdrh ** 2448e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2449e78e8284Sdrh ** 2450e78e8284Sdrh ** This statement is parsed up as follows: 2451e78e8284Sdrh ** 2452e78e8284Sdrh ** SELECT c FROM t3 2453e78e8284Sdrh ** | 2454e78e8284Sdrh ** `-----> SELECT b FROM t2 2455e78e8284Sdrh ** | 24564b11c6d3Sjplyon ** `------> SELECT a FROM t1 2457e78e8284Sdrh ** 2458e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2459e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2460e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2461e78e8284Sdrh ** 2462e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2463e78e8284Sdrh ** individual selects always group from left to right. 246482c3d636Sdrh */ 246584ac9d02Sdanielk1977 static int multiSelect( 2466fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2467fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2468a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 246984ac9d02Sdanielk1977 ){ 247084ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 247110e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 247210e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 24731013c932Sdrh SelectDest dest; /* Alternative data destination */ 2474eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2475633e6d57Sdrh sqlite3 *db; /* Database connection */ 24767f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 2477edf83d1eSdrh int iSub1 = 0; /* EQP id of left-hand query */ 2478edf83d1eSdrh int iSub2 = 0; /* EQP id of right-hand query */ 24797f61e92cSdan #endif 248082c3d636Sdrh 24817b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2482fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 248382c3d636Sdrh */ 2484701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2485eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2486633e6d57Sdrh db = pParse->db; 2487d8bc7086Sdrh pPrior = p->pPrior; 2488bc10377aSdrh dest = *pDest; 248963347e7dSdrh if( pPrior->pOrderBy || pPrior->pLimit ){ 249063347e7dSdrh sqlite3ErrorMsg(pParse,"%s clause should come after %s not before", 249163347e7dSdrh pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op)); 249284ac9d02Sdanielk1977 rc = 1; 249384ac9d02Sdanielk1977 goto multi_select_end; 24947b58daeaSdrh } 249582c3d636Sdrh 24964adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2497701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2498d8bc7086Sdrh 24991cc3d75fSdrh /* Create the destination temporary table if necessary 25001cc3d75fSdrh */ 25016c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2502b4964b72Sdanielk1977 assert( p->pEList ); 25032b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 25046c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 25051cc3d75fSdrh } 25061cc3d75fSdrh 250745f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 250845f54a57Sdrh */ 2509772460fdSdrh if( p->selFlags & SF_MultiValue ){ 251045f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 251145f54a57Sdrh goto multi_select_end; 251245f54a57Sdrh } 251345f54a57Sdrh 2514f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2515f6e369a1Sdrh ** in their result sets. 2516f6e369a1Sdrh */ 2517f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2518923cadb1Sdan assert( p->pEList->nExpr==pPrior->pEList->nExpr ); 2519f6e369a1Sdrh 2520eede6a53Sdan #ifndef SQLITE_OMIT_CTE 2521eae73fbfSdan if( p->selFlags & SF_Recursive ){ 2522781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 25238ce7184bSdan }else 25248ce7184bSdan #endif 2525f6e369a1Sdrh 2526a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2527a9671a22Sdrh */ 2528f6e369a1Sdrh if( p->pOrderBy ){ 2529a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 2530eede6a53Sdan }else 2531f6e369a1Sdrh 2532f46f905aSdrh /* Generate code for the left and right SELECT statements. 2533d8bc7086Sdrh */ 253482c3d636Sdrh switch( p->op ){ 2535f46f905aSdrh case TK_ALL: { 2536ec7429aeSdrh int addr = 0; 253795aa47b1Sdrh int nLimit; 2538a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2539547180baSdrh pPrior->iLimit = p->iLimit; 2540547180baSdrh pPrior->iOffset = p->iOffset; 2541a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 25427f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 25437d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2544ad68cb6bSdanielk1977 p->pLimit = 0; 254584ac9d02Sdanielk1977 if( rc ){ 254684ac9d02Sdanielk1977 goto multi_select_end; 254784ac9d02Sdanielk1977 } 2548f46f905aSdrh p->pPrior = 0; 25497b58daeaSdrh p->iLimit = pPrior->iLimit; 25507b58daeaSdrh p->iOffset = pPrior->iOffset; 255192b01d53Sdrh if( p->iLimit ){ 255216897072Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); 2553d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 25549f1ef45fSdrh if( p->iOffset ){ 2555cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, 2556cc2fa4cfSdrh p->iLimit, p->iOffset+1, p->iOffset); 25579f1ef45fSdrh } 2558ec7429aeSdrh } 25597f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 25607d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2561373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2562eca7e01aSdanielk1977 pDelete = p->pPrior; 2563f46f905aSdrh p->pPrior = pPrior; 2564c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 256595aa47b1Sdrh if( pPrior->pLimit 25668c0833fbSdrh && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit) 2567c3489bbfSdrh && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 256895aa47b1Sdrh ){ 2569c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)nLimit); 257095aa47b1Sdrh } 2571ec7429aeSdrh if( addr ){ 2572ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2573ec7429aeSdrh } 2574f46f905aSdrh break; 2575f46f905aSdrh } 257682c3d636Sdrh case TK_EXCEPT: 257782c3d636Sdrh case TK_UNION: { 2578d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 2579ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2580d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 25818c0833fbSdrh Expr *pLimit; /* Saved values of p->nLimit */ 2582dc1bdc4fSdanielk1977 int addr; 25836c8c8ce0Sdanielk1977 SelectDest uniondest; 258482c3d636Sdrh 2585373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2586373cc2ddSdrh testcase( p->op==TK_UNION ); 258793a960a0Sdrh priorOp = SRT_Union; 2588d227a291Sdrh if( dest.eDest==priorOp ){ 2589d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2590c926afbcSdrh ** right. 2591d8bc7086Sdrh */ 2592e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 25932b596da8Sdrh unionTab = dest.iSDParm; 259482c3d636Sdrh }else{ 2595d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2596d8bc7086Sdrh ** intermediate results. 2597d8bc7086Sdrh */ 259882c3d636Sdrh unionTab = pParse->nTab++; 259993a960a0Sdrh assert( p->pOrderBy==0 ); 260066a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2601b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2602b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2603d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 260484ac9d02Sdanielk1977 assert( p->pEList ); 2605d8bc7086Sdrh } 2606d8bc7086Sdrh 2607d8bc7086Sdrh /* Code the SELECT statements to our left 2608d8bc7086Sdrh */ 2609b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 26101013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 26117f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 26127d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 261384ac9d02Sdanielk1977 if( rc ){ 261484ac9d02Sdanielk1977 goto multi_select_end; 261584ac9d02Sdanielk1977 } 2616d8bc7086Sdrh 2617d8bc7086Sdrh /* Code the current SELECT statement 2618d8bc7086Sdrh */ 26194cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 26204cfb22f7Sdrh op = SRT_Except; 26214cfb22f7Sdrh }else{ 26224cfb22f7Sdrh assert( p->op==TK_UNION ); 26234cfb22f7Sdrh op = SRT_Union; 2624d8bc7086Sdrh } 262582c3d636Sdrh p->pPrior = 0; 2626a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2627a2dc3b1aSdanielk1977 p->pLimit = 0; 26286c8c8ce0Sdanielk1977 uniondest.eDest = op; 26297f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 26307d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2631373cc2ddSdrh testcase( rc!=SQLITE_OK ); 26325bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 26335bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2634633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 2635eca7e01aSdanielk1977 pDelete = p->pPrior; 263682c3d636Sdrh p->pPrior = pPrior; 2637a9671a22Sdrh p->pOrderBy = 0; 2638c3489bbfSdrh if( p->op==TK_UNION ){ 2639c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 2640c3489bbfSdrh } 2641633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2642a2dc3b1aSdanielk1977 p->pLimit = pLimit; 264392b01d53Sdrh p->iLimit = 0; 264492b01d53Sdrh p->iOffset = 0; 2645d8bc7086Sdrh 2646d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2647d8bc7086Sdrh ** it is that we currently need. 2648d8bc7086Sdrh */ 26492b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2650373cc2ddSdrh if( dest.eDest!=priorOp ){ 26516b56344dSdrh int iCont, iBreak, iStart; 265282c3d636Sdrh assert( p->pEList ); 26534adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 26544adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2655ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2656688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 26574adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 26582def2f7eSdrh selectInnerLoop(pParse, p, unionTab, 2659e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 26604adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2661688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 26624adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 266366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 266482c3d636Sdrh } 266582c3d636Sdrh break; 266682c3d636Sdrh } 2667373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 266882c3d636Sdrh int tab1, tab2; 26696b56344dSdrh int iCont, iBreak, iStart; 26708c0833fbSdrh Expr *pLimit; 2671dc1bdc4fSdanielk1977 int addr; 26721013c932Sdrh SelectDest intersectdest; 26739cbf3425Sdrh int r1; 267482c3d636Sdrh 2675d8bc7086Sdrh /* INTERSECT is different from the others since it requires 26766206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2677d8bc7086Sdrh ** by allocating the tables we will need. 2678d8bc7086Sdrh */ 267982c3d636Sdrh tab1 = pParse->nTab++; 268082c3d636Sdrh tab2 = pParse->nTab++; 268193a960a0Sdrh assert( p->pOrderBy==0 ); 2682dc1bdc4fSdanielk1977 268366a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2684b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2685b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2686d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 268784ac9d02Sdanielk1977 assert( p->pEList ); 2688d8bc7086Sdrh 2689d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2690d8bc7086Sdrh */ 26911013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 26927f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 26937d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 269484ac9d02Sdanielk1977 if( rc ){ 269584ac9d02Sdanielk1977 goto multi_select_end; 269684ac9d02Sdanielk1977 } 2697d8bc7086Sdrh 2698d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2699d8bc7086Sdrh */ 270066a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2701b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2702b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 270382c3d636Sdrh p->pPrior = 0; 2704a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2705a2dc3b1aSdanielk1977 p->pLimit = 0; 27062b596da8Sdrh intersectdest.iSDParm = tab2; 27077f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 27087d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 2709373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2710eca7e01aSdanielk1977 pDelete = p->pPrior; 271182c3d636Sdrh p->pPrior = pPrior; 271295aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2713633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2714a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2715d8bc7086Sdrh 2716d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2717d8bc7086Sdrh ** tables. 2718d8bc7086Sdrh */ 271982c3d636Sdrh assert( p->pEList ); 27204adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 27214adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2722ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2723688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 27249cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 27259057fc7cSdrh iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); 2726688852abSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); 27279cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 27282def2f7eSdrh selectInnerLoop(pParse, p, tab1, 2729e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 27304adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2731688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); 27324adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 273366a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 273466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 273582c3d636Sdrh break; 273682c3d636Sdrh } 273782c3d636Sdrh } 27388cdbf836Sdrh 27397f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 27407f61e92cSdan 2741a9671a22Sdrh /* Compute collating sequences used by 2742a9671a22Sdrh ** temporary tables needed to implement the compound select. 2743a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 27448cdbf836Sdrh ** 27458cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 27468cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 27478cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 27488cdbf836Sdrh ** no temp tables are required. 2749fbc4ee7bSdrh */ 27507d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 2751fbc4ee7bSdrh int i; /* Loop counter */ 2752fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 27530342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 2754f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 275593a960a0Sdrh int nCol; /* Number of columns in result set */ 2756fbc4ee7bSdrh 2757d227a291Sdrh assert( p->pNext==0 ); 275893a960a0Sdrh nCol = p->pEList->nExpr; 2759ad124329Sdrh pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); 2760dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 2761fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT; 2762dc1bdc4fSdanielk1977 goto multi_select_end; 2763dc1bdc4fSdanielk1977 } 27640342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 27650342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 27660342b1f5Sdrh if( 0==*apColl ){ 2767633e6d57Sdrh *apColl = db->pDfltColl; 2768dc1bdc4fSdanielk1977 } 2769dc1bdc4fSdanielk1977 } 2770dc1bdc4fSdanielk1977 27710342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 27720342b1f5Sdrh for(i=0; i<2; i++){ 2773b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 27740342b1f5Sdrh if( addr<0 ){ 27750342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 27760342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 2777b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 27780342b1f5Sdrh break; 27790342b1f5Sdrh } 27800342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 27812ec2fb22Sdrh sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), 27822ec2fb22Sdrh P4_KEYINFO); 27830ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 27840342b1f5Sdrh } 2785dc1bdc4fSdanielk1977 } 27862ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyInfo); 2787dc1bdc4fSdanielk1977 } 2788dc1bdc4fSdanielk1977 2789dc1bdc4fSdanielk1977 multi_select_end: 27902b596da8Sdrh pDest->iSdst = dest.iSdst; 27912b596da8Sdrh pDest->nSdst = dest.nSdst; 2792633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 279384ac9d02Sdanielk1977 return rc; 27942282792aSdrh } 2795b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 27962282792aSdrh 2797b21e7c70Sdrh /* 279889b31d73Smistachkin ** Error message for when two or more terms of a compound select have different 279989b31d73Smistachkin ** size result sets. 280089b31d73Smistachkin */ 280189b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ 280289b31d73Smistachkin if( p->selFlags & SF_Values ){ 280389b31d73Smistachkin sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 280489b31d73Smistachkin }else{ 280589b31d73Smistachkin sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 280689b31d73Smistachkin " do not have the same number of result columns", selectOpName(p->op)); 280789b31d73Smistachkin } 280889b31d73Smistachkin } 280989b31d73Smistachkin 281089b31d73Smistachkin /* 2811b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 2812b21e7c70Sdrh ** SELECT statment. 28130acb7e48Sdrh ** 28142b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 28152b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 28160acb7e48Sdrh ** be sent. 28170acb7e48Sdrh ** 28180acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 28190acb7e48Sdrh ** return address. 28200acb7e48Sdrh ** 2821f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 28220acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 28230acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 28240acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 28250acb7e48Sdrh ** keys. 28260acb7e48Sdrh ** 28270acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 28280acb7e48Sdrh ** iBreak. 2829b21e7c70Sdrh */ 28300acb7e48Sdrh static int generateOutputSubroutine( 283192b01d53Sdrh Parse *pParse, /* Parsing context */ 283292b01d53Sdrh Select *p, /* The SELECT statement */ 283392b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 283492b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 283592b01d53Sdrh int regReturn, /* The return address register */ 28360acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 28370acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 283892b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 2839b21e7c70Sdrh ){ 2840b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 284192b01d53Sdrh int iContinue; 284292b01d53Sdrh int addr; 2843b21e7c70Sdrh 284492b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 284592b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 28460acb7e48Sdrh 28470acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 28480acb7e48Sdrh */ 28490acb7e48Sdrh if( regPrev ){ 2850728e0f91Sdrh int addr1, addr2; 2851728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 2852728e0f91Sdrh addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 28532ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 2854728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); 2855728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 2856e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2857ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 28580acb7e48Sdrh } 28591f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 28600acb7e48Sdrh 2861d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 28620acb7e48Sdrh */ 2863aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 2864b21e7c70Sdrh 2865e2248cfdSdrh assert( pDest->eDest!=SRT_Exists ); 2866e2248cfdSdrh assert( pDest->eDest!=SRT_Table ); 2867b21e7c70Sdrh switch( pDest->eDest ){ 2868b21e7c70Sdrh /* Store the result as data using a unique key. 2869b21e7c70Sdrh */ 2870b21e7c70Sdrh case SRT_EphemTab: { 2871b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 2872b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 28732b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 28742b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 28752b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2876b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2877b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 2878b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2879b21e7c70Sdrh break; 2880b21e7c70Sdrh } 2881b21e7c70Sdrh 2882b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 28831431807aSdrh /* If we are creating a set for an "expr IN (SELECT ...)". 2884b21e7c70Sdrh */ 2885b21e7c70Sdrh case SRT_Set: { 28866fccc35aSdrh int r1; 288763cecc41Sdrh testcase( pIn->nSdst>1 ); 2888b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 288971c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 28901431807aSdrh r1, pDest->zAffSdst, pIn->nSdst); 28911431807aSdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 28929b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, 28939b4eaebcSdrh pIn->iSdst, pIn->nSdst); 2894b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2895b21e7c70Sdrh break; 2896b21e7c70Sdrh } 2897b21e7c70Sdrh 2898b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2899b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2900b21e7c70Sdrh ** of the scan loop. 2901b21e7c70Sdrh */ 2902b21e7c70Sdrh case SRT_Mem: { 2903a276e3fdSdrh assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); 29042b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); 2905b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2906b21e7c70Sdrh break; 2907b21e7c70Sdrh } 2908b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2909b21e7c70Sdrh 29107d10d5a6Sdrh /* The results are stored in a sequence of registers 29112b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 2912b21e7c70Sdrh */ 291392b01d53Sdrh case SRT_Coroutine: { 29142b596da8Sdrh if( pDest->iSdst==0 ){ 29152b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 29162b596da8Sdrh pDest->nSdst = pIn->nSdst; 2917b21e7c70Sdrh } 29184b79bde7Sdan sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); 29192b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 292092b01d53Sdrh break; 292192b01d53Sdrh } 292292b01d53Sdrh 2923ccfcbceaSdrh /* If none of the above, then the result destination must be 2924ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2925ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2926ccfcbceaSdrh ** 2927ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2928ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2929ccfcbceaSdrh ** return the next row of result. 29307d10d5a6Sdrh */ 2931ccfcbceaSdrh default: { 2932ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 29332b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 29342b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 2935b21e7c70Sdrh break; 2936b21e7c70Sdrh } 2937b21e7c70Sdrh } 293892b01d53Sdrh 293992b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 294092b01d53Sdrh */ 294192b01d53Sdrh if( p->iLimit ){ 294216897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 294392b01d53Sdrh } 294492b01d53Sdrh 294592b01d53Sdrh /* Generate the subroutine return 294692b01d53Sdrh */ 29470acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 294892b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 294992b01d53Sdrh 295092b01d53Sdrh return addr; 2951b21e7c70Sdrh } 2952b21e7c70Sdrh 2953b21e7c70Sdrh /* 2954b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2955b21e7c70Sdrh ** is an ORDER BY clause. 2956b21e7c70Sdrh ** 2957b21e7c70Sdrh ** We assume a query of the following form: 2958b21e7c70Sdrh ** 2959b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2960b21e7c70Sdrh ** 2961b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2962b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2963b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2964b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2965b21e7c70Sdrh ** selectB) there are 7 subroutines: 2966b21e7c70Sdrh ** 2967b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2968b21e7c70Sdrh ** of the compound query. 2969b21e7c70Sdrh ** 2970b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2971b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2972b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2973b21e7c70Sdrh ** appears only in B.) 2974b21e7c70Sdrh ** 2975b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2976b21e7c70Sdrh ** 2977b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2978b21e7c70Sdrh ** 2979b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2980b21e7c70Sdrh ** 2981b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2982b21e7c70Sdrh ** 2983b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2984b21e7c70Sdrh ** 2985b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2986b21e7c70Sdrh ** <operator> is used: 2987b21e7c70Sdrh ** 2988b21e7c70Sdrh ** 2989b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2990b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2991b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2992b21e7c70Sdrh ** 29930acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2994b21e7c70Sdrh ** 2995b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2996b21e7c70Sdrh ** 29970acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2998b21e7c70Sdrh ** 29990acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 30000acb7e48Sdrh ** 30010acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 30020acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 30030acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 30040acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 30050acb7e48Sdrh ** 30060acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 30070acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 30080acb7e48Sdrh ** output value. A comparison is made against this value and the output 30090acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 3010b21e7c70Sdrh ** 3011b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 3012b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 3013b21e7c70Sdrh ** 3014b21e7c70Sdrh ** goto Init 3015b21e7c70Sdrh ** coA: coroutine for left query (A) 3016b21e7c70Sdrh ** coB: coroutine for right query (B) 3017b21e7c70Sdrh ** outA: output one row of A 3018b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 3019b21e7c70Sdrh ** EofA: ... 3020b21e7c70Sdrh ** EofB: ... 3021b21e7c70Sdrh ** AltB: ... 3022b21e7c70Sdrh ** AeqB: ... 3023b21e7c70Sdrh ** AgtB: ... 3024b21e7c70Sdrh ** Init: initialize coroutine registers 3025b21e7c70Sdrh ** yield coA 3026b21e7c70Sdrh ** if eof(A) goto EofA 3027b21e7c70Sdrh ** yield coB 3028b21e7c70Sdrh ** if eof(B) goto EofB 3029b21e7c70Sdrh ** Cmpr: Compare A, B 3030b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 3031b21e7c70Sdrh ** End: ... 3032b21e7c70Sdrh ** 3033b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 3034b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 3035b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 3036b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 3037b21e7c70Sdrh */ 3038de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3039b21e7c70Sdrh static int multiSelectOrderBy( 3040b21e7c70Sdrh Parse *pParse, /* Parsing context */ 3041b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 3042a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 3043b21e7c70Sdrh ){ 30440acb7e48Sdrh int i, j; /* Loop counters */ 3045b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 3046b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 3047b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 3048b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 304992b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 305092b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 305192b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 305292b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 305392b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 305492b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 305592b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 3056b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 305792b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 305881cf13ecSdrh int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ 305992b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 306092b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 306192b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 306292b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 306392b01d53Sdrh int regLimitA; /* Limit register for select-A */ 306492b01d53Sdrh int regLimitB; /* Limit register for select-A */ 30650acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 306692b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 306792b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 306892b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 306992b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 3070728e0f91Sdrh int addr1; /* Jump instructions that get retargetted */ 307192b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 307296067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 30730acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 30740acb7e48Sdrh sqlite3 *db; /* Database connection */ 30750acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 30760acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 30770acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 30787f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 30797f61e92cSdan int iSub1; /* EQP id of left-hand query */ 30807f61e92cSdan int iSub2; /* EQP id of right-hand query */ 30817f61e92cSdan #endif 3082b21e7c70Sdrh 308392b01d53Sdrh assert( p->pOrderBy!=0 ); 308496067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 30850acb7e48Sdrh db = pParse->db; 308692b01d53Sdrh v = pParse->pVdbe; 3087ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 308892b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 308992b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 30900acb7e48Sdrh 3091b21e7c70Sdrh 309292b01d53Sdrh /* Patch up the ORDER BY clause 309392b01d53Sdrh */ 309492b01d53Sdrh op = p->op; 3095b21e7c70Sdrh pPrior = p->pPrior; 309692b01d53Sdrh assert( pPrior->pOrderBy==0 ); 30970acb7e48Sdrh pOrderBy = p->pOrderBy; 309893a960a0Sdrh assert( pOrderBy ); 30990acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 310093a960a0Sdrh 31010acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 31020acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 31030acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 31040acb7e48Sdrh */ 31050acb7e48Sdrh if( op!=TK_ALL ){ 31060acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 31077d10d5a6Sdrh struct ExprList_item *pItem; 31087d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 3109c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 ); 3110c2acc4e4Sdrh if( pItem->u.x.iOrderByCol==i ) break; 31110acb7e48Sdrh } 31120acb7e48Sdrh if( j==nOrderBy ){ 3113b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 3114fad3039cSmistachkin if( pNew==0 ) return SQLITE_NOMEM_BKPT; 31150acb7e48Sdrh pNew->flags |= EP_IntValue; 311633e619fcSdrh pNew->u.iValue = i; 311743606175Sdrh p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 3118c2acc4e4Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; 31190acb7e48Sdrh } 31200acb7e48Sdrh } 31210acb7e48Sdrh } 31220acb7e48Sdrh 31230acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 312410c081adSdrh ** the permutation used to determine if the next 31250acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 31260acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 31270acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 31280acb7e48Sdrh ** collation. 31290acb7e48Sdrh */ 3130575fad65Sdrh aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); 31310acb7e48Sdrh if( aPermute ){ 31327d10d5a6Sdrh struct ExprList_item *pItem; 3133b1702026Sdrh aPermute[0] = nOrderBy; 3134b1702026Sdrh for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ 31356736618aSdrh assert( pItem->u.x.iOrderByCol>0 ); 31362ec18a3cSdrh assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 3137c2acc4e4Sdrh aPermute[i] = pItem->u.x.iOrderByCol - 1; 31380acb7e48Sdrh } 313953bed45eSdan pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 31400acb7e48Sdrh }else{ 31410acb7e48Sdrh pKeyMerge = 0; 31420acb7e48Sdrh } 31430acb7e48Sdrh 31440acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 31450acb7e48Sdrh */ 31460acb7e48Sdrh p->pOrderBy = pOrderBy; 31476ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 31480acb7e48Sdrh 31490acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 31500acb7e48Sdrh ** for the logic that removes duplicate result rows when the 31510acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 31520acb7e48Sdrh */ 31530acb7e48Sdrh if( op==TK_ALL ){ 31540acb7e48Sdrh regPrev = 0; 31550acb7e48Sdrh }else{ 31560acb7e48Sdrh int nExpr = p->pEList->nExpr; 31571c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 3158c8ac0d16Sdrh regPrev = pParse->nMem+1; 3159c8ac0d16Sdrh pParse->nMem += nExpr+1; 31600acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 3161ad124329Sdrh pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); 31620acb7e48Sdrh if( pKeyDup ){ 31632ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); 31640acb7e48Sdrh for(i=0; i<nExpr; i++){ 31650acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 31660acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 31670acb7e48Sdrh } 31680acb7e48Sdrh } 31690acb7e48Sdrh } 317092b01d53Sdrh 317192b01d53Sdrh /* Separate the left and the right query from one another 317292b01d53Sdrh */ 317392b01d53Sdrh p->pPrior = 0; 3174d227a291Sdrh pPrior->pNext = 0; 31757d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 31760acb7e48Sdrh if( pPrior->pPrior==0 ){ 31777d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 31780acb7e48Sdrh } 317992b01d53Sdrh 318092b01d53Sdrh /* Compute the limit registers */ 318192b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 31820acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 318392b01d53Sdrh regLimitA = ++pParse->nMem; 318492b01d53Sdrh regLimitB = ++pParse->nMem; 318592b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 318692b01d53Sdrh regLimitA); 318792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 318892b01d53Sdrh }else{ 318992b01d53Sdrh regLimitA = regLimitB = 0; 319092b01d53Sdrh } 3191633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 31920acb7e48Sdrh p->pLimit = 0; 319392b01d53Sdrh 3194b21e7c70Sdrh regAddrA = ++pParse->nMem; 3195b21e7c70Sdrh regAddrB = ++pParse->nMem; 3196b21e7c70Sdrh regOutA = ++pParse->nMem; 3197b21e7c70Sdrh regOutB = ++pParse->nMem; 3198b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 3199b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 3200b21e7c70Sdrh 320192b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 32020acb7e48Sdrh ** left of the compound operator - the "A" select. 32030acb7e48Sdrh */ 3204ed71a839Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 3205728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 3206ed71a839Sdrh VdbeComment((v, "left SELECT")); 320792b01d53Sdrh pPrior->iLimit = regLimitA; 32087f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 32097d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 32102fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrA); 3211728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3212b21e7c70Sdrh 321392b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 321492b01d53Sdrh ** the right - the "B" select 321592b01d53Sdrh */ 3216ed71a839Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 3217728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 3218ed71a839Sdrh VdbeComment((v, "right SELECT")); 321992b01d53Sdrh savedLimit = p->iLimit; 322092b01d53Sdrh savedOffset = p->iOffset; 322192b01d53Sdrh p->iLimit = regLimitB; 322292b01d53Sdrh p->iOffset = 0; 32237f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 32247d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 322592b01d53Sdrh p->iLimit = savedLimit; 322692b01d53Sdrh p->iOffset = savedOffset; 32272fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrB); 3228b21e7c70Sdrh 322992b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 32300acb7e48Sdrh ** select as the next output row of the compound select. 323192b01d53Sdrh */ 3232b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 32330acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 32340acb7e48Sdrh p, &destA, pDest, regOutA, 32352ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 3236b21e7c70Sdrh 323792b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 32380acb7e48Sdrh ** select as the next output row of the compound select. 323992b01d53Sdrh */ 32400acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 3241b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 32420acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 32430acb7e48Sdrh p, &destB, pDest, regOutB, 32442ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 32450acb7e48Sdrh } 32462ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyDup); 3247b21e7c70Sdrh 324892b01d53Sdrh /* Generate a subroutine to run when the results from select A 324992b01d53Sdrh ** are exhausted and only data in select B remains. 325092b01d53Sdrh */ 325192b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 325281cf13ecSdrh addrEofA_noB = addrEofA = labelEnd; 325392b01d53Sdrh }else{ 325481cf13ecSdrh VdbeNoopComment((v, "eof-A subroutine")); 325581cf13ecSdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 325681cf13ecSdrh addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 3257688852abSdrh VdbeCoverage(v); 3258076e85f5Sdrh sqlite3VdbeGoto(v, addrEofA); 3259c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 3260b21e7c70Sdrh } 3261b21e7c70Sdrh 326292b01d53Sdrh /* Generate a subroutine to run when the results from select B 326392b01d53Sdrh ** are exhausted and only data in select A remains. 326492b01d53Sdrh */ 3265b21e7c70Sdrh if( op==TK_INTERSECT ){ 326692b01d53Sdrh addrEofB = addrEofA; 326795aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3268b21e7c70Sdrh }else{ 326992b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 327081cf13ecSdrh addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3271688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 3272076e85f5Sdrh sqlite3VdbeGoto(v, addrEofB); 3273b21e7c70Sdrh } 3274b21e7c70Sdrh 327592b01d53Sdrh /* Generate code to handle the case of A<B 327692b01d53Sdrh */ 3277b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 32780acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3279688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3280076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3281b21e7c70Sdrh 328292b01d53Sdrh /* Generate code to handle the case of A==B 328392b01d53Sdrh */ 3284b21e7c70Sdrh if( op==TK_ALL ){ 3285b21e7c70Sdrh addrAeqB = addrAltB; 32860acb7e48Sdrh }else if( op==TK_INTERSECT ){ 32870acb7e48Sdrh addrAeqB = addrAltB; 32880acb7e48Sdrh addrAltB++; 328992b01d53Sdrh }else{ 3290b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 32910acb7e48Sdrh addrAeqB = 3292688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3293076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 329492b01d53Sdrh } 3295b21e7c70Sdrh 329692b01d53Sdrh /* Generate code to handle the case of A>B 329792b01d53Sdrh */ 3298b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 3299b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 3300b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 3301b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 330292b01d53Sdrh } 3303688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3304076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3305b21e7c70Sdrh 330692b01d53Sdrh /* This code runs once to initialize everything. 330792b01d53Sdrh */ 3308728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3309688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3310688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 331192b01d53Sdrh 331292b01d53Sdrh /* Implement the main merge loop 331392b01d53Sdrh */ 331492b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 33150acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 33162b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 33172ec2fb22Sdrh (char*)pKeyMerge, P4_KEYINFO); 3318953f7611Sdrh sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3319688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 332092b01d53Sdrh 332192b01d53Sdrh /* Jump to the this point in order to terminate the query. 332292b01d53Sdrh */ 3323b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 3324b21e7c70Sdrh 33250acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 33260acb7e48Sdrh ** by the calling function */ 33275e7ad508Sdanielk1977 if( p->pPrior ){ 3328633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 33295e7ad508Sdanielk1977 } 33300acb7e48Sdrh p->pPrior = pPrior; 3331d227a291Sdrh pPrior->pNext = p; 333292b01d53Sdrh 333392b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 333492b01d53Sdrh **** subqueries ****/ 33357f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 33363dc4cc66Sdrh return pParse->nErr!=0; 333792b01d53Sdrh } 3338de3e41e3Sdanielk1977 #endif 3339b21e7c70Sdrh 33403514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 334146967de2Sdrh 334246967de2Sdrh /* An instance of the SubstContext object describes an substitution edit 334346967de2Sdrh ** to be performed on a parse tree. 334446967de2Sdrh ** 334546967de2Sdrh ** All references to columns in table iTable are to be replaced by corresponding 334646967de2Sdrh ** expressions in pEList. 334746967de2Sdrh */ 334846967de2Sdrh typedef struct SubstContext { 334946967de2Sdrh Parse *pParse; /* The parsing context */ 335046967de2Sdrh int iTable; /* Replace references to this table */ 335131d6fd55Sdrh int iNewTable; /* New table number */ 335231d6fd55Sdrh int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ 335346967de2Sdrh ExprList *pEList; /* Replacement expressions */ 335446967de2Sdrh } SubstContext; 335546967de2Sdrh 335617435752Sdrh /* Forward Declarations */ 335746967de2Sdrh static void substExprList(SubstContext*, ExprList*); 335846967de2Sdrh static void substSelect(SubstContext*, Select*, int); 335917435752Sdrh 33602282792aSdrh /* 3361832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 33626a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 336384e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 33646a3ea0e6Sdrh ** unchanged.) 3365832508b7Sdrh ** 3366832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 3367832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 3368832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3369aca19e19Sdrh ** FORM clause entry is iTable. This routine makes the necessary 3370832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 3371832508b7Sdrh ** of the subquery rather the result set of the subquery. 3372832508b7Sdrh */ 3373b7916a78Sdrh static Expr *substExpr( 337446967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 337546967de2Sdrh Expr *pExpr /* Expr in which substitution occurs */ 337617435752Sdrh ){ 3377b7916a78Sdrh if( pExpr==0 ) return 0; 33783d240d21Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) 33793d240d21Sdrh && pExpr->iRightJoinTable==pSubst->iTable 33803d240d21Sdrh ){ 3381399c7e21Sdrh pExpr->iRightJoinTable = pSubst->iNewTable; 3382399c7e21Sdrh } 338346967de2Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){ 338450350a15Sdrh if( pExpr->iColumn<0 ){ 338550350a15Sdrh pExpr->op = TK_NULL; 338650350a15Sdrh }else{ 3387832508b7Sdrh Expr *pNew; 338846967de2Sdrh Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; 338931d6fd55Sdrh Expr ifNullRow; 339046967de2Sdrh assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr ); 33916ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 339244c5604cSdan if( sqlite3ExprIsVector(pCopy) ){ 339346967de2Sdrh sqlite3VectorErrorMsg(pSubst->pParse, pCopy); 339444c5604cSdan }else{ 339546967de2Sdrh sqlite3 *db = pSubst->pParse->db; 339631d6fd55Sdrh if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){ 339731d6fd55Sdrh memset(&ifNullRow, 0, sizeof(ifNullRow)); 339831d6fd55Sdrh ifNullRow.op = TK_IF_NULL_ROW; 339931d6fd55Sdrh ifNullRow.pLeft = pCopy; 340031d6fd55Sdrh ifNullRow.iTable = pSubst->iNewTable; 340131d6fd55Sdrh pCopy = &ifNullRow; 340231d6fd55Sdrh } 340344c5604cSdan pNew = sqlite3ExprDup(db, pCopy, 0); 3404bd11a2acSdan if( pNew && pSubst->isLeftJoin ){ 3405bd11a2acSdan ExprSetProperty(pNew, EP_CanBeNull); 3406bd11a2acSdan } 3407bd11a2acSdan if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){ 340892ddb3bdSdan pNew->iRightJoinTable = pExpr->iRightJoinTable; 3409bd11a2acSdan ExprSetProperty(pNew, EP_FromJoin); 341092ddb3bdSdan } 3411b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 3412b7916a78Sdrh pExpr = pNew; 341350350a15Sdrh } 341444c5604cSdan } 3415832508b7Sdrh }else{ 34167c1544e0Sdrh if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ 34177c1544e0Sdrh pExpr->iTable = pSubst->iNewTable; 34187c1544e0Sdrh } 341946967de2Sdrh pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); 342046967de2Sdrh pExpr->pRight = substExpr(pSubst, pExpr->pRight); 34216ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 342246967de2Sdrh substSelect(pSubst, pExpr->x.pSelect, 1); 34236ab3a2ecSdanielk1977 }else{ 342446967de2Sdrh substExprList(pSubst, pExpr->x.pList); 34256ab3a2ecSdanielk1977 } 3426832508b7Sdrh } 3427b7916a78Sdrh return pExpr; 3428832508b7Sdrh } 342917435752Sdrh static void substExprList( 343046967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 343146967de2Sdrh ExprList *pList /* List to scan and in which to make substitutes */ 343217435752Sdrh ){ 3433832508b7Sdrh int i; 3434832508b7Sdrh if( pList==0 ) return; 3435832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 343646967de2Sdrh pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); 3437832508b7Sdrh } 3438832508b7Sdrh } 343917435752Sdrh static void substSelect( 344046967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 344117435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 3442d12b6363Sdrh int doPrior /* Do substitutes on p->pPrior too */ 344317435752Sdrh ){ 3444588a9a1aSdrh SrcList *pSrc; 3445588a9a1aSdrh struct SrcList_item *pItem; 3446588a9a1aSdrh int i; 3447b3bce662Sdanielk1977 if( !p ) return; 3448d12b6363Sdrh do{ 344946967de2Sdrh substExprList(pSubst, p->pEList); 345046967de2Sdrh substExprList(pSubst, p->pGroupBy); 345146967de2Sdrh substExprList(pSubst, p->pOrderBy); 345246967de2Sdrh p->pHaving = substExpr(pSubst, p->pHaving); 345346967de2Sdrh p->pWhere = substExpr(pSubst, p->pWhere); 3454588a9a1aSdrh pSrc = p->pSrc; 34552906490bSdrh assert( pSrc!=0 ); 3456588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 345746967de2Sdrh substSelect(pSubst, pItem->pSelect, 1); 3458d12b6363Sdrh if( pItem->fg.isTabFunc ){ 345946967de2Sdrh substExprList(pSubst, pItem->u1.pFuncArg); 3460588a9a1aSdrh } 3461588a9a1aSdrh } 3462d12b6363Sdrh }while( doPrior && (p = p->pPrior)!=0 ); 3463b3bce662Sdanielk1977 } 34643514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3465832508b7Sdrh 34663514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3467832508b7Sdrh /* 3468630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3469630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 34701350b030Sdrh ** 34711350b030Sdrh ** To understand the concept of flattening, consider the following 34721350b030Sdrh ** query: 34731350b030Sdrh ** 34741350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 34751350b030Sdrh ** 34761350b030Sdrh ** The default way of implementing this query is to execute the 34771350b030Sdrh ** subquery first and store the results in a temporary table, then 34781350b030Sdrh ** run the outer query on that temporary table. This requires two 34791350b030Sdrh ** passes over the data. Furthermore, because the temporary table 34801350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3481832508b7Sdrh ** optimized. 34821350b030Sdrh ** 3483832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 34841350b030Sdrh ** a single flat select, like this: 34851350b030Sdrh ** 34861350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 34871350b030Sdrh ** 348860ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 3489832508b7Sdrh ** but only has to scan the data once. And because indices might 3490832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 3491832508b7Sdrh ** avoided. 34921350b030Sdrh ** 3493d981e828Sdrh ** Flattening is subject to the following constraints: 34941350b030Sdrh ** 349525c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 349625c221ebSdrh ** The subquery and the outer query cannot both be aggregates. 34971350b030Sdrh ** 349825c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3499d981e828Sdrh ** (2) If the subquery is an aggregate then 3500d981e828Sdrh ** (2a) the outer query must not be a join and 3501d981e828Sdrh ** (2b) the outer query must not use subqueries 3502d981e828Sdrh ** other than the one FROM-clause subquery that is a candidate 3503d981e828Sdrh ** for flattening. (This is due to ticket [2f7170d73bf9abf80] 3504d981e828Sdrh ** from 2015-02-09.) 3505832508b7Sdrh ** 3506d981e828Sdrh ** (3) If the subquery is the right operand of a LEFT JOIN then 3507d981e828Sdrh ** (3a) the subquery may not be a join and 3508d981e828Sdrh ** (3b) the FROM clause of the subquery may not contain a virtual 3509d981e828Sdrh ** table and 3510d981e828Sdrh ** (3c) the outer query may not be an aggregate. 3511832508b7Sdrh ** 3512d981e828Sdrh ** (4) The subquery can not be DISTINCT. 3513832508b7Sdrh ** 351449ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 351549ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 351649ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 3517832508b7Sdrh ** 351825c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 351925c221ebSdrh ** If the subquery is aggregate, the outer query may not be DISTINCT. 3520832508b7Sdrh ** 3521d981e828Sdrh ** (7) The subquery must have a FROM clause. TODO: For subqueries without 352231d6fd55Sdrh ** A FROM clause, consider adding a FROM clause with the special 3523630d296cSdrh ** table sqlite_once that consists of a single row containing a 3524630d296cSdrh ** single NULL. 352508192d5fSdrh ** 3526d981e828Sdrh ** (8) If the subquery uses LIMIT then the outer query may not be a join. 3527df199a25Sdrh ** 3528d981e828Sdrh ** (9) If the subquery uses LIMIT then the outer query may not be aggregate. 3529df199a25Sdrh ** 35306092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 35316092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 3532d981e828Sdrh ** constraint: "If the subquery is aggregate then the outer query 3533d981e828Sdrh ** may not use LIMIT." 3534df199a25Sdrh ** 3535d981e828Sdrh ** (11) The subquery and the outer query may not both have ORDER BY clauses. 3536174b6195Sdrh ** 35377b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 35382b300d5dSdrh ** a separate restriction deriving from ticket #350. 35393fc673e6Sdrh ** 3540d981e828Sdrh ** (13) The subquery and outer query may not both use LIMIT. 3541ac83963aSdrh ** 3542d981e828Sdrh ** (14) The subquery may not use OFFSET. 3543ac83963aSdrh ** 3544d981e828Sdrh ** (15) If the outer query is part of a compound select, then the 3545d981e828Sdrh ** subquery may not use LIMIT. 3546f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 3547ad91c6cdSdrh ** 3548d981e828Sdrh ** (16) If the outer query is aggregate, then the subquery may not 3549d981e828Sdrh ** use ORDER BY. (Ticket #2942) This used to not matter 3550c52e355dSdrh ** until we introduced the group_concat() function. 3551c52e355dSdrh ** 3552d981e828Sdrh ** (17) If the subquery is a compound select, then 3553d981e828Sdrh ** (17a) all compound operators must be a UNION ALL, and 3554d981e828Sdrh ** (17b) no terms within the subquery compound may be aggregate 3555e76acc65Sdrh ** or DISTINCT, and 3556d981e828Sdrh ** (17c) every term within the subquery compound must have a FROM clause 3557d981e828Sdrh ** (17d) the outer query may not be 3558d981e828Sdrh ** (17d1) aggregate, or 3559d981e828Sdrh ** (17d2) DISTINCT, or 3560d981e828Sdrh ** (17d3) a join. 3561f23329a2Sdanielk1977 ** 35624914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 35634914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 3564630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 3565630d296cSdrh ** operator other than UNION ALL because all the other compound 3566630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 3567630d296cSdrh ** restriction (4). 3568f23329a2Sdanielk1977 ** 356967c70142Sdan ** Also, each component of the sub-query must return the same number 357067c70142Sdan ** of result columns. This is actually a requirement for any compound 357167c70142Sdan ** SELECT statement, but all the code here does is make sure that no 357267c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 357367c70142Sdan ** syntax error and return a detailed message. 357467c70142Sdan ** 357549fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 3576d981e828Sdrh ** ORDER BY clause of the parent must be simple references to 357749fc1f60Sdanielk1977 ** columns of the sub-query. 357849fc1f60Sdanielk1977 ** 3579d981e828Sdrh ** (19) If the subquery uses LIMIT then the outer query may not 3580229cf702Sdrh ** have a WHERE clause. 3581229cf702Sdrh ** 3582fca23557Sdrh ** (20) If the sub-query is a compound select, then it must not use 3583fca23557Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 3584fca23557Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 3585fca23557Sdrh ** appear as unmodified result columns in the outer query. But we 3586fca23557Sdrh ** have other optimizations in mind to deal with that case. 3587e8902a70Sdrh ** 3588d981e828Sdrh ** (21) If the subquery uses LIMIT then the outer query may not be 3589a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 3590a91491e5Sshaneh ** 3591d981e828Sdrh ** (22) The subquery may not be a recursive CTE. 35928290c2adSdan ** 3593cdb2f607Sdrh ** (**) Subsumed into restriction (17d3). Was: If the outer query is 3594cdb2f607Sdrh ** a recursive CTE, then the sub-query may not be a compound query. 3595cdb2f607Sdrh ** This restriction is because transforming the 35968290c2adSdan ** parent to a compound query confuses the code that handles 35978290c2adSdan ** recursive queries in multiSelect(). 35988290c2adSdan ** 3599508e2d00Sdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 3600508e2d00Sdrh ** The subquery may not be an aggregate that uses the built-in min() or 36019588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 36029588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 36039588ad95Sdrh ** return the value X for which Y was maximal.) 36049588ad95Sdrh ** 36058290c2adSdan ** 3606832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 3607832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 360825c221ebSdrh ** uses aggregates. 3609832508b7Sdrh ** 3610665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 3611832508b7Sdrh ** If flattening is attempted this routine returns 1. 3612832508b7Sdrh ** 3613832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 3614832508b7Sdrh ** the subquery before this routine runs. 36151350b030Sdrh */ 36168c74a8caSdrh static int flattenSubquery( 3617524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 36188c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 36198c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 362025c221ebSdrh int isAgg /* True if outer SELECT uses aggregate functions */ 36218c74a8caSdrh ){ 3622524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 3623d12b6363Sdrh Select *pParent; /* Current UNION ALL term of the other query */ 36240bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 3625f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3626ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 3627ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 36286a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 3629399c7e21Sdrh int iNewParent = -1;/* Replacement table for iParent */ 3630399c7e21Sdrh int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ 363191bb0eedSdrh int i; /* Loop counter */ 363291bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 363391bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 3634524cc21eSdanielk1977 sqlite3 *db = pParse->db; 36351350b030Sdrh 3636832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 3637832508b7Sdrh */ 3638a78c22c4Sdrh assert( p!=0 ); 3639d981e828Sdrh assert( p->pPrior==0 ); 36407e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3641832508b7Sdrh pSrc = p->pSrc; 3642ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 364391bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 364449fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 364591bb0eedSdrh pSub = pSubitem->pSelect; 3646832508b7Sdrh assert( pSub!=0 ); 3647885a5b03Sdrh 3648832508b7Sdrh pSubSrc = pSub->pSrc; 3649832508b7Sdrh assert( pSubSrc ); 3650ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 365160ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3652ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 3653ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 3654ac83963aSdrh ** and (14). */ 3655ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 36568c0833fbSdrh if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ 3657d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3658ad91c6cdSdrh return 0; /* Restriction (15) */ 3659ad91c6cdSdrh } 3660ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 3661d981e828Sdrh if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ 366249ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 366349ad330dSdan return 0; /* Restrictions (8)(9) */ 3664df199a25Sdrh } 36657d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 3666ac83963aSdrh return 0; /* Restriction (11) */ 3667ac83963aSdrh } 3668c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 3669229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 3670a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 3671a91491e5Sshaneh return 0; /* Restriction (21) */ 3672a91491e5Sshaneh } 3673508e2d00Sdrh if( pSub->selFlags & (SF_Recursive) ){ 3674508e2d00Sdrh return 0; /* Restrictions (22) */ 36759588ad95Sdrh } 3676832508b7Sdrh 3677399c7e21Sdrh /* 3678399c7e21Sdrh ** If the subquery is the right operand of a LEFT JOIN, then the 3679d981e828Sdrh ** subquery may not be a join itself (3a). Example of why this is not 3680d981e828Sdrh ** allowed: 36818af4d3acSdrh ** 36828af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 36838af4d3acSdrh ** 36848af4d3acSdrh ** If we flatten the above, we would get 36858af4d3acSdrh ** 36868af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 36878af4d3acSdrh ** 36888af4d3acSdrh ** which is not at all the same thing. 36892b300d5dSdrh ** 36903c790f2aSdrh ** If the subquery is the right operand of a LEFT JOIN, then the outer 3691d981e828Sdrh ** query cannot be an aggregate. (3c) This is an artifact of the way 3692d981e828Sdrh ** aggregates are processed - there is no mechanism to determine if 3693d981e828Sdrh ** the LEFT JOIN table should be all-NULL. 36943c790f2aSdrh ** 369531d6fd55Sdrh ** See also tickets #306, #350, and #3300. 36963fc673e6Sdrh */ 36978a48b9c0Sdrh if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ 3698399c7e21Sdrh isLeftJoin = 1; 369946133d98Sdan if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){ 3700d981e828Sdrh /* (3a) (3c) (3b) */ 3701d981e828Sdrh return 0; 3702399c7e21Sdrh } 37033fc673e6Sdrh } 3704dc6de479Sdrh #ifdef SQLITE_EXTRA_IFNULLROW 3705dc6de479Sdrh else if( iFrom>0 && !isAgg ){ 3706dc6de479Sdrh /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for 37073d240d21Sdrh ** every reference to any result column from subquery in a join, even 37083d240d21Sdrh ** though they are not necessary. This will stress-test the OP_IfNullRow 37093d240d21Sdrh ** opcode. */ 3710dc6de479Sdrh isLeftJoin = -1; 3711dc6de479Sdrh } 3712dc6de479Sdrh #endif 37133fc673e6Sdrh 3714d981e828Sdrh /* Restriction (17): If the sub-query is a compound SELECT, then it must 3715f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 3716f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 3717f23329a2Sdanielk1977 ** queries. 3718f23329a2Sdanielk1977 */ 3719f23329a2Sdanielk1977 if( pSub->pPrior ){ 3720fca23557Sdrh if( pSub->pOrderBy ){ 3721fca23557Sdrh return 0; /* Restriction (20) */ 3722fca23557Sdrh } 3723e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3724d981e828Sdrh return 0; /* (17d1), (17d2), or (17d3) */ 3725f23329a2Sdanielk1977 } 3726f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3727ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3728ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 37294b3ac73cSdrh assert( pSub->pSrc!=0 ); 37302ec18a3cSdrh assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); 3731d981e828Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ 3732d981e828Sdrh || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ 3733d981e828Sdrh || pSub1->pSrc->nSrc<1 /* (17c) */ 373480b3c548Sdanielk1977 ){ 3735f23329a2Sdanielk1977 return 0; 3736f23329a2Sdanielk1977 } 37374b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 3738f23329a2Sdanielk1977 } 373949fc1f60Sdanielk1977 3740d981e828Sdrh /* Restriction (18). */ 374149fc1f60Sdanielk1977 if( p->pOrderBy ){ 374249fc1f60Sdanielk1977 int ii; 374349fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3744c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 374549fc1f60Sdanielk1977 } 374649fc1f60Sdanielk1977 } 3747f23329a2Sdanielk1977 } 3748f23329a2Sdanielk1977 3749cdb2f607Sdrh /* Ex-restriction (23): 3750cdb2f607Sdrh ** The only way that the recursive part of a CTE can contain a compound 3751cdb2f607Sdrh ** subquery is for the subquery to be one term of a join. But if the 3752cdb2f607Sdrh ** subquery is a join, then the flattening has already been stopped by 3753cdb2f607Sdrh ** restriction (17d3) 3754cdb2f607Sdrh */ 3755cdb2f607Sdrh assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 ); 3756cdb2f607Sdrh 37577d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 3758eb9b884cSdrh SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", 3759eb9b884cSdrh pSub->zSelName, pSub, iFrom)); 37607d10d5a6Sdrh 37617d10d5a6Sdrh /* Authorize the subquery */ 3762524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 3763a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 3764a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 3765524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 3766524cc21eSdanielk1977 37677d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 37687d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 37697d10d5a6Sdrh ** be of the form: 3770f23329a2Sdanielk1977 ** 3771f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 3772f23329a2Sdanielk1977 ** 3773f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 3774a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 3775f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 3776f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 3777f23329a2Sdanielk1977 ** select statements in the compound sub-query. 3778a78c22c4Sdrh ** 3779a78c22c4Sdrh ** Example: 3780a78c22c4Sdrh ** 3781a78c22c4Sdrh ** SELECT a+1 FROM ( 3782a78c22c4Sdrh ** SELECT x FROM tab 3783a78c22c4Sdrh ** UNION ALL 3784a78c22c4Sdrh ** SELECT y FROM tab 3785a78c22c4Sdrh ** UNION ALL 3786a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 3787a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 3788a78c22c4Sdrh ** 3789a78c22c4Sdrh ** Transformed into: 3790a78c22c4Sdrh ** 3791a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 3792a78c22c4Sdrh ** UNION ALL 3793a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 3794a78c22c4Sdrh ** UNION ALL 3795a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 3796a78c22c4Sdrh ** ORDER BY 1 3797a78c22c4Sdrh ** 3798a78c22c4Sdrh ** We call this the "compound-subquery flattening". 3799f23329a2Sdanielk1977 */ 3800f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 3801f23329a2Sdanielk1977 Select *pNew; 3802f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 38034b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 3804f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 3805f23329a2Sdanielk1977 p->pOrderBy = 0; 3806f23329a2Sdanielk1977 p->pSrc = 0; 3807f23329a2Sdanielk1977 p->pPrior = 0; 38084b86ef1dSdanielk1977 p->pLimit = 0; 38096ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 3810eb9b884cSdrh sqlite3SelectSetName(pNew, pSub->zSelName); 38114b86ef1dSdanielk1977 p->pLimit = pLimit; 3812a78c22c4Sdrh p->pOrderBy = pOrderBy; 3813a78c22c4Sdrh p->pSrc = pSrc; 3814a78c22c4Sdrh p->op = TK_ALL; 3815a78c22c4Sdrh if( pNew==0 ){ 3816d227a291Sdrh p->pPrior = pPrior; 3817a78c22c4Sdrh }else{ 3818a78c22c4Sdrh pNew->pPrior = pPrior; 3819d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 3820d227a291Sdrh pNew->pNext = p; 3821a78c22c4Sdrh p->pPrior = pNew; 3822eb9b884cSdrh SELECTTRACE(2,pParse,p, 3823eb9b884cSdrh ("compound-subquery flattener creates %s.%p as peer\n", 3824eb9b884cSdrh pNew->zSelName, pNew)); 3825d227a291Sdrh } 3826a78c22c4Sdrh if( db->mallocFailed ) return 1; 3827a78c22c4Sdrh } 3828f23329a2Sdanielk1977 38297d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 38307d10d5a6Sdrh ** in the outer query. 3831832508b7Sdrh */ 3832f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 3833c31c2eb8Sdrh 3834a78c22c4Sdrh /* Delete the transient table structure associated with the 3835a78c22c4Sdrh ** subquery 3836a78c22c4Sdrh */ 3837a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 3838a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 3839a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 3840a78c22c4Sdrh pSubitem->zDatabase = 0; 3841a78c22c4Sdrh pSubitem->zName = 0; 3842a78c22c4Sdrh pSubitem->zAlias = 0; 3843a78c22c4Sdrh pSubitem->pSelect = 0; 3844a78c22c4Sdrh 3845a78c22c4Sdrh /* Defer deleting the Table object associated with the 3846a78c22c4Sdrh ** subquery until code generation is 3847a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 3848a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 3849ccfcbceaSdrh ** 3850ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 3851a78c22c4Sdrh */ 3852ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 3853a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 385479df7782Sdrh if( pTabToDel->nTabRef==1 ){ 385565a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 385665a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 385765a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 3858a78c22c4Sdrh }else{ 385979df7782Sdrh pTabToDel->nTabRef--; 3860a78c22c4Sdrh } 3861a78c22c4Sdrh pSubitem->pTab = 0; 3862a78c22c4Sdrh } 3863a78c22c4Sdrh 3864a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 3865a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 3866a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 3867a78c22c4Sdrh ** then this loop only runs once. 3868a78c22c4Sdrh ** 3869a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 3870c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 3871c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 3872c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 3873c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 3874c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 3875c31c2eb8Sdrh ** elements we are now copying in. 3876c31c2eb8Sdrh */ 3877a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 3878a78c22c4Sdrh int nSubSrc; 3879ea678832Sdrh u8 jointype = 0; 3880a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 3881a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 3882a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 3883588a9a1aSdrh 3884a78c22c4Sdrh if( pSrc ){ 3885a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 38868a48b9c0Sdrh jointype = pSubitem->fg.jointype; 3887588a9a1aSdrh }else{ 3888a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 3889a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 3890cfa063b3Sdrh if( pSrc==0 ){ 3891a78c22c4Sdrh assert( db->mallocFailed ); 3892a78c22c4Sdrh break; 3893cfa063b3Sdrh } 3894c31c2eb8Sdrh } 3895a78c22c4Sdrh 3896a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 3897a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 3898a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 3899a78c22c4Sdrh ** of the subquery. 3900a78c22c4Sdrh ** 3901a78c22c4Sdrh ** Example: 3902a78c22c4Sdrh ** 3903a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 3904a78c22c4Sdrh ** 3905a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 3906a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 3907d12b6363Sdrh ** block of code will expand the outer query FROM clause to 4 slots. 3908d12b6363Sdrh ** The middle slot is expanded to two slots in order to make space 3909d12b6363Sdrh ** for the two elements in the FROM clause of the subquery. 3910a78c22c4Sdrh */ 3911a78c22c4Sdrh if( nSubSrc>1 ){ 3912a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 3913a78c22c4Sdrh if( db->mallocFailed ){ 3914a78c22c4Sdrh break; 3915c31c2eb8Sdrh } 3916c31c2eb8Sdrh } 3917a78c22c4Sdrh 3918a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 3919a78c22c4Sdrh ** outer query. 3920a78c22c4Sdrh */ 3921c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 3922c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 392320292310Sdrh assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); 3924c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 3925399c7e21Sdrh iNewParent = pSubSrc->a[i].iCursor; 3926c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3927c31c2eb8Sdrh } 39288a48b9c0Sdrh pSrc->a[iFrom].fg.jointype = jointype; 3929c31c2eb8Sdrh 3930c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 3931c31c2eb8Sdrh ** references to the iParent in the outer query. 3932c31c2eb8Sdrh ** 3933c31c2eb8Sdrh ** Example: 3934c31c2eb8Sdrh ** 3935c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3936c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 3937c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 3938c31c2eb8Sdrh ** 3939c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 3940c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3941c31c2eb8Sdrh */ 3942174b6195Sdrh if( pSub->pOrderBy ){ 39437c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 39447c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 39457c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 39467c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 39477c0a4720Sdan ** zero them before transfering the ORDER BY clause. 39487c0a4720Sdan ** 39497c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 39507c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 39517c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 39527c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 39537c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 39547c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 39557c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 39567c0a4720Sdan } 3957f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 39587c0a4720Sdan pParent->pOrderBy = pOrderBy; 3959174b6195Sdrh pSub->pOrderBy = 0; 3960174b6195Sdrh } 39616ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3962dc6de479Sdrh if( isLeftJoin>0 ){ 3963399c7e21Sdrh setJoinExpr(pWhere, iNewParent); 3964399c7e21Sdrh } 39654c5ebee0Sdan pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere); 3966c3becddbSdan if( db->mallocFailed==0 ){ 396746967de2Sdrh SubstContext x; 396846967de2Sdrh x.pParse = pParse; 396946967de2Sdrh x.iTable = iParent; 3970399c7e21Sdrh x.iNewTable = iNewParent; 397131d6fd55Sdrh x.isLeftJoin = isLeftJoin; 397246967de2Sdrh x.pEList = pSub->pEList; 397346967de2Sdrh substSelect(&x, pParent, 0); 3974c3becddbSdan } 3975c31c2eb8Sdrh 3976c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3977c31c2eb8Sdrh ** outer query is distinct. 3978c31c2eb8Sdrh */ 39797d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 39808c74a8caSdrh 3981a58fdfb1Sdanielk1977 /* 3982a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3983ac83963aSdrh ** 3984ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3985ac83963aSdrh ** does not work if either limit is negative. 3986a58fdfb1Sdanielk1977 */ 3987a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3988f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3989a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3990df199a25Sdrh } 3991f23329a2Sdanielk1977 } 39928c74a8caSdrh 3993c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3994c31c2eb8Sdrh ** success. 3995c31c2eb8Sdrh */ 3996633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3997f23329a2Sdanielk1977 3998c90713d3Sdrh #if SELECTTRACE_ENABLED 3999c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 4000bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After flattening:\n")); 4001c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4002c90713d3Sdrh } 4003c90713d3Sdrh #endif 4004c90713d3Sdrh 4005832508b7Sdrh return 1; 40061350b030Sdrh } 40073514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 40081350b030Sdrh 400969b72d5aSdrh 401069b72d5aSdrh 401169b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 401269b72d5aSdrh /* 401369b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into 401469b72d5aSdrh ** the WHERE clause of subquery. Example: 401569b72d5aSdrh ** 401669b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; 401769b72d5aSdrh ** 401869b72d5aSdrh ** Transformed into: 401969b72d5aSdrh ** 402069b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) 402169b72d5aSdrh ** WHERE x=5 AND y=10; 402269b72d5aSdrh ** 402369b72d5aSdrh ** The hope is that the terms added to the inner query will make it more 402469b72d5aSdrh ** efficient. 402569b72d5aSdrh ** 402669b72d5aSdrh ** Do not attempt this optimization if: 402769b72d5aSdrh ** 402825c221ebSdrh ** (1) (** This restriction was removed on 2017-09-29. We used to 402925c221ebSdrh ** disallow this optimization for aggregate subqueries, but now 403067cc51a4Sdrh ** it is allowed by putting the extra terms on the HAVING clause. 403167cc51a4Sdrh ** The added HAVING clause is pointless if the subquery lacks 403267cc51a4Sdrh ** a GROUP BY clause. But such a HAVING clause is also harmless 403367cc51a4Sdrh ** so there does not appear to be any reason to add extra logic 403467cc51a4Sdrh ** to suppress it. **) 403569b72d5aSdrh ** 403669b72d5aSdrh ** (2) The inner query is the recursive part of a common table expression. 403769b72d5aSdrh ** 403869b72d5aSdrh ** (3) The inner query has a LIMIT clause (since the changes to the WHERE 403969b72d5aSdrh ** close would change the meaning of the LIMIT). 404069b72d5aSdrh ** 40416a9b9527Sdrh ** (4) The inner query is the right operand of a LEFT JOIN and the 40426a9b9527Sdrh ** expression to be pushed down does not come from the ON clause 40436a9b9527Sdrh ** on that LEFT JOIN. 404469b72d5aSdrh ** 404538978dd4Sdrh ** (5) The WHERE clause expression originates in the ON or USING clause 40467fbb101cSdrh ** of a LEFT JOIN where iCursor is not the right-hand table of that 40477fbb101cSdrh ** left join. An example: 40487fbb101cSdrh ** 40497fbb101cSdrh ** SELECT * 40507fbb101cSdrh ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa 40517fbb101cSdrh ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) 40527fbb101cSdrh ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); 40537fbb101cSdrh ** 40547fbb101cSdrh ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). 40557fbb101cSdrh ** But if the (b2=2) term were to be pushed down into the bb subquery, 40567fbb101cSdrh ** then the (1,1,NULL) row would be suppressed. 405738978dd4Sdrh ** 405869b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause 405969b72d5aSdrh ** terms are duplicated into the subquery. 406069b72d5aSdrh */ 406169b72d5aSdrh static int pushDownWhereTerms( 406244c5604cSdan Parse *pParse, /* Parse context (for malloc() and error reporting) */ 406369b72d5aSdrh Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ 406469b72d5aSdrh Expr *pWhere, /* The WHERE clause of the outer query */ 40656a9b9527Sdrh int iCursor, /* Cursor number of the subquery */ 40666a9b9527Sdrh int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ 406769b72d5aSdrh ){ 406869b72d5aSdrh Expr *pNew; 406969b72d5aSdrh int nChng = 0; 407069b72d5aSdrh if( pWhere==0 ) return 0; 4071508e2d00Sdrh if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ 4072508e2d00Sdrh 4073508e2d00Sdrh #ifdef SQLITE_DEBUG 4074508e2d00Sdrh /* Only the first term of a compound can have a WITH clause. But make 4075508e2d00Sdrh ** sure no other terms are marked SF_Recursive in case something changes 4076508e2d00Sdrh ** in the future. 4077508e2d00Sdrh */ 4078508e2d00Sdrh { 4079508e2d00Sdrh Select *pX; 4080b1ec87afSdrh for(pX=pSubq; pX; pX=pX->pPrior){ 4081508e2d00Sdrh assert( (pX->selFlags & (SF_Recursive))==0 ); 408269b72d5aSdrh } 4083b1ec87afSdrh } 4084508e2d00Sdrh #endif 4085508e2d00Sdrh 408669b72d5aSdrh if( pSubq->pLimit!=0 ){ 408769b72d5aSdrh return 0; /* restriction (3) */ 408869b72d5aSdrh } 408969b72d5aSdrh while( pWhere->op==TK_AND ){ 40906a9b9527Sdrh nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, 40916a9b9527Sdrh iCursor, isLeftJoin); 409269b72d5aSdrh pWhere = pWhere->pLeft; 409369b72d5aSdrh } 40946a9b9527Sdrh if( isLeftJoin 40956a9b9527Sdrh && (ExprHasProperty(pWhere,EP_FromJoin)==0 40966a9b9527Sdrh || pWhere->iRightJoinTable!=iCursor) 40976a9b9527Sdrh ){ 40986a9b9527Sdrh return 0; /* restriction (4) */ 40996a9b9527Sdrh } 41007fbb101cSdrh if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){ 41017fbb101cSdrh return 0; /* restriction (5) */ 41027fbb101cSdrh } 410369b72d5aSdrh if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ 410469b72d5aSdrh nChng++; 410569b72d5aSdrh while( pSubq ){ 410646967de2Sdrh SubstContext x; 410744c5604cSdan pNew = sqlite3ExprDup(pParse->db, pWhere, 0); 41087fbb101cSdrh unsetJoinExpr(pNew, -1); 410946967de2Sdrh x.pParse = pParse; 411046967de2Sdrh x.iTable = iCursor; 4111399c7e21Sdrh x.iNewTable = iCursor; 411231d6fd55Sdrh x.isLeftJoin = 0; 411346967de2Sdrh x.pEList = pSubq->pEList; 411446967de2Sdrh pNew = substExpr(&x, pNew); 411525c221ebSdrh if( pSubq->selFlags & SF_Aggregate ){ 411625c221ebSdrh pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew); 411725c221ebSdrh }else{ 411844c5604cSdan pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew); 411925c221ebSdrh } 412069b72d5aSdrh pSubq = pSubq->pPrior; 412169b72d5aSdrh } 412269b72d5aSdrh } 412369b72d5aSdrh return nChng; 412469b72d5aSdrh } 412569b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 412669b72d5aSdrh 41271350b030Sdrh /* 412847d9f839Sdrh ** The pFunc is the only aggregate function in the query. Check to see 412947d9f839Sdrh ** if the query is a candidate for the min/max optimization. 4130a9d1ccb9Sdanielk1977 ** 413147d9f839Sdrh ** If the query is a candidate for the min/max optimization, then set 413247d9f839Sdrh ** *ppMinMax to be an ORDER BY clause to be used for the optimization 413347d9f839Sdrh ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on 413447d9f839Sdrh ** whether pFunc is a min() or max() function. 4135738bdcfbSdanielk1977 ** 413647d9f839Sdrh ** If the query is not a candidate for the min/max optimization, return 413747d9f839Sdrh ** WHERE_ORDERBY_NORMAL (which must be zero). 41384ac391fcSdan ** 413947d9f839Sdrh ** This routine must be called after aggregate functions have been 414047d9f839Sdrh ** located but before their arguments have been subjected to aggregate 414147d9f839Sdrh ** analysis. 4142a9d1ccb9Sdanielk1977 */ 414347d9f839Sdrh static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ 41444ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 414547d9f839Sdrh ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */ 414647d9f839Sdrh const char *zFunc; /* Name of aggregate function pFunc */ 414747d9f839Sdrh ExprList *pOrderBy; 414847d9f839Sdrh u8 sortOrder; 4149a9d1ccb9Sdanielk1977 415047d9f839Sdrh assert( *ppMinMax==0 ); 415147d9f839Sdrh assert( pFunc->op==TK_AGG_FUNCTION ); 415247d9f839Sdrh if( pEList==0 || pEList->nExpr!=1 ) return eRet; 415347d9f839Sdrh zFunc = pFunc->u.zToken; 41544ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 41554ac391fcSdan eRet = WHERE_ORDERBY_MIN; 415647d9f839Sdrh sortOrder = SQLITE_SO_ASC; 41574ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 41584ac391fcSdan eRet = WHERE_ORDERBY_MAX; 415947d9f839Sdrh sortOrder = SQLITE_SO_DESC; 416047d9f839Sdrh }else{ 416147d9f839Sdrh return eRet; 4162a9d1ccb9Sdanielk1977 } 416347d9f839Sdrh *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0); 416447d9f839Sdrh assert( pOrderBy!=0 || db->mallocFailed ); 416547d9f839Sdrh if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder; 41664ac391fcSdan return eRet; 4167a9d1ccb9Sdanielk1977 } 4168a9d1ccb9Sdanielk1977 4169a9d1ccb9Sdanielk1977 /* 4170a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 417160ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 4172a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 4173a5533162Sdanielk1977 ** 4174a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 4175a5533162Sdanielk1977 ** 4176a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 4177a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 4178a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 4179a5533162Sdanielk1977 */ 4180a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 4181a5533162Sdanielk1977 Table *pTab; 4182a5533162Sdanielk1977 Expr *pExpr; 4183a5533162Sdanielk1977 4184a5533162Sdanielk1977 assert( !p->pGroupBy ); 4185a5533162Sdanielk1977 41867a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 4187a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 4188a5533162Sdanielk1977 ){ 4189a5533162Sdanielk1977 return 0; 4190a5533162Sdanielk1977 } 4191a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 4192a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 419302f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 419402f33725Sdanielk1977 419502f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 4196a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 4197fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 4198d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 4199a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 4200a5533162Sdanielk1977 4201a5533162Sdanielk1977 return pTab; 4202a5533162Sdanielk1977 } 4203a5533162Sdanielk1977 4204a5533162Sdanielk1977 /* 4205b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 4206b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 4207b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 4208b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 4209b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 4210b1c685b0Sdanielk1977 */ 4211b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 42128a48b9c0Sdrh if( pFrom->pTab && pFrom->fg.isIndexedBy ){ 4213b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 42148a48b9c0Sdrh char *zIndexedBy = pFrom->u1.zIndexedBy; 4215b1c685b0Sdanielk1977 Index *pIdx; 4216b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 4217d62fbb50Sdrh pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 4218b1c685b0Sdanielk1977 pIdx=pIdx->pNext 4219b1c685b0Sdanielk1977 ); 4220b1c685b0Sdanielk1977 if( !pIdx ){ 4221d62fbb50Sdrh sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); 42221db95106Sdan pParse->checkSchema = 1; 4223b1c685b0Sdanielk1977 return SQLITE_ERROR; 4224b1c685b0Sdanielk1977 } 42258a48b9c0Sdrh pFrom->pIBIndex = pIdx; 4226b1c685b0Sdanielk1977 } 4227b1c685b0Sdanielk1977 return SQLITE_OK; 4228b1c685b0Sdanielk1977 } 4229c01b7306Sdrh /* 4230c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 4231c01b7306Sdrh ** an alternative collating sequence. 4232c01b7306Sdrh ** 4233c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 4234c01b7306Sdrh ** 4235c01b7306Sdrh ** These are rewritten as a subquery: 4236c01b7306Sdrh ** 4237c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 4238c01b7306Sdrh ** ORDER BY ... COLLATE ... 4239c01b7306Sdrh ** 4240c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 4241c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 4242c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 4243c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 4244c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 4245c01b7306Sdrh ** 4246c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 4247c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 4248c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 4249c01b7306Sdrh */ 4250c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 4251c01b7306Sdrh int i; 4252c01b7306Sdrh Select *pNew; 4253c01b7306Sdrh Select *pX; 4254c01b7306Sdrh sqlite3 *db; 4255c01b7306Sdrh struct ExprList_item *a; 4256c01b7306Sdrh SrcList *pNewSrc; 4257c01b7306Sdrh Parse *pParse; 4258c01b7306Sdrh Token dummy; 4259c01b7306Sdrh 4260c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 4261c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 4262c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 4263c01b7306Sdrh if( pX==0 ) return WRC_Continue; 4264c01b7306Sdrh a = p->pOrderBy->a; 4265c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 4266c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 4267c01b7306Sdrh } 4268c01b7306Sdrh if( i<0 ) return WRC_Continue; 4269c01b7306Sdrh 4270c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 4271c01b7306Sdrh 4272c01b7306Sdrh pParse = pWalker->pParse; 4273c01b7306Sdrh db = pParse->db; 4274c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 4275c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 4276c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 4277c01b7306Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 4278c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 4279c01b7306Sdrh *pNew = *p; 4280c01b7306Sdrh p->pSrc = pNewSrc; 42811a1d3cd2Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); 4282c01b7306Sdrh p->op = TK_SELECT; 4283c01b7306Sdrh p->pWhere = 0; 4284c01b7306Sdrh pNew->pGroupBy = 0; 4285c01b7306Sdrh pNew->pHaving = 0; 4286c01b7306Sdrh pNew->pOrderBy = 0; 4287c01b7306Sdrh p->pPrior = 0; 42888af9ad95Sdrh p->pNext = 0; 4289f932f714Sdrh p->pWith = 0; 42908af9ad95Sdrh p->selFlags &= ~SF_Compound; 4291b33c50f2Sdan assert( (p->selFlags & SF_Converted)==0 ); 4292b33c50f2Sdan p->selFlags |= SF_Converted; 4293a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 4294a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 4295c01b7306Sdrh pNew->pLimit = 0; 4296c01b7306Sdrh return WRC_Continue; 4297c01b7306Sdrh } 4298b1c685b0Sdanielk1977 429920292310Sdrh /* 430020292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function 430120292310Sdrh ** arguments. If it does, leave an error message in pParse and return 430220292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function. 430320292310Sdrh */ 430420292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ 430520292310Sdrh if( pFrom->fg.isTabFunc ){ 430620292310Sdrh sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); 430720292310Sdrh return 1; 430820292310Sdrh } 430920292310Sdrh return 0; 431020292310Sdrh } 431120292310Sdrh 4312eede6a53Sdan #ifndef SQLITE_OMIT_CTE 4313eede6a53Sdan /* 4314eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 4315eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 4316eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 4317eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 4318eede6a53Sdan ** return NULL. 431998f45e53Sdan ** 432098f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 432198f45e53Sdan ** object that the returned CTE belongs to. 432260c1a2f0Sdrh */ 432398f45e53Sdan static struct Cte *searchWith( 43242476a6f2Sdrh With *pWith, /* Current innermost WITH clause */ 432598f45e53Sdan struct SrcList_item *pItem, /* FROM clause element to resolve */ 432698f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 432798f45e53Sdan ){ 43287b19f252Sdrh const char *zName; 43297b19f252Sdrh if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 4330eede6a53Sdan With *p; 4331eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 43324e9119d9Sdan int i; 4333eede6a53Sdan for(i=0; i<p->nCte; i++){ 4334eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 433598f45e53Sdan *ppContext = p; 4336eede6a53Sdan return &p->a[i]; 43374e9119d9Sdan } 43384e9119d9Sdan } 43394e9119d9Sdan } 43404e9119d9Sdan } 43414e9119d9Sdan return 0; 43424e9119d9Sdan } 43434e9119d9Sdan 4344c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 4345c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 4346c49832c2Sdrh ** 4347b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 4348b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 4349b290f117Sdan ** WITH clause will never be popped from the stack. In this case it 4350b290f117Sdan ** should be freed along with the Parse object. In other cases, when 4351b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 4352b290f117Sdan ** statement with which it is associated. 4353c49832c2Sdrh */ 4354b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 43556e772266Sdrh assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); 43564e9119d9Sdan if( pWith ){ 43572476a6f2Sdrh assert( pParse->pWith!=pWith ); 43584e9119d9Sdan pWith->pOuter = pParse->pWith; 43594e9119d9Sdan pParse->pWith = pWith; 43606e772266Sdrh if( bFree ) pParse->pWithToFree = pWith; 43614e9119d9Sdan } 43624e9119d9Sdan } 43634e9119d9Sdan 4364eede6a53Sdan /* 4365eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 4366eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And, 4367eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive 4368eede6a53Sdan ** reference to the current CTE. 4369eede6a53Sdan ** 4370eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab 4371eede6a53Sdan ** and other fields are populated accordingly. The caller should check 4372eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match 4373eede6a53Sdan ** was found. 4374eede6a53Sdan ** 4375eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error 4376eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the 4377eede6a53Sdan ** parser and some error code other than SQLITE_OK returned. 4378eede6a53Sdan */ 43798ce7184bSdan static int withExpand( 43808ce7184bSdan Walker *pWalker, 4381eede6a53Sdan struct SrcList_item *pFrom 43828ce7184bSdan ){ 43838ce7184bSdan Parse *pParse = pWalker->pParse; 43848ce7184bSdan sqlite3 *db = pParse->db; 438598f45e53Sdan struct Cte *pCte; /* Matched CTE (or NULL if no match) */ 438698f45e53Sdan With *pWith; /* WITH clause that pCte belongs to */ 43878ce7184bSdan 43888ce7184bSdan assert( pFrom->pTab==0 ); 43898ce7184bSdan 439098f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 4391eae73fbfSdan if( pCte ){ 439298f45e53Sdan Table *pTab; 43938ce7184bSdan ExprList *pEList; 43948ce7184bSdan Select *pSel; 439560e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 4396f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 439798f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 4398f2655fe8Sdan 43990576bc59Sdrh /* If pCte->zCteErr is non-NULL at this point, then this is an illegal 4400f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 44010576bc59Sdrh ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. 4402f2655fe8Sdan ** In this case, proceed. */ 44030576bc59Sdrh if( pCte->zCteErr ){ 44040576bc59Sdrh sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); 440598f45e53Sdan return SQLITE_ERROR; 4406f2655fe8Sdan } 440720292310Sdrh if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; 44088ce7184bSdan 4409c25e2ebcSdrh assert( pFrom->pTab==0 ); 44108ce7184bSdan pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 44118ce7184bSdan if( pTab==0 ) return WRC_Abort; 441279df7782Sdrh pTab->nTabRef = 1; 44132d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 44148ce7184bSdan pTab->iPKey = -1; 4415cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4416fccda8a1Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 44178ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 4418fad3039cSmistachkin if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; 44198ce7184bSdan assert( pFrom->pSelect ); 44208ce7184bSdan 4421eae73fbfSdan /* Check if this is a recursive CTE. */ 44228ce7184bSdan pSel = pFrom->pSelect; 4423f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 4424f2655fe8Sdan if( bMayRecursive ){ 4425eae73fbfSdan int i; 4426eae73fbfSdan SrcList *pSrc = pFrom->pSelect->pSrc; 4427eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 4428eae73fbfSdan struct SrcList_item *pItem = &pSrc->a[i]; 4429eae73fbfSdan if( pItem->zDatabase==0 4430eae73fbfSdan && pItem->zName!=0 4431eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4432eae73fbfSdan ){ 4433eae73fbfSdan pItem->pTab = pTab; 44348a48b9c0Sdrh pItem->fg.isRecursive = 1; 443579df7782Sdrh pTab->nTabRef++; 4436eae73fbfSdan pSel->selFlags |= SF_Recursive; 44378ce7184bSdan } 4438eae73fbfSdan } 4439eae73fbfSdan } 4440eae73fbfSdan 4441eae73fbfSdan /* Only one recursive reference is permitted. */ 444279df7782Sdrh if( pTab->nTabRef>2 ){ 4443eae73fbfSdan sqlite3ErrorMsg( 4444727a99f1Sdrh pParse, "multiple references to recursive table: %s", pCte->zName 4445eae73fbfSdan ); 444698f45e53Sdan return SQLITE_ERROR; 4447eae73fbfSdan } 44483d240d21Sdrh assert( pTab->nTabRef==1 || 44493d240d21Sdrh ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); 4450eae73fbfSdan 44510576bc59Sdrh pCte->zCteErr = "circular reference: %s"; 445298f45e53Sdan pSavedWith = pParse->pWith; 445398f45e53Sdan pParse->pWith = pWith; 4454067cd837Sdan if( bMayRecursive ){ 4455067cd837Sdan Select *pPrior = pSel->pPrior; 4456067cd837Sdan assert( pPrior->pWith==0 ); 4457067cd837Sdan pPrior->pWith = pSel->pWith; 4458067cd837Sdan sqlite3WalkSelect(pWalker, pPrior); 4459067cd837Sdan pPrior->pWith = 0; 4460067cd837Sdan }else{ 4461067cd837Sdan sqlite3WalkSelect(pWalker, pSel); 4462067cd837Sdan } 44636e772266Sdrh pParse->pWith = pWith; 44648ce7184bSdan 44658ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 44668ce7184bSdan pEList = pLeft->pEList; 446760e7068dSdan if( pCte->pCols ){ 44688f9d0b2bSdrh if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ 4469727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 447060e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 447160e7068dSdan ); 447298f45e53Sdan pParse->pWith = pSavedWith; 447398f45e53Sdan return SQLITE_ERROR; 44748ce7184bSdan } 447560e7068dSdan pEList = pCte->pCols; 447660e7068dSdan } 44778ce7184bSdan 44788981b904Sdrh sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4479f2655fe8Sdan if( bMayRecursive ){ 4480f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 44810576bc59Sdrh pCte->zCteErr = "multiple recursive references: %s"; 4482f2655fe8Sdan }else{ 44830576bc59Sdrh pCte->zCteErr = "recursive reference in a subquery: %s"; 4484f2655fe8Sdan } 4485f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 4486f2655fe8Sdan } 44870576bc59Sdrh pCte->zCteErr = 0; 448898f45e53Sdan pParse->pWith = pSavedWith; 44898ce7184bSdan } 44908ce7184bSdan 44918ce7184bSdan return SQLITE_OK; 44928ce7184bSdan } 4493eede6a53Sdan #endif 44944e9119d9Sdan 4495b290f117Sdan #ifndef SQLITE_OMIT_CTE 449671856944Sdan /* 449771856944Sdan ** If the SELECT passed as the second argument has an associated WITH 449871856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 449971856944Sdan ** 450071856944Sdan ** This function is used as the xSelectCallback2() callback by 450171856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 450271856944Sdan ** names and other FROM clause elements. 450371856944Sdan */ 4504b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){ 4505b290f117Sdan Parse *pParse = pWalker->pParse; 45062f65b2f5Sdrh if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ 4507d227a291Sdrh With *pWith = findRightmost(p)->pWith; 4508d227a291Sdrh if( pWith!=0 ){ 4509d227a291Sdrh assert( pParse->pWith==pWith ); 4510d227a291Sdrh pParse->pWith = pWith->pOuter; 4511b290f117Sdan } 4512b290f117Sdan } 4513067cd837Sdan } 4514b290f117Sdan #else 4515b290f117Sdan #define selectPopWith 0 4516b290f117Sdan #endif 4517b290f117Sdan 4518b1c685b0Sdanielk1977 /* 45197d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 45207d10d5a6Sdrh ** "Expanding" means to do the following: 45217d10d5a6Sdrh ** 45227d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 45237d10d5a6Sdrh ** element of the FROM clause. 45247d10d5a6Sdrh ** 45257d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 45267d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 45277d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 45287d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 45297d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 453060ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 45317d10d5a6Sdrh ** of the view. 45327d10d5a6Sdrh ** 453360ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 45347d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 45357d10d5a6Sdrh ** 45367d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 45377d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 45387d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 45397d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 45407d10d5a6Sdrh ** 4541b3bce662Sdanielk1977 */ 45427d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 45437d10d5a6Sdrh Parse *pParse = pWalker->pParse; 45447d10d5a6Sdrh int i, j, k; 45457d10d5a6Sdrh SrcList *pTabList; 45467d10d5a6Sdrh ExprList *pEList; 45477d10d5a6Sdrh struct SrcList_item *pFrom; 45487d10d5a6Sdrh sqlite3 *db = pParse->db; 45493e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 4550785097daSdrh u16 selFlags = p->selFlags; 4551fca23557Sdrh u32 elistFlags = 0; 45527d10d5a6Sdrh 4553785097daSdrh p->selFlags |= SF_Expanded; 45547d10d5a6Sdrh if( db->mallocFailed ){ 45557d10d5a6Sdrh return WRC_Abort; 45567d10d5a6Sdrh } 45579d9c41e2Sdrh assert( p->pSrc!=0 ); 45589d9c41e2Sdrh if( (selFlags & SF_Expanded)!=0 ){ 45597d10d5a6Sdrh return WRC_Prune; 45607d10d5a6Sdrh } 45617d10d5a6Sdrh pTabList = p->pSrc; 45627d10d5a6Sdrh pEList = p->pEList; 4563067cd837Sdan sqlite3WithPush(pParse, p->pWith, 0); 45647d10d5a6Sdrh 45657d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 45667d10d5a6Sdrh ** the FROM clause of the SELECT statement. 45677d10d5a6Sdrh */ 45687d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 45697d10d5a6Sdrh 45707d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 45717d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 45727d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 45737d10d5a6Sdrh */ 45747d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 45757d10d5a6Sdrh Table *pTab; 4576e2b7d7a0Sdrh assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); 45778a48b9c0Sdrh if( pFrom->fg.isRecursive ) continue; 4578e2b7d7a0Sdrh assert( pFrom->pTab==0 ); 45794e9119d9Sdan #ifndef SQLITE_OMIT_CTE 4580eede6a53Sdan if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4581eede6a53Sdan if( pFrom->pTab ) {} else 45824e9119d9Sdan #endif 45837d10d5a6Sdrh if( pFrom->zName==0 ){ 45847d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 45857d10d5a6Sdrh Select *pSel = pFrom->pSelect; 45867d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 45877d10d5a6Sdrh assert( pSel!=0 ); 45887d10d5a6Sdrh assert( pFrom->pTab==0 ); 45892b8c5a00Sdrh if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; 45907d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 45917d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 459279df7782Sdrh pTab->nTabRef = 1; 459323768298Sdrh if( pFrom->zAlias ){ 459423768298Sdrh pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias); 459523768298Sdrh }else{ 459623768298Sdrh pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab); 459723768298Sdrh } 45987d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 45998981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); 46007d10d5a6Sdrh pTab->iPKey = -1; 4601cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 46027d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 46037d10d5a6Sdrh #endif 46047d10d5a6Sdrh }else{ 46057d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 46067d10d5a6Sdrh assert( pFrom->pTab==0 ); 460741fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 46087d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 460979df7782Sdrh if( pTab->nTabRef>=0xffff ){ 4610d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 4611d2a56238Sdrh pTab->zName); 4612d2a56238Sdrh pFrom->pTab = 0; 4613d2a56238Sdrh return WRC_Abort; 4614d2a56238Sdrh } 461579df7782Sdrh pTab->nTabRef++; 461620292310Sdrh if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ 461720292310Sdrh return WRC_Abort; 461820292310Sdrh } 46197d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 462020292310Sdrh if( IsVirtual(pTab) || pTab->pSelect ){ 4621bfad7be7Sdrh i16 nCol; 46227d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 462343152cf8Sdrh assert( pFrom->pSelect==0 ); 46246ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 4625eb9b884cSdrh sqlite3SelectSetName(pFrom->pSelect, pTab->zName); 4626bfad7be7Sdrh nCol = pTab->nCol; 4627bfad7be7Sdrh pTab->nCol = -1; 46287d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 4629bfad7be7Sdrh pTab->nCol = nCol; 46307d10d5a6Sdrh } 46317d10d5a6Sdrh #endif 46327d10d5a6Sdrh } 463385574e31Sdanielk1977 463485574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 4635b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 463685574e31Sdanielk1977 return WRC_Abort; 463785574e31Sdanielk1977 } 46387d10d5a6Sdrh } 46397d10d5a6Sdrh 46407d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 46417d10d5a6Sdrh */ 46427d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 46437d10d5a6Sdrh return WRC_Abort; 46447d10d5a6Sdrh } 46457d10d5a6Sdrh 46467d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 46477d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 46487d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 46491a1d3cd2Sdrh ** with the TK_ASTERISK operator for each "*" that it found in the column 46501a1d3cd2Sdrh ** list. The following code just has to locate the TK_ASTERISK 46511a1d3cd2Sdrh ** expressions and expand each one to the list of all columns in 46521a1d3cd2Sdrh ** all tables. 46537d10d5a6Sdrh ** 46547d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 46557d10d5a6Sdrh ** that need expanding. 46567d10d5a6Sdrh */ 46577d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 46583e3f1a5bSdrh pE = pEList->a[k].pExpr; 46591a1d3cd2Sdrh if( pE->op==TK_ASTERISK ) break; 466043152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 466143152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 46621a1d3cd2Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; 4663fca23557Sdrh elistFlags |= pE->flags; 46647d10d5a6Sdrh } 46657d10d5a6Sdrh if( k<pEList->nExpr ){ 46667d10d5a6Sdrh /* 46677d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 46687d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 46697d10d5a6Sdrh ** in the result set and expand them one by one. 46707d10d5a6Sdrh */ 46717d10d5a6Sdrh struct ExprList_item *a = pEList->a; 46727d10d5a6Sdrh ExprList *pNew = 0; 46737d10d5a6Sdrh int flags = pParse->db->flags; 46747d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 467538b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 467638b384a0Sdrh 46777d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 46783e3f1a5bSdrh pE = a[k].pExpr; 4679fca23557Sdrh elistFlags |= pE->flags; 46803e3f1a5bSdrh pRight = pE->pRight; 46813e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 46821a1d3cd2Sdrh if( pE->op!=TK_ASTERISK 46831a1d3cd2Sdrh && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) 46841a1d3cd2Sdrh ){ 46857d10d5a6Sdrh /* This particular expression does not need to be expanded. 46867d10d5a6Sdrh */ 4687b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 46887d10d5a6Sdrh if( pNew ){ 46897d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 4690b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 4691b7916a78Sdrh a[k].zName = 0; 4692b7916a78Sdrh a[k].zSpan = 0; 46937d10d5a6Sdrh } 46947d10d5a6Sdrh a[k].pExpr = 0; 46957d10d5a6Sdrh }else{ 46967d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 46977d10d5a6Sdrh ** expanded. */ 46987d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 46993e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 470043152cf8Sdrh if( pE->op==TK_DOT ){ 470143152cf8Sdrh assert( pE->pLeft!=0 ); 470233e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 470333e619fcSdrh zTName = pE->pLeft->u.zToken; 47047d10d5a6Sdrh } 47057d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 47067d10d5a6Sdrh Table *pTab = pFrom->pTab; 47073e3f1a5bSdrh Select *pSub = pFrom->pSelect; 47087d10d5a6Sdrh char *zTabName = pFrom->zAlias; 47093e3f1a5bSdrh const char *zSchemaName = 0; 4710c75e09c7Sdrh int iDb; 471143152cf8Sdrh if( zTabName==0 ){ 47127d10d5a6Sdrh zTabName = pTab->zName; 47137d10d5a6Sdrh } 47147d10d5a6Sdrh if( db->mallocFailed ) break; 47153e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 47163e3f1a5bSdrh pSub = 0; 47177d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 47187d10d5a6Sdrh continue; 47197d10d5a6Sdrh } 47203e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 472169c33826Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; 47223e3f1a5bSdrh } 47237d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 47247d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 4725b7916a78Sdrh char *zColname; /* The computed column name */ 4726b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 4727b7916a78Sdrh Token sColname; /* Computed column name as a token */ 47287d10d5a6Sdrh 4729c75e09c7Sdrh assert( zName ); 47303e3f1a5bSdrh if( zTName && pSub 47313e3f1a5bSdrh && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 47323e3f1a5bSdrh ){ 47333e3f1a5bSdrh continue; 47343e3f1a5bSdrh } 47353e3f1a5bSdrh 473680090f92Sdrh /* If a column is marked as 'hidden', omit it from the expanded 473780090f92Sdrh ** result-set list unless the SELECT has the SF_IncludeHidden 473880090f92Sdrh ** bit set. 47397d10d5a6Sdrh */ 474080090f92Sdrh if( (p->selFlags & SF_IncludeHidden)==0 474180090f92Sdrh && IsHiddenColumn(&pTab->aCol[j]) 474280090f92Sdrh ){ 47437d10d5a6Sdrh continue; 47447d10d5a6Sdrh } 47453e3f1a5bSdrh tableSeen = 1; 47467d10d5a6Sdrh 4747da55c48aSdrh if( i>0 && zTName==0 ){ 47488a48b9c0Sdrh if( (pFrom->fg.jointype & JT_NATURAL)!=0 47492179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 47502179b434Sdrh ){ 47517d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 47522179b434Sdrh ** table to the right of the join */ 47537d10d5a6Sdrh continue; 47547d10d5a6Sdrh } 47552179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 47567d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 47577d10d5a6Sdrh ** using clause from the table on the right. */ 47587d10d5a6Sdrh continue; 47597d10d5a6Sdrh } 47607d10d5a6Sdrh } 4761b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 4762b7916a78Sdrh zColname = zName; 4763b7916a78Sdrh zToFree = 0; 47647d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 4765b7916a78Sdrh Expr *pLeft; 4766b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 4767abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); 476838b384a0Sdrh if( zSchemaName ){ 4769c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 4770abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); 4771c75e09c7Sdrh } 4772b7916a78Sdrh if( longNames ){ 4773b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 4774b7916a78Sdrh zToFree = zColname; 4775b7916a78Sdrh } 47767d10d5a6Sdrh }else{ 47777d10d5a6Sdrh pExpr = pRight; 47787d10d5a6Sdrh } 4779b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 478040aced5cSdrh sqlite3TokenInit(&sColname, zColname); 4781b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 47828f25d18bSdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ 47833e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 47843e3f1a5bSdrh if( pSub ){ 47853e3f1a5bSdrh pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); 4786c75e09c7Sdrh testcase( pX->zSpan==0 ); 47873e3f1a5bSdrh }else{ 47883e3f1a5bSdrh pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", 47893e3f1a5bSdrh zSchemaName, zTabName, zColname); 4790c75e09c7Sdrh testcase( pX->zSpan==0 ); 47913e3f1a5bSdrh } 47923e3f1a5bSdrh pX->bSpanIsTab = 1; 47938f25d18bSdrh } 4794b7916a78Sdrh sqlite3DbFree(db, zToFree); 47957d10d5a6Sdrh } 47967d10d5a6Sdrh } 47977d10d5a6Sdrh if( !tableSeen ){ 47987d10d5a6Sdrh if( zTName ){ 47997d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 48007d10d5a6Sdrh }else{ 48017d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 48027d10d5a6Sdrh } 48037d10d5a6Sdrh } 48047d10d5a6Sdrh } 48057d10d5a6Sdrh } 48067d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 48077d10d5a6Sdrh p->pEList = pNew; 48087d10d5a6Sdrh } 4809fca23557Sdrh if( p->pEList ){ 4810fca23557Sdrh if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 48117d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 48128836cbbcSdan return WRC_Abort; 48137d10d5a6Sdrh } 4814fca23557Sdrh if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ 4815fca23557Sdrh p->selFlags |= SF_ComplexResult; 4816fca23557Sdrh } 4817fca23557Sdrh } 48187d10d5a6Sdrh return WRC_Continue; 48197d10d5a6Sdrh } 48207d10d5a6Sdrh 48217d10d5a6Sdrh /* 48227d10d5a6Sdrh ** No-op routine for the parse-tree walker. 48237d10d5a6Sdrh ** 48247d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 48257d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 48267d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 48277d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 48287d10d5a6Sdrh ** subquery in the parser tree. 48297d10d5a6Sdrh */ 48305b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 483162c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 48327d10d5a6Sdrh return WRC_Continue; 48337d10d5a6Sdrh } 48347d10d5a6Sdrh 48357d10d5a6Sdrh /* 4836979dd1beSdrh ** No-op routine for the parse-tree walker for SELECT statements. 4837979dd1beSdrh ** subquery in the parser tree. 4838979dd1beSdrh */ 4839979dd1beSdrh int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){ 4840979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 4841979dd1beSdrh return WRC_Continue; 4842979dd1beSdrh } 4843979dd1beSdrh 4844979dd1beSdrh #if SQLITE_DEBUG 4845979dd1beSdrh /* 4846979dd1beSdrh ** Always assert. This xSelectCallback2 implementation proves that the 4847979dd1beSdrh ** xSelectCallback2 is never invoked. 4848979dd1beSdrh */ 4849979dd1beSdrh void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ 4850979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 4851979dd1beSdrh assert( 0 ); 4852979dd1beSdrh } 4853979dd1beSdrh #endif 4854979dd1beSdrh /* 48557d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 48567d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 48577d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 48587d10d5a6Sdrh ** 48597d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 48607d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 48617d10d5a6Sdrh ** name resolution is performed. 48627d10d5a6Sdrh ** 48637d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 48647d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 48657d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 48667d10d5a6Sdrh */ 48677d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 48687d10d5a6Sdrh Walker w; 48695b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 48707d10d5a6Sdrh w.pParse = pParse; 4871878fcf9dSdrh if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ 4872d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 4873979dd1beSdrh w.xSelectCallback2 = 0; 48747d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 4875d58d3278Sdrh } 4876c01b7306Sdrh w.xSelectCallback = selectExpander; 4877b290f117Sdan w.xSelectCallback2 = selectPopWith; 4878c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 48797d10d5a6Sdrh } 48807d10d5a6Sdrh 48817d10d5a6Sdrh 48827d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 48837d10d5a6Sdrh /* 48847d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 48857d10d5a6Sdrh ** interface. 48867d10d5a6Sdrh ** 48877d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 48887d10d5a6Sdrh ** information to the Table structure that represents the result set 48897d10d5a6Sdrh ** of that subquery. 48907d10d5a6Sdrh ** 48917d10d5a6Sdrh ** The Table structure that represents the result set was constructed 48927d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 48937d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 48947d10d5a6Sdrh ** routine is called after identifier resolution. 48957d10d5a6Sdrh */ 4896b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 48977d10d5a6Sdrh Parse *pParse; 48987d10d5a6Sdrh int i; 48997d10d5a6Sdrh SrcList *pTabList; 49007d10d5a6Sdrh struct SrcList_item *pFrom; 49017d10d5a6Sdrh 49029d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 4903e2b7d7a0Sdrh assert( (p->selFlags & SF_HasTypeInfo)==0 ); 49047d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 49057d10d5a6Sdrh pParse = pWalker->pParse; 49067d10d5a6Sdrh pTabList = p->pSrc; 49077d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 49087d10d5a6Sdrh Table *pTab = pFrom->pTab; 4909e2b7d7a0Sdrh assert( pTab!=0 ); 4910e2b7d7a0Sdrh if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ 49117d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 49127d10d5a6Sdrh Select *pSel = pFrom->pSelect; 49138ce7184bSdan if( pSel ){ 49147d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 4915ed06a131Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel); 49167d10d5a6Sdrh } 49177d10d5a6Sdrh } 49185a29d9cbSdrh } 49198ce7184bSdan } 49207d10d5a6Sdrh #endif 49217d10d5a6Sdrh 49227d10d5a6Sdrh 49237d10d5a6Sdrh /* 49247d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 49257d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 49267d10d5a6Sdrh ** SELECT statement. 49277d10d5a6Sdrh ** 49287d10d5a6Sdrh ** Use this routine after name resolution. 49297d10d5a6Sdrh */ 49307d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 49317d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 49327d10d5a6Sdrh Walker w; 4933979dd1beSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 4934b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 49355b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 49367d10d5a6Sdrh w.pParse = pParse; 49377d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 49387d10d5a6Sdrh #endif 49397d10d5a6Sdrh } 49407d10d5a6Sdrh 49417d10d5a6Sdrh 49427d10d5a6Sdrh /* 4943030796dfSdrh ** This routine sets up a SELECT statement for processing. The 49447d10d5a6Sdrh ** following is accomplished: 49457d10d5a6Sdrh ** 49467d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 49477d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 49487d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 49497d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 49507d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 49517d10d5a6Sdrh ** 49527d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 49537d10d5a6Sdrh */ 49547d10d5a6Sdrh void sqlite3SelectPrep( 4955b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 4956b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 49577d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 4958b3bce662Sdanielk1977 ){ 4959e2463398Sdrh assert( p!=0 || pParse->db->mallocFailed ); 4960e2463398Sdrh if( pParse->db->mallocFailed ) return; 49617d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 49627d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 4963b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 49647d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 4965b7651e6bSdrh if( pParse->nErr || pParse->db->mallocFailed ) return; 49667d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 4967f6bbe022Sdrh } 4968b3bce662Sdanielk1977 4969b3bce662Sdanielk1977 /* 497013449892Sdrh ** Reset the aggregate accumulator. 497113449892Sdrh ** 497213449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 497313449892Sdrh ** intermediate results while calculating an aggregate. This 4974030796dfSdrh ** routine generates code that stores NULLs in all of those memory 4975030796dfSdrh ** cells. 4976b3bce662Sdanielk1977 */ 497713449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 497813449892Sdrh Vdbe *v = pParse->pVdbe; 497913449892Sdrh int i; 4980c99130fdSdrh struct AggInfo_func *pFunc; 49817e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 49827e61d18eSdrh if( nReg==0 ) return; 49837e61d18eSdrh #ifdef SQLITE_DEBUG 49847e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 49857e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 49867e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 498713449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 49887e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 49897e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 499013449892Sdrh } 49917e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 49927e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 49937e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 49947e61d18eSdrh } 49957e61d18eSdrh #endif 49967e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 4997c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 4998c99130fdSdrh if( pFunc->iDistinct>=0 ){ 4999c99130fdSdrh Expr *pE = pFunc->pExpr; 50006ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 50016ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 50020daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 50030daa002cSdrh "argument"); 5004c99130fdSdrh pFunc->iDistinct = -1; 5005c99130fdSdrh }else{ 5006079a3072Sdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0); 500766a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 50082ec2fb22Sdrh (char*)pKeyInfo, P4_KEYINFO); 5009c99130fdSdrh } 5010c99130fdSdrh } 501113449892Sdrh } 5012b3bce662Sdanielk1977 } 5013b3bce662Sdanielk1977 5014b3bce662Sdanielk1977 /* 501513449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 501613449892Sdrh ** in the AggInfo structure. 5017b3bce662Sdanielk1977 */ 501813449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 501913449892Sdrh Vdbe *v = pParse->pVdbe; 502013449892Sdrh int i; 502113449892Sdrh struct AggInfo_func *pF; 502213449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 50236ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 50246ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 50252700acaaSdrh sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); 50262700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5027b3bce662Sdanielk1977 } 502813449892Sdrh } 502913449892Sdrh 503013449892Sdrh /* 503113449892Sdrh ** Update the accumulator memory cells for an aggregate based on 503213449892Sdrh ** the current cursor position. 503313449892Sdrh */ 503413449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 503513449892Sdrh Vdbe *v = pParse->pVdbe; 503613449892Sdrh int i; 50377a95789cSdrh int regHit = 0; 50387a95789cSdrh int addrHitTest = 0; 503913449892Sdrh struct AggInfo_func *pF; 504013449892Sdrh struct AggInfo_col *pC; 504113449892Sdrh 504213449892Sdrh pAggInfo->directMode = 1; 504313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 504413449892Sdrh int nArg; 5045c99130fdSdrh int addrNext = 0; 504698757157Sdrh int regAgg; 50476ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 50486ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 504913449892Sdrh if( pList ){ 505013449892Sdrh nArg = pList->nExpr; 5051892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 50525579d59fSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); 505313449892Sdrh }else{ 505413449892Sdrh nArg = 0; 505598757157Sdrh regAgg = 0; 505613449892Sdrh } 5057c99130fdSdrh if( pF->iDistinct>=0 ){ 5058c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 50597c052da5Sdrh testcase( nArg==0 ); /* Error condition */ 50607c052da5Sdrh testcase( nArg>1 ); /* Also an error */ 50612dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 5062c99130fdSdrh } 5063d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 506413449892Sdrh CollSeq *pColl = 0; 506513449892Sdrh struct ExprList_item *pItem; 506613449892Sdrh int j; 5067e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 506843617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 506913449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 507013449892Sdrh } 507113449892Sdrh if( !pColl ){ 507213449892Sdrh pColl = pParse->db->pDfltColl; 507313449892Sdrh } 50747a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 50757a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 507613449892Sdrh } 50772700acaaSdrh sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem); 50782700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 5079ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 5080da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 5081f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 5082c99130fdSdrh if( addrNext ){ 5083c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 5084ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5085c99130fdSdrh } 508613449892Sdrh } 508767a6a40cSdan 508867a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 508967a6a40cSdan ** Otherwise, if any of the required column values are already present 509067a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 509167a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 509267a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 509367a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 509467a6a40cSdan ** 509567a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 509667a6a40cSdan ** values to an OP_Copy. 509767a6a40cSdan */ 50987a95789cSdrh if( regHit ){ 5099688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 51007a95789cSdrh } 510167a6a40cSdan sqlite3ExprCacheClear(pParse); 510213449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 5103389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 510413449892Sdrh } 510513449892Sdrh pAggInfo->directMode = 0; 5106ceea3321Sdrh sqlite3ExprCacheClear(pParse); 51077a95789cSdrh if( addrHitTest ){ 51087a95789cSdrh sqlite3VdbeJumpHere(v, addrHitTest); 51097a95789cSdrh } 511013449892Sdrh } 511113449892Sdrh 5112b3bce662Sdanielk1977 /* 5113ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 5114ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 5115ef7075deSdan */ 5116ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 5117ef7075deSdan static void explainSimpleCount( 5118ef7075deSdan Parse *pParse, /* Parse context */ 5119ef7075deSdan Table *pTab, /* Table being queried */ 5120ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 5121ef7075deSdan ){ 5122ef7075deSdan if( pParse->explain==2 ){ 512348dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 51248a4380d7Sdrh char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", 5125ef7075deSdan pTab->zName, 5126e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 5127e96f2df3Sdan bCover ? pIdx->zName : "" 5128ef7075deSdan ); 5129ef7075deSdan sqlite3VdbeAddOp4( 5130ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 5131ef7075deSdan ); 5132ef7075deSdan } 5133ef7075deSdan } 5134ef7075deSdan #else 5135ef7075deSdan # define explainSimpleCount(a,b,c) 5136ef7075deSdan #endif 5137ef7075deSdan 5138ef7075deSdan /* 5139ab31a845Sdan ** sqlite3WalkExpr() callback used by havingToWhere(). 5140ab31a845Sdan ** 5141ab31a845Sdan ** If the node passed to the callback is a TK_AND node, return 5142ab31a845Sdan ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes. 5143ab31a845Sdan ** 5144ab31a845Sdan ** Otherwise, return WRC_Prune. In this case, also check if the 5145ab31a845Sdan ** sub-expression matches the criteria for being moved to the WHERE 5146ab31a845Sdan ** clause. If so, add it to the WHERE clause and replace the sub-expression 5147ab31a845Sdan ** within the HAVING expression with a constant "1". 5148ab31a845Sdan */ 5149ab31a845Sdan static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ 5150ab31a845Sdan if( pExpr->op!=TK_AND ){ 5151cd0abc24Sdrh Select *pS = pWalker->u.pSelect; 5152cd0abc24Sdrh if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){ 5153ab31a845Sdan sqlite3 *db = pWalker->pParse->db; 5154ab31a845Sdan Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0); 5155ab31a845Sdan if( pNew ){ 5156cd0abc24Sdrh Expr *pWhere = pS->pWhere; 5157ab31a845Sdan SWAP(Expr, *pNew, *pExpr); 5158ab31a845Sdan pNew = sqlite3ExprAnd(db, pWhere, pNew); 5159cd0abc24Sdrh pS->pWhere = pNew; 5160cd0abc24Sdrh pWalker->eCode = 1; 5161ab31a845Sdan } 5162ab31a845Sdan } 5163ab31a845Sdan return WRC_Prune; 5164ab31a845Sdan } 5165ab31a845Sdan return WRC_Continue; 5166ab31a845Sdan } 5167ab31a845Sdan 5168ab31a845Sdan /* 5169ab31a845Sdan ** Transfer eligible terms from the HAVING clause of a query, which is 5170ab31a845Sdan ** processed after grouping, to the WHERE clause, which is processed before 5171ab31a845Sdan ** grouping. For example, the query: 5172ab31a845Sdan ** 5173ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=? 5174ab31a845Sdan ** 5175ab31a845Sdan ** can be rewritten as: 5176ab31a845Sdan ** 5177ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=? 5178ab31a845Sdan ** 5179ab31a845Sdan ** A term of the HAVING expression is eligible for transfer if it consists 5180ab31a845Sdan ** entirely of constants and expressions that are also GROUP BY terms that 5181ab31a845Sdan ** use the "BINARY" collation sequence. 5182ab31a845Sdan */ 5183cd0abc24Sdrh static void havingToWhere(Parse *pParse, Select *p){ 5184ab31a845Sdan Walker sWalker; 5185ab31a845Sdan memset(&sWalker, 0, sizeof(sWalker)); 5186ab31a845Sdan sWalker.pParse = pParse; 5187ab31a845Sdan sWalker.xExprCallback = havingToWhereExprCb; 5188cd0abc24Sdrh sWalker.u.pSelect = p; 5189cd0abc24Sdrh sqlite3WalkExpr(&sWalker, p->pHaving); 5190cd0abc24Sdrh #if SELECTTRACE_ENABLED 5191cd0abc24Sdrh if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){ 5192cd0abc24Sdrh SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); 5193cd0abc24Sdrh sqlite3TreeViewSelect(0, p, 0); 5194cd0abc24Sdrh } 5195cd0abc24Sdrh #endif 5196ab31a845Sdan } 5197ab31a845Sdan 5198ab31a845Sdan /* 5199e08e8d6bSdrh ** Check to see if the pThis entry of pTabList is a self-join of a prior view. 5200e08e8d6bSdrh ** If it is, then return the SrcList_item for the prior view. If it is not, 5201e08e8d6bSdrh ** then return 0. 5202e08e8d6bSdrh */ 5203e08e8d6bSdrh static struct SrcList_item *isSelfJoinView( 5204e08e8d6bSdrh SrcList *pTabList, /* Search for self-joins in this FROM clause */ 5205e08e8d6bSdrh struct SrcList_item *pThis /* Search for prior reference to this subquery */ 5206e08e8d6bSdrh ){ 5207e08e8d6bSdrh struct SrcList_item *pItem; 5208e08e8d6bSdrh for(pItem = pTabList->a; pItem<pThis; pItem++){ 5209e08e8d6bSdrh if( pItem->pSelect==0 ) continue; 5210e08e8d6bSdrh if( pItem->fg.viaCoroutine ) continue; 521133543c23Sdrh if( pItem->zName==0 ) continue; 521233543c23Sdrh if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue; 5213ed712980Sdrh if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; 52145aa550cfSdan if( sqlite3ExprCompare(0, 52155aa550cfSdan pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1) 52165aa550cfSdan ){ 5217ed712980Sdrh /* The view was modified by some other optimization such as 5218ed712980Sdrh ** pushDownWhereTerms() */ 5219ed712980Sdrh continue; 5220ed712980Sdrh } 5221ed712980Sdrh return pItem; 5222e08e8d6bSdrh } 5223e08e8d6bSdrh return 0; 5224e08e8d6bSdrh } 5225e08e8d6bSdrh 5226269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5227269ba804Sdrh /* 5228269ba804Sdrh ** Attempt to transform a query of the form 5229269ba804Sdrh ** 5230269ba804Sdrh ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) 5231269ba804Sdrh ** 5232269ba804Sdrh ** Into this: 5233269ba804Sdrh ** 5234269ba804Sdrh ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) 5235269ba804Sdrh ** 5236269ba804Sdrh ** The transformation only works if all of the following are true: 5237269ba804Sdrh ** 5238269ba804Sdrh ** * The subquery is a UNION ALL of two or more terms 5239269ba804Sdrh ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries 5240269ba804Sdrh ** * The outer query is a simple count(*) 5241269ba804Sdrh ** 5242269ba804Sdrh ** Return TRUE if the optimization is undertaken. 5243269ba804Sdrh */ 5244269ba804Sdrh static int countOfViewOptimization(Parse *pParse, Select *p){ 5245269ba804Sdrh Select *pSub, *pPrior; 5246269ba804Sdrh Expr *pExpr; 5247269ba804Sdrh Expr *pCount; 5248269ba804Sdrh sqlite3 *db; 52493d240d21Sdrh if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ 5250269ba804Sdrh if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ 5251269ba804Sdrh pExpr = p->pEList->a[0].pExpr; 5252269ba804Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ 52533d240d21Sdrh if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ 5254269ba804Sdrh if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ 52553d240d21Sdrh if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ 5256269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5257269ba804Sdrh if( pSub==0 ) return 0; /* The FROM is a subquery */ 52583d240d21Sdrh if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ 5259269ba804Sdrh do{ 5260269ba804Sdrh if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ 5261269ba804Sdrh if( pSub->pWhere ) return 0; /* No WHERE clause */ 5262269ba804Sdrh if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ 52633d240d21Sdrh pSub = pSub->pPrior; /* Repeat over compound */ 5264269ba804Sdrh }while( pSub ); 5265269ba804Sdrh 52663d240d21Sdrh /* If we reach this point then it is OK to perform the transformation */ 5267269ba804Sdrh 5268269ba804Sdrh db = pParse->db; 5269269ba804Sdrh pCount = pExpr; 5270269ba804Sdrh pExpr = 0; 5271269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 5272269ba804Sdrh p->pSrc->a[0].pSelect = 0; 5273269ba804Sdrh sqlite3SrcListDelete(db, p->pSrc); 5274269ba804Sdrh p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); 5275269ba804Sdrh while( pSub ){ 5276269ba804Sdrh Expr *pTerm; 5277269ba804Sdrh pPrior = pSub->pPrior; 5278269ba804Sdrh pSub->pPrior = 0; 5279269ba804Sdrh pSub->pNext = 0; 5280269ba804Sdrh pSub->selFlags |= SF_Aggregate; 5281269ba804Sdrh pSub->selFlags &= ~SF_Compound; 5282269ba804Sdrh pSub->nSelectRow = 0; 5283269ba804Sdrh sqlite3ExprListDelete(db, pSub->pEList); 5284269ba804Sdrh pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; 5285269ba804Sdrh pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm); 5286269ba804Sdrh pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0); 5287269ba804Sdrh sqlite3PExprAddSelect(pParse, pTerm, pSub); 5288269ba804Sdrh if( pExpr==0 ){ 5289269ba804Sdrh pExpr = pTerm; 5290269ba804Sdrh }else{ 5291269ba804Sdrh pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); 5292269ba804Sdrh } 5293269ba804Sdrh pSub = pPrior; 5294269ba804Sdrh } 5295269ba804Sdrh p->pEList->a[0].pExpr = pExpr; 5296269ba804Sdrh p->selFlags &= ~SF_Aggregate; 5297269ba804Sdrh 5298269ba804Sdrh #if SELECTTRACE_ENABLED 5299269ba804Sdrh if( sqlite3SelectTrace & 0x400 ){ 5300269ba804Sdrh SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); 5301269ba804Sdrh sqlite3TreeViewSelect(0, p, 0); 5302269ba804Sdrh } 5303269ba804Sdrh #endif 5304269ba804Sdrh return 1; 5305269ba804Sdrh } 5306269ba804Sdrh #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ 5307269ba804Sdrh 5308e08e8d6bSdrh /* 53097d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 53109bb61fe7Sdrh ** 5311340309fdSdrh ** The results are returned according to the SelectDest structure. 5312340309fdSdrh ** See comments in sqliteInt.h for further information. 5313e78e8284Sdrh ** 53149bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 53159bb61fe7Sdrh ** encountered, then an appropriate error message is left in 53169bb61fe7Sdrh ** pParse->zErrMsg. 53179bb61fe7Sdrh ** 53189bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 53199bb61fe7Sdrh ** calling function needs to do that. 53209bb61fe7Sdrh */ 53214adee20fSdanielk1977 int sqlite3Select( 5322cce7d176Sdrh Parse *pParse, /* The parser context */ 53239bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 53247d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 5325cce7d176Sdrh ){ 532613449892Sdrh int i, j; /* Loop counters */ 532713449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 532813449892Sdrh Vdbe *v; /* The virtual machine under construction */ 5329b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 5330c29cbb0bSmistachkin ExprList *pEList = 0; /* List of columns to extract. */ 5331ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 53329bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 53332282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 53342282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 53351d83f052Sdrh int rc = 1; /* Value to return from this function */ 5336e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 5337079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 533813449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 5339ec7429aeSdrh int iEnd; /* Address of the end of the query */ 534017435752Sdrh sqlite3 *db; /* The database connection */ 534147d9f839Sdrh ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ 534247d9f839Sdrh u8 minMaxFlag; /* Flag for min/max queries */ 53439bb61fe7Sdrh 53442ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 53452ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 53462ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 53472ce22453Sdan #endif 53482ce22453Sdan 534917435752Sdrh db = pParse->db; 535017435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 53516f7adc8aSdrh return 1; 53526f7adc8aSdrh } 53534adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 535413449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 5355eb9b884cSdrh #if SELECTTRACE_ENABLED 5356b3b0d317Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->iSelectId)); 5357c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 5358c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 5359c90713d3Sdrh } 5360eb9b884cSdrh #endif 5361daffd0e5Sdrh 53628e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 53638e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 53649afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 53659afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 53666c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 53679ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 53689afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 53698e1ee88cSdrh pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || 53708e1ee88cSdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); 5371ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 5372ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 5373ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 5374ccfcbceaSdrh p->pOrderBy = 0; 53757d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 53769a99334dSdrh } 53777d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 5378079a3072Sdrh memset(&sSort, 0, sizeof(sSort)); 5379079a3072Sdrh sSort.pOrderBy = p->pOrderBy; 5380b27b7f5dSdrh pTabList = p->pSrc; 5381956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 53829a99334dSdrh goto select_end; 53839a99334dSdrh } 5384adc57f68Sdrh assert( p->pEList!=0 ); 53857d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 538617645f5eSdrh #if SELECTTRACE_ENABLED 538717645f5eSdrh if( sqlite3SelectTrace & 0x100 ){ 538817645f5eSdrh SELECTTRACE(0x100,pParse,p, ("after name resolution:\n")); 538917645f5eSdrh sqlite3TreeViewSelect(0, p, 0); 539017645f5eSdrh } 539117645f5eSdrh #endif 5392cce7d176Sdrh 5393f35f2f92Sdrh /* Get a pointer the VDBE under construction, allocating a new VDBE if one 5394f35f2f92Sdrh ** does not already exist */ 5395f35f2f92Sdrh v = sqlite3GetVdbe(pParse); 5396f35f2f92Sdrh if( v==0 ) goto select_end; 5397f35f2f92Sdrh if( pDest->eDest==SRT_Output ){ 5398f35f2f92Sdrh generateColumnNames(pParse, p); 5399f35f2f92Sdrh } 5400f35f2f92Sdrh 54012589787cSdrh /* Try to various optimizations (flattening subqueries, and strength 54022589787cSdrh ** reduction of join operators) in the FROM clause up into the main query 5403d820cb1bSdrh */ 540451522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5405f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 540613449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 5407daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 54082679f14fSdrh Table *pTab = pItem->pTab; 54092589787cSdrh 54102589787cSdrh /* Convert LEFT JOIN into JOIN if there are terms of the right table 54112589787cSdrh ** of the LEFT JOIN used in the WHERE clause. 54122589787cSdrh */ 54132589787cSdrh if( (pItem->fg.jointype & JT_LEFT)!=0 54142589787cSdrh && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) 54152589787cSdrh && OptimizationEnabled(db, SQLITE_SimplifyJoin) 54162589787cSdrh ){ 54172589787cSdrh SELECTTRACE(0x100,pParse,p, 54182589787cSdrh ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); 5419efce69deSdrh pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); 54202589787cSdrh unsetJoinExpr(p->pWhere, pItem->iCursor); 54212589787cSdrh } 54222589787cSdrh 54232589787cSdrh /* No futher action if this term of the FROM clause is no a subquery */ 54244490c40bSdrh if( pSub==0 ) continue; 54252679f14fSdrh 54262679f14fSdrh /* Catch mismatch in the declared columns of a view and the number of 54272679f14fSdrh ** columns in the SELECT on the RHS */ 54282679f14fSdrh if( pTab->nCol!=pSub->pEList->nExpr ){ 54292679f14fSdrh sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", 54302679f14fSdrh pTab->nCol, pTab->zName, pSub->pEList->nExpr); 54312679f14fSdrh goto select_end; 54322679f14fSdrh } 54332679f14fSdrh 543425c221ebSdrh /* Do not try to flatten an aggregate subquery. 543525c221ebSdrh ** 543625c221ebSdrh ** Flattening an aggregate subquery is only possible if the outer query 543725c221ebSdrh ** is not a join. But if the outer query is not a join, then the subquery 543825c221ebSdrh ** will be implemented as a co-routine and there is no advantage to 543925c221ebSdrh ** flattening in that case. 544025c221ebSdrh */ 544125c221ebSdrh if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; 544225c221ebSdrh assert( pSub->pGroupBy==0 ); 544325c221ebSdrh 5444fca23557Sdrh /* If the outer query contains a "complex" result set (that is, 5445fca23557Sdrh ** if the result set of the outer query uses functions or subqueries) 5446fca23557Sdrh ** and if the subquery contains an ORDER BY clause and if 5447648fe49fSdrh ** it will be implemented as a co-routine, then do not flatten. This 5448648fe49fSdrh ** restriction allows SQL constructs like this: 5449648fe49fSdrh ** 5450648fe49fSdrh ** SELECT expensive_function(x) 5451648fe49fSdrh ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5452648fe49fSdrh ** 5453648fe49fSdrh ** The expensive_function() is only computed on the 10 rows that 5454648fe49fSdrh ** are output, rather than every row of the table. 5455fca23557Sdrh ** 5456fca23557Sdrh ** The requirement that the outer query have a complex result set 5457fca23557Sdrh ** means that flattening does occur on simpler SQL constraints without 5458fca23557Sdrh ** the expensive_function() like: 5459fca23557Sdrh ** 5460fca23557Sdrh ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 5461648fe49fSdrh */ 546225c221ebSdrh if( pSub->pOrderBy!=0 5463648fe49fSdrh && i==0 5464fca23557Sdrh && (p->selFlags & SF_ComplexResult)!=0 5465648fe49fSdrh && (pTabList->nSrc==1 5466648fe49fSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) 5467648fe49fSdrh ){ 5468648fe49fSdrh continue; 5469648fe49fSdrh } 5470648fe49fSdrh 547125c221ebSdrh if( flattenSubquery(pParse, p, i, isAgg) ){ 54724490c40bSdrh /* This subquery can be absorbed into its parent. */ 54734490c40bSdrh i = -1; 54744490c40bSdrh } 54754490c40bSdrh pTabList = p->pSrc; 54764490c40bSdrh if( db->mallocFailed ) goto select_end; 54774490c40bSdrh if( !IgnorableOrderby(pDest) ){ 54784490c40bSdrh sSort.pOrderBy = p->pOrderBy; 54794490c40bSdrh } 54804490c40bSdrh } 54814490c40bSdrh #endif 54824490c40bSdrh 54834490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 54844490c40bSdrh /* Handle compound SELECT statements using the separate multiSelect() 54854490c40bSdrh ** procedure. 54864490c40bSdrh */ 54874490c40bSdrh if( p->pPrior ){ 54884490c40bSdrh rc = multiSelect(pParse, p, pDest); 54894490c40bSdrh #if SELECTTRACE_ENABLED 54904490c40bSdrh SELECTTRACE(1,pParse,p,("end compound-select processing\n")); 54914490c40bSdrh #endif 5492*1bddf23bSdrh explainSetInteger(pParse->iSelectId, iRestoreSelectId); 54934490c40bSdrh return rc; 54944490c40bSdrh } 54954490c40bSdrh #endif 54964490c40bSdrh 5497701caf1eSdrh /* For each term in the FROM clause, do two things: 5498701caf1eSdrh ** (1) Authorized unreferenced tables 5499701caf1eSdrh ** (2) Generate code for all sub-queries 5500d820cb1bSdrh */ 55014490c40bSdrh for(i=0; i<pTabList->nSrc; i++){ 5502742f947bSdanielk1977 struct SrcList_item *pItem = &pTabList->a[i]; 5503c31c2eb8Sdrh SelectDest dest; 5504701caf1eSdrh Select *pSub; 5505824d21afSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5506824d21afSdrh const char *zSavedAuthContext; 5507824d21afSdrh #endif 5508701caf1eSdrh 55093d240d21Sdrh /* Issue SQLITE_READ authorizations with a fake column name for any 55103d240d21Sdrh ** tables that are referenced but from which no values are extracted. 55113d240d21Sdrh ** Examples of where these kinds of null SQLITE_READ authorizations 55123d240d21Sdrh ** would occur: 5513701caf1eSdrh ** 55142336c935Sdrh ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" 55152336c935Sdrh ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" 55162336c935Sdrh ** 55172336c935Sdrh ** The fake column name is an empty string. It is possible for a table to 55182336c935Sdrh ** have a column named by the empty string, in which case there is no way to 55192336c935Sdrh ** distinguish between an unreferenced table and an actual reference to the 55202336c935Sdrh ** "" column. The original design was for the fake column name to be a NULL, 55212336c935Sdrh ** which would be unambiguous. But legacy authorization callbacks might 55223d240d21Sdrh ** assume the column name is non-NULL and segfault. The use of an empty 55233d240d21Sdrh ** string for the fake column name seems safer. 5524701caf1eSdrh */ 5525701caf1eSdrh if( pItem->colUsed==0 ){ 55262336c935Sdrh sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); 5527701caf1eSdrh } 5528701caf1eSdrh 5529701caf1eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 5530701caf1eSdrh /* Generate code for all sub-queries in the FROM clause 5531701caf1eSdrh */ 5532701caf1eSdrh pSub = pItem->pSelect; 55335b6a9ed4Sdrh if( pSub==0 ) continue; 553421172c4cSdrh 553521172c4cSdrh /* Sometimes the code for a subquery will be generated more than 553621172c4cSdrh ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, 553721172c4cSdrh ** for example. In that case, do not regenerate the code to manifest 553821172c4cSdrh ** a view or the co-routine to implement a view. The first instance 553921172c4cSdrh ** is sufficient, though the subroutine to manifest the view does need 554021172c4cSdrh ** to be invoked again. */ 55415b6a9ed4Sdrh if( pItem->addrFillSub ){ 55428a48b9c0Sdrh if( pItem->fg.viaCoroutine==0 ){ 55437555581fSdrh /* The subroutine that manifests the view might be a one-time routine, 55447555581fSdrh ** or it might need to be rerun on each iteration because it 55457555581fSdrh ** encodes a correlated subquery. */ 55467555581fSdrh testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once ); 55475b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 554821172c4cSdrh } 55495b6a9ed4Sdrh continue; 55505b6a9ed4Sdrh } 5551daf79acbSdanielk1977 5552fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 5553f7b5496eSdrh ** tree referred to by this, the parent select. The child select 5554fc976065Sdanielk1977 ** may contain expression trees of at most 5555fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 5556fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 5557fc976065Sdanielk1977 ** an exact limit. 5558fc976065Sdanielk1977 */ 5559fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 5560daf79acbSdanielk1977 5561adc57f68Sdrh /* Make copies of constant WHERE-clause terms in the outer query down 5562adc57f68Sdrh ** inside the subquery. This can help the subquery to run more efficiently. 5563adc57f68Sdrh */ 55647fbb101cSdrh if( OptimizationEnabled(db, SQLITE_PushDown) 55656a9b9527Sdrh && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, 55666a9b9527Sdrh (pItem->fg.jointype & JT_OUTER)!=0) 556769b72d5aSdrh ){ 556869b72d5aSdrh #if SELECTTRACE_ENABLED 556969b72d5aSdrh if( sqlite3SelectTrace & 0x100 ){ 5570bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n")); 557169b72d5aSdrh sqlite3TreeViewSelect(0, p, 0); 5572daf79acbSdanielk1977 } 557369b72d5aSdrh #endif 55742d277bb5Sdrh }else{ 55752d277bb5Sdrh SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); 557669b72d5aSdrh } 5577adc57f68Sdrh 5578824d21afSdrh zSavedAuthContext = pParse->zAuthContext; 5579824d21afSdrh pParse->zAuthContext = pItem->zName; 5580824d21afSdrh 5581adc57f68Sdrh /* Generate code to implement the subquery 55820ff47e9eSdrh ** 558325c221ebSdrh ** The subquery is implemented as a co-routine if the subquery is 558425c221ebSdrh ** guaranteed to be the outer loop (so that it does not need to be 558525c221ebSdrh ** computed more than once) 55860ff47e9eSdrh ** 55870ff47e9eSdrh ** TODO: Are there other reasons beside (1) to use a co-routine 55880ff47e9eSdrh ** implementation? 5589adc57f68Sdrh */ 55900ff47e9eSdrh if( i==0 55910ff47e9eSdrh && (pTabList->nSrc==1 55920ff47e9eSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ 5593a5759677Sdrh ){ 559421172c4cSdrh /* Implement a co-routine that will return a single row of the result 559521172c4cSdrh ** set on each invocation. 559621172c4cSdrh */ 5597725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 5598824d21afSdrh 559921172c4cSdrh pItem->regReturn = ++pParse->nMem; 5600725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 5601725de29aSdrh VdbeComment((v, "%s", pItem->pTab->zName)); 560221172c4cSdrh pItem->addrFillSub = addrTop; 560321172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 560421172c4cSdrh explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 560521172c4cSdrh sqlite3Select(pParse, pSub, &dest); 5606c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 56078a48b9c0Sdrh pItem->fg.viaCoroutine = 1; 56085f612295Sdrh pItem->regResult = dest.iSdst; 56092fade2f7Sdrh sqlite3VdbeEndCoroutine(v, pItem->regReturn); 561021172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 561121172c4cSdrh sqlite3ClearTempRegCache(pParse); 5612daf79acbSdanielk1977 }else{ 56135b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 56145b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 56155b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 56165b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 56175b6a9ed4Sdrh */ 56187157e8eaSdrh int topAddr; 561948f2d3b1Sdrh int onceAddr = 0; 56207157e8eaSdrh int retAddr; 5621e08e8d6bSdrh struct SrcList_item *pPrior; 5622e08e8d6bSdrh 56235b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 56245b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 56257157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 56267157e8eaSdrh pItem->addrFillSub = topAddr+1; 56278a48b9c0Sdrh if( pItem->fg.isCorrelated==0 ){ 5628ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 56295b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 56305b6a9ed4Sdrh ** once. */ 5631511f9e8dSdrh onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 5632725de29aSdrh VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 5633725de29aSdrh }else{ 5634725de29aSdrh VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 56355b6a9ed4Sdrh } 5636e08e8d6bSdrh pPrior = isSelfJoinView(pTabList, pItem); 5637e08e8d6bSdrh if( pPrior ){ 5638e08e8d6bSdrh sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); 5639d8a29566Sdrh explainSetInteger(pItem->iSelectId, pPrior->iSelectId); 5640eafc6dfeSdrh assert( pPrior->pSelect!=0 ); 5641eafc6dfeSdrh pSub->nSelectRow = pPrior->pSelect->nSelectRow; 5642e08e8d6bSdrh }else{ 56431013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 5644ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 56457d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 5646e08e8d6bSdrh } 5647c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 564848f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 56497157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 56507157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 56517157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 5652cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 5653daf79acbSdanielk1977 } 5654adc57f68Sdrh if( db->mallocFailed ) goto select_end; 5655fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 5656824d21afSdrh pParse->zAuthContext = zSavedAuthContext; 5657daf79acbSdanielk1977 #endif 5658701caf1eSdrh } 5659adc57f68Sdrh 566038b4149cSdrh /* Various elements of the SELECT copied into local variables for 566138b4149cSdrh ** convenience */ 5662adc57f68Sdrh pEList = p->pEList; 5663daf79acbSdanielk1977 pWhere = p->pWhere; 5664832508b7Sdrh pGroupBy = p->pGroupBy; 5665832508b7Sdrh pHaving = p->pHaving; 5666e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 5667832508b7Sdrh 5668bc8edba1Sdrh #if SELECTTRACE_ENABLED 5669bc8edba1Sdrh if( sqlite3SelectTrace & 0x400 ){ 5670bc8edba1Sdrh SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); 5671bc8edba1Sdrh sqlite3TreeViewSelect(0, p, 0); 5672f23329a2Sdanielk1977 } 5673f23329a2Sdanielk1977 #endif 5674f23329a2Sdanielk1977 5675269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 5676269ba804Sdrh if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) 5677269ba804Sdrh && countOfViewOptimization(pParse, p) 5678269ba804Sdrh ){ 5679269ba804Sdrh if( db->mallocFailed ) goto select_end; 5680269ba804Sdrh pEList = p->pEList; 5681269ba804Sdrh pTabList = p->pSrc; 5682269ba804Sdrh } 5683269ba804Sdrh #endif 5684269ba804Sdrh 568550118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 568650118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 568750118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 568850118cdfSdan ** 568950118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 569050118cdfSdan ** 569150118cdfSdan ** is transformed to: 569250118cdfSdan ** 5693dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 569450118cdfSdan ** 569550118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 569650118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 569750118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 569850118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 569950118cdfSdan */ 570050118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 5701adc57f68Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 570250118cdfSdan ){ 570350118cdfSdan p->selFlags &= ~SF_Distinct; 5704adc57f68Sdrh pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); 5705e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 5706e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 5707e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 5708e8e4af76Sdrh assert( sDistinct.isTnct ); 57097512cb47Sdrh 57107512cb47Sdrh #if SELECTTRACE_ENABLED 57117512cb47Sdrh if( sqlite3SelectTrace & 0x400 ){ 57127512cb47Sdrh SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); 57137512cb47Sdrh sqlite3TreeViewSelect(0, p, 0); 57147512cb47Sdrh } 57157512cb47Sdrh #endif 571650118cdfSdan } 571750118cdfSdan 5718adc57f68Sdrh /* If there is an ORDER BY clause, then create an ephemeral index to 5719adc57f68Sdrh ** do the sorting. But this sorting ephemeral index might end up 5720adc57f68Sdrh ** being unused if the data can be extracted in pre-sorted order. 5721adc57f68Sdrh ** If that is the case, then the OP_OpenEphemeral instruction will be 5722adc57f68Sdrh ** changed to an OP_Noop once we figure out that the sorting index is 5723adc57f68Sdrh ** not needed. The sSort.addrSortIndex variable is used to facilitate 5724adc57f68Sdrh ** that change. 57257cedc8d4Sdanielk1977 */ 5726079a3072Sdrh if( sSort.pOrderBy ){ 57270342b1f5Sdrh KeyInfo *pKeyInfo; 57283f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr); 5729079a3072Sdrh sSort.iECursor = pParse->nTab++; 5730079a3072Sdrh sSort.addrSortIndex = 573166a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5732f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 5733f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 5734f45f2326Sdrh ); 57359d2985c7Sdrh }else{ 5736079a3072Sdrh sSort.addrSortIndex = -1; 57377cedc8d4Sdanielk1977 } 57387cedc8d4Sdanielk1977 57392d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 57402d0794e3Sdrh */ 57416c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 57422b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 57432d0794e3Sdrh } 57442d0794e3Sdrh 5745f42bacc2Sdrh /* Set the limiter. 5746f42bacc2Sdrh */ 5747f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 574869b9383eSdan if( (p->selFlags & SF_FixedLimit)==0 ){ 5749c3489bbfSdrh p->nSelectRow = 320; /* 4 billion rows */ 575069b9383eSdan } 5751f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 5752079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 57530ff287fbSdrh sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); 5754079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 5755c6aff30cSdrh } 5756f42bacc2Sdrh 5757adc57f68Sdrh /* Open an ephemeral index to use for the distinct set. 5758cce7d176Sdrh */ 57592ce22453Sdan if( p->selFlags & SF_Distinct ){ 5760e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 5761e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5762e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 5763079a3072Sdrh (char*)keyInfoFromExprList(pParse, p->pEList,0,0), 57642ec2fb22Sdrh P4_KEYINFO); 5765d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 5766e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 5767832508b7Sdrh }else{ 5768e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 5769efb7251dSdrh } 5770832508b7Sdrh 577113449892Sdrh if( !isAgg && pGroupBy==0 ){ 5772e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 57736457a353Sdrh u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); 5774c3489bbfSdrh assert( WHERE_USE_LIMIT==SF_FixedLimit ); 5775c3489bbfSdrh wctrlFlags |= p->selFlags & SF_FixedLimit; 577638cc40c2Sdan 577738cc40c2Sdan /* Begin the database scan. */ 5778cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 5779079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 5780c3489bbfSdrh p->pEList, wctrlFlags, p->nSelectRow); 57811d83f052Sdrh if( pWInfo==0 ) goto select_end; 57826f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 57836f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 57846f32848dSdrh } 57856457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 57866f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 57876f32848dSdrh } 5788079a3072Sdrh if( sSort.pOrderBy ){ 5789079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 5790a536df4eSdrh sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo); 5791079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 5792079a3072Sdrh sSort.pOrderBy = 0; 5793079a3072Sdrh } 5794079a3072Sdrh } 5795cce7d176Sdrh 5796b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 5797b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 57989d2985c7Sdrh ** into an OP_Noop. 57999d2985c7Sdrh */ 5800079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 5801079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 58029d2985c7Sdrh } 58039d2985c7Sdrh 580438cc40c2Sdan /* Use the standard inner loop. */ 58052def2f7eSdrh assert( p->pEList==pEList ); 58062def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, 58076f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 58086f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 58092282792aSdrh 5810cce7d176Sdrh /* End the database scan loop. 5811cce7d176Sdrh */ 58124adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 581313449892Sdrh }else{ 5814e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 5815e8e4af76Sdrh ** or both */ 581613449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 581713449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 581813449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 581913449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 582013449892Sdrh ** one row of the input to the aggregator has been 582113449892Sdrh ** processed */ 582213449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 582313449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 5824d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 58251c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 58261c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 5827374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 5828d176611bSdrh 5829d176611bSdrh /* Remove any and all aliases between the result set and the 5830d176611bSdrh ** GROUP BY clause. 5831d176611bSdrh */ 5832d176611bSdrh if( pGroupBy ){ 5833dc5ea5c7Sdrh int k; /* Loop counter */ 5834d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 5835d176611bSdrh 5836dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 5837c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5838d176611bSdrh } 5839dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 5840c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5841d176611bSdrh } 5842c3489bbfSdrh assert( 66==sqlite3LogEst(100) ); 5843c3489bbfSdrh if( p->nSelectRow>66 ) p->nSelectRow = 66; 584495aa47b1Sdrh }else{ 5845c3489bbfSdrh assert( 0==sqlite3LogEst(1) ); 5846c3489bbfSdrh p->nSelectRow = 0; 5847d176611bSdrh } 5848cce7d176Sdrh 5849374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 5850374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 5851374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 5852adc57f68Sdrh ** in the correct order. It also may not - the GROUP BY might use a 5853374cd78cSdan ** database index that causes rows to be grouped together as required 5854374cd78cSdan ** but not actually sorted. Either way, record the fact that the 5855374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 5856374cd78cSdan ** variable. */ 5857374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 5858374cd78cSdan orderByGrp = 1; 5859374cd78cSdan } 586013449892Sdrh 5861d176611bSdrh /* Create a label to jump to when we want to abort the query */ 586213449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 586313449892Sdrh 586413449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 586513449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 586613449892Sdrh ** SELECT statement. 58672282792aSdrh */ 586813449892Sdrh memset(&sNC, 0, sizeof(sNC)); 586913449892Sdrh sNC.pParse = pParse; 587013449892Sdrh sNC.pSrcList = pTabList; 587125c3b8caSdrh sNC.uNC.pAggInfo = &sAggInfo; 587225c3b8caSdrh VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) 58737e61d18eSdrh sAggInfo.mnReg = pParse->nMem+1; 5874dd23c6bfSdan sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 58759d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 5876d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 5877079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 5878d2b3e23bSdrh if( pHaving ){ 5879ab31a845Sdan if( pGroupBy ){ 5880ab31a845Sdan assert( pWhere==p->pWhere ); 5881cd0abc24Sdrh assert( pHaving==p->pHaving ); 5882cd0abc24Sdrh assert( pGroupBy==p->pGroupBy ); 5883cd0abc24Sdrh havingToWhere(pParse, p); 5884ab31a845Sdan pWhere = p->pWhere; 5885ab31a845Sdan } 5886d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 588713449892Sdrh } 588813449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 588947d9f839Sdrh if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){ 589047d9f839Sdrh minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy); 589147d9f839Sdrh }else{ 589247d9f839Sdrh minMaxFlag = WHERE_ORDERBY_NORMAL; 589347d9f839Sdrh } 589413449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 58956ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 58963a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 58976ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 58983a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 589913449892Sdrh } 59007e61d18eSdrh sAggInfo.mxReg = pParse->nMem; 590117435752Sdrh if( db->mallocFailed ) goto select_end; 59027ea11066Sdrh #if SELECTTRACE_ENABLED 59037ea11066Sdrh if( sqlite3SelectTrace & 0x400 ){ 59047ea11066Sdrh int ii; 59057ea11066Sdrh SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n")); 59067ea11066Sdrh sqlite3TreeViewSelect(0, p, 0); 59077ea11066Sdrh for(ii=0; ii<sAggInfo.nColumn; ii++){ 59087ea11066Sdrh sqlite3DebugPrintf("agg-column[%d] iMem=%d\n", 59097ea11066Sdrh ii, sAggInfo.aCol[ii].iMem); 59107ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0); 59117ea11066Sdrh } 59127ea11066Sdrh for(ii=0; ii<sAggInfo.nFunc; ii++){ 59137ea11066Sdrh sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", 59147ea11066Sdrh ii, sAggInfo.aFunc[ii].iMem); 59157ea11066Sdrh sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0); 59167ea11066Sdrh } 59177ea11066Sdrh } 59187ea11066Sdrh #endif 59197ea11066Sdrh 592013449892Sdrh 592113449892Sdrh /* Processing for aggregates with GROUP BY is very different and 59223c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 592313449892Sdrh */ 592413449892Sdrh if( pGroupBy ){ 592513449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 5926728e0f91Sdrh int addr1; /* A-vs-B comparision jump */ 5927d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 5928d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 5929d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 5930d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 5931d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 5932d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 5933d176611bSdrh int regReset; /* Return address register for reset subroutine */ 593413449892Sdrh 593513449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 593613449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 59371c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 593813449892Sdrh ** will be converted into a Noop. 593913449892Sdrh */ 594013449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 59413f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); 59421c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 5943cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 59442ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 594513449892Sdrh 594613449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 594713449892Sdrh */ 59480a07c107Sdrh iUseFlag = ++pParse->nMem; 59490a07c107Sdrh iAbortFlag = ++pParse->nMem; 5950d176611bSdrh regOutputRow = ++pParse->nMem; 5951d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 5952d176611bSdrh regReset = ++pParse->nMem; 5953d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 59540a07c107Sdrh iAMem = pParse->nMem + 1; 595513449892Sdrh pParse->nMem += pGroupBy->nExpr; 59560a07c107Sdrh iBMem = pParse->nMem + 1; 595713449892Sdrh pParse->nMem += pGroupBy->nExpr; 59584c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 5959d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 59604c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 5961d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 5962b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 5963e313382eSdrh 596413449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 596513449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 596613449892Sdrh ** it might be a single loop that uses an index to extract information 596713449892Sdrh ** in the right order to begin with. 596813449892Sdrh */ 59692eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 5970cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 597193ec45d5Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 5972374cd78cSdan WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 5973374cd78cSdan ); 59745360ad34Sdrh if( pWInfo==0 ) goto select_end; 5975ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 597613449892Sdrh /* The optimizer is able to deliver rows in group by order so 5977b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 597813449892Sdrh ** cancelled later because we still need to use the pKeyInfo 597913449892Sdrh */ 598013449892Sdrh groupBySort = 0; 598113449892Sdrh }else{ 598213449892Sdrh /* Rows are coming out in undetermined order. We have to push 598313449892Sdrh ** each row into a sorting index, terminate the first loop, 598413449892Sdrh ** then loop over the sorting index in order to get the output 598513449892Sdrh ** in sorted order 598613449892Sdrh */ 5987892d3179Sdrh int regBase; 5988892d3179Sdrh int regRecord; 5989892d3179Sdrh int nCol; 5990892d3179Sdrh int nGroupBy; 5991892d3179Sdrh 59922ce22453Sdan explainTempTable(pParse, 5993e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 5994e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 59952ce22453Sdan 599613449892Sdrh groupBySort = 1; 5997892d3179Sdrh nGroupBy = pGroupBy->nExpr; 5998dd23c6bfSdan nCol = nGroupBy; 5999dd23c6bfSdan j = nGroupBy; 600013449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6001892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 6002892d3179Sdrh nCol++; 600313449892Sdrh j++; 600413449892Sdrh } 6005892d3179Sdrh } 6006892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 6007ceea3321Sdrh sqlite3ExprCacheClear(pParse); 60085579d59fSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); 6009dd23c6bfSdan j = nGroupBy; 6010892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 6011892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 6012892d3179Sdrh if( pCol->iSorterColumn>=j ){ 6013e55cbd72Sdrh int r1 = j + regBase; 6014ce78bc6eSdrh sqlite3ExprCodeGetColumnToReg(pParse, 6015ce78bc6eSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1); 60166a012f04Sdrh j++; 6017892d3179Sdrh } 6018892d3179Sdrh } 6019892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 60201db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 60211c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 6022892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 6023892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 602413449892Sdrh sqlite3WhereEnd(pWInfo); 60255134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 60261c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 60271c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 60281c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 6029688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 603013449892Sdrh sAggInfo.useSortingIdx = 1; 6031ceea3321Sdrh sqlite3ExprCacheClear(pParse); 6032374cd78cSdan 6033374cd78cSdan } 6034374cd78cSdan 6035374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 6036374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 6037374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 6038374cd78cSdan ** 6039374cd78cSdan ** This is an optimization - the correct answer should result regardless. 6040374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 6041374cd78cSdan ** disable this optimization for testing purposes. */ 6042374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 6043374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 6044374cd78cSdan ){ 6045374cd78cSdan sSort.pOrderBy = 0; 6046374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 604713449892Sdrh } 604813449892Sdrh 604913449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 605013449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 605113449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 605213449892Sdrh ** from the previous row currently stored in a0, a1, a2... 605313449892Sdrh */ 605413449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 6055ceea3321Sdrh sqlite3ExprCacheClear(pParse); 60561c9d835dSdrh if( groupBySort ){ 605738b4149cSdrh sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, 605838b4149cSdrh sortOut, sortPTab); 60591c9d835dSdrh } 606013449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 606113449892Sdrh if( groupBySort ){ 60621c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 606313449892Sdrh }else{ 606413449892Sdrh sAggInfo.directMode = 1; 60652dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 606613449892Sdrh } 606713449892Sdrh } 606816ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 60692ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 6070728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 6071728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); 607213449892Sdrh 607313449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 6074e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 607513449892Sdrh ** block. If there were no changes, this block is skipped. 607613449892Sdrh ** 607713449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 607813449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 607913449892Sdrh ** and resets the aggregate accumulator registers in preparation 608013449892Sdrh ** for the next GROUP BY batch. 608113449892Sdrh */ 6082b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 60832eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6084d4e70ebdSdrh VdbeComment((v, "output one row")); 6085688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 6086d4e70ebdSdrh VdbeComment((v, "check abort flag")); 60872eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 6088d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 608913449892Sdrh 609013449892Sdrh /* Update the aggregate accumulators based on the content of 609113449892Sdrh ** the current row 609213449892Sdrh */ 6093728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 609413449892Sdrh updateAccumulator(pParse, &sAggInfo); 60954c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 6096d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 609713449892Sdrh 609813449892Sdrh /* End of the loop 609913449892Sdrh */ 610013449892Sdrh if( groupBySort ){ 61011c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 6102688852abSdrh VdbeCoverage(v); 610313449892Sdrh }else{ 610413449892Sdrh sqlite3WhereEnd(pWInfo); 610548f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 610613449892Sdrh } 610713449892Sdrh 610813449892Sdrh /* Output the final row of result 610913449892Sdrh */ 61102eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 6111d4e70ebdSdrh VdbeComment((v, "output final row")); 611213449892Sdrh 6113d176611bSdrh /* Jump over the subroutines 6114d176611bSdrh */ 6115076e85f5Sdrh sqlite3VdbeGoto(v, addrEnd); 6116d176611bSdrh 6117d176611bSdrh /* Generate a subroutine that outputs a single row of the result 6118d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 6119d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 6120d176611bSdrh ** the processing calls for the query to abort, this subroutine 6121d176611bSdrh ** increments the iAbortFlag memory location before returning in 6122d176611bSdrh ** order to signal the caller to abort. 6123d176611bSdrh */ 6124d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 6125d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 6126d176611bSdrh VdbeComment((v, "set abort flag")); 6127d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6128d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 6129d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 6130d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 613138b4149cSdrh VdbeCoverage(v); 6132d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 6133d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6134d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 6135d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 61362def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, 6137e8e4af76Sdrh &sDistinct, pDest, 6138d176611bSdrh addrOutputRow+1, addrSetAbort); 6139d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 6140d176611bSdrh VdbeComment((v, "end groupby result generator")); 6141d176611bSdrh 6142d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 6143d176611bSdrh */ 6144d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 6145d176611bSdrh resetAccumulator(pParse, &sAggInfo); 6146d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 6147d176611bSdrh 614843152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 614913449892Sdrh else { 6150a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 6151a5533162Sdanielk1977 Table *pTab; 6152a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 6153a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 6154a5533162Sdanielk1977 ** the SQL statement is of the form: 6155a5533162Sdanielk1977 ** 6156a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 6157a5533162Sdanielk1977 ** 6158a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 6159a5533162Sdanielk1977 ** 6160a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 6161a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 6162a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 6163a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 6164a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 6165a5533162Sdanielk1977 */ 6166a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 6167a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 6168a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 6169a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 6170a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 6171a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 6172a9d1ccb9Sdanielk1977 6173a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 6174a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 6175a5533162Sdanielk1977 6176d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 6177a5533162Sdanielk1977 ** 61783e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 61793e9548b3Sdrh ** 6180abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 61815f33f375Sdrh ** 6182a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 6183a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 6184a5533162Sdanielk1977 */ 61855c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 6186a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 6187d9e3cad2Sdrh if( pIdx->bUnordered==0 6188e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 6189d3037a41Sdrh && pIdx->pPartIdxWhere==0 6190e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 6191d9e3cad2Sdrh ){ 6192a5533162Sdanielk1977 pBest = pIdx; 6193a5533162Sdanielk1977 } 6194a5533162Sdanielk1977 } 6195d9e3cad2Sdrh if( pBest ){ 6196a5533162Sdanielk1977 iRoot = pBest->tnum; 61972ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 6198a5533162Sdanielk1977 } 6199a5533162Sdanielk1977 6200a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 6201261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); 6202a5533162Sdanielk1977 if( pKeyInfo ){ 62032ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 6204a5533162Sdanielk1977 } 6205a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 6206a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 6207ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 6208a5533162Sdanielk1977 }else 6209a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 6210a5533162Sdanielk1977 { 621113449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 621213449892Sdrh ** processing is much simpler since there is only a single row 621313449892Sdrh ** of output. 621413449892Sdrh */ 621547d9f839Sdrh assert( p->pGroupBy==0 ); 621613449892Sdrh resetAccumulator(pParse, &sAggInfo); 621747d9f839Sdrh 621847d9f839Sdrh /* If this query is a candidate for the min/max optimization, then 621947d9f839Sdrh ** minMaxFlag will have been previously set to either 622047d9f839Sdrh ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will 622147d9f839Sdrh ** be an appropriate ORDER BY expression for the optimization. 622247d9f839Sdrh */ 622347d9f839Sdrh assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); 622447d9f839Sdrh assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); 622547d9f839Sdrh 6226cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 622747d9f839Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, 622847d9f839Sdrh 0, minMaxFlag, 0); 6229dba0137eSdanielk1977 if( pWInfo==0 ){ 6230dba0137eSdanielk1977 goto select_end; 6231dba0137eSdanielk1977 } 623213449892Sdrh updateAccumulator(pParse, &sAggInfo); 6233ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 6234076e85f5Sdrh sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); 6235a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 623647d9f839Sdrh (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max"))); 6237a9d1ccb9Sdanielk1977 } 623813449892Sdrh sqlite3WhereEnd(pWInfo); 623913449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 62407a895a80Sdanielk1977 } 62417a895a80Sdanielk1977 6242079a3072Sdrh sSort.pOrderBy = 0; 624335573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 62442def2f7eSdrh selectInnerLoop(pParse, p, -1, 0, 0, 6245a9671a22Sdrh pDest, addrEnd, addrEnd); 624613449892Sdrh } 624713449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 624813449892Sdrh 624913449892Sdrh } /* endif aggregate query */ 62502282792aSdrh 6251e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 62522ce22453Sdan explainTempTable(pParse, "DISTINCT"); 62532ce22453Sdan } 62542ce22453Sdan 6255cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 6256cce7d176Sdrh ** and send them to the callback one by one. 6257cce7d176Sdrh */ 6258079a3072Sdrh if( sSort.pOrderBy ){ 625938b4149cSdrh explainTempTable(pParse, 626038b4149cSdrh sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 626124e25d32Sdan assert( p->pEList==pEList ); 6262079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 6263cce7d176Sdrh } 62646a535340Sdrh 6265ec7429aeSdrh /* Jump here to skip this query 6266ec7429aeSdrh */ 6267ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 6268ec7429aeSdrh 62695b1c07e7Sdan /* The SELECT has been coded. If there is an error in the Parse structure, 62705b1c07e7Sdan ** set the return code to 1. Otherwise 0. */ 62715b1c07e7Sdan rc = (pParse->nErr>0); 62721d83f052Sdrh 62731d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 62741d83f052Sdrh ** successful coding of the SELECT. 62751d83f052Sdrh */ 62761d83f052Sdrh select_end: 627747d9f839Sdrh sqlite3ExprListDelete(db, pMinMaxOrderBy); 6278633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 6279633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 6280eb9b884cSdrh #if SELECTTRACE_ENABLED 6281eb9b884cSdrh SELECTTRACE(1,pParse,p,("end processing\n")); 6282eb9b884cSdrh #endif 6283*1bddf23bSdrh explainSetInteger(pParse->iSelectId, iRestoreSelectId); 62841d83f052Sdrh return rc; 6285cce7d176Sdrh } 6286