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 /* 18079a3072Sdrh ** An instance of the following object is used to record information about 19079a3072Sdrh ** how to process the DISTINCT keyword, to simplify passing that information 20079a3072Sdrh ** into the selectInnerLoop() routine. 21eda639e1Sdrh */ 22079a3072Sdrh typedef struct DistinctCtx DistinctCtx; 23079a3072Sdrh struct DistinctCtx { 24d6df8550Sdrh u8 isTnct; /* 0: Not distinct. 1: DISTICT 2: DISTINCT and ORDER BY */ 25079a3072Sdrh u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ 26079a3072Sdrh int tabTnct; /* Ephemeral table used for DISTINCT processing */ 27079a3072Sdrh int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ 28079a3072Sdrh }; 29079a3072Sdrh 30079a3072Sdrh /* 31079a3072Sdrh ** An instance of the following object is used to record information about 32079a3072Sdrh ** the ORDER BY (or GROUP BY) clause of query is being coded. 3324e25d32Sdan ** 3424e25d32Sdan ** The aDefer[] array is used by the sorter-references optimization. For 3524e25d32Sdan ** example, assuming there is no index that can be used for the ORDER BY, 3624e25d32Sdan ** for the query: 3724e25d32Sdan ** 3824e25d32Sdan ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10; 3924e25d32Sdan ** 4024e25d32Sdan ** it may be more efficient to add just the "a" values to the sorter, and 4124e25d32Sdan ** retrieve the associated "bigblob" values directly from table t1 as the 4224e25d32Sdan ** 10 smallest "a" values are extracted from the sorter. 4324e25d32Sdan ** 4424e25d32Sdan ** When the sorter-reference optimization is used, there is one entry in the 4524e25d32Sdan ** aDefer[] array for each database table that may be read as values are 4624e25d32Sdan ** extracted from the sorter. 47079a3072Sdrh */ 48079a3072Sdrh typedef struct SortCtx SortCtx; 49079a3072Sdrh struct SortCtx { 50079a3072Sdrh ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ 51079a3072Sdrh int nOBSat; /* Number of ORDER BY terms satisfied by indices */ 52079a3072Sdrh int iECursor; /* Cursor number for the sorter */ 53079a3072Sdrh int regReturn; /* Register holding block-output return address */ 54079a3072Sdrh int labelBkOut; /* Start label for the block-output subroutine */ 55079a3072Sdrh int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ 56a04a8be2Sdrh int labelDone; /* Jump here when done, ex: LIMIT reached */ 576ee5a7b4Sdrh int labelOBLopt; /* Jump here when sorter is full */ 58079a3072Sdrh u8 sortFlags; /* Zero or more SORTFLAG_* bits */ 5924e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 6024e25d32Sdan u8 nDefer; /* Number of valid entries in aDefer[] */ 6124e25d32Sdan struct DeferredCsr { 6224e25d32Sdan Table *pTab; /* Table definition */ 6324e25d32Sdan int iCsr; /* Cursor number for table */ 6424e25d32Sdan int nKey; /* Number of PK columns for table pTab (>=1) */ 6524e25d32Sdan } aDefer[4]; 6624e25d32Sdan #endif 67bbd4ae5aSdrh struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */ 68079a3072Sdrh }; 69079a3072Sdrh #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ 70315555caSdrh 71cce7d176Sdrh /* 72b87fbed5Sdrh ** Delete all the content of a Select structure. Deallocate the structure 73a9ebfe20Sdrh ** itself depending on the value of bFree 74a9ebfe20Sdrh ** 75a9ebfe20Sdrh ** If bFree==1, call sqlite3DbFree() on the p object. 76a9ebfe20Sdrh ** If bFree==0, Leave the first Select object unfreed 77eda639e1Sdrh */ 78b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){ 79b87fbed5Sdrh while( p ){ 80b87fbed5Sdrh Select *pPrior = p->pPrior; 81633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 82633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 83633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 84633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 85633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 86633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 87633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 8850f9f6c6Sdan if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith); 8967a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 90e3bf632cSdan if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){ 91e3bf632cSdan sqlite3WindowListDelete(db, p->pWinDefn); 92e3bf632cSdan } 9350f9f6c6Sdan while( p->pWin ){ 9450f9f6c6Sdan assert( p->pWin->ppThis==&p->pWin ); 9550f9f6c6Sdan sqlite3WindowUnlinkFromSelect(p->pWin); 9650f9f6c6Sdan } 9767a9b8edSdan #endif 98dbd6a7dcSdrh if( bFree ) sqlite3DbFreeNN(db, p); 99b87fbed5Sdrh p = pPrior; 100b87fbed5Sdrh bFree = 1; 101b87fbed5Sdrh } 102eda639e1Sdrh } 103eda639e1Sdrh 1041013c932Sdrh /* 1051013c932Sdrh ** Initialize a SelectDest structure. 1061013c932Sdrh */ 1071013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 108ea678832Sdrh pDest->eDest = (u8)eDest; 1092b596da8Sdrh pDest->iSDParm = iParm; 1109ed322d6Sdan pDest->iSDParm2 = 0; 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 ){ 132d3bf7661Sdrh Select *pNew, *pAllocated; 133eda639e1Sdrh Select standin; 134d3bf7661Sdrh pAllocated = 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; 148fef37760Sdrh pNew->selId = ++pParse->nSelect; 149ca3862dcSdrh pNew->addrOpenEphm[0] = -1; 150ca3862dcSdrh pNew->addrOpenEphm[1] = -1; 151ca3862dcSdrh pNew->nSelectRow = 0; 152ef90a6b8Sdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); 1539bb61fe7Sdrh pNew->pSrc = pSrc; 1549bb61fe7Sdrh pNew->pWhere = pWhere; 1559bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 1569bb61fe7Sdrh pNew->pHaving = pHaving; 1579bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 158ca3862dcSdrh pNew->pPrior = 0; 159ca3862dcSdrh pNew->pNext = 0; 160a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 161ca3862dcSdrh pNew->pWith = 0; 16267a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 16386fb6e17Sdan pNew->pWin = 0; 164e3bf632cSdan pNew->pWinDefn = 0; 16567a9b8edSdan #endif 166ef90a6b8Sdrh if( pParse->db->mallocFailed ) { 167ef90a6b8Sdrh clearSelect(pParse->db, pNew, pNew!=&standin); 168d3bf7661Sdrh pAllocated = 0; 169a464c234Sdrh }else{ 170a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 171daffd0e5Sdrh } 172d3bf7661Sdrh return pAllocated; 1739bb61fe7Sdrh } 1749bb61fe7Sdrh 175eb9b884cSdrh 1769bb61fe7Sdrh /* 177eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 178eda639e1Sdrh */ 179633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 1808906a4b8Sdrh if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1); 181eda639e1Sdrh } 182eda639e1Sdrh 183eda639e1Sdrh /* 184d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound. 185d227a291Sdrh */ 186d227a291Sdrh static Select *findRightmost(Select *p){ 187d227a291Sdrh while( p->pNext ) p = p->pNext; 188d227a291Sdrh return p; 1899bb61fe7Sdrh } 1909bb61fe7Sdrh 1919bb61fe7Sdrh /* 192f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the 19301f3f253Sdrh ** type of join. Return an integer constant that expresses that type 19401f3f253Sdrh ** in terms of the following bit values: 19501f3f253Sdrh ** 19601f3f253Sdrh ** JT_INNER 1973dec223cSdrh ** JT_CROSS 19801f3f253Sdrh ** JT_OUTER 19901f3f253Sdrh ** JT_NATURAL 20001f3f253Sdrh ** JT_LEFT 20101f3f253Sdrh ** JT_RIGHT 20201f3f253Sdrh ** 20301f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 20401f3f253Sdrh ** 20501f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 20601f3f253Sdrh ** a join type, but put an error in the pParse structure. 20781a23623Sdrh ** 20881a23623Sdrh ** These are the valid join types: 20981a23623Sdrh ** 21081a23623Sdrh ** 21181a23623Sdrh ** pA pB pC Return Value 21281a23623Sdrh ** ------- ----- ----- ------------ 21381a23623Sdrh ** CROSS - - JT_CROSS 21481a23623Sdrh ** INNER - - JT_INNER 21581a23623Sdrh ** LEFT - - JT_LEFT|JT_OUTER 21681a23623Sdrh ** LEFT OUTER - JT_LEFT|JT_OUTER 21781a23623Sdrh ** RIGHT - - JT_RIGHT|JT_OUTER 21881a23623Sdrh ** RIGHT OUTER - JT_RIGHT|JT_OUTER 21981a23623Sdrh ** FULL - - JT_LEFT|JT_RIGHT|JT_OUTER 22081a23623Sdrh ** FULL OUTER - JT_LEFT|JT_RIGHT|JT_OUTER 22181a23623Sdrh ** NATURAL INNER - JT_NATURAL|JT_INNER 22281a23623Sdrh ** NATURAL LEFT - JT_NATURAL|JT_LEFT|JT_OUTER 22381a23623Sdrh ** NATURAL LEFT OUTER JT_NATURAL|JT_LEFT|JT_OUTER 22481a23623Sdrh ** NATURAL RIGHT - JT_NATURAL|JT_RIGHT|JT_OUTER 22581a23623Sdrh ** NATURAL RIGHT OUTER JT_NATURAL|JT_RIGHT|JT_OUTER 22681a23623Sdrh ** NATURAL FULL - JT_NATURAL|JT_LEFT|JT_RIGHT 22781a23623Sdrh ** NATURAL FULL OUTER JT_NATRUAL|JT_LEFT|JT_RIGHT 22881a23623Sdrh ** 22981a23623Sdrh ** To preserve historical compatibly, SQLite also accepts a variety 23081a23623Sdrh ** of other non-standard and in many cases non-sensical join types. 23181a23623Sdrh ** This routine makes as much sense at it can from the nonsense join 23281a23623Sdrh ** type and returns a result. Examples of accepted nonsense join types 23381a23623Sdrh ** include but are not limited to: 23481a23623Sdrh ** 23581a23623Sdrh ** INNER CROSS JOIN -> same as JOIN 23681a23623Sdrh ** NATURAL CROSS JOIN -> same as NATURAL JOIN 23781a23623Sdrh ** OUTER LEFT JOIN -> same as LEFT JOIN 23881a23623Sdrh ** LEFT NATURAL JOIN -> same as NATURAL LEFT JOIN 23981a23623Sdrh ** LEFT RIGHT JOIN -> same as FULL JOIN 24081a23623Sdrh ** RIGHT OUTER FULL JOIN -> same as FULL JOIN 24181a23623Sdrh ** CROSS CROSS CROSS JOIN -> same as JOIN 24281a23623Sdrh ** 24381a23623Sdrh ** The only restrictions on the join type name are: 24481a23623Sdrh ** 24581a23623Sdrh ** * "INNER" cannot appear together with "OUTER", "LEFT", "RIGHT", 24681a23623Sdrh ** or "FULL". 24781a23623Sdrh ** 24881a23623Sdrh ** * "CROSS" cannot appear together with "OUTER", "LEFT", "RIGHT, 24981a23623Sdrh ** or "FULL". 25081a23623Sdrh ** 25181a23623Sdrh ** * If "OUTER" is present then there must also be one of 25281a23623Sdrh ** "LEFT", "RIGHT", or "FULL" 25301f3f253Sdrh */ 2544adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 25501f3f253Sdrh int jointype = 0; 25601f3f253Sdrh Token *apAll[3]; 25701f3f253Sdrh Token *p; 258373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 259373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 2605719628aSdrh static const struct { 261373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 262373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 263373cc2ddSdrh u8 code; /* Join type mask */ 264373cc2ddSdrh } aKeyword[] = { 26581a23623Sdrh /* (0) natural */ { 0, 7, JT_NATURAL }, 26681a23623Sdrh /* (1) left */ { 6, 4, JT_LEFT|JT_OUTER }, 26781a23623Sdrh /* (2) outer */ { 10, 5, JT_OUTER }, 26881a23623Sdrh /* (3) right */ { 14, 5, JT_RIGHT|JT_OUTER }, 26981a23623Sdrh /* (4) full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 27081a23623Sdrh /* (5) inner */ { 23, 5, JT_INNER }, 27181a23623Sdrh /* (6) cross */ { 28, 5, JT_INNER|JT_CROSS }, 27201f3f253Sdrh }; 27301f3f253Sdrh int i, j; 27401f3f253Sdrh apAll[0] = pA; 27501f3f253Sdrh apAll[1] = pB; 27601f3f253Sdrh apAll[2] = pC; 277195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 27801f3f253Sdrh p = apAll[i]; 279373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 280373cc2ddSdrh if( p->n==aKeyword[j].nChar 281373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 282373cc2ddSdrh jointype |= aKeyword[j].code; 28301f3f253Sdrh break; 28401f3f253Sdrh } 28501f3f253Sdrh } 286373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 287373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 28801f3f253Sdrh jointype |= JT_ERROR; 28901f3f253Sdrh break; 29001f3f253Sdrh } 29101f3f253Sdrh } 292ad2d8307Sdrh if( 293ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 29481a23623Sdrh (jointype & JT_ERROR)!=0 || 29581a23623Sdrh (jointype & (JT_OUTER|JT_LEFT|JT_RIGHT))==JT_OUTER 296ad2d8307Sdrh ){ 29781a23623Sdrh const char *zSp1 = " "; 29881a23623Sdrh const char *zSp2 = " "; 29981a23623Sdrh if( pB==0 ){ zSp1++; } 30081a23623Sdrh if( pC==0 ){ zSp2++; } 3010879d5f9Sdrh sqlite3ErrorMsg(pParse, "unknown join type: " 30281a23623Sdrh "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); 30301f3f253Sdrh jointype = JT_INNER; 30401f3f253Sdrh } 30501f3f253Sdrh return jointype; 30601f3f253Sdrh } 30701f3f253Sdrh 30801f3f253Sdrh /* 309ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 310ad2d8307Sdrh ** is not contained in the table. 311ad2d8307Sdrh */ 3126e6d9833Sdan int sqlite3ColumnIndex(Table *pTab, const char *zCol){ 313ad2d8307Sdrh int i; 314a192807cSdrh u8 h = sqlite3StrIHash(zCol); 315a192807cSdrh Column *pCol; 316a192807cSdrh for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){ 317cf9d36d1Sdrh if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i; 318ad2d8307Sdrh } 319ad2d8307Sdrh return -1; 320ad2d8307Sdrh } 321ad2d8307Sdrh 322ad2d8307Sdrh /* 323fe146997Sdrh ** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a 324fe146997Sdrh ** table that has a column named zCol. The search is left-to-right. 325fe146997Sdrh ** The first match found is returned. 32622c4bc89Sdrh ** 3272179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 3282179b434Sdrh ** of the matching column and return TRUE. 3292179b434Sdrh ** 3302179b434Sdrh ** If not found, return FALSE. 3312179b434Sdrh */ 3322179b434Sdrh static int tableAndColumnIndex( 3332179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 334fe146997Sdrh int iStart, /* First member of pSrc->a[] to check */ 335fe146997Sdrh int iEnd, /* Last member of pSrc->a[] to check */ 3362179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 3372179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 3389d41af23Sdan int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 339fe146997Sdrh int bIgnoreHidden /* Ignore hidden columns */ 3402179b434Sdrh ){ 3412179b434Sdrh int i; /* For looping over tables in pSrc */ 3422179b434Sdrh int iCol; /* Index of column matching zCol */ 34322c4bc89Sdrh 344fe146997Sdrh assert( iEnd<pSrc->nSrc ); 345fe146997Sdrh assert( iStart>=0 ); 3462179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 347fe146997Sdrh 348fe146997Sdrh for(i=iStart; i<=iEnd; i++){ 3496e6d9833Sdan iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol); 3509d41af23Sdan if( iCol>=0 3519d41af23Sdan && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0) 3529d41af23Sdan ){ 3532179b434Sdrh if( piTab ){ 3542179b434Sdrh *piTab = i; 3552179b434Sdrh *piCol = iCol; 3562179b434Sdrh } 357fe146997Sdrh return 1; 3582179b434Sdrh } 3592179b434Sdrh } 360fe146997Sdrh return 0; 361ad2d8307Sdrh } 362ad2d8307Sdrh 363ad2d8307Sdrh /* 3641f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 365d1985262Sdrh ** And set the Expr.w.iJoin to iTable for every term in the 36622d6a53aSdrh ** expression. 3671cc093c2Sdrh ** 368e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 369b77c07a7Sdrh ** the OUTER JOIN processing logic that this term is part of the 3701f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 3711f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 3721f16230bSdrh ** WHERE clause during join processing but we need to remember that they 3731f16230bSdrh ** originated in the ON or USING clause. 37422d6a53aSdrh ** 375d1985262Sdrh ** The Expr.w.iJoin tells the WHERE clause processing that the 376d1985262Sdrh ** expression depends on table w.iJoin even if that table is not 37722d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 37822d6a53aSdrh ** for cases like this: 37922d6a53aSdrh ** 38022d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 38122d6a53aSdrh ** 38222d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 38322d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 38422d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 38522d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 38622d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 38722d6a53aSdrh ** the output, which is incorrect. 3881cc093c2Sdrh */ 3893a6e4c59Sdrh void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){ 3903a6e4c59Sdrh assert( joinFlag==EP_FromJoin || joinFlag==EP_InnerJoin ); 3911cc093c2Sdrh while( p ){ 3923a6e4c59Sdrh ExprSetProperty(p, joinFlag); 393c5cd1249Sdrh assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 394ebb6a65dSdrh ExprSetVVAProperty(p, EP_NoReduce); 395d1985262Sdrh p->w.iJoin = iTable; 396a4eeccdfSdrh if( p->op==TK_FUNCTION ){ 397a4eeccdfSdrh assert( ExprUseXList(p) ); 398a4eeccdfSdrh if( p->x.pList ){ 399606f2344Sdrh int i; 400606f2344Sdrh for(i=0; i<p->x.pList->nExpr; i++){ 4013a6e4c59Sdrh sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag); 402606f2344Sdrh } 403606f2344Sdrh } 404a4eeccdfSdrh } 4053a6e4c59Sdrh sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag); 4061cc093c2Sdrh p = p->pRight; 4071cc093c2Sdrh } 4081cc093c2Sdrh } 4091cc093c2Sdrh 4108103a036Sdrh /* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every 411d1985262Sdrh ** term that is marked with EP_FromJoin and w.iJoin==iTable into 4122589787cSdrh ** an ordinary term that omits the EP_FromJoin mark. 4132589787cSdrh ** 4142589787cSdrh ** This happens when a LEFT JOIN is simplified into an ordinary JOIN. 4152589787cSdrh */ 4162589787cSdrh static void unsetJoinExpr(Expr *p, int iTable){ 4172589787cSdrh while( p ){ 4187fbb101cSdrh if( ExprHasProperty(p, EP_FromJoin) 419d1985262Sdrh && (iTable<0 || p->w.iJoin==iTable) ){ 4202589787cSdrh ExprClearProperty(p, EP_FromJoin); 4213a6e4c59Sdrh ExprSetProperty(p, EP_InnerJoin); 4222589787cSdrh } 4238ddf6862Sdan if( p->op==TK_COLUMN && p->iTable==iTable ){ 4248ddf6862Sdan ExprClearProperty(p, EP_CanBeNull); 4258ddf6862Sdan } 426a4eeccdfSdrh if( p->op==TK_FUNCTION ){ 427a4eeccdfSdrh assert( ExprUseXList(p) ); 428a4eeccdfSdrh if( p->x.pList ){ 4292589787cSdrh int i; 4302589787cSdrh for(i=0; i<p->x.pList->nExpr; i++){ 4312589787cSdrh unsetJoinExpr(p->x.pList->a[i].pExpr, iTable); 4322589787cSdrh } 4332589787cSdrh } 434a4eeccdfSdrh } 4352589787cSdrh unsetJoinExpr(p->pLeft, iTable); 4362589787cSdrh p = p->pRight; 4372589787cSdrh } 4382589787cSdrh } 4392589787cSdrh 4401cc093c2Sdrh /* 441ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 442ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 443ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 444ad2d8307Sdrh ** 44591bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 44691bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 44791bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 44891bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 44991bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 45091bb0eedSdrh ** also attached to the left entry. 45191bb0eedSdrh ** 452ad2d8307Sdrh ** This routine returns the number of errors encountered. 453ad2d8307Sdrh */ 454358424aeSdrh static int sqlite3ProcessJoin(Parse *pParse, Select *p){ 45591bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 45691bb0eedSdrh int i, j; /* Loop counters */ 4577601294aSdrh SrcItem *pLeft; /* Left table being joined */ 4587601294aSdrh SrcItem *pRight; /* Right table being joined */ 459ad2d8307Sdrh 46091bb0eedSdrh pSrc = p->pSrc; 46191bb0eedSdrh pLeft = &pSrc->a[0]; 46291bb0eedSdrh pRight = &pLeft[1]; 46391bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 46491bb0eedSdrh Table *pRightTab = pRight->pTab; 4653a6e4c59Sdrh u32 joinType; 46691bb0eedSdrh 467ce2c482eSdrh if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue; 4683a6e4c59Sdrh joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_FromJoin : EP_InnerJoin; 469ad2d8307Sdrh 47022c4bc89Sdrh /* If this is a NATURAL join, synthesize an approprate USING clause 47122c4bc89Sdrh ** to specify which columns should be joined. 472ad2d8307Sdrh */ 4738a48b9c0Sdrh if( pRight->fg.jointype & JT_NATURAL ){ 47422c4bc89Sdrh IdList *pUsing = 0; 475d44f8b23Sdrh if( pRight->fg.isUsing || pRight->u3.pOn ){ 4764adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 477ad2d8307Sdrh "an ON or USING clause", 0); 478ad2d8307Sdrh return 1; 479ad2d8307Sdrh } 4802179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4812179b434Sdrh char *zName; /* Name of column in the right table */ 4822179b434Sdrh 4839d41af23Sdan if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue; 484cf9d36d1Sdrh zName = pRightTab->aCol[j].zCnName; 485fe146997Sdrh if( tableAndColumnIndex(pSrc, 0, i, zName, 0, 0, 1) ){ 486d0453f7eSdrh pUsing = sqlite3IdListAppend(pParse, pUsing, 0); 487d0453f7eSdrh if( pUsing ){ 488d0453f7eSdrh assert( pUsing->nId>0 ); 489d0453f7eSdrh assert( pUsing->a[pUsing->nId-1].zName==0 ); 490d0453f7eSdrh pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName); 491d0453f7eSdrh } 492ad2d8307Sdrh } 493ad2d8307Sdrh } 49422c4bc89Sdrh if( pUsing ){ 49522c4bc89Sdrh pRight->fg.isUsing = 1; 4964ce7bf91Sdrh pRight->fg.isSynthUsing = 1; 49722c4bc89Sdrh pRight->u3.pUsing = pUsing; 49822c4bc89Sdrh } 499abf86bd3Sdrh if( pParse->nErr ) return 1; 500ad2d8307Sdrh } 501ad2d8307Sdrh 502ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 503ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 504ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 505ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 506ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 507ad2d8307Sdrh ** not contained in both tables to be joined. 508ad2d8307Sdrh */ 509d44f8b23Sdrh if( pRight->fg.isUsing ){ 510d44f8b23Sdrh IdList *pList = pRight->u3.pUsing; 511fe146997Sdrh sqlite3 *db = pParse->db; 512d44f8b23Sdrh assert( pList!=0 ); 513ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 5142179b434Sdrh char *zName; /* Name of the term in the USING clause */ 5152179b434Sdrh int iLeft; /* Table on the left with matching column name */ 5162179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 5172179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 518fe146997Sdrh Expr *pE1; /* Reference to the column on the LEFT of the join */ 519fe146997Sdrh Expr *pE2; /* Reference to the column on the RIGHT of the join */ 520fe146997Sdrh Expr *pEq; /* Equality constraint. pE1 == pE2 */ 5212179b434Sdrh 5222179b434Sdrh zName = pList->a[j].zName; 5236e6d9833Sdan iRightCol = sqlite3ColumnIndex(pRightTab, zName); 5242179b434Sdrh if( iRightCol<0 525fe146997Sdrh || tableAndColumnIndex(pSrc, 0, i, zName, &iLeft, &iLeftCol, 526fe146997Sdrh pRight->fg.isSynthUsing)==0 5272179b434Sdrh ){ 5284adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 52991bb0eedSdrh "not present in both tables", zName); 530ad2d8307Sdrh return 1; 531ad2d8307Sdrh } 532fe146997Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol); 533fe146997Sdrh if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){ 534fe146997Sdrh /* This branch runs if the query contains one or more RIGHT or FULL 535fe146997Sdrh ** JOINs. If only a single table on the left side of this join 536fe146997Sdrh ** contains the zName column, then this routine is branch is 537fe146997Sdrh ** a no-op. But if there are two or more tables on the left side 538fe146997Sdrh ** of the join, construct a coalesce() function that gathers all 539fe146997Sdrh ** such tables. Raise an error if more than one of those references 540fe146997Sdrh ** to zName is not also within a prior USING clause. 541fe146997Sdrh ** 542fe146997Sdrh ** We really ought to raise an error if there are two or more 543fe146997Sdrh ** non-USING references to zName on the left of an INNER or LEFT 544fe146997Sdrh ** JOIN. But older versions of SQLite do not do that, so we avoid 545fe146997Sdrh ** adding a new error so as to not break legacy applications. 546052953a4Sdrh */ 547fe146997Sdrh ExprList *pFuncArgs = 0; /* Arguments to the coalesce() */ 548052953a4Sdrh static const Token tkCoalesce = { "coalesce", 8 }; 549fe146997Sdrh while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol, 550fe146997Sdrh pRight->fg.isSynthUsing)!=0 ){ 551fe146997Sdrh if( pSrc->a[iLeft].fg.isUsing==0 552fe146997Sdrh || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0 553fe146997Sdrh ){ 554fe146997Sdrh sqlite3ErrorMsg(pParse, "ambiguous reference to %s in USING()", 555fe146997Sdrh zName); 556fe146997Sdrh break; 557052953a4Sdrh } 558fe146997Sdrh pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1); 559fe146997Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol); 560fe146997Sdrh } 561fe146997Sdrh if( pFuncArgs ){ 562fe146997Sdrh pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1); 563fe146997Sdrh pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0); 564fe146997Sdrh } 565fe146997Sdrh } 566052953a4Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol); 567fe146997Sdrh pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); 568052953a4Sdrh assert( pE2!=0 || pEq==0 ); 569052953a4Sdrh if( pEq ){ 570052953a4Sdrh ExprSetProperty(pEq, joinType); 571052953a4Sdrh assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); 572052953a4Sdrh ExprSetVVAProperty(pEq, EP_NoReduce); 573052953a4Sdrh pEq->w.iJoin = pE2->iTable; 574052953a4Sdrh } 575052953a4Sdrh p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq); 576052953a4Sdrh } 577ad2d8307Sdrh } 578d44f8b23Sdrh 579d44f8b23Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 580d44f8b23Sdrh ** an AND operator. 581d44f8b23Sdrh */ 582d44f8b23Sdrh else if( pRight->u3.pOn ){ 5833a6e4c59Sdrh sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType); 584d44f8b23Sdrh p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn); 585d44f8b23Sdrh pRight->u3.pOn = 0; 586d44f8b23Sdrh } 587ad2d8307Sdrh } 588ad2d8307Sdrh return 0; 589ad2d8307Sdrh } 590ad2d8307Sdrh 591ad2d8307Sdrh /* 592bbd4ae5aSdrh ** An instance of this object holds information (beyond pParse and pSelect) 593bbd4ae5aSdrh ** needed to load the next result row that is to be added to the sorter. 594bbd4ae5aSdrh */ 595bbd4ae5aSdrh typedef struct RowLoadInfo RowLoadInfo; 596bbd4ae5aSdrh struct RowLoadInfo { 597bbd4ae5aSdrh int regResult; /* Store results in array of registers here */ 598bbd4ae5aSdrh u8 ecelFlags; /* Flag argument to ExprCodeExprList() */ 599bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 600bbd4ae5aSdrh ExprList *pExtra; /* Extra columns needed by sorter refs */ 601bbd4ae5aSdrh int regExtraResult; /* Where to load the extra columns */ 602bbd4ae5aSdrh #endif 603bbd4ae5aSdrh }; 604bbd4ae5aSdrh 605bbd4ae5aSdrh /* 606bbd4ae5aSdrh ** This routine does the work of loading query data into an array of 607bbd4ae5aSdrh ** registers so that it can be added to the sorter. 608bbd4ae5aSdrh */ 609bbd4ae5aSdrh static void innerLoopLoadRow( 610bbd4ae5aSdrh Parse *pParse, /* Statement under construction */ 611bbd4ae5aSdrh Select *pSelect, /* The query being coded */ 612bbd4ae5aSdrh RowLoadInfo *pInfo /* Info needed to complete the row load */ 613bbd4ae5aSdrh ){ 614bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult, 615bbd4ae5aSdrh 0, pInfo->ecelFlags); 616bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 617bbd4ae5aSdrh if( pInfo->pExtra ){ 618bbd4ae5aSdrh sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0); 619bbd4ae5aSdrh sqlite3ExprListDelete(pParse->db, pInfo->pExtra); 620bbd4ae5aSdrh } 621bbd4ae5aSdrh #endif 622bbd4ae5aSdrh } 623bbd4ae5aSdrh 624bbd4ae5aSdrh /* 625bbd4ae5aSdrh ** Code the OP_MakeRecord instruction that generates the entry to be 626bbd4ae5aSdrh ** added into the sorter. 627bbd4ae5aSdrh ** 628bbd4ae5aSdrh ** Return the register in which the result is stored. 629bbd4ae5aSdrh */ 630bbd4ae5aSdrh static int makeSorterRecord( 631bbd4ae5aSdrh Parse *pParse, 632bbd4ae5aSdrh SortCtx *pSort, 633bbd4ae5aSdrh Select *pSelect, 634bbd4ae5aSdrh int regBase, 635bbd4ae5aSdrh int nBase 636bbd4ae5aSdrh ){ 637bbd4ae5aSdrh int nOBSat = pSort->nOBSat; 638bbd4ae5aSdrh Vdbe *v = pParse->pVdbe; 639bbd4ae5aSdrh int regOut = ++pParse->nMem; 640bbd4ae5aSdrh if( pSort->pDeferredRowLoad ){ 641bbd4ae5aSdrh innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad); 642bbd4ae5aSdrh } 643bbd4ae5aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut); 644bbd4ae5aSdrh return regOut; 645bbd4ae5aSdrh } 646bbd4ae5aSdrh 647bbd4ae5aSdrh /* 648f45f2326Sdrh ** Generate code that will push the record in registers regData 649f45f2326Sdrh ** through regData+nData-1 onto the sorter. 650c926afbcSdrh */ 651d59ba6ceSdrh static void pushOntoSorter( 652d59ba6ceSdrh Parse *pParse, /* Parser context */ 653079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 654b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 655f45f2326Sdrh int regData, /* First register holding data to be sorted */ 6565579d59fSdrh int regOrigData, /* First register holding data before packing */ 657bbd4ae5aSdrh int nData, /* Number of elements in the regData data array */ 658fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 659d59ba6ceSdrh ){ 660f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 66178d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 662f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 66378d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 664fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 665bbd4ae5aSdrh int regRecord = 0; /* Assembled sorter record */ 66678d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 667f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 668a04a8be2Sdrh int iLimit; /* LIMIT counter */ 669bbd4ae5aSdrh int iSkip = 0; /* End of the sorter insert loop */ 670f45f2326Sdrh 67178d58432Sdan assert( bSeq==0 || bSeq==1 ); 672bbd4ae5aSdrh 673bbd4ae5aSdrh /* Three cases: 674bbd4ae5aSdrh ** (1) The data to be sorted has already been packed into a Record 675bbd4ae5aSdrh ** by a prior OP_MakeRecord. In this case nData==1 and regData 676bbd4ae5aSdrh ** will be completely unrelated to regOrigData. 677bbd4ae5aSdrh ** (2) All output columns are included in the sort record. In that 678bbd4ae5aSdrh ** case regData==regOrigData. 679bbd4ae5aSdrh ** (3) Some output columns are omitted from the sort record due to 680bbd4ae5aSdrh ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the 681c6f36fa3Sdrh ** SQLITE_ECEL_OMITREF optimization, or due to the 682c6f36fa3Sdrh ** SortCtx.pDeferredRowLoad optimiation. In any of these cases 683c6f36fa3Sdrh ** regOrigData is 0 to prevent this routine from trying to copy 684c6f36fa3Sdrh ** values that might not yet exist. 685bbd4ae5aSdrh */ 6869af90b72Sdan assert( nData==1 || regData==regOrigData || regOrigData==0 ); 687bbd4ae5aSdrh 688fd0a2f97Sdrh if( nPrefixReg ){ 68978d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 690bbd4ae5aSdrh regBase = regData - nPrefixReg; 691fd0a2f97Sdrh }else{ 692fb0d6e56Sdrh regBase = pParse->nMem + 1; 693fb0d6e56Sdrh pParse->nMem += nBase; 694fd0a2f97Sdrh } 695a04a8be2Sdrh assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); 696a04a8be2Sdrh iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; 697ec4ccdbcSdrh pSort->labelDone = sqlite3VdbeMakeLabel(pParse); 6985579d59fSdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, 6999af90b72Sdan SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); 70078d58432Sdan if( bSeq ){ 701079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 702fd0a2f97Sdrh } 703257c13faSdan if( nPrefixReg==0 && nData>0 ){ 704236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 70578d58432Sdan } 706079a3072Sdrh if( nOBSat>0 ){ 707079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 708079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 709079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 710079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 711079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 712dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 713079a3072Sdrh 714bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 71526d7e7c6Sdrh regPrevKey = pParse->nMem+1; 71626d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 71778d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 71878d58432Sdan if( bSeq ){ 71978d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 72078d58432Sdan }else{ 72178d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 72278d58432Sdan } 72378d58432Sdan VdbeCoverage(v); 72426d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 725079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 72659b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 727fb0d6e56Sdrh pOp->p2 = nKey + nData; 728dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 7296e11892dSdan memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */ 730dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 731a485ad19Sdrh testcase( pKI->nAllField > pKI->nKeyField+2 ); 732f9eae18bSdan pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat, 733a485ad19Sdrh pKI->nAllField-pKI->nKeyField-1); 734166bc383Sdrh pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */ 735079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 736079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 737ec4ccdbcSdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse); 738079a3072Sdrh pSort->regReturn = ++pParse->nMem; 739079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 74065ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 741a04a8be2Sdrh if( iLimit ){ 742a04a8be2Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); 743a04a8be2Sdrh VdbeCoverage(v); 744a04a8be2Sdrh } 745079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 746236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 747079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 748079a3072Sdrh } 749f226f03dSdan if( iLimit ){ 750f226f03dSdan /* At this point the values for the new sorter entry are stored 751f226f03dSdan ** in an array of registers. They need to be composed into a record 752f226f03dSdan ** and inserted into the sorter if either (a) there are currently 753f226f03dSdan ** less than LIMIT+OFFSET items or (b) the new record is smaller than 754f226f03dSdan ** the largest record currently in the sorter. If (b) is true and there 755f226f03dSdan ** are already LIMIT+OFFSET items in the sorter, delete the largest 756f226f03dSdan ** entry before inserting the new one. This way there are never more 757f226f03dSdan ** than LIMIT+OFFSET items in the sorter. 758f226f03dSdan ** 759f226f03dSdan ** If the new record does not need to be inserted into the sorter, 7606ee5a7b4Sdrh ** jump to the next iteration of the loop. If the pSort->labelOBLopt 7616ee5a7b4Sdrh ** value is not zero, then it is a label of where to jump. Otherwise, 7626ee5a7b4Sdrh ** just bypass the row insert logic. See the header comment on the 7636ee5a7b4Sdrh ** sqlite3WhereOrderByLimitOptLabel() function for additional info. 764f226f03dSdan */ 765f226f03dSdan int iCsr = pSort->iECursor; 766f226f03dSdan sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4); 767f226f03dSdan VdbeCoverage(v); 768f226f03dSdan sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0); 769bbd4ae5aSdrh iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE, 770bbd4ae5aSdrh iCsr, 0, regBase+nOBSat, nExpr-nOBSat); 771f226f03dSdan VdbeCoverage(v); 772f226f03dSdan sqlite3VdbeAddOp1(v, OP_Delete, iCsr); 773f226f03dSdan } 774bbd4ae5aSdrh if( regRecord==0 ){ 775bbd4ae5aSdrh regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase); 776f226f03dSdan } 777079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 778c6aff30cSdrh op = OP_SorterInsert; 779c6aff30cSdrh }else{ 780c6aff30cSdrh op = OP_IdxInsert; 781c6aff30cSdrh } 7824a8b013eSdrh sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, 7834a8b013eSdrh regBase+nOBSat, nBase-nOBSat); 784bbd4ae5aSdrh if( iSkip ){ 785bbd4ae5aSdrh sqlite3VdbeChangeP2(v, iSkip, 7866ee5a7b4Sdrh pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v)); 787bbd4ae5aSdrh } 788c926afbcSdrh } 789c926afbcSdrh 790c926afbcSdrh /* 791ec7429aeSdrh ** Add code to implement the OFFSET 792ea48eb2eSdrh */ 793ec7429aeSdrh static void codeOffset( 794bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 795aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 796b7654111Sdrh int iContinue /* Jump here to skip the current record */ 797ea48eb2eSdrh ){ 798a22a75e5Sdrh if( iOffset>0 ){ 7998b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); 8008b0cf38aSdrh VdbeComment((v, "OFFSET")); 801ea48eb2eSdrh } 802ea48eb2eSdrh } 803ea48eb2eSdrh 804ea48eb2eSdrh /* 80596ecb7b0Sdan ** Add code that will check to make sure the array of registers starting at 80696ecb7b0Sdan ** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and 80776075807Sdan ** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies 80876075807Sdan ** are available. Which is used depends on the value of parameter eTnctType, 80976075807Sdan ** as follows: 810a2a49dc9Sdrh ** 81196ecb7b0Sdan ** WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP: 8129be1339fSdrh ** Build an ephemeral table that contains all entries seen before and 8139be1339fSdrh ** skip entries which have been seen before. 8149be1339fSdrh ** 81576075807Sdan ** Parameter iTab is the cursor number of an ephemeral table that must 81676075807Sdan ** be opened before the VM code generated by this routine is executed. 8175383db71Sdan ** The ephemeral cursor table is queried for a record identical to the 81896ecb7b0Sdan ** record formed by the current array of registers. If one is found, 81996ecb7b0Sdan ** jump to VM address addrRepeat. Otherwise, insert a new record into 82096ecb7b0Sdan ** the ephemeral cursor and proceed. 82196ecb7b0Sdan ** 82276075807Sdan ** The returned value in this case is a copy of parameter iTab. 82376075807Sdan ** 82496ecb7b0Sdan ** WHERE_DISTINCT_ORDERED: 8259be1339fSdrh ** In this case rows are being delivered sorted order. The ephermal 8269be1339fSdrh ** table is not required. Instead, the current set of values 8279be1339fSdrh ** is compared against previous row. If they match, the new row 82896ecb7b0Sdan ** is not distinct and control jumps to VM address addrRepeat. Otherwise, 82996ecb7b0Sdan ** the VM program proceeds with processing the new row. 83096ecb7b0Sdan ** 83176075807Sdan ** The returned value in this case is the register number of the first 83276075807Sdan ** in an array of registers used to store the previous result row so that 8339be1339fSdrh ** it can be compared to the next. The caller must ensure that this 8349be1339fSdrh ** register is initialized to NULL. (The fixDistinctOpenEph() routine 8359be1339fSdrh ** will take care of this initialization.) 83676075807Sdan ** 83796ecb7b0Sdan ** WHERE_DISTINCT_UNIQUE: 83896ecb7b0Sdan ** In this case it has already been determined that the rows are distinct. 8399be1339fSdrh ** No special action is required. The return value is zero. 84096ecb7b0Sdan ** 84196ecb7b0Sdan ** Parameter pEList is the list of expressions used to generated the 84296ecb7b0Sdan ** contents of each row. It is used by this routine to determine (a) 84396ecb7b0Sdan ** how many elements there are in the array of registers and (b) the 84496ecb7b0Sdan ** collation sequences that should be used for the comparisons if 84596ecb7b0Sdan ** eTnctType is WHERE_DISTINCT_ORDERED. 846a2a49dc9Sdrh */ 8475383db71Sdan static int codeDistinct( 8482dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 8494fcb30b7Sdan int eTnctType, /* WHERE_DISTINCT_* value */ 850a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 851a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 8524fcb30b7Sdan ExprList *pEList, /* Expression for each element */ 8534fcb30b7Sdan int regElem /* First element */ 854a2a49dc9Sdrh ){ 8555383db71Sdan int iRet = 0; 8564fcb30b7Sdan int nResultCol = pEList->nExpr; 8574fcb30b7Sdan Vdbe *v = pParse->pVdbe; 8582dcef11bSdrh 8594fcb30b7Sdan switch( eTnctType ){ 8604fcb30b7Sdan case WHERE_DISTINCT_ORDERED: { 8614fcb30b7Sdan int i; 8624fcb30b7Sdan int iJump; /* Jump destination */ 8634fcb30b7Sdan int regPrev; /* Previous row content */ 8644fcb30b7Sdan 8654fcb30b7Sdan /* Allocate space for the previous row */ 8665383db71Sdan iRet = regPrev = pParse->nMem+1; 8674fcb30b7Sdan pParse->nMem += nResultCol; 8684fcb30b7Sdan 8694fcb30b7Sdan iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 8704fcb30b7Sdan for(i=0; i<nResultCol; i++){ 8714fcb30b7Sdan CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr); 8724fcb30b7Sdan if( i<nResultCol-1 ){ 8734fcb30b7Sdan sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i); 8744fcb30b7Sdan VdbeCoverage(v); 8754fcb30b7Sdan }else{ 8764fcb30b7Sdan sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i); 8774fcb30b7Sdan VdbeCoverage(v); 8784fcb30b7Sdan } 8794fcb30b7Sdan sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 8804fcb30b7Sdan sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 8814fcb30b7Sdan } 8824fcb30b7Sdan assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 8834fcb30b7Sdan sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1); 8844fcb30b7Sdan break; 8854fcb30b7Sdan } 8864fcb30b7Sdan 8874fcb30b7Sdan case WHERE_DISTINCT_UNIQUE: { 8885383db71Sdan /* nothing to do */ 8894fcb30b7Sdan break; 8904fcb30b7Sdan } 8914fcb30b7Sdan 8924fcb30b7Sdan default: { 8934fcb30b7Sdan int r1 = sqlite3GetTempReg(pParse); 8944fcb30b7Sdan sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol); 8954fcb30b7Sdan VdbeCoverage(v); 8964fcb30b7Sdan sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1); 8974fcb30b7Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol); 898a67b5cb6Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 8992dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 9005383db71Sdan iRet = iTab; 9014fcb30b7Sdan break; 9024fcb30b7Sdan } 9034fcb30b7Sdan } 9045383db71Sdan 9055383db71Sdan return iRet; 9065383db71Sdan } 9075383db71Sdan 90876075807Sdan /* 9099be1339fSdrh ** This routine runs after codeDistinct(). It makes necessary 9109be1339fSdrh ** adjustments to the OP_OpenEphemeral opcode that the codeDistinct() 9119be1339fSdrh ** routine made use of. This processing must be done separately since 9129be1339fSdrh ** sometimes codeDistinct is called before the OP_OpenEphemeral is actually 9139be1339fSdrh ** laid down. 91476075807Sdan ** 9159be1339fSdrh ** WHERE_DISTINCT_NOOP: 9169be1339fSdrh ** WHERE_DISTINCT_UNORDERED: 9179be1339fSdrh ** 9189be1339fSdrh ** No adjustments necessary. This function is a no-op. 91976075807Sdan ** 92076075807Sdan ** WHERE_DISTINCT_UNIQUE: 9219be1339fSdrh ** 9229be1339fSdrh ** The ephemeral table is not needed. So change the 9239be1339fSdrh ** OP_OpenEphemeral opcode into an OP_Noop. 92476075807Sdan ** 92576075807Sdan ** WHERE_DISTINCT_ORDERED: 9269be1339fSdrh ** 9279be1339fSdrh ** The ephemeral table is not needed. But we do need register 9289be1339fSdrh ** iVal to be initialized to NULL. So change the OP_OpenEphemeral 9299be1339fSdrh ** into an OP_Null on the iVal register. 93076075807Sdan */ 9315383db71Sdan static void fixDistinctOpenEph( 9325383db71Sdan Parse *pParse, /* Parsing and code generating context */ 9335383db71Sdan int eTnctType, /* WHERE_DISTINCT_* value */ 9345383db71Sdan int iVal, /* Value returned by codeDistinct() */ 93576075807Sdan int iOpenEphAddr /* Address of OP_OpenEphemeral instruction for iTab */ 9365383db71Sdan ){ 937c6da6dbaSdrh if( pParse->nErr==0 938c6da6dbaSdrh && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED) 939c6da6dbaSdrh ){ 9405383db71Sdan Vdbe *v = pParse->pVdbe; 94176075807Sdan sqlite3VdbeChangeToNoop(v, iOpenEphAddr); 9429be1339fSdrh if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){ 9439be1339fSdrh sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1); 9449be1339fSdrh } 9455383db71Sdan if( eTnctType==WHERE_DISTINCT_ORDERED ){ 9465383db71Sdan /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared 9475383db71Sdan ** bit on the first register of the previous value. This will cause the 9485383db71Sdan ** OP_Ne added in codeDistinct() to always fail on the first iteration of 9495383db71Sdan ** the loop even if the first row is all NULLs. */ 95076075807Sdan VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr); 9515383db71Sdan pOp->opcode = OP_Null; 9525383db71Sdan pOp->p1 = 1; 9535383db71Sdan pOp->p2 = iVal; 9545383db71Sdan } 9555383db71Sdan } 956a2a49dc9Sdrh } 957a2a49dc9Sdrh 95824e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 95924e25d32Sdan /* 96024e25d32Sdan ** This function is called as part of inner-loop generation for a SELECT 96124e25d32Sdan ** statement with an ORDER BY that is not optimized by an index. It 96224e25d32Sdan ** determines the expressions, if any, that the sorter-reference 96324e25d32Sdan ** optimization should be used for. The sorter-reference optimization 96424e25d32Sdan ** is used for SELECT queries like: 96524e25d32Sdan ** 96624e25d32Sdan ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10 96724e25d32Sdan ** 96824e25d32Sdan ** If the optimization is used for expression "bigblob", then instead of 96924e25d32Sdan ** storing values read from that column in the sorter records, the PK of 97024e25d32Sdan ** the row from table t1 is stored instead. Then, as records are extracted from 97124e25d32Sdan ** the sorter to return to the user, the required value of bigblob is 97224e25d32Sdan ** retrieved directly from table t1. If the values are very large, this 97324e25d32Sdan ** can be more efficient than storing them directly in the sorter records. 97424e25d32Sdan ** 97524e25d32Sdan ** The ExprList_item.bSorterRef flag is set for each expression in pEList 97624e25d32Sdan ** for which the sorter-reference optimization should be enabled. 97724e25d32Sdan ** Additionally, the pSort->aDefer[] array is populated with entries 97824e25d32Sdan ** for all cursors required to evaluate all selected expressions. Finally. 97924e25d32Sdan ** output variable (*ppExtra) is set to an expression list containing 98024e25d32Sdan ** expressions for all extra PK values that should be stored in the 98124e25d32Sdan ** sorter records. 98224e25d32Sdan */ 98324e25d32Sdan static void selectExprDefer( 98424e25d32Sdan Parse *pParse, /* Leave any error here */ 98524e25d32Sdan SortCtx *pSort, /* Sorter context */ 98624e25d32Sdan ExprList *pEList, /* Expressions destined for sorter */ 98724e25d32Sdan ExprList **ppExtra /* Expressions to append to sorter record */ 98824e25d32Sdan ){ 98924e25d32Sdan int i; 99024e25d32Sdan int nDefer = 0; 99124e25d32Sdan ExprList *pExtra = 0; 99224e25d32Sdan for(i=0; i<pEList->nExpr; i++){ 99324e25d32Sdan struct ExprList_item *pItem = &pEList->a[i]; 99424e25d32Sdan if( pItem->u.x.iOrderByCol==0 ){ 99524e25d32Sdan Expr *pExpr = pItem->pExpr; 996477572b9Sdrh Table *pTab; 997ffa5b054Sdrh if( pExpr->op==TK_COLUMN 998ffa5b054Sdrh && pExpr->iColumn>=0 999ffa5b054Sdrh && ALWAYS( ExprUseYTab(pExpr) ) 1000ffa5b054Sdrh && (pTab = pExpr->y.pTab)!=0 1001ffa5b054Sdrh && IsOrdinaryTable(pTab) 1002ffa5b054Sdrh && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0 100324e25d32Sdan ){ 100424e25d32Sdan int j; 100524e25d32Sdan for(j=0; j<nDefer; j++){ 100624e25d32Sdan if( pSort->aDefer[j].iCsr==pExpr->iTable ) break; 100724e25d32Sdan } 100824e25d32Sdan if( j==nDefer ){ 100924e25d32Sdan if( nDefer==ArraySize(pSort->aDefer) ){ 101024e25d32Sdan continue; 101124e25d32Sdan }else{ 101224e25d32Sdan int nKey = 1; 101324e25d32Sdan int k; 101424e25d32Sdan Index *pPk = 0; 101524e25d32Sdan if( !HasRowid(pTab) ){ 101624e25d32Sdan pPk = sqlite3PrimaryKeyIndex(pTab); 101724e25d32Sdan nKey = pPk->nKeyCol; 101824e25d32Sdan } 101924e25d32Sdan for(k=0; k<nKey; k++){ 102024e25d32Sdan Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0); 102124e25d32Sdan if( pNew ){ 102224e25d32Sdan pNew->iTable = pExpr->iTable; 1023477572b9Sdrh assert( ExprUseYTab(pNew) ); 1024eda079cdSdrh pNew->y.pTab = pExpr->y.pTab; 102524e25d32Sdan pNew->iColumn = pPk ? pPk->aiColumn[k] : -1; 102624e25d32Sdan pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew); 102724e25d32Sdan } 102824e25d32Sdan } 1029eda079cdSdrh pSort->aDefer[nDefer].pTab = pExpr->y.pTab; 103024e25d32Sdan pSort->aDefer[nDefer].iCsr = pExpr->iTable; 103124e25d32Sdan pSort->aDefer[nDefer].nKey = nKey; 103224e25d32Sdan nDefer++; 103324e25d32Sdan } 103424e25d32Sdan } 103524e25d32Sdan pItem->bSorterRef = 1; 103624e25d32Sdan } 103724e25d32Sdan } 103824e25d32Sdan } 103924e25d32Sdan pSort->nDefer = (u8)nDefer; 104024e25d32Sdan *ppExtra = pExtra; 104124e25d32Sdan } 104224e25d32Sdan #endif 104324e25d32Sdan 1044c99130fdSdrh /* 10452282792aSdrh ** This routine generates the code for the inside of the inner loop 10462282792aSdrh ** of a SELECT. 104782c3d636Sdrh ** 10482def2f7eSdrh ** If srcTab is negative, then the p->pEList expressions 1049340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 10502def2f7eSdrh ** zero or more, then data is pulled from srcTab and p->pEList is used only 1051257c13faSdan ** to get the number of columns and the collation sequence for each column. 10522282792aSdrh */ 1053d2b3e23bSdrh static void selectInnerLoop( 10542282792aSdrh Parse *pParse, /* The parser context */ 1055df199a25Sdrh Select *p, /* The complete select statement being coded */ 10562def2f7eSdrh int srcTab, /* Pull data from this table if non-negative */ 1057079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 1058e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 10596c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 10602282792aSdrh int iContinue, /* Jump here to continue with next row */ 1061a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 10622282792aSdrh ){ 10632282792aSdrh Vdbe *v = pParse->pVdbe; 1064d847eaadSdrh int i; 1065ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 1066d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 10672b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 1068d847eaadSdrh int nResultCol; /* Number of result columns */ 1069fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 1070bbd4ae5aSdrh RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */ 107138640e15Sdrh 10729af90b72Sdan /* Usually, regResult is the first cell in an array of memory cells 10739af90b72Sdan ** containing the current result row. In this case regOrig is set to the 10749af90b72Sdan ** same value. However, if the results are being sent to the sorter, the 10759af90b72Sdan ** values for any expressions that are also part of the sort-key are omitted 10769af90b72Sdan ** from this array. In this case regOrig is set to zero. */ 10779af90b72Sdan int regResult; /* Start of memory holding current results */ 10789af90b72Sdan int regOrig; /* Start of memory holding full result (or 0) */ 10799af90b72Sdan 10801c767f0dSdrh assert( v ); 10812def2f7eSdrh assert( p->pEList!=0 ); 1082e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 1083079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 1084079a3072Sdrh if( pSort==0 && !hasDistinct ){ 1085a22a75e5Sdrh assert( iContinue!=0 ); 1086aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 1087df199a25Sdrh } 1088df199a25Sdrh 1089967e8b73Sdrh /* Pull the requested columns. 10902282792aSdrh */ 10912def2f7eSdrh nResultCol = p->pEList->nExpr; 109205a86c5cSdrh 10932b596da8Sdrh if( pDest->iSdst==0 ){ 1094fd0a2f97Sdrh if( pSort ){ 109578d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 109678d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 1097fd0a2f97Sdrh pParse->nMem += nPrefixReg; 10981013c932Sdrh } 1099a2a49dc9Sdrh pDest->iSdst = pParse->nMem+1; 1100477df4b3Sdrh pParse->nMem += nResultCol; 110105a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 110205a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 110305a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 110405a86c5cSdrh ** there are columns in the table on the left. The error will be caught 110505a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 110605a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 110705a86c5cSdrh pParse->nMem += nResultCol; 11084c583128Sdrh } 110905a86c5cSdrh pDest->nSdst = nResultCol; 11109af90b72Sdan regOrig = regResult = pDest->iSdst; 1111340309fdSdrh if( srcTab>=0 ){ 1112340309fdSdrh for(i=0; i<nResultCol; i++){ 1113d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 111441cee668Sdrh VdbeComment((v, "%s", p->pEList->a[i].zEName)); 111582c3d636Sdrh } 11169ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 111724e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 111824e25d32Sdan ExprList *pExtra = 0; 111924e25d32Sdan #endif 11209ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 11219ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 11229ed1dfa8Sdanielk1977 */ 1123bbd4ae5aSdrh u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */ 1124bbd4ae5aSdrh ExprList *pEList; 1125df553659Sdrh if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ 1126df553659Sdrh ecelFlags = SQLITE_ECEL_DUP; 1127df553659Sdrh }else{ 1128df553659Sdrh ecelFlags = 0; 1129a2a49dc9Sdrh } 1130ac56ab7eSdan if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ 11312def2f7eSdrh /* For each expression in p->pEList that is a copy of an expression in 1132257c13faSdan ** the ORDER BY clause (pSort->pOrderBy), set the associated 1133257c13faSdan ** iOrderByCol value to one more than the index of the ORDER BY 1134257c13faSdan ** expression within the sort-key that pushOntoSorter() will generate. 11352def2f7eSdrh ** This allows the p->pEList field to be omitted from the sorted record, 1136257c13faSdan ** saving space and CPU cycles. */ 1137257c13faSdan ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); 1138bbd4ae5aSdrh 1139257c13faSdan for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ 1140257c13faSdan int j; 1141257c13faSdan if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ 11422def2f7eSdrh p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; 1143257c13faSdan } 1144257c13faSdan } 114524e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 114624e25d32Sdan selectExprDefer(pParse, pSort, p->pEList, &pExtra); 11475a2e65edSdrh if( pExtra && pParse->db->mallocFailed==0 ){ 114824e25d32Sdan /* If there are any extra PK columns to add to the sorter records, 114924e25d32Sdan ** allocate extra memory cells and adjust the OpenEphemeral 115024e25d32Sdan ** instruction to account for the larger records. This is only 115124e25d32Sdan ** required if there are one or more WITHOUT ROWID tables with 115224e25d32Sdan ** composite primary keys in the SortCtx.aDefer[] array. */ 115324e25d32Sdan VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 115424e25d32Sdan pOp->p2 += (pExtra->nExpr - pSort->nDefer); 115524e25d32Sdan pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer); 115624e25d32Sdan pParse->nMem += pExtra->nExpr; 115724e25d32Sdan } 115824e25d32Sdan #endif 1159bbd4ae5aSdrh 1160bbd4ae5aSdrh /* Adjust nResultCol to account for columns that are omitted 1161bbd4ae5aSdrh ** from the sorter by the optimizations in this branch */ 1162bbd4ae5aSdrh pEList = p->pEList; 1163bbd4ae5aSdrh for(i=0; i<pEList->nExpr; i++){ 1164bbd4ae5aSdrh if( pEList->a[i].u.x.iOrderByCol>0 1165bbd4ae5aSdrh #ifdef SQLITE_ENABLE_SORTER_REFERENCES 1166bbd4ae5aSdrh || pEList->a[i].bSorterRef 1167bbd4ae5aSdrh #endif 1168bbd4ae5aSdrh ){ 1169bbd4ae5aSdrh nResultCol--; 11709af90b72Sdan regOrig = 0; 1171bbd4ae5aSdrh } 1172bbd4ae5aSdrh } 1173bbd4ae5aSdrh 1174bbd4ae5aSdrh testcase( regOrig ); 1175bbd4ae5aSdrh testcase( eDest==SRT_Set ); 1176bbd4ae5aSdrh testcase( eDest==SRT_Mem ); 1177bbd4ae5aSdrh testcase( eDest==SRT_Coroutine ); 1178bbd4ae5aSdrh testcase( eDest==SRT_Output ); 1179257c13faSdan assert( eDest==SRT_Set || eDest==SRT_Mem 1180f2972b60Sdan || eDest==SRT_Coroutine || eDest==SRT_Output 1181f2972b60Sdan || eDest==SRT_Upfrom ); 1182257c13faSdan } 1183bbd4ae5aSdrh sRowLoadInfo.regResult = regResult; 1184bbd4ae5aSdrh sRowLoadInfo.ecelFlags = ecelFlags; 118524e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 1186bbd4ae5aSdrh sRowLoadInfo.pExtra = pExtra; 1187bbd4ae5aSdrh sRowLoadInfo.regExtraResult = regResult + nResultCol; 1188bbd4ae5aSdrh if( pExtra ) nResultCol += pExtra->nExpr; 118924e25d32Sdan #endif 1190bbd4ae5aSdrh if( p->iLimit 1191bbd4ae5aSdrh && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 1192bbd4ae5aSdrh && nPrefixReg>0 1193bbd4ae5aSdrh ){ 1194bbd4ae5aSdrh assert( pSort!=0 ); 1195bbd4ae5aSdrh assert( hasDistinct==0 ); 1196bbd4ae5aSdrh pSort->pDeferredRowLoad = &sRowLoadInfo; 1197c6f36fa3Sdrh regOrig = 0; 1198bbd4ae5aSdrh }else{ 1199bbd4ae5aSdrh innerLoopLoadRow(pParse, p, &sRowLoadInfo); 1200bbd4ae5aSdrh } 1201a2a49dc9Sdrh } 12022282792aSdrh 1203daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 1204daffd0e5Sdrh ** and this row has been seen before, then do not make this row 1205daffd0e5Sdrh ** part of the result. 12062282792aSdrh */ 1207ea48eb2eSdrh if( hasDistinct ){ 12085383db71Sdan int eType = pDistinct->eTnctType; 12095383db71Sdan int iTab = pDistinct->tabTnct; 12104fcb30b7Sdan assert( nResultCol==p->pEList->nExpr ); 12115383db71Sdan iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult); 12125383db71Sdan fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct); 1213079a3072Sdrh if( pSort==0 ){ 1214aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 1215ea48eb2eSdrh } 12162282792aSdrh } 121782c3d636Sdrh 1218c926afbcSdrh switch( eDest ){ 121982c3d636Sdrh /* In this mode, write each query result to the key of the temporary 122082c3d636Sdrh ** table iParm. 12212282792aSdrh */ 122213449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1223c926afbcSdrh case SRT_Union: { 12249cbf3425Sdrh int r1; 12259cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 1226340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 12279b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 12289cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 1229c926afbcSdrh break; 1230c926afbcSdrh } 123182c3d636Sdrh 123282c3d636Sdrh /* Construct a record from the query result, but instead of 123382c3d636Sdrh ** saving that record, use it as a key to delete elements from 123482c3d636Sdrh ** the temporary table iParm. 123582c3d636Sdrh */ 1236c926afbcSdrh case SRT_Except: { 1237340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 1238c926afbcSdrh break; 1239c926afbcSdrh } 1240781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 12415338a5f7Sdanielk1977 12425338a5f7Sdanielk1977 /* Store the result as data using a unique key. 12435338a5f7Sdanielk1977 */ 12448e1ee88cSdrh case SRT_Fifo: 12458e1ee88cSdrh case SRT_DistFifo: 12465338a5f7Sdanielk1977 case SRT_Table: 1247b9bb7c18Sdrh case SRT_EphemTab: { 1248fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 1249373cc2ddSdrh testcase( eDest==SRT_Table ); 1250373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 1251e2248cfdSdrh testcase( eDest==SRT_Fifo ); 1252e2248cfdSdrh testcase( eDest==SRT_DistFifo ); 1253fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 12548ce7184bSdan #ifndef SQLITE_OMIT_CTE 12558e1ee88cSdrh if( eDest==SRT_DistFifo ){ 12568e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 12578ce7184bSdan ** on an ephemeral index. If the current row is already present 12588ce7184bSdan ** in the index, do not write it to the output. If not, add the 12598ce7184bSdan ** current row to the index and proceed with writing it to the 12608ce7184bSdan ** output table as well. */ 12618ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 126238b4149cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); 126338b4149cSdrh VdbeCoverage(v); 12649b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); 1265079a3072Sdrh assert( pSort==0 ); 12668ce7184bSdan } 12678ce7184bSdan #endif 1268079a3072Sdrh if( pSort ){ 1269bbd4ae5aSdrh assert( regResult==regOrig ); 1270bbd4ae5aSdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg); 12715338a5f7Sdanielk1977 }else{ 1272b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 1273b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 1274b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 1275b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1276b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 12775338a5f7Sdanielk1977 } 1278fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 12795338a5f7Sdanielk1977 break; 12805338a5f7Sdanielk1977 } 12812282792aSdrh 12829ed322d6Sdan case SRT_Upfrom: { 1283f2972b60Sdan if( pSort ){ 1284f2972b60Sdan pushOntoSorter( 1285f2972b60Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 12862add24c0Sdrh }else{ 12879ed322d6Sdan int i2 = pDest->iSDParm2; 12889ed322d6Sdan int r1 = sqlite3GetTempReg(pParse); 128909cf5692Sdrh 129009cf5692Sdrh /* If the UPDATE FROM join is an aggregate that matches no rows, it 129109cf5692Sdrh ** might still be trying to return one row, because that is what 129209cf5692Sdrh ** aggregates do. Don't record that empty row in the output table. */ 129309cf5692Sdrh sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v); 129409cf5692Sdrh 129509cf5692Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, 129609cf5692Sdrh regResult+(i2<0), nResultCol-(i2<0), r1); 12979ed322d6Sdan if( i2<0 ){ 12989ed322d6Sdan sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult); 12999ed322d6Sdan }else{ 13009ed322d6Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2); 13019ed322d6Sdan } 1302f2972b60Sdan } 13039ed322d6Sdan break; 13049ed322d6Sdan } 13059ed322d6Sdan 13069ed322d6Sdan #ifndef SQLITE_OMIT_SUBQUERY 13072282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 13082282792aSdrh ** then there should be a single item on the stack. Write this 13092282792aSdrh ** item into the set table with bogus data. 13102282792aSdrh */ 1311c926afbcSdrh case SRT_Set: { 1312079a3072Sdrh if( pSort ){ 1313de941c60Sdrh /* At first glance you would think we could optimize out the 1314de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 1315de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 1316de941c60Sdrh ** case the order does matter */ 131751d82d1dSdan pushOntoSorter( 13189af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1319c926afbcSdrh }else{ 1320b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 13219ed322d6Sdan assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); 13229ed322d6Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 13239ed322d6Sdan r1, pDest->zAffSdst, nResultCol); 13249b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 1325b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 1326c926afbcSdrh } 1327c926afbcSdrh break; 1328c926afbcSdrh } 132982c3d636Sdrh 13309ed322d6Sdan 1331504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 1332ec7429aeSdrh */ 1333ec7429aeSdrh case SRT_Exists: { 13344c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 1335ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1336ec7429aeSdrh break; 1337ec7429aeSdrh } 1338ec7429aeSdrh 13392282792aSdrh /* If this is a scalar select that is part of an expression, then 1340870a0705Sdan ** store the results in the appropriate memory cell or array of 1341870a0705Sdan ** memory cells and break out of the scan loop. 13422282792aSdrh */ 1343c926afbcSdrh case SRT_Mem: { 1344079a3072Sdrh if( pSort ){ 1345257c13faSdan assert( nResultCol<=pDest->nSdst ); 1346870a0705Sdan pushOntoSorter( 13479af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 1348c926afbcSdrh }else{ 1349257c13faSdan assert( nResultCol==pDest->nSdst ); 135053932ce8Sdrh assert( regResult==iParm ); 1351ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 1352c926afbcSdrh } 1353c926afbcSdrh break; 1354c926afbcSdrh } 135593758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 13562282792aSdrh 135781cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 135881cf13ecSdrh case SRT_Output: { /* Return the results */ 1359373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 1360373cc2ddSdrh testcase( eDest==SRT_Output ); 1361079a3072Sdrh if( pSort ){ 13629af90b72Sdan pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, 13635579d59fSdrh nPrefixReg); 1364e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 13652b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1366c182d163Sdrh }else{ 1367340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 1368ac82fcf5Sdrh } 1369142e30dfSdrh break; 1370142e30dfSdrh } 1371142e30dfSdrh 1372fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 1373fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 1374fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 1375fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 1376fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 1377fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 1378fe1c6bb9Sdrh */ 1379fe1c6bb9Sdrh case SRT_DistQueue: 1380fe1c6bb9Sdrh case SRT_Queue: { 1381fe1c6bb9Sdrh int nKey; 1382fe1c6bb9Sdrh int r1, r2, r3; 1383fe1c6bb9Sdrh int addrTest = 0; 1384fe1c6bb9Sdrh ExprList *pSO; 1385fe1c6bb9Sdrh pSO = pDest->pOrderBy; 1386fe1c6bb9Sdrh assert( pSO ); 1387fe1c6bb9Sdrh nKey = pSO->nExpr; 1388fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 1389fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 1390fe1c6bb9Sdrh r3 = r2+nKey+1; 1391fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 1392fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 1393fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 13947e4efaecSdrh ** added to the queue. */ 13957e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 13967e4efaecSdrh regResult, nResultCol); 1397688852abSdrh VdbeCoverage(v); 13987e4efaecSdrh } 13997e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 14007e4efaecSdrh if( eDest==SRT_DistQueue ){ 1401fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 1402cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1403fe1c6bb9Sdrh } 1404fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 1405fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 1406fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 1407fe1c6bb9Sdrh r2+i); 1408fe1c6bb9Sdrh } 1409fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 1410fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 14119b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); 1412fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 1413fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 1414fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 1415fe1c6bb9Sdrh break; 1416fe1c6bb9Sdrh } 1417fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 1418fe1c6bb9Sdrh 1419fe1c6bb9Sdrh 1420fe1c6bb9Sdrh 14216a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 1422d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 1423d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 1424d7489c39Sdrh ** user-defined functions that have side effects. We do not care 1425d7489c39Sdrh ** about the actual results of the select. 1426d7489c39Sdrh */ 1427c926afbcSdrh default: { 1428f46f905aSdrh assert( eDest==SRT_Discard ); 1429c926afbcSdrh break; 1430c926afbcSdrh } 143193758c8dSdanielk1977 #endif 1432c926afbcSdrh } 1433ec7429aeSdrh 14345e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 14355e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 14365e87be87Sdrh ** the output for us. 1437ec7429aeSdrh */ 1438079a3072Sdrh if( pSort==0 && p->iLimit ){ 143916897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 1440ec7429aeSdrh } 144182c3d636Sdrh } 144282c3d636Sdrh 144382c3d636Sdrh /* 1444ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 1445ad124329Sdrh ** X extra columns. 1446323df790Sdrh */ 1447ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 1448d4ab003dSdrh int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*); 1449d8e4b132Sdrh KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); 1450323df790Sdrh if( p ){ 14516e11892dSdan p->aSortFlags = (u8*)&p->aColl[N+X]; 1452a485ad19Sdrh p->nKeyField = (u16)N; 1453a485ad19Sdrh p->nAllField = (u16)(N+X); 1454323df790Sdrh p->enc = ENC(db); 1455323df790Sdrh p->db = db; 14562ec2fb22Sdrh p->nRef = 1; 1457c263f7c4Sdrh memset(&p[1], 0, nExtra); 14582ec2fb22Sdrh }else{ 14593cdb1394Sdrh return (KeyInfo*)sqlite3OomFault(db); 1460323df790Sdrh } 1461323df790Sdrh return p; 1462323df790Sdrh } 1463323df790Sdrh 1464323df790Sdrh /* 14652ec2fb22Sdrh ** Deallocate a KeyInfo object 14662ec2fb22Sdrh */ 14672ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 14682ec2fb22Sdrh if( p ){ 14692ec2fb22Sdrh assert( p->nRef>0 ); 14702ec2fb22Sdrh p->nRef--; 1471dbd6a7dcSdrh if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); 14722ec2fb22Sdrh } 14732ec2fb22Sdrh } 14742ec2fb22Sdrh 14752ec2fb22Sdrh /* 14762ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 14772ec2fb22Sdrh */ 14782ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 14792ec2fb22Sdrh if( p ){ 14802ec2fb22Sdrh assert( p->nRef>0 ); 14812ec2fb22Sdrh p->nRef++; 14822ec2fb22Sdrh } 14832ec2fb22Sdrh return p; 14842ec2fb22Sdrh } 14852ec2fb22Sdrh 14862ec2fb22Sdrh #ifdef SQLITE_DEBUG 14872ec2fb22Sdrh /* 14882ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 14892ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 14902ec2fb22Sdrh ** 14912ec2fb22Sdrh ** This routine is used only inside of assert() statements. 14922ec2fb22Sdrh */ 14932ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 14942ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 14952ec2fb22Sdrh 14962ec2fb22Sdrh /* 1497dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1498dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1499dece1a84Sdrh ** 15000342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 15010342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 15020342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 15030342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 15040342b1f5Sdrh ** index to implement a DISTINCT test. 15050342b1f5Sdrh ** 150660ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1507dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 15082ec2fb22Sdrh ** freed. 1509dece1a84Sdrh */ 1510f9eae18bSdan KeyInfo *sqlite3KeyInfoFromExprList( 1511079a3072Sdrh Parse *pParse, /* Parsing context */ 1512079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1513079a3072Sdrh int iStart, /* Begin with this column of pList */ 1514079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1515079a3072Sdrh ){ 1516dece1a84Sdrh int nExpr; 1517dece1a84Sdrh KeyInfo *pInfo; 1518dece1a84Sdrh struct ExprList_item *pItem; 1519323df790Sdrh sqlite3 *db = pParse->db; 1520dece1a84Sdrh int i; 1521dece1a84Sdrh 1522dece1a84Sdrh nExpr = pList->nExpr; 15233f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1524dece1a84Sdrh if( pInfo ){ 15252ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 15266284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 152770efa84dSdrh pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr); 15286e11892dSdan pInfo->aSortFlags[i-iStart] = pItem->sortFlags; 1529dece1a84Sdrh } 1530dece1a84Sdrh } 1531dece1a84Sdrh return pInfo; 1532dece1a84Sdrh } 1533dece1a84Sdrh 15347f61e92cSdan /* 15357f61e92cSdan ** Name of the connection operator, used for error messages. 15367f61e92cSdan */ 1537aae0f74eSdrh const char *sqlite3SelectOpName(int id){ 15387f61e92cSdan char *z; 15397f61e92cSdan switch( id ){ 15407f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 15417f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 15427f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 15437f61e92cSdan default: z = "UNION"; break; 15447f61e92cSdan } 15457f61e92cSdan return z; 15467f61e92cSdan } 15477f61e92cSdan 15482ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 154917c0bc0cSdan /* 155017c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 155117c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 155217c0bc0cSdan ** where the caption is of the form: 155317c0bc0cSdan ** 155417c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 155517c0bc0cSdan ** 155617c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 155717c0bc0cSdan ** is determined by the zUsage argument. 155817c0bc0cSdan */ 15592ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 1560e2ca99c9Sdrh ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage)); 15612ce22453Sdan } 156217c0bc0cSdan 156317c0bc0cSdan /* 1564bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1565bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1566bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1567bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1568bb2b4418Sdan ** code with #ifndef directives. 1569bb2b4418Sdan */ 1570bb2b4418Sdan # define explainSetInteger(a, b) a = b 1571bb2b4418Sdan 1572bb2b4418Sdan #else 1573bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1574bb2b4418Sdan # define explainTempTable(y,z) 1575bb2b4418Sdan # define explainSetInteger(y,z) 1576bb2b4418Sdan #endif 1577bb2b4418Sdan 1578dece1a84Sdrh 1579dece1a84Sdrh /* 1580d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1581d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1582d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1583d8bc7086Sdrh ** routine generates the code needed to do that. 1584d8bc7086Sdrh */ 1585c926afbcSdrh static void generateSortTail( 1586cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1587c926afbcSdrh Select *p, /* The SELECT statement */ 1588079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1589c926afbcSdrh int nColumn, /* Number of columns of data */ 15906c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1591c926afbcSdrh ){ 1592ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1593a04a8be2Sdrh int addrBreak = pSort->labelDone; /* Jump here to exit loop */ 1594ec4ccdbcSdrh int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */ 159524e25d32Sdan int addr; /* Top of output loop. Jump for Next. */ 1596079a3072Sdrh int addrOnce = 0; 15970342b1f5Sdrh int iTab; 1598079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 15996c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 16002b596da8Sdrh int iParm = pDest->iSDParm; 16012d401ab8Sdrh int regRow; 16022d401ab8Sdrh int regRowid; 1603257c13faSdan int iCol; 160424e25d32Sdan int nKey; /* Number of key columns in sorter record */ 1605f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1606f45f2326Sdrh int i; 160778d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 160824e25d32Sdan int nRefKey = 0; 160970f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 16102d401ab8Sdrh 1611a04a8be2Sdrh assert( addrBreak<0 ); 1612079a3072Sdrh if( pSort->labelBkOut ){ 1613079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1614076e85f5Sdrh sqlite3VdbeGoto(v, addrBreak); 1615079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1616079a3072Sdrh } 161724e25d32Sdan 161824e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 161924e25d32Sdan /* Open any cursors needed for sorter-reference expressions */ 162024e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 162124e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 162224e25d32Sdan int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 162324e25d32Sdan sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead); 162424e25d32Sdan nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey); 162524e25d32Sdan } 162624e25d32Sdan #endif 162724e25d32Sdan 1628079a3072Sdrh iTab = pSort->iECursor; 162971c57db0Sdan if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ 16308efc6a8cSdrh if( eDest==SRT_Mem && p->iOffset ){ 16318efc6a8cSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst); 16328efc6a8cSdrh } 16333e9ca094Sdrh regRowid = 0; 1634f45f2326Sdrh regRow = pDest->iSdst; 1635ed24da4bSdrh }else{ 163651d82d1dSdan regRowid = sqlite3GetTempReg(pParse); 1637375afb8bSdrh if( eDest==SRT_EphemTab || eDest==SRT_Table ){ 1638375afb8bSdrh regRow = sqlite3GetTempReg(pParse); 1639375afb8bSdrh nColumn = 0; 1640375afb8bSdrh }else{ 164151d82d1dSdan regRow = sqlite3GetTempRange(pParse, nColumn); 1642cdd536f0Sdrh } 1643375afb8bSdrh } 1644079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1645079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1646c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1647f45f2326Sdrh iSortTab = pParse->nTab++; 164883553eefSdrh if( pSort->labelBkOut ){ 1649511f9e8dSdrh addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 165083553eefSdrh } 165124e25d32Sdan sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, 165224e25d32Sdan nKey+1+nColumn+nRefKey); 1653079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1654c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1655688852abSdrh VdbeCoverage(v); 1656aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 16576cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 165878d58432Sdan bSeq = 0; 1659c6aff30cSdrh }else{ 1660688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1661aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1662f45f2326Sdrh iSortTab = iTab; 166378d58432Sdan bSeq = 1; 1664f45f2326Sdrh } 1665d6189eafSdan for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){ 166624e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 166724e25d32Sdan if( aOutEx[i].bSorterRef ) continue; 166824e25d32Sdan #endif 16699f895239Sdrh if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++; 16709f895239Sdrh } 167124e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 167224e25d32Sdan if( pSort->nDefer ){ 167324e25d32Sdan int iKey = iCol+1; 167424e25d32Sdan int regKey = sqlite3GetTempRange(pParse, nRefKey); 167524e25d32Sdan 167624e25d32Sdan for(i=0; i<pSort->nDefer; i++){ 167724e25d32Sdan int iCsr = pSort->aDefer[i].iCsr; 167824e25d32Sdan Table *pTab = pSort->aDefer[i].pTab; 167924e25d32Sdan int nKey = pSort->aDefer[i].nKey; 168024e25d32Sdan 168124e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 168224e25d32Sdan if( HasRowid(pTab) ){ 168324e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey); 168424e25d32Sdan sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, 168524e25d32Sdan sqlite3VdbeCurrentAddr(v)+1, regKey); 168624e25d32Sdan }else{ 168724e25d32Sdan int k; 168824e25d32Sdan int iJmp; 16897590d093Sdrh assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey ); 169024e25d32Sdan for(k=0; k<nKey; k++){ 169124e25d32Sdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k); 169224e25d32Sdan } 169324e25d32Sdan iJmp = sqlite3VdbeCurrentAddr(v); 169424e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey); 169524e25d32Sdan sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey); 169624e25d32Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iCsr); 169724e25d32Sdan } 169824e25d32Sdan } 169924e25d32Sdan sqlite3ReleaseTempRange(pParse, regKey, nRefKey); 170024e25d32Sdan } 170124e25d32Sdan #endif 1702d6189eafSdan for(i=nColumn-1; i>=0; i--){ 170324e25d32Sdan #ifdef SQLITE_ENABLE_SORTER_REFERENCES 170424e25d32Sdan if( aOutEx[i].bSorterRef ){ 170524e25d32Sdan sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i); 170624e25d32Sdan }else 170724e25d32Sdan #endif 170824e25d32Sdan { 1709257c13faSdan int iRead; 1710257c13faSdan if( aOutEx[i].u.x.iOrderByCol ){ 1711257c13faSdan iRead = aOutEx[i].u.x.iOrderByCol-1; 1712257c13faSdan }else{ 17139f895239Sdrh iRead = iCol--; 1714257c13faSdan } 1715257c13faSdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); 1716cbb9da33Sdrh VdbeComment((v, "%s", aOutEx[i].zEName)); 1717c6aff30cSdrh } 171824e25d32Sdan } 1719c926afbcSdrh switch( eDest ){ 1720ac56ab7eSdan case SRT_Table: 1721b9bb7c18Sdrh case SRT_EphemTab: { 1722375afb8bSdrh sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow); 17232d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 17242d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 17252d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1726c926afbcSdrh break; 1727c926afbcSdrh } 172893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1729c926afbcSdrh case SRT_Set: { 173071c57db0Sdan assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); 173171c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, 1732553168c7Sdan pDest->zAffSdst, nColumn); 17339b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); 1734c926afbcSdrh break; 1735c926afbcSdrh } 1736c926afbcSdrh case SRT_Mem: { 1737ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1738c926afbcSdrh break; 1739c926afbcSdrh } 174093758c8dSdanielk1977 #endif 1741f2972b60Sdan case SRT_Upfrom: { 1742f2972b60Sdan int i2 = pDest->iSDParm2; 1743f2972b60Sdan int r1 = sqlite3GetTempReg(pParse); 1744f2972b60Sdan sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1); 1745f2972b60Sdan if( i2<0 ){ 1746f2972b60Sdan sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow); 1747f2972b60Sdan }else{ 1748f2972b60Sdan sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2); 1749f2972b60Sdan } 1750f2972b60Sdan break; 1751f2972b60Sdan } 1752373cc2ddSdrh default: { 1753373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 17541c767f0dSdrh testcase( eDest==SRT_Output ); 17551c767f0dSdrh testcase( eDest==SRT_Coroutine ); 17567d10d5a6Sdrh if( eDest==SRT_Output ){ 17572b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 1758a9671a22Sdrh }else{ 17592b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1760ce665cf6Sdrh } 1761ac82fcf5Sdrh break; 1762ac82fcf5Sdrh } 1763c926afbcSdrh } 1764f45f2326Sdrh if( regRowid ){ 176551d82d1dSdan if( eDest==SRT_Set ){ 176651d82d1dSdan sqlite3ReleaseTempRange(pParse, regRow, nColumn); 176751d82d1dSdan }else{ 17682d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 176951d82d1dSdan } 17702d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1771f45f2326Sdrh } 1772ec7429aeSdrh /* The bottom of the loop 1773ec7429aeSdrh */ 1774dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1775079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1776688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1777c6aff30cSdrh }else{ 1778688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1779c6aff30cSdrh } 1780079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1781dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1782d8bc7086Sdrh } 1783d8bc7086Sdrh 1784d8bc7086Sdrh /* 1785517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1786517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1787e78e8284Sdrh ** 17885f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 17895f3e5e74Sdrh ** result in *pEstWidth. 17905f3e5e74Sdrh ** 1791955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1792955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1793955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1794955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1795955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1796955de52cSdanielk1977 ** considered a column by this function. 1797e78e8284Sdrh ** 1798955de52cSdanielk1977 ** SELECT col FROM tbl; 1799955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1800955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1801955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1802955de52cSdanielk1977 ** 1803955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 18045f3e5e74Sdrh ** 18055f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 18065f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1807fcb78a49Sdrh */ 18085f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1809cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E) 1810b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1811cafc2f7bSdrh # define columnType(A,B,C,D,E) columnTypeImpl(A,B) 1812b121dd14Sdrh #endif 18135f3e5e74Sdrh static const char *columnTypeImpl( 1814955de52cSdanielk1977 NameContext *pNC, 1815cafc2f7bSdrh #ifndef SQLITE_ENABLE_COLUMN_METADATA 1816cafc2f7bSdrh Expr *pExpr 1817cafc2f7bSdrh #else 1818955de52cSdanielk1977 Expr *pExpr, 18195f3e5e74Sdrh const char **pzOrigDb, 18205f3e5e74Sdrh const char **pzOrigTab, 1821cafc2f7bSdrh const char **pzOrigCol 1822b121dd14Sdrh #endif 1823955de52cSdanielk1977 ){ 1824955de52cSdanielk1977 char const *zType = 0; 1825517eb646Sdanielk1977 int j; 1826b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1827b121dd14Sdrh char const *zOrigDb = 0; 1828b121dd14Sdrh char const *zOrigTab = 0; 1829b121dd14Sdrh char const *zOrigCol = 0; 1830b121dd14Sdrh #endif 18315338a5f7Sdanielk1977 1832f7ce4291Sdrh assert( pExpr!=0 ); 1833f7ce4291Sdrh assert( pNC->pSrcList!=0 ); 183400e279d9Sdanielk1977 switch( pExpr->op ){ 183500e279d9Sdanielk1977 case TK_COLUMN: { 1836955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1837955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1838955de52cSdanielk1977 ** database table or a subquery. 1839955de52cSdanielk1977 */ 1840955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1841955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1842955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 184343bc88bbSdan while( pNC && !pTab ){ 1844b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1845b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1846b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 18476a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1848955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1849b3bce662Sdanielk1977 }else{ 1850b3bce662Sdanielk1977 pNC = pNC->pNext; 1851b3bce662Sdanielk1977 } 1852b3bce662Sdanielk1977 } 1853955de52cSdanielk1977 185443bc88bbSdan if( pTab==0 ){ 1855417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1856417168adSdrh ** cause this condition to run. Since then, we have restructured how 1857417168adSdrh ** trigger code is generated and so this condition is no longer 185843bc88bbSdan ** possible. However, it can still be true for statements like 185943bc88bbSdan ** the following: 186043bc88bbSdan ** 186143bc88bbSdan ** CREATE TABLE t1(col INTEGER); 186243bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 186343bc88bbSdan ** 186443bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 186543bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 186643bc88bbSdan ** though it should really be "INTEGER". 186743bc88bbSdan ** 186843bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 186943bc88bbSdan ** used. When columnType() is called on the expression 187043bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 187143bc88bbSdan ** branch below. */ 18727e62779aSdrh break; 18737e62779aSdrh } 1874955de52cSdanielk1977 1875477572b9Sdrh assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab ); 1876955de52cSdanielk1977 if( pS ){ 1877955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1878955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1879955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1880955de52cSdanielk1977 */ 18816e5020e8Sdrh if( iCol<pS->pEList->nExpr 18826e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW 18836e5020e8Sdrh && iCol>=0 18846e5020e8Sdrh #else 18856e5020e8Sdrh && ALWAYS(iCol>=0) 18866e5020e8Sdrh #endif 18876e5020e8Sdrh ){ 1888955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1889955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1890955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 1891955de52cSdanielk1977 */ 1892955de52cSdanielk1977 NameContext sNC; 1893955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1894955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 189543bc88bbSdan sNC.pNext = pNC; 1896955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1897cafc2f7bSdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 1898955de52cSdanielk1977 } 1899a78d757cSdrh }else{ 1900a78d757cSdrh /* A real table or a CTE table */ 1901955de52cSdanielk1977 assert( !pS ); 19025f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1903a78d757cSdrh if( iCol<0 ) iCol = pTab->iPKey; 1904a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 1905fcb78a49Sdrh if( iCol<0 ){ 1906fcb78a49Sdrh zType = "INTEGER"; 19075f3e5e74Sdrh zOrigCol = "rowid"; 1908fcb78a49Sdrh }else{ 1909cf9d36d1Sdrh zOrigCol = pTab->aCol[iCol].zCnName; 1910d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 1911955de52cSdanielk1977 } 19125f3e5e74Sdrh zOrigTab = pTab->zName; 1913a78d757cSdrh if( pNC->pParse && pTab->pSchema ){ 1914955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1915e59be010Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; 1916955de52cSdanielk1977 } 19175f3e5e74Sdrh #else 1918a78d757cSdrh assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) ); 19195f3e5e74Sdrh if( iCol<0 ){ 19205f3e5e74Sdrh zType = "INTEGER"; 19215f3e5e74Sdrh }else{ 1922d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 19235f3e5e74Sdrh } 19245f3e5e74Sdrh #endif 1925fcb78a49Sdrh } 192600e279d9Sdanielk1977 break; 1927736c22b8Sdrh } 192893758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 192900e279d9Sdanielk1977 case TK_SELECT: { 1930955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1931955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1932955de52cSdanielk1977 ** statement. 1933955de52cSdanielk1977 */ 1934b3bce662Sdanielk1977 NameContext sNC; 1935a4eeccdfSdrh Select *pS; 1936a4eeccdfSdrh Expr *p; 1937a4eeccdfSdrh assert( ExprUseXSelect(pExpr) ); 1938a4eeccdfSdrh pS = pExpr->x.pSelect; 1939a4eeccdfSdrh p = pS->pEList->a[0].pExpr; 1940955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1941b3bce662Sdanielk1977 sNC.pNext = pNC; 1942955de52cSdanielk1977 sNC.pParse = pNC->pParse; 1943cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 194400e279d9Sdanielk1977 break; 1945fcb78a49Sdrh } 194693758c8dSdanielk1977 #endif 194700e279d9Sdanielk1977 } 194800e279d9Sdanielk1977 19495f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 19505f3e5e74Sdrh if( pzOrigDb ){ 19515f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 19525f3e5e74Sdrh *pzOrigDb = zOrigDb; 19535f3e5e74Sdrh *pzOrigTab = zOrigTab; 19545f3e5e74Sdrh *pzOrigCol = zOrigCol; 1955955de52cSdanielk1977 } 19565f3e5e74Sdrh #endif 1957517eb646Sdanielk1977 return zType; 1958517eb646Sdanielk1977 } 1959517eb646Sdanielk1977 1960517eb646Sdanielk1977 /* 1961517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1962517eb646Sdanielk1977 ** in the result set. 1963517eb646Sdanielk1977 */ 1964517eb646Sdanielk1977 static void generateColumnTypes( 1965517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1966517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1967517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1968517eb646Sdanielk1977 ){ 19693f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1970517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1971517eb646Sdanielk1977 int i; 1972b3bce662Sdanielk1977 NameContext sNC; 1973b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1974955de52cSdanielk1977 sNC.pParse = pParse; 1975eac5fc04Sdrh sNC.pNext = 0; 1976517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1977517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 19783f913576Sdrh const char *zType; 19793f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1980955de52cSdanielk1977 const char *zOrigDb = 0; 1981955de52cSdanielk1977 const char *zOrigTab = 0; 1982955de52cSdanielk1977 const char *zOrigCol = 0; 1983cafc2f7bSdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 1984955de52cSdanielk1977 198585b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 19864b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 19874b1ae99dSdanielk1977 ** virtual machine is deleted. 1988fbcd585fSdanielk1977 */ 198910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 199010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 199110fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 19923f913576Sdrh #else 1993cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 19943f913576Sdrh #endif 199510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1996fcb78a49Sdrh } 19975f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1998fcb78a49Sdrh } 1999fcb78a49Sdrh 2000eac5fc04Sdrh 2001eac5fc04Sdrh /* 2002ec360a8dSdrh ** Compute the column names for a SELECT statement. 2003ec360a8dSdrh ** 2004ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 2005ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 2006ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 2007ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 2008ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 2009ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 2010ec360a8dSdrh ** 2011ec360a8dSdrh ** See Also: sqlite3ColumnsFromExprList() 2012ec360a8dSdrh ** 2013ec360a8dSdrh ** The PRAGMA short_column_names and PRAGMA full_column_names settings are 2014ec360a8dSdrh ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all 2015ec360a8dSdrh ** applications should operate this way. Nevertheless, we need to support the 2016ec360a8dSdrh ** other modes for legacy: 2017ec360a8dSdrh ** 2018ec360a8dSdrh ** short=OFF, full=OFF: Column name is the text of the expression has it 2019ec360a8dSdrh ** originally appears in the SELECT statement. In 2020ec360a8dSdrh ** other words, the zSpan of the result expression. 2021ec360a8dSdrh ** 2022ec360a8dSdrh ** short=ON, full=OFF: (This is the default setting). If the result 20233d240d21Sdrh ** refers directly to a table column, then the 20243d240d21Sdrh ** result column name is just the table column 20253d240d21Sdrh ** name: COLUMN. Otherwise use zSpan. 2026ec360a8dSdrh ** 2027ec360a8dSdrh ** full=ON, short=ANY: If the result refers directly to a table column, 2028ec360a8dSdrh ** then the result column name with the table name 2029ec360a8dSdrh ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan. 203082c3d636Sdrh */ 20319088186bSdrh void sqlite3GenerateColumnNames( 2032832508b7Sdrh Parse *pParse, /* Parser context */ 2033f35f2f92Sdrh Select *pSelect /* Generate column names for this SELECT statement */ 2034832508b7Sdrh ){ 2035d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 2036eac5fc04Sdrh int i; 2037eac5fc04Sdrh Table *pTab; 2038f35f2f92Sdrh SrcList *pTabList; 2039f35f2f92Sdrh ExprList *pEList; 20409bb575fdSdrh sqlite3 *db = pParse->db; 2041ec360a8dSdrh int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */ 2042ec360a8dSdrh int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */ 2043fcabd464Sdrh 2044fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 20453cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 20463cf86063Sdanielk1977 if( pParse->explain ){ 204761de0d1bSdanielk1977 return; 20483cf86063Sdanielk1977 } 20495338a5f7Sdanielk1977 #endif 20503cf86063Sdanielk1977 20515e8b9853Sdrh if( pParse->colNamesSet ) return; 2052f35f2f92Sdrh /* Column names are determined by the left-most term of a compound select */ 2053f35f2f92Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 205407859486Sdrh SELECTTRACE(1,pParse,pSelect,("generating column names\n")); 2055f35f2f92Sdrh pTabList = pSelect->pSrc; 2056f35f2f92Sdrh pEList = pSelect->pEList; 20579802947fSdrh assert( v!=0 ); 2058f7ce4291Sdrh assert( pTabList!=0 ); 2059d8bc7086Sdrh pParse->colNamesSet = 1; 2060ec360a8dSdrh fullName = (db->flags & SQLITE_FullColNames)!=0; 2061ec360a8dSdrh srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName; 206222322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 206382c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 2064ec360a8dSdrh Expr *p = pEList->a[i].pExpr; 2065ec360a8dSdrh 2066ec360a8dSdrh assert( p!=0 ); 20674dd89d5aSdrh assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */ 2068477572b9Sdrh assert( p->op!=TK_COLUMN 2069477572b9Sdrh || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */ 2070cbb9da33Sdrh if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){ 2071ec360a8dSdrh /* An AS clause always takes first priority */ 207241cee668Sdrh char *zName = pEList->a[i].zEName; 207310fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 2074f35f2f92Sdrh }else if( srcName && p->op==TK_COLUMN ){ 207597665873Sdrh char *zCol; 20768aff1015Sdrh int iCol = p->iColumn; 2077eda079cdSdrh pTab = p->y.pTab; 2078f35f2f92Sdrh assert( pTab!=0 ); 20798aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 208097665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 2081b1363206Sdrh if( iCol<0 ){ 208247a6db2bSdrh zCol = "rowid"; 2083b1363206Sdrh }else{ 2084cf9d36d1Sdrh zCol = pTab->aCol[iCol].zCnName; 2085b1363206Sdrh } 2086ec360a8dSdrh if( fullName ){ 208782c3d636Sdrh char *zName = 0; 20881c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 208910fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 209082c3d636Sdrh }else{ 209110fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 209282c3d636Sdrh } 20931bee3d7bSdrh }else{ 2094cbb9da33Sdrh const char *z = pEList->a[i].zEName; 2095859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 2096859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 209782c3d636Sdrh } 209882c3d636Sdrh } 209976d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 21005080aaa7Sdrh } 210182c3d636Sdrh 2102d8bc7086Sdrh /* 210360ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 21047d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 21057d10d5a6Sdrh ** column names for a table that would hold the expression list. 21067d10d5a6Sdrh ** 21077d10d5a6Sdrh ** All column names will be unique. 21087d10d5a6Sdrh ** 21097d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 21107d10d5a6Sdrh ** and other fields of Column are zeroed. 21117d10d5a6Sdrh ** 21127d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 21137d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 2114ec360a8dSdrh ** 2115ec360a8dSdrh ** The only guarantee that SQLite makes about column names is that if the 2116ec360a8dSdrh ** column has an AS clause assigning it a name, that will be the name used. 2117ec360a8dSdrh ** That is the only documented guarantee. However, countless applications 2118ec360a8dSdrh ** developed over the years have made baseless assumptions about column names 2119ec360a8dSdrh ** and will break if those assumptions changes. Hence, use extreme caution 2120ec360a8dSdrh ** when modifying this routine to avoid breaking legacy. 2121ec360a8dSdrh ** 21229088186bSdrh ** See Also: sqlite3GenerateColumnNames() 2123315555caSdrh */ 21248981b904Sdrh int sqlite3ColumnsFromExprList( 21257d10d5a6Sdrh Parse *pParse, /* Parsing context */ 21267d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 2127d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 21287d10d5a6Sdrh Column **paCol /* Write the new column list here */ 21297d10d5a6Sdrh ){ 2130dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 2131dc5ea5c7Sdrh int i, j; /* Loop counters */ 2132ebed3fa3Sdrh u32 cnt; /* Index added to make the name unique */ 2133dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 2134dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 2135dc5ea5c7Sdrh char *zName; /* Column name */ 2136dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 21370315e3ccSdrh Hash ht; /* Hash table of column names */ 21386d5ab2a1Sdrh Table *pTab; 213979d5f63fSdrh 21400315e3ccSdrh sqlite3HashInit(&ht); 21418c2e0f02Sdan if( pEList ){ 21428c2e0f02Sdan nCol = pEList->nExpr; 21438c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 21448c2e0f02Sdan testcase( aCol==0 ); 2145080fe6deSdrh if( NEVER(nCol>32767) ) nCol = 32767; 21468c2e0f02Sdan }else{ 21478c2e0f02Sdan nCol = 0; 21488c2e0f02Sdan aCol = 0; 21498c2e0f02Sdan } 21508836cbbcSdan assert( nCol==(i16)nCol ); 21518c2e0f02Sdan *pnCol = nCol; 21528c2e0f02Sdan *paCol = aCol; 21538c2e0f02Sdan 21540315e3ccSdrh for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ 215579d5f63fSdrh /* Get an appropriate name for the column 215679d5f63fSdrh */ 2157cbb9da33Sdrh if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){ 215879d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 21597d10d5a6Sdrh }else{ 21600d950af3Sdrh Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr); 2161235667a8Sdrh while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){ 2162b07028f7Sdrh pColExpr = pColExpr->pRight; 2163b07028f7Sdrh assert( pColExpr!=0 ); 2164b07028f7Sdrh } 2165477572b9Sdrh if( pColExpr->op==TK_COLUMN 2166477572b9Sdrh && ALWAYS( ExprUseYTab(pColExpr) ) 2167477572b9Sdrh && (pTab = pColExpr->y.pTab)!=0 2168477572b9Sdrh ){ 216993a960a0Sdrh /* For columns use the column name name */ 2170dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 2171f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 2172cf9d36d1Sdrh zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid"; 2173b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 217433e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 217596ceaf86Sdrh zName = pColExpr->u.zToken; 217693a960a0Sdrh }else{ 217779d5f63fSdrh /* Use the original text of the column expression as its name */ 2178cbb9da33Sdrh zName = pEList->a[i].zEName; 21797d10d5a6Sdrh } 218022f70c32Sdrh } 21810cbec59cSdrh if( zName && !sqlite3IsTrueOrFalse(zName) ){ 2182d7ca600eSdrh zName = sqlite3DbStrDup(db, zName); 2183d7ca600eSdrh }else{ 2184155507b3Sdrh zName = sqlite3MPrintf(db,"column%d",i+1); 2185d7ca600eSdrh } 218679d5f63fSdrh 218779d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 218860ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 218979d5f63fSdrh */ 21900315e3ccSdrh cnt = 0; 21910315e3ccSdrh while( zName && sqlite3HashFind(&ht, zName)!=0 ){ 21920315e3ccSdrh nName = sqlite3Strlen30(zName); 2193f7ee8965Sdrh if( nName>0 ){ 21940315e3ccSdrh for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} 21950315e3ccSdrh if( zName[j]==':' ) nName = j; 2196f7ee8965Sdrh } 219796ceaf86Sdrh zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); 2198ebed3fa3Sdrh if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); 219979d5f63fSdrh } 2200cf9d36d1Sdrh pCol->zCnName = zName; 2201d44390c8Sdrh pCol->hName = sqlite3StrIHash(zName); 2202ba68f8f3Sdan sqlite3ColumnPropertiesFromName(0, pCol); 220303d69a68Sdrh if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ 22044a642b60Sdrh sqlite3OomFault(db); 22057d10d5a6Sdrh } 22060315e3ccSdrh } 22070315e3ccSdrh sqlite3HashClear(&ht); 22087d10d5a6Sdrh if( db->mallocFailed ){ 22097d10d5a6Sdrh for(j=0; j<i; j++){ 2210cf9d36d1Sdrh sqlite3DbFree(db, aCol[j].zCnName); 22117d10d5a6Sdrh } 22127d10d5a6Sdrh sqlite3DbFree(db, aCol); 22137d10d5a6Sdrh *paCol = 0; 22147d10d5a6Sdrh *pnCol = 0; 2215fad3039cSmistachkin return SQLITE_NOMEM_BKPT; 22167d10d5a6Sdrh } 22177d10d5a6Sdrh return SQLITE_OK; 22187d10d5a6Sdrh } 2219e014a838Sdanielk1977 22207d10d5a6Sdrh /* 22217d10d5a6Sdrh ** Add type and collation information to a column list based on 22227d10d5a6Sdrh ** a SELECT statement. 22237d10d5a6Sdrh ** 22247d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 22257d10d5a6Sdrh ** The column list has only names, not types or collations. This 22267d10d5a6Sdrh ** routine goes through and adds the types and collations. 22277d10d5a6Sdrh ** 2228b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 22297d10d5a6Sdrh ** statement be resolved. 223079d5f63fSdrh */ 2231ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation( 22327d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 2233186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 223481506b88Sdrh Select *pSelect, /* SELECT used to determine types and collations */ 223581506b88Sdrh char aff /* Default affinity for columns */ 22367d10d5a6Sdrh ){ 22377d10d5a6Sdrh sqlite3 *db = pParse->db; 22387d10d5a6Sdrh NameContext sNC; 22397d10d5a6Sdrh Column *pCol; 22407d10d5a6Sdrh CollSeq *pColl; 22417d10d5a6Sdrh int i; 22427d10d5a6Sdrh Expr *p; 22437d10d5a6Sdrh struct ExprList_item *a; 22447d10d5a6Sdrh 22457d10d5a6Sdrh assert( pSelect!=0 ); 22467d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 2247186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 22487d10d5a6Sdrh if( db->mallocFailed ) return; 2249c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 2250b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 22517d10d5a6Sdrh a = pSelect->pEList->a; 2252186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 2253ed06a131Sdrh const char *zType; 2254913306a5Sdrh i64 n, m; 22556f6e60ddSdrh pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT); 22567d10d5a6Sdrh p = a[i].pExpr; 2257cafc2f7bSdrh zType = columnType(&sNC, p, 0, 0, 0); 2258cafc2f7bSdrh /* pCol->szEst = ... // Column size est for SELECT tables never used */ 2259c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 22600c4db034Sdrh if( zType ){ 22610c4db034Sdrh m = sqlite3Strlen30(zType); 2262cf9d36d1Sdrh n = sqlite3Strlen30(pCol->zCnName); 2263cf9d36d1Sdrh pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2); 2264cf9d36d1Sdrh if( pCol->zCnName ){ 2265cf9d36d1Sdrh memcpy(&pCol->zCnName[n+1], zType, m+1); 2266ed06a131Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 2267146121f5Sdrh }else{ 2268146121f5Sdrh testcase( pCol->colFlags & COLFLAG_HASTYPE ); 2269146121f5Sdrh pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL); 2270ed06a131Sdrh } 2271ed06a131Sdrh } 227296fb16eeSdrh if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff; 2273b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 22745ced0a91Sdrh if( pColl ){ 227565b40093Sdrh assert( pTab->pIndex==0 ); 227665b40093Sdrh sqlite3ColumnSetColl(db, pCol, pColl->zName); 22770202b29eSdanielk1977 } 227822f70c32Sdrh } 2279cafc2f7bSdrh pTab->szTabRow = 1; /* Any non-zero value works */ 22807d10d5a6Sdrh } 22817d10d5a6Sdrh 22827d10d5a6Sdrh /* 22837d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 22847d10d5a6Sdrh ** the result set of that SELECT. 22857d10d5a6Sdrh */ 228681506b88Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){ 22877d10d5a6Sdrh Table *pTab; 22887d10d5a6Sdrh sqlite3 *db = pParse->db; 228970d5dfbaSdrh u64 savedFlags; 22907d10d5a6Sdrh 22917d10d5a6Sdrh savedFlags = db->flags; 2292d5b44d60Sdrh db->flags &= ~(u64)SQLITE_FullColNames; 22937d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 22947d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 2295491b6d89Sdrh db->flags = savedFlags; 22967d10d5a6Sdrh if( pParse->nErr ) return 0; 22977d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 22987d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 22997d10d5a6Sdrh if( pTab==0 ){ 23007d10d5a6Sdrh return 0; 23017d10d5a6Sdrh } 230279df7782Sdrh pTab->nTabRef = 1; 23037d10d5a6Sdrh pTab->zName = 0; 2304cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 23058981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 230681506b88Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff); 230722f70c32Sdrh pTab->iPKey = -1; 23087ce72f69Sdrh if( db->mallocFailed ){ 23091feeaed2Sdan sqlite3DeleteTable(db, pTab); 23107ce72f69Sdrh return 0; 23117ce72f69Sdrh } 231222f70c32Sdrh return pTab; 231322f70c32Sdrh } 231422f70c32Sdrh 231522f70c32Sdrh /* 2316d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 2317d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 2318d8bc7086Sdrh */ 231955965619Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){ 232055965619Sdrh if( pParse->pVdbe ){ 232155965619Sdrh return pParse->pVdbe; 232255965619Sdrh } 2323e0e261a4Sdrh if( pParse->pToplevel==0 2324e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 2325e0e261a4Sdrh ){ 2326e0e261a4Sdrh pParse->okConstFactor = 1; 2327949f9cd5Sdrh } 232855965619Sdrh return sqlite3VdbeCreate(pParse); 23296f077343Sdrh } 2330d8bc7086Sdrh 233115007a99Sdrh 2332d8bc7086Sdrh /* 23337b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 23348c0833fbSdrh ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions 23357b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 2336a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 2337a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 2338a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 2339a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 23407b58daeaSdrh ** 2341d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 23428c0833fbSdrh ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit 23438c0833fbSdrh ** and iOffset should have been preset to appropriate default values (zero) 2344aa9ce707Sdrh ** prior to calling this routine. 2345aa9ce707Sdrh ** 2346aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 2347aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 2348aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 2349aa9ce707Sdrh ** 23508c0833fbSdrh ** Only if pLimit->pLeft!=0 do the limit registers get 23517b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 23527b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 23537b58daeaSdrh ** SELECT statements. 23547b58daeaSdrh */ 2355ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 235602afc861Sdrh Vdbe *v = 0; 235702afc861Sdrh int iLimit = 0; 235815007a99Sdrh int iOffset; 23598b0cf38aSdrh int n; 23608c0833fbSdrh Expr *pLimit = p->pLimit; 23618c0833fbSdrh 23620acb7e48Sdrh if( p->iLimit ) return; 236315007a99Sdrh 23647b58daeaSdrh /* 23657b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 2366f7b5496eSdrh ** controversy about what the correct behavior should be. 23677b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 23687b58daeaSdrh ** no rows. 23697b58daeaSdrh */ 23708c0833fbSdrh if( pLimit ){ 23718c0833fbSdrh assert( pLimit->op==TK_LIMIT ); 23728c0833fbSdrh assert( pLimit->pLeft!=0 ); 23730a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 237415007a99Sdrh v = sqlite3GetVdbe(pParse); 2375aa9ce707Sdrh assert( v!=0 ); 23768c0833fbSdrh if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){ 23779b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 23789b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 2379456e4e4fSdrh if( n==0 ){ 2380076e85f5Sdrh sqlite3VdbeGoto(v, iBreak); 2381c3489bbfSdrh }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ 2382c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)n); 2383c3489bbfSdrh p->selFlags |= SF_FixedLimit; 23849b918ed1Sdrh } 23859b918ed1Sdrh }else{ 23868c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pLeft, iLimit); 2387688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 2388d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 238916897072Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); 23909b918ed1Sdrh } 23918c0833fbSdrh if( pLimit->pRight ){ 23920a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 2393b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 23948c0833fbSdrh sqlite3ExprCode(pParse, pLimit->pRight, iOffset); 2395688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 2396d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 2397cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); 2398d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 2399b7654111Sdrh } 2400d59ba6ceSdrh } 24017b58daeaSdrh } 24027b58daeaSdrh 2403b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 2404fbc4ee7bSdrh /* 2405fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 2406fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 2407fbc4ee7bSdrh ** the column has no default collating sequence. 2408fbc4ee7bSdrh ** 2409fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 2410fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 2411fbc4ee7bSdrh */ 2412dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 2413fbc4ee7bSdrh CollSeq *pRet; 2414dc1bdc4fSdanielk1977 if( p->pPrior ){ 2415dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 2416fbc4ee7bSdrh }else{ 2417fbc4ee7bSdrh pRet = 0; 2418dc1bdc4fSdanielk1977 } 241910c081adSdrh assert( iCol>=0 ); 24202ec18a3cSdrh /* iCol must be less than p->pEList->nExpr. Otherwise an error would 24212ec18a3cSdrh ** have been thrown during name resolution and we would not have gotten 24222ec18a3cSdrh ** this far */ 24232ec18a3cSdrh if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ 2424dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 2425dc1bdc4fSdanielk1977 } 2426dc1bdc4fSdanielk1977 return pRet; 2427d3d39e93Sdrh } 2428d3d39e93Sdrh 242953bed45eSdan /* 243053bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 243153bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 243253bed45eSdan ** structure suitable for implementing the ORDER BY. 243353bed45eSdan ** 243453bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 243553bed45eSdan ** function is responsible for ensuring that this structure is eventually 243653bed45eSdan ** freed. 243753bed45eSdan */ 243853bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 243953bed45eSdan ExprList *pOrderBy = p->pOrderBy; 24407d4c94bcSdrh int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0; 244153bed45eSdan sqlite3 *db = pParse->db; 244253bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 244353bed45eSdan if( pRet ){ 244453bed45eSdan int i; 244553bed45eSdan for(i=0; i<nOrderBy; i++){ 244653bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 244753bed45eSdan Expr *pTerm = pItem->pExpr; 244853bed45eSdan CollSeq *pColl; 244953bed45eSdan 245053bed45eSdan if( pTerm->flags & EP_Collate ){ 245153bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 245253bed45eSdan }else{ 245353bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 245453bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 245553bed45eSdan pOrderBy->a[i].pExpr = 245653bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 245753bed45eSdan } 245853bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 245953bed45eSdan pRet->aColl[i] = pColl; 24606e11892dSdan pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags; 246153bed45eSdan } 246253bed45eSdan } 246353bed45eSdan 246453bed45eSdan return pRet; 246553bed45eSdan } 2466d3d39e93Sdrh 2467781def29Sdrh #ifndef SQLITE_OMIT_CTE 2468781def29Sdrh /* 2469781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 2470781def29Sdrh ** query of the form: 2471781def29Sdrh ** 2472781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 2473781def29Sdrh ** \___________/ \_______________/ 2474781def29Sdrh ** p->pPrior p 2475781def29Sdrh ** 2476781def29Sdrh ** 2477781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 24788a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. 2479781def29Sdrh ** 2480781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 2481781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 2482fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 2483fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 2484fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 2485781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 2486781def29Sdrh ** and the iteration continues until the Queue table is empty. 2487781def29Sdrh ** 2488781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 2489781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 2490781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 2491781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 2492781def29Sdrh ** 2493781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 2494781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 2495781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 2496781def29Sdrh ** 2497781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 2498781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 2499781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 2500781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 2501781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 2502781def29Sdrh ** rows have been skipped. 2503781def29Sdrh */ 2504781def29Sdrh static void generateWithRecursiveQuery( 2505781def29Sdrh Parse *pParse, /* Parsing context */ 2506781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 2507781def29Sdrh SelectDest *pDest /* What to do with query results */ 2508781def29Sdrh ){ 2509781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 2510781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 2511781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 2512e85e1da0Sdrh Select *pSetup; /* The setup query */ 251334055854Sdrh Select *pFirstRec; /* Left-most recursive term */ 2514781def29Sdrh int addrTop; /* Top of the loop */ 2515781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 2516edf83d1eSdrh int iCurrent = 0; /* The Current table */ 2517781def29Sdrh int regCurrent; /* Register holding Current table */ 2518781def29Sdrh int iQueue; /* The Queue table */ 2519781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 25208e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 2521781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 2522781def29Sdrh int i; /* Loop counter */ 2523781def29Sdrh int rc; /* Result code */ 2524fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 25258c0833fbSdrh Expr *pLimit; /* Saved LIMIT and OFFSET */ 2526aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 2527781def29Sdrh 25286afa35c9Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 25296afa35c9Sdan if( p->pWin ){ 25306afa35c9Sdan sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries"); 25316afa35c9Sdan return; 25326afa35c9Sdan } 25336afa35c9Sdan #endif 25346afa35c9Sdan 2535781def29Sdrh /* Obtain authorization to do a recursive query */ 2536781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 2537781def29Sdrh 2538aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 2539ec4ccdbcSdrh addrBreak = sqlite3VdbeMakeLabel(pParse); 254069b9383eSdan p->nSelectRow = 320; /* 4 billion rows */ 2541aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 2542aa9ce707Sdrh pLimit = p->pLimit; 2543aa9ce707Sdrh regLimit = p->iLimit; 2544aa9ce707Sdrh regOffset = p->iOffset; 25458c0833fbSdrh p->pLimit = 0; 2546aa9ce707Sdrh p->iLimit = p->iOffset = 0; 254753bed45eSdan pOrderBy = p->pOrderBy; 2548781def29Sdrh 2549781def29Sdrh /* Locate the cursor number of the Current table */ 2550781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 25518a48b9c0Sdrh if( pSrc->a[i].fg.isRecursive ){ 2552781def29Sdrh iCurrent = pSrc->a[i].iCursor; 2553781def29Sdrh break; 2554781def29Sdrh } 2555781def29Sdrh } 2556781def29Sdrh 2557fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2558781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 25598e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2560781def29Sdrh iQueue = pParse->nTab++; 2561781def29Sdrh if( p->op==TK_UNION ){ 25628e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 2563781def29Sdrh iDistinct = pParse->nTab++; 2564fe1c6bb9Sdrh }else{ 25658e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2566781def29Sdrh } 2567781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2568781def29Sdrh 2569781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2570781def29Sdrh regCurrent = ++pParse->nMem; 2571781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2572fe1c6bb9Sdrh if( pOrderBy ){ 257353bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2574fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2575fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2576fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2577fe1c6bb9Sdrh }else{ 2578781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2579fe1c6bb9Sdrh } 2580fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2581781def29Sdrh if( iDistinct ){ 2582781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2583781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2584781def29Sdrh } 2585781def29Sdrh 258653bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 258753bed45eSdan p->pOrderBy = 0; 258853bed45eSdan 258934055854Sdrh /* Figure out how many elements of the compound SELECT are part of the 259034055854Sdrh ** recursive query. Make sure no recursive elements use aggregate 259134055854Sdrh ** functions. Mark the recursive elements as UNION ALL even if they 259234055854Sdrh ** are really UNION because the distinctness will be enforced by the 259334055854Sdrh ** iDistinct table. pFirstRec is left pointing to the left-most 259434055854Sdrh ** recursive term of the CTE. 259534055854Sdrh */ 259634055854Sdrh for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){ 259734055854Sdrh if( pFirstRec->selFlags & SF_Aggregate ){ 259834055854Sdrh sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); 259934055854Sdrh goto end_of_recursive_query; 260034055854Sdrh } 260134055854Sdrh pFirstRec->op = TK_ALL; 260234055854Sdrh if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break; 260334055854Sdrh } 260434055854Sdrh 2605781def29Sdrh /* Store the results of the setup-query in Queue. */ 260634055854Sdrh pSetup = pFirstRec->pPrior; 2607d227a291Sdrh pSetup->pNext = 0; 260884a01debSdrh ExplainQueryPlan((pParse, 1, "SETUP")); 2609781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2610d227a291Sdrh pSetup->pNext = p; 2611fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2612781def29Sdrh 2613781def29Sdrh /* Find the next row in the Queue and output that row */ 2614688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2615781def29Sdrh 2616781def29Sdrh /* Transfer the next row in Queue over to Current */ 2617781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2618fe1c6bb9Sdrh if( pOrderBy ){ 2619fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2620fe1c6bb9Sdrh }else{ 2621781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2622fe1c6bb9Sdrh } 2623781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2624781def29Sdrh 2625fe1c6bb9Sdrh /* Output the single row in Current */ 2626ec4ccdbcSdrh addrCont = sqlite3VdbeMakeLabel(pParse); 2627aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 26282def2f7eSdrh selectInnerLoop(pParse, p, iCurrent, 2629079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2630688852abSdrh if( regLimit ){ 263116897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); 2632688852abSdrh VdbeCoverage(v); 2633688852abSdrh } 2634fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2635fe1c6bb9Sdrh 2636781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2637781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2638781def29Sdrh */ 263934055854Sdrh pFirstRec->pPrior = 0; 264084a01debSdrh ExplainQueryPlan((pParse, 1, "RECURSIVE STEP")); 2641781def29Sdrh sqlite3Select(pParse, p, &destQueue); 264234055854Sdrh assert( pFirstRec->pPrior==0 ); 264334055854Sdrh pFirstRec->pPrior = pSetup; 2644781def29Sdrh 2645781def29Sdrh /* Keep running the loop until the Queue is empty */ 2646076e85f5Sdrh sqlite3VdbeGoto(v, addrTop); 2647781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2648fe1c6bb9Sdrh 2649fe1c6bb9Sdrh end_of_recursive_query: 26509afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2651fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2652aa9ce707Sdrh p->pLimit = pLimit; 2653fe1c6bb9Sdrh return; 2654781def29Sdrh } 2655b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2656781def29Sdrh 2657781def29Sdrh /* Forward references */ 2658b21e7c70Sdrh static int multiSelectOrderBy( 2659b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2660b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2661a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2662b21e7c70Sdrh ); 2663b21e7c70Sdrh 266445f54a57Sdrh /* 266545f54a57Sdrh ** Handle the special case of a compound-select that originates from a 266645f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 266745f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 266845f54a57Sdrh ** on a VALUES clause. 266945f54a57Sdrh ** 267045f54a57Sdrh ** Because the Select object originates from a VALUES clause: 2671b058d054Sdrh ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1 267245f54a57Sdrh ** (2) All terms are UNION ALL 267345f54a57Sdrh ** (3) There is no ORDER BY clause 2674b058d054Sdrh ** 2675b058d054Sdrh ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES 2676b058d054Sdrh ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))"). 2677b058d054Sdrh ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case. 2678d1f0a86cSdrh ** Since the limit is exactly 1, we only need to evaluate the left-most VALUES. 267945f54a57Sdrh */ 268045f54a57Sdrh static int multiSelectValues( 268145f54a57Sdrh Parse *pParse, /* Parsing context */ 268245f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 268345f54a57Sdrh SelectDest *pDest /* What to do with query results */ 268445f54a57Sdrh ){ 268545f54a57Sdrh int nRow = 1; 268645f54a57Sdrh int rc = 0; 2687fa16f5d9Sdrh int bShowAll = p->pLimit==0; 2688772460fdSdrh assert( p->selFlags & SF_MultiValue ); 268945f54a57Sdrh do{ 269045f54a57Sdrh assert( p->selFlags & SF_Values ); 269145f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 2692923cadb1Sdan assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); 2693ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 269429cdbadfSdrh if( p->pWin ) return -1; 2695ef9f719dSdrh #endif 269645f54a57Sdrh if( p->pPrior==0 ) break; 269745f54a57Sdrh assert( p->pPrior->pNext==p ); 269845f54a57Sdrh p = p->pPrior; 2699fa16f5d9Sdrh nRow += bShowAll; 270045f54a57Sdrh }while(1); 2701fa16f5d9Sdrh ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow, 2702fa16f5d9Sdrh nRow==1 ? "" : "S")); 270345f54a57Sdrh while( p ){ 2704fa16f5d9Sdrh selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1); 2705fa16f5d9Sdrh if( !bShowAll ) break; 270645f54a57Sdrh p->nSelectRow = nRow; 270745f54a57Sdrh p = p->pNext; 270845f54a57Sdrh } 270945f54a57Sdrh return rc; 271045f54a57Sdrh } 2711b21e7c70Sdrh 2712d3d39e93Sdrh /* 271334055854Sdrh ** Return true if the SELECT statement which is known to be the recursive 271434055854Sdrh ** part of a recursive CTE still has its anchor terms attached. If the 271534055854Sdrh ** anchor terms have already been removed, then return false. 271634055854Sdrh */ 271734055854Sdrh static int hasAnchor(Select *p){ 271834055854Sdrh while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; } 271934055854Sdrh return p!=0; 272034055854Sdrh } 272134055854Sdrh 272234055854Sdrh /* 272316ee60ffSdrh ** This routine is called to process a compound query form from 272416ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 272516ee60ffSdrh ** INTERSECT 2726c926afbcSdrh ** 2727e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2728e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2729e78e8284Sdrh ** in which case this routine will be called recursively. 2730e78e8284Sdrh ** 2731e78e8284Sdrh ** The results of the total query are to be written into a destination 2732e78e8284Sdrh ** of type eDest with parameter iParm. 2733e78e8284Sdrh ** 2734e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2735e78e8284Sdrh ** 2736e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2737e78e8284Sdrh ** 2738e78e8284Sdrh ** This statement is parsed up as follows: 2739e78e8284Sdrh ** 2740e78e8284Sdrh ** SELECT c FROM t3 2741e78e8284Sdrh ** | 2742e78e8284Sdrh ** `-----> SELECT b FROM t2 2743e78e8284Sdrh ** | 27444b11c6d3Sjplyon ** `------> SELECT a FROM t1 2745e78e8284Sdrh ** 2746e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2747e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2748e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2749e78e8284Sdrh ** 2750e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2751e78e8284Sdrh ** individual selects always group from left to right. 275282c3d636Sdrh */ 275384ac9d02Sdanielk1977 static int multiSelect( 2754fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2755fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2756a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 275784ac9d02Sdanielk1977 ){ 275884ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 275910e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 276010e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 27611013c932Sdrh SelectDest dest; /* Alternative data destination */ 2762eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2763633e6d57Sdrh sqlite3 *db; /* Database connection */ 276482c3d636Sdrh 27657b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2766fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 276782c3d636Sdrh */ 2768701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2769eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2770b0968b6bSdrh assert( p->selFlags & SF_Compound ); 2771633e6d57Sdrh db = pParse->db; 2772d8bc7086Sdrh pPrior = p->pPrior; 2773bc10377aSdrh dest = *pDest; 2774aae0f74eSdrh assert( pPrior->pOrderBy==0 ); 2775aae0f74eSdrh assert( pPrior->pLimit==0 ); 277682c3d636Sdrh 27774adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2778701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2779d8bc7086Sdrh 27801cc3d75fSdrh /* Create the destination temporary table if necessary 27811cc3d75fSdrh */ 27826c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2783b4964b72Sdanielk1977 assert( p->pEList ); 27842b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 27856c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 27861cc3d75fSdrh } 27871cc3d75fSdrh 278845f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 278945f54a57Sdrh */ 2790772460fdSdrh if( p->selFlags & SF_MultiValue ){ 279145f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 279229cdbadfSdrh if( rc>=0 ) goto multi_select_end; 279329cdbadfSdrh rc = SQLITE_OK; 279445f54a57Sdrh } 279545f54a57Sdrh 2796f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2797f6e369a1Sdrh ** in their result sets. 2798f6e369a1Sdrh */ 2799f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2800923cadb1Sdan assert( p->pEList->nExpr==pPrior->pEList->nExpr ); 2801f6e369a1Sdrh 2802eede6a53Sdan #ifndef SQLITE_OMIT_CTE 280334055854Sdrh if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){ 2804781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 28058ce7184bSdan }else 28068ce7184bSdan #endif 2807f6e369a1Sdrh 2808a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2809a9671a22Sdrh */ 2810f6e369a1Sdrh if( p->pOrderBy ){ 2811a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 281203c3905fSdrh }else{ 2813f6e369a1Sdrh 2814c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN 281503c3905fSdrh if( pPrior->pPrior==0 ){ 28164d79983cSdrh ExplainQueryPlan((pParse, 1, "COMPOUND QUERY")); 2817c631ded5Sdrh ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY")); 2818c631ded5Sdrh } 2819c631ded5Sdrh #endif 2820c631ded5Sdrh 2821f46f905aSdrh /* Generate code for the left and right SELECT statements. 2822d8bc7086Sdrh */ 282382c3d636Sdrh switch( p->op ){ 2824f46f905aSdrh case TK_ALL: { 2825ec7429aeSdrh int addr = 0; 2826252d582aSdrh int nLimit = 0; /* Initialize to suppress harmless compiler warning */ 2827a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2828547180baSdrh pPrior->iLimit = p->iLimit; 2829547180baSdrh pPrior->iOffset = p->iOffset; 2830a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 283193ffb50fSdrh SELECTTRACE(1, pParse, p, ("multiSelect UNION ALL left...\n")); 28327d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2833bc7819d1Sdrh pPrior->pLimit = 0; 283484ac9d02Sdanielk1977 if( rc ){ 283584ac9d02Sdanielk1977 goto multi_select_end; 283684ac9d02Sdanielk1977 } 2837f46f905aSdrh p->pPrior = 0; 28387b58daeaSdrh p->iLimit = pPrior->iLimit; 28397b58daeaSdrh p->iOffset = pPrior->iOffset; 284092b01d53Sdrh if( p->iLimit ){ 284116897072Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); 2842d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 28439f1ef45fSdrh if( p->iOffset ){ 2844cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, 2845cc2fa4cfSdrh p->iLimit, p->iOffset+1, p->iOffset); 28469f1ef45fSdrh } 2847ec7429aeSdrh } 2848c631ded5Sdrh ExplainQueryPlan((pParse, 1, "UNION ALL")); 284993ffb50fSdrh SELECTTRACE(1, pParse, p, ("multiSelect UNION ALL right...\n")); 28507d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2851373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2852eca7e01aSdanielk1977 pDelete = p->pPrior; 2853f46f905aSdrh p->pPrior = pPrior; 2854c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 2855bc7819d1Sdrh if( p->pLimit 2856bc7819d1Sdrh && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit) 2857c3489bbfSdrh && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 285895aa47b1Sdrh ){ 2859c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)nLimit); 286095aa47b1Sdrh } 2861ec7429aeSdrh if( addr ){ 2862ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2863ec7429aeSdrh } 2864f46f905aSdrh break; 2865f46f905aSdrh } 286682c3d636Sdrh case TK_EXCEPT: 286782c3d636Sdrh case TK_UNION: { 286803c3905fSdrh int unionTab; /* Cursor number of the temp table holding result */ 2869ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2870d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 28718c0833fbSdrh Expr *pLimit; /* Saved values of p->nLimit */ 2872dc1bdc4fSdanielk1977 int addr; 28736c8c8ce0Sdanielk1977 SelectDest uniondest; 287482c3d636Sdrh 2875373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2876373cc2ddSdrh testcase( p->op==TK_UNION ); 287793a960a0Sdrh priorOp = SRT_Union; 2878d227a291Sdrh if( dest.eDest==priorOp ){ 2879d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2880c926afbcSdrh ** right. 2881d8bc7086Sdrh */ 2882e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 28832b596da8Sdrh unionTab = dest.iSDParm; 288482c3d636Sdrh }else{ 2885d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2886d8bc7086Sdrh ** intermediate results. 2887d8bc7086Sdrh */ 288882c3d636Sdrh unionTab = pParse->nTab++; 288993a960a0Sdrh assert( p->pOrderBy==0 ); 289066a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2891b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2892b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2893d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 289484ac9d02Sdanielk1977 assert( p->pEList ); 2895d8bc7086Sdrh } 2896d8bc7086Sdrh 289734055854Sdrh 2898d8bc7086Sdrh /* Code the SELECT statements to our left 2899d8bc7086Sdrh */ 2900b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 29011013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 290293ffb50fSdrh SELECTTRACE(1, pParse, p, ("multiSelect EXCEPT/UNION left...\n")); 29037d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 290484ac9d02Sdanielk1977 if( rc ){ 290584ac9d02Sdanielk1977 goto multi_select_end; 290684ac9d02Sdanielk1977 } 2907d8bc7086Sdrh 2908d8bc7086Sdrh /* Code the current SELECT statement 2909d8bc7086Sdrh */ 29104cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 29114cfb22f7Sdrh op = SRT_Except; 29124cfb22f7Sdrh }else{ 29134cfb22f7Sdrh assert( p->op==TK_UNION ); 29144cfb22f7Sdrh op = SRT_Union; 2915d8bc7086Sdrh } 291682c3d636Sdrh p->pPrior = 0; 2917a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2918a2dc3b1aSdanielk1977 p->pLimit = 0; 29196c8c8ce0Sdanielk1977 uniondest.eDest = op; 2920c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2921aae0f74eSdrh sqlite3SelectOpName(p->op))); 292293ffb50fSdrh SELECTTRACE(1, pParse, p, ("multiSelect EXCEPT/UNION right...\n")); 29237d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2924373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2925b7cbf5c1Sdrh assert( p->pOrderBy==0 ); 2926eca7e01aSdanielk1977 pDelete = p->pPrior; 292782c3d636Sdrh p->pPrior = pPrior; 2928a9671a22Sdrh p->pOrderBy = 0; 2929c3489bbfSdrh if( p->op==TK_UNION ){ 2930c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 2931c3489bbfSdrh } 2932633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2933a2dc3b1aSdanielk1977 p->pLimit = pLimit; 293492b01d53Sdrh p->iLimit = 0; 293592b01d53Sdrh p->iOffset = 0; 2936d8bc7086Sdrh 2937d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2938d8bc7086Sdrh ** it is that we currently need. 2939d8bc7086Sdrh */ 29402b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2941a9ebfe20Sdrh assert( p->pEList || db->mallocFailed ); 2942a9ebfe20Sdrh if( dest.eDest!=priorOp && db->mallocFailed==0 ){ 29436b56344dSdrh int iCont, iBreak, iStart; 2944ec4ccdbcSdrh iBreak = sqlite3VdbeMakeLabel(pParse); 2945ec4ccdbcSdrh iCont = sqlite3VdbeMakeLabel(pParse); 2946ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2947688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 29484adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 29492def2f7eSdrh selectInnerLoop(pParse, p, unionTab, 2950e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 29514adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2952688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 29534adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 295466a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 295582c3d636Sdrh } 295682c3d636Sdrh break; 295782c3d636Sdrh } 2958373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 295982c3d636Sdrh int tab1, tab2; 29606b56344dSdrh int iCont, iBreak, iStart; 29618c0833fbSdrh Expr *pLimit; 2962dc1bdc4fSdanielk1977 int addr; 29631013c932Sdrh SelectDest intersectdest; 29649cbf3425Sdrh int r1; 296582c3d636Sdrh 2966d8bc7086Sdrh /* INTERSECT is different from the others since it requires 29676206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2968d8bc7086Sdrh ** by allocating the tables we will need. 2969d8bc7086Sdrh */ 297082c3d636Sdrh tab1 = pParse->nTab++; 297182c3d636Sdrh tab2 = pParse->nTab++; 297293a960a0Sdrh assert( p->pOrderBy==0 ); 2973dc1bdc4fSdanielk1977 297466a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2975b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2976b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2977d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 297884ac9d02Sdanielk1977 assert( p->pEList ); 2979d8bc7086Sdrh 2980d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2981d8bc7086Sdrh */ 29821013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 298393ffb50fSdrh SELECTTRACE(1, pParse, p, ("multiSelect INTERSECT left...\n")); 29847d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 298584ac9d02Sdanielk1977 if( rc ){ 298684ac9d02Sdanielk1977 goto multi_select_end; 298784ac9d02Sdanielk1977 } 2988d8bc7086Sdrh 2989d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2990d8bc7086Sdrh */ 299166a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2992b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2993b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 299482c3d636Sdrh p->pPrior = 0; 2995a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2996a2dc3b1aSdanielk1977 p->pLimit = 0; 29972b596da8Sdrh intersectdest.iSDParm = tab2; 2998c631ded5Sdrh ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE", 2999aae0f74eSdrh sqlite3SelectOpName(p->op))); 300093ffb50fSdrh SELECTTRACE(1, pParse, p, ("multiSelect INTERSECT right...\n")); 30017d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 3002373cc2ddSdrh testcase( rc!=SQLITE_OK ); 3003eca7e01aSdanielk1977 pDelete = p->pPrior; 300482c3d636Sdrh p->pPrior = pPrior; 300503c3905fSdrh if( p->nSelectRow>pPrior->nSelectRow ){ 300603c3905fSdrh p->nSelectRow = pPrior->nSelectRow; 300703c3905fSdrh } 3008633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 3009a2dc3b1aSdanielk1977 p->pLimit = pLimit; 3010d8bc7086Sdrh 3011d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 3012d8bc7086Sdrh ** tables. 3013d8bc7086Sdrh */ 30145f695124Sdrh if( rc ) break; 301582c3d636Sdrh assert( p->pEList ); 3016ec4ccdbcSdrh iBreak = sqlite3VdbeMakeLabel(pParse); 3017ec4ccdbcSdrh iCont = sqlite3VdbeMakeLabel(pParse); 3018ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 3019688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 30209cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 30219057fc7cSdrh iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); 302203c3905fSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); 302303c3905fSdrh VdbeCoverage(v); 30249cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 30252def2f7eSdrh selectInnerLoop(pParse, p, tab1, 3026e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 30274adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 3028688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); 30294adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 303066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 303166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 303282c3d636Sdrh break; 303382c3d636Sdrh } 303482c3d636Sdrh } 30358cdbf836Sdrh 3036c631ded5Sdrh #ifndef SQLITE_OMIT_EXPLAIN 3037c631ded5Sdrh if( p->pNext==0 ){ 3038e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 3039c631ded5Sdrh } 3040c631ded5Sdrh #endif 304103c3905fSdrh } 30428428b3b4Sdrh if( pParse->nErr ) goto multi_select_end; 30437f61e92cSdan 3044a9671a22Sdrh /* Compute collating sequences used by 3045a9671a22Sdrh ** temporary tables needed to implement the compound select. 3046a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 30478cdbf836Sdrh ** 30488cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 30498cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 30508cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 30518cdbf836Sdrh ** no temp tables are required. 3052fbc4ee7bSdrh */ 30537d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 3054fbc4ee7bSdrh int i; /* Loop counter */ 3055fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 30560342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 3057f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 305893a960a0Sdrh int nCol; /* Number of columns in result set */ 3059fbc4ee7bSdrh 3060d227a291Sdrh assert( p->pNext==0 ); 3061aa6fe5bfSdrh assert( p->pEList!=0 ); 306293a960a0Sdrh nCol = p->pEList->nExpr; 3063ad124329Sdrh pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); 3064dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 3065fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT; 3066dc1bdc4fSdanielk1977 goto multi_select_end; 3067dc1bdc4fSdanielk1977 } 30680342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 30690342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 30700342b1f5Sdrh if( 0==*apColl ){ 3071633e6d57Sdrh *apColl = db->pDfltColl; 3072dc1bdc4fSdanielk1977 } 3073dc1bdc4fSdanielk1977 } 3074dc1bdc4fSdanielk1977 30750342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 30760342b1f5Sdrh for(i=0; i<2; i++){ 3077b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 30780342b1f5Sdrh if( addr<0 ){ 30790342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 30800342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 3081b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 30820342b1f5Sdrh break; 30830342b1f5Sdrh } 30840342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 30852ec2fb22Sdrh sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), 30862ec2fb22Sdrh P4_KEYINFO); 30870ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 30880342b1f5Sdrh } 3089dc1bdc4fSdanielk1977 } 30902ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyInfo); 3091dc1bdc4fSdanielk1977 } 3092dc1bdc4fSdanielk1977 3093dc1bdc4fSdanielk1977 multi_select_end: 30942b596da8Sdrh pDest->iSdst = dest.iSdst; 30952b596da8Sdrh pDest->nSdst = dest.nSdst; 3096ce68b6bfSdrh if( pDelete ){ 3097ce68b6bfSdrh sqlite3ParserAddCleanup(pParse, 3098ce68b6bfSdrh (void(*)(sqlite3*,void*))sqlite3SelectDelete, 3099ce68b6bfSdrh pDelete); 3100ce68b6bfSdrh } 310184ac9d02Sdanielk1977 return rc; 31022282792aSdrh } 3103b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 31042282792aSdrh 3105b21e7c70Sdrh /* 310689b31d73Smistachkin ** Error message for when two or more terms of a compound select have different 310789b31d73Smistachkin ** size result sets. 310889b31d73Smistachkin */ 310989b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ 311089b31d73Smistachkin if( p->selFlags & SF_Values ){ 311189b31d73Smistachkin sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 311289b31d73Smistachkin }else{ 311389b31d73Smistachkin sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 3114aae0f74eSdrh " do not have the same number of result columns", 3115aae0f74eSdrh sqlite3SelectOpName(p->op)); 311689b31d73Smistachkin } 311789b31d73Smistachkin } 311889b31d73Smistachkin 311989b31d73Smistachkin /* 3120b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 3121b21e7c70Sdrh ** SELECT statment. 31220acb7e48Sdrh ** 31232b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 31242b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 31250acb7e48Sdrh ** be sent. 31260acb7e48Sdrh ** 31270acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 31280acb7e48Sdrh ** return address. 31290acb7e48Sdrh ** 3130f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 31310acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 31320acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 31330acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 31340acb7e48Sdrh ** keys. 31350acb7e48Sdrh ** 31360acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 31370acb7e48Sdrh ** iBreak. 3138b21e7c70Sdrh */ 31390acb7e48Sdrh static int generateOutputSubroutine( 314092b01d53Sdrh Parse *pParse, /* Parsing context */ 314192b01d53Sdrh Select *p, /* The SELECT statement */ 314292b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 314392b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 314492b01d53Sdrh int regReturn, /* The return address register */ 31450acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 31460acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 314792b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 3148b21e7c70Sdrh ){ 3149b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 315092b01d53Sdrh int iContinue; 315192b01d53Sdrh int addr; 3152b21e7c70Sdrh 315392b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 3154ec4ccdbcSdrh iContinue = sqlite3VdbeMakeLabel(pParse); 31550acb7e48Sdrh 31560acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 31570acb7e48Sdrh */ 31580acb7e48Sdrh if( regPrev ){ 3159728e0f91Sdrh int addr1, addr2; 3160728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 3161728e0f91Sdrh addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 31622ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 3163728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); 3164728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3165e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 3166ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 31670acb7e48Sdrh } 31681f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 31690acb7e48Sdrh 3170d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 31710acb7e48Sdrh */ 3172aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 3173b21e7c70Sdrh 3174e2248cfdSdrh assert( pDest->eDest!=SRT_Exists ); 3175e2248cfdSdrh assert( pDest->eDest!=SRT_Table ); 3176b21e7c70Sdrh switch( pDest->eDest ){ 3177b21e7c70Sdrh /* Store the result as data using a unique key. 3178b21e7c70Sdrh */ 3179b21e7c70Sdrh case SRT_EphemTab: { 3180b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 3181b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 31822b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 31832b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 31842b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 3185b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 3186b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 3187b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 3188b21e7c70Sdrh break; 3189b21e7c70Sdrh } 3190b21e7c70Sdrh 3191b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 31921431807aSdrh /* If we are creating a set for an "expr IN (SELECT ...)". 3193b21e7c70Sdrh */ 3194b21e7c70Sdrh case SRT_Set: { 31956fccc35aSdrh int r1; 319663cecc41Sdrh testcase( pIn->nSdst>1 ); 3197b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 319871c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 31991431807aSdrh r1, pDest->zAffSdst, pIn->nSdst); 32009b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, 32019b4eaebcSdrh pIn->iSdst, pIn->nSdst); 3202b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 3203b21e7c70Sdrh break; 3204b21e7c70Sdrh } 3205b21e7c70Sdrh 3206b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 3207b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 3208cb99c57aSdrh ** of the scan loop. Note that the select might return multiple columns 3209cb99c57aSdrh ** if it is the RHS of a row-value IN operator. 3210b21e7c70Sdrh */ 3211b21e7c70Sdrh case SRT_Mem: { 3212cb99c57aSdrh testcase( pIn->nSdst>1 ); 3213cb99c57aSdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst); 3214b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 3215b21e7c70Sdrh break; 3216b21e7c70Sdrh } 3217b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 3218b21e7c70Sdrh 32197d10d5a6Sdrh /* The results are stored in a sequence of registers 32202b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 3221b21e7c70Sdrh */ 322292b01d53Sdrh case SRT_Coroutine: { 32232b596da8Sdrh if( pDest->iSdst==0 ){ 32242b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 32252b596da8Sdrh pDest->nSdst = pIn->nSdst; 3226b21e7c70Sdrh } 32274b79bde7Sdan sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); 32282b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 322992b01d53Sdrh break; 323092b01d53Sdrh } 323192b01d53Sdrh 3232ccfcbceaSdrh /* If none of the above, then the result destination must be 3233ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 3234ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 3235ccfcbceaSdrh ** 3236ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 3237ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 3238ccfcbceaSdrh ** return the next row of result. 32397d10d5a6Sdrh */ 3240ccfcbceaSdrh default: { 3241ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 32422b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 3243b21e7c70Sdrh break; 3244b21e7c70Sdrh } 3245b21e7c70Sdrh } 324692b01d53Sdrh 324792b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 324892b01d53Sdrh */ 324992b01d53Sdrh if( p->iLimit ){ 325016897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 325192b01d53Sdrh } 325292b01d53Sdrh 325392b01d53Sdrh /* Generate the subroutine return 325492b01d53Sdrh */ 32550acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 325692b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 325792b01d53Sdrh 325892b01d53Sdrh return addr; 3259b21e7c70Sdrh } 3260b21e7c70Sdrh 3261b21e7c70Sdrh /* 3262b21e7c70Sdrh ** Alternative compound select code generator for cases when there 3263b21e7c70Sdrh ** is an ORDER BY clause. 3264b21e7c70Sdrh ** 3265b21e7c70Sdrh ** We assume a query of the following form: 3266b21e7c70Sdrh ** 3267b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 3268b21e7c70Sdrh ** 3269b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 3270b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 3271b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 3272b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 3273b21e7c70Sdrh ** selectB) there are 7 subroutines: 3274b21e7c70Sdrh ** 3275b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 3276b21e7c70Sdrh ** of the compound query. 3277b21e7c70Sdrh ** 3278b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 3279b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 3280b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 3281b21e7c70Sdrh ** appears only in B.) 3282b21e7c70Sdrh ** 3283b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 3284b21e7c70Sdrh ** 3285b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 3286b21e7c70Sdrh ** 3287b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 3288b21e7c70Sdrh ** 3289b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 3290b21e7c70Sdrh ** 3291b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 3292b21e7c70Sdrh ** 3293b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 3294b21e7c70Sdrh ** <operator> is used: 3295b21e7c70Sdrh ** 3296b21e7c70Sdrh ** 3297b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 3298b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 3299b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 3300b21e7c70Sdrh ** 33010acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 3302b21e7c70Sdrh ** 3303b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 3304b21e7c70Sdrh ** 33050acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 3306b21e7c70Sdrh ** 33070acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 33080acb7e48Sdrh ** 33090acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 33100acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 33110acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 33120acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 33130acb7e48Sdrh ** 33140acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 33150acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 33160acb7e48Sdrh ** output value. A comparison is made against this value and the output 33170acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 3318b21e7c70Sdrh ** 3319b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 3320b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 3321b21e7c70Sdrh ** 3322b21e7c70Sdrh ** goto Init 3323b21e7c70Sdrh ** coA: coroutine for left query (A) 3324b21e7c70Sdrh ** coB: coroutine for right query (B) 3325b21e7c70Sdrh ** outA: output one row of A 3326b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 3327b21e7c70Sdrh ** EofA: ... 3328b21e7c70Sdrh ** EofB: ... 3329b21e7c70Sdrh ** AltB: ... 3330b21e7c70Sdrh ** AeqB: ... 3331b21e7c70Sdrh ** AgtB: ... 3332b21e7c70Sdrh ** Init: initialize coroutine registers 3333b21e7c70Sdrh ** yield coA 3334b21e7c70Sdrh ** if eof(A) goto EofA 3335b21e7c70Sdrh ** yield coB 3336b21e7c70Sdrh ** if eof(B) goto EofB 3337b21e7c70Sdrh ** Cmpr: Compare A, B 3338b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 3339b21e7c70Sdrh ** End: ... 3340b21e7c70Sdrh ** 3341b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 3342b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 3343b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 3344b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 3345b21e7c70Sdrh */ 3346de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 3347b21e7c70Sdrh static int multiSelectOrderBy( 3348b21e7c70Sdrh Parse *pParse, /* Parsing context */ 3349b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 3350a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 3351b21e7c70Sdrh ){ 33520acb7e48Sdrh int i, j; /* Loop counters */ 3353b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 335438cebe07Sdrh Select *pSplit; /* Left-most SELECT in the right-hand group */ 335538cebe07Sdrh int nSelect; /* Number of SELECT statements in the compound */ 3356b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 3357b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 3358b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 335992b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 336092b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 336192b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 336292b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 336392b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 336492b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 336592b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 3366b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 336792b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 336881cf13ecSdrh int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ 336992b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 337092b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 337192b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 337292b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 337392b01d53Sdrh int regLimitA; /* Limit register for select-A */ 337492b01d53Sdrh int regLimitB; /* Limit register for select-A */ 33750acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 337692b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 337792b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 337892b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 337992b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 3380728e0f91Sdrh int addr1; /* Jump instructions that get retargetted */ 338192b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 338296067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 33830acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 33840acb7e48Sdrh sqlite3 *db; /* Database connection */ 33850acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 33860acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 3387abc38158Sdrh u32 *aPermute; /* Mapping from ORDER BY terms to result set columns */ 3388b21e7c70Sdrh 338992b01d53Sdrh assert( p->pOrderBy!=0 ); 339096067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 33910acb7e48Sdrh db = pParse->db; 339292b01d53Sdrh v = pParse->pVdbe; 3393ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 3394ec4ccdbcSdrh labelEnd = sqlite3VdbeMakeLabel(pParse); 3395ec4ccdbcSdrh labelCmpr = sqlite3VdbeMakeLabel(pParse); 33960acb7e48Sdrh 3397b21e7c70Sdrh 339892b01d53Sdrh /* Patch up the ORDER BY clause 339992b01d53Sdrh */ 340092b01d53Sdrh op = p->op; 340138cebe07Sdrh assert( p->pPrior->pOrderBy==0 ); 34020acb7e48Sdrh pOrderBy = p->pOrderBy; 340393a960a0Sdrh assert( pOrderBy ); 34040acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 340593a960a0Sdrh 34060acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 34070acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 34080acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 34090acb7e48Sdrh */ 34100acb7e48Sdrh if( op!=TK_ALL ){ 34110acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 34127d10d5a6Sdrh struct ExprList_item *pItem; 34137d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 34147d4c94bcSdrh assert( pItem!=0 ); 3415c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 ); 3416c2acc4e4Sdrh if( pItem->u.x.iOrderByCol==i ) break; 34170acb7e48Sdrh } 34180acb7e48Sdrh if( j==nOrderBy ){ 3419b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 3420fad3039cSmistachkin if( pNew==0 ) return SQLITE_NOMEM_BKPT; 34210acb7e48Sdrh pNew->flags |= EP_IntValue; 342233e619fcSdrh pNew->u.iValue = i; 342343606175Sdrh p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 3424c2acc4e4Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; 34250acb7e48Sdrh } 34260acb7e48Sdrh } 34270acb7e48Sdrh } 34280acb7e48Sdrh 34290acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 343010c081adSdrh ** the permutation used to determine if the next 34310acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 34320acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 34330acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 34340acb7e48Sdrh ** collation. 34350acb7e48Sdrh */ 3436abc38158Sdrh aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1)); 34370acb7e48Sdrh if( aPermute ){ 34387d10d5a6Sdrh struct ExprList_item *pItem; 3439b1702026Sdrh aPermute[0] = nOrderBy; 3440b1702026Sdrh for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ 34417d4c94bcSdrh assert( pItem!=0 ); 34426736618aSdrh assert( pItem->u.x.iOrderByCol>0 ); 34432ec18a3cSdrh assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 3444c2acc4e4Sdrh aPermute[i] = pItem->u.x.iOrderByCol - 1; 34450acb7e48Sdrh } 344653bed45eSdan pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 34470acb7e48Sdrh }else{ 34480acb7e48Sdrh pKeyMerge = 0; 34490acb7e48Sdrh } 34500acb7e48Sdrh 34510acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 34520acb7e48Sdrh ** for the logic that removes duplicate result rows when the 34530acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 34540acb7e48Sdrh */ 34550acb7e48Sdrh if( op==TK_ALL ){ 34560acb7e48Sdrh regPrev = 0; 34570acb7e48Sdrh }else{ 34580acb7e48Sdrh int nExpr = p->pEList->nExpr; 34591c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 3460c8ac0d16Sdrh regPrev = pParse->nMem+1; 3461c8ac0d16Sdrh pParse->nMem += nExpr+1; 34620acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 3463ad124329Sdrh pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); 34640acb7e48Sdrh if( pKeyDup ){ 34652ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); 34660acb7e48Sdrh for(i=0; i<nExpr; i++){ 34670acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 34686e11892dSdan pKeyDup->aSortFlags[i] = 0; 34690acb7e48Sdrh } 34700acb7e48Sdrh } 34710acb7e48Sdrh } 347292b01d53Sdrh 347392b01d53Sdrh /* Separate the left and the right query from one another 347492b01d53Sdrh */ 347538cebe07Sdrh nSelect = 1; 347638cebe07Sdrh if( (op==TK_ALL || op==TK_UNION) 347738cebe07Sdrh && OptimizationEnabled(db, SQLITE_BalancedMerge) 347838cebe07Sdrh ){ 347938cebe07Sdrh for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){ 348038cebe07Sdrh nSelect++; 348138cebe07Sdrh assert( pSplit->pPrior->pNext==pSplit ); 348238cebe07Sdrh } 348338cebe07Sdrh } 348438cebe07Sdrh if( nSelect<=3 ){ 348538cebe07Sdrh pSplit = p; 348638cebe07Sdrh }else{ 348738cebe07Sdrh pSplit = p; 348838cebe07Sdrh for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; } 348938cebe07Sdrh } 349038cebe07Sdrh pPrior = pSplit->pPrior; 349198bb34c5Sdrh assert( pPrior!=0 ); 349238cebe07Sdrh pSplit->pPrior = 0; 3493d227a291Sdrh pPrior->pNext = 0; 349438cebe07Sdrh assert( p->pOrderBy == pOrderBy ); 349538cebe07Sdrh assert( pOrderBy!=0 || db->mallocFailed ); 349638cebe07Sdrh pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 34977d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 34987d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 349992b01d53Sdrh 350092b01d53Sdrh /* Compute the limit registers */ 350192b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 35020acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 350392b01d53Sdrh regLimitA = ++pParse->nMem; 350492b01d53Sdrh regLimitB = ++pParse->nMem; 350592b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 350692b01d53Sdrh regLimitA); 350792b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 350892b01d53Sdrh }else{ 350992b01d53Sdrh regLimitA = regLimitB = 0; 351092b01d53Sdrh } 3511633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 35120acb7e48Sdrh p->pLimit = 0; 351392b01d53Sdrh 3514b21e7c70Sdrh regAddrA = ++pParse->nMem; 3515b21e7c70Sdrh regAddrB = ++pParse->nMem; 3516b21e7c70Sdrh regOutA = ++pParse->nMem; 3517b21e7c70Sdrh regOutB = ++pParse->nMem; 3518b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 3519b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 3520e2ca99c9Sdrh 3521aae0f74eSdrh ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op))); 3522b21e7c70Sdrh 352392b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 35240acb7e48Sdrh ** left of the compound operator - the "A" select. 35250acb7e48Sdrh */ 3526ed71a839Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 3527728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 3528ed71a839Sdrh VdbeComment((v, "left SELECT")); 352992b01d53Sdrh pPrior->iLimit = regLimitA; 3530c631ded5Sdrh ExplainQueryPlan((pParse, 1, "LEFT")); 35317d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 35322fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrA); 3533728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3534b21e7c70Sdrh 353592b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 353692b01d53Sdrh ** the right - the "B" select 353792b01d53Sdrh */ 3538ed71a839Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 3539728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 3540ed71a839Sdrh VdbeComment((v, "right SELECT")); 354192b01d53Sdrh savedLimit = p->iLimit; 354292b01d53Sdrh savedOffset = p->iOffset; 354392b01d53Sdrh p->iLimit = regLimitB; 354492b01d53Sdrh p->iOffset = 0; 3545c631ded5Sdrh ExplainQueryPlan((pParse, 1, "RIGHT")); 35467d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 354792b01d53Sdrh p->iLimit = savedLimit; 354892b01d53Sdrh p->iOffset = savedOffset; 35492fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrB); 3550b21e7c70Sdrh 355192b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 35520acb7e48Sdrh ** select as the next output row of the compound select. 355392b01d53Sdrh */ 3554b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 35550acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 35560acb7e48Sdrh p, &destA, pDest, regOutA, 35572ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 3558b21e7c70Sdrh 355992b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 35600acb7e48Sdrh ** select as the next output row of the compound select. 356192b01d53Sdrh */ 35620acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 3563b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 35640acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 35650acb7e48Sdrh p, &destB, pDest, regOutB, 35662ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 35670acb7e48Sdrh } 35682ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyDup); 3569b21e7c70Sdrh 357092b01d53Sdrh /* Generate a subroutine to run when the results from select A 357192b01d53Sdrh ** are exhausted and only data in select B remains. 357292b01d53Sdrh */ 357392b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 357481cf13ecSdrh addrEofA_noB = addrEofA = labelEnd; 357592b01d53Sdrh }else{ 357681cf13ecSdrh VdbeNoopComment((v, "eof-A subroutine")); 357781cf13ecSdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 357881cf13ecSdrh addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 3579688852abSdrh VdbeCoverage(v); 3580076e85f5Sdrh sqlite3VdbeGoto(v, addrEofA); 3581c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 3582b21e7c70Sdrh } 3583b21e7c70Sdrh 358492b01d53Sdrh /* Generate a subroutine to run when the results from select B 358592b01d53Sdrh ** are exhausted and only data in select A remains. 358692b01d53Sdrh */ 3587b21e7c70Sdrh if( op==TK_INTERSECT ){ 358892b01d53Sdrh addrEofB = addrEofA; 358995aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3590b21e7c70Sdrh }else{ 359192b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 359281cf13ecSdrh addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3593688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 3594076e85f5Sdrh sqlite3VdbeGoto(v, addrEofB); 3595b21e7c70Sdrh } 3596b21e7c70Sdrh 359792b01d53Sdrh /* Generate code to handle the case of A<B 359892b01d53Sdrh */ 3599b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 36000acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3601688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3602076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3603b21e7c70Sdrh 360492b01d53Sdrh /* Generate code to handle the case of A==B 360592b01d53Sdrh */ 3606b21e7c70Sdrh if( op==TK_ALL ){ 3607b21e7c70Sdrh addrAeqB = addrAltB; 36080acb7e48Sdrh }else if( op==TK_INTERSECT ){ 36090acb7e48Sdrh addrAeqB = addrAltB; 36100acb7e48Sdrh addrAltB++; 361192b01d53Sdrh }else{ 3612b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 36130acb7e48Sdrh addrAeqB = 3614688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3615076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 361692b01d53Sdrh } 3617b21e7c70Sdrh 361892b01d53Sdrh /* Generate code to handle the case of A>B 361992b01d53Sdrh */ 3620b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 3621b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 3622b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 3623b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 362492b01d53Sdrh } 3625688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3626076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3627b21e7c70Sdrh 362892b01d53Sdrh /* This code runs once to initialize everything. 362992b01d53Sdrh */ 3630728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3631688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3632688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 363392b01d53Sdrh 363492b01d53Sdrh /* Implement the main merge loop 363592b01d53Sdrh */ 363692b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 36370acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 36382b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 36392ec2fb22Sdrh (char*)pKeyMerge, P4_KEYINFO); 3640953f7611Sdrh sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3641688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 364292b01d53Sdrh 364392b01d53Sdrh /* Jump to the this point in order to terminate the query. 364492b01d53Sdrh */ 3645b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 3646b21e7c70Sdrh 36470acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 36480acb7e48Sdrh ** by the calling function */ 364938cebe07Sdrh if( pSplit->pPrior ){ 365038cebe07Sdrh sqlite3SelectDelete(db, pSplit->pPrior); 36515e7ad508Sdanielk1977 } 365238cebe07Sdrh pSplit->pPrior = pPrior; 365338cebe07Sdrh pPrior->pNext = pSplit; 3654cd0b2459Sdan sqlite3ExprListDelete(db, pPrior->pOrderBy); 3655cd0b2459Sdan pPrior->pOrderBy = 0; 3656cd0b2459Sdan 365792b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 365892b01d53Sdrh **** subqueries ****/ 3659e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 36603dc4cc66Sdrh return pParse->nErr!=0; 366192b01d53Sdrh } 3662de3e41e3Sdanielk1977 #endif 3663b21e7c70Sdrh 36643514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 366546967de2Sdrh 366646967de2Sdrh /* An instance of the SubstContext object describes an substitution edit 366746967de2Sdrh ** to be performed on a parse tree. 366846967de2Sdrh ** 366946967de2Sdrh ** All references to columns in table iTable are to be replaced by corresponding 367046967de2Sdrh ** expressions in pEList. 3671c133bab7Sdrh ** 3672c133bab7Sdrh ** ## About "isOuterJoin": 3673c133bab7Sdrh ** 3674c133bab7Sdrh ** The isOuterJoin column indicates that the replacement will occur into a 3675c133bab7Sdrh ** position in the parent that NULL-able due to an OUTER JOIN. Either the 3676c133bab7Sdrh ** target slot in the parent is the right operand of a LEFT JOIN, or one of 3677c133bab7Sdrh ** the left operands of a RIGHT JOIN. In either case, we need to potentially 3678c133bab7Sdrh ** bypass the substituted expression with OP_IfNullRow. 3679c133bab7Sdrh ** 3680c133bab7Sdrh ** Suppose the original expression integer constant. Even though the table 3681c133bab7Sdrh ** has the nullRow flag set, because the expression is an integer constant, 3682c133bab7Sdrh ** it will not be NULLed out. So instead, we insert an OP_IfNullRow opcode 3683c133bab7Sdrh ** that checks to see if the nullRow flag is set on the table. If the nullRow 3684c133bab7Sdrh ** flag is set, then the value in the register is set to NULL and the original 3685c133bab7Sdrh ** expression is bypassed. If the nullRow flag is not set, then the original 3686c133bab7Sdrh ** expression runs to populate the register. 3687c133bab7Sdrh ** 3688c133bab7Sdrh ** Example where this is needed: 3689c133bab7Sdrh ** 3690c133bab7Sdrh ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT); 3691c133bab7Sdrh ** CREATE TABLE t2(x INT UNIQUE); 3692c133bab7Sdrh ** 3693c133bab7Sdrh ** SELECT a,b,m,x FROM t1 LEFT JOIN (SELECT 59 AS m,x FROM t2) ON b=x; 3694c133bab7Sdrh ** 3695c133bab7Sdrh ** When the subquery on the right side of the LEFT JOIN is flattened, we 3696c133bab7Sdrh ** have to add OP_IfNullRow in front of the OP_Integer that implements the 3697c133bab7Sdrh ** "m" value of the subquery so that a NULL will be loaded instead of 59 3698c133bab7Sdrh ** when processing a non-matched row of the left. 369946967de2Sdrh */ 370046967de2Sdrh typedef struct SubstContext { 370146967de2Sdrh Parse *pParse; /* The parsing context */ 370246967de2Sdrh int iTable; /* Replace references to this table */ 370331d6fd55Sdrh int iNewTable; /* New table number */ 3704c133bab7Sdrh int isOuterJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ 370546967de2Sdrh ExprList *pEList; /* Replacement expressions */ 370646967de2Sdrh } SubstContext; 370746967de2Sdrh 370817435752Sdrh /* Forward Declarations */ 370946967de2Sdrh static void substExprList(SubstContext*, ExprList*); 371046967de2Sdrh static void substSelect(SubstContext*, Select*, int); 371117435752Sdrh 37122282792aSdrh /* 3713832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 37146a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 371584e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 37166a3ea0e6Sdrh ** unchanged.) 3717832508b7Sdrh ** 3718832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 3719832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 3720832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3721aca19e19Sdrh ** FORM clause entry is iTable. This routine makes the necessary 3722832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 3723832508b7Sdrh ** of the subquery rather the result set of the subquery. 3724832508b7Sdrh */ 3725b7916a78Sdrh static Expr *substExpr( 372646967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 372746967de2Sdrh Expr *pExpr /* Expr in which substitution occurs */ 372817435752Sdrh ){ 3729b7916a78Sdrh if( pExpr==0 ) return 0; 37303d240d21Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) 3731d1985262Sdrh && pExpr->w.iJoin==pSubst->iTable 37323d240d21Sdrh ){ 3733d1985262Sdrh pExpr->w.iJoin = pSubst->iNewTable; 3734399c7e21Sdrh } 37352e52a9c6Sdrh if( pExpr->op==TK_COLUMN 37362e52a9c6Sdrh && pExpr->iTable==pSubst->iTable 37372e52a9c6Sdrh && !ExprHasProperty(pExpr, EP_FixedCol) 37382e52a9c6Sdrh ){ 37396e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW 374050350a15Sdrh if( pExpr->iColumn<0 ){ 374150350a15Sdrh pExpr->op = TK_NULL; 37426e5020e8Sdrh }else 37436e5020e8Sdrh #endif 37446e5020e8Sdrh { 3745832508b7Sdrh Expr *pNew; 374646967de2Sdrh Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; 374731d6fd55Sdrh Expr ifNullRow; 374846967de2Sdrh assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr ); 37491fd4e7bbSdrh assert( pExpr->pRight==0 ); 375044c5604cSdan if( sqlite3ExprIsVector(pCopy) ){ 375146967de2Sdrh sqlite3VectorErrorMsg(pSubst->pParse, pCopy); 375244c5604cSdan }else{ 375346967de2Sdrh sqlite3 *db = pSubst->pParse->db; 3754c133bab7Sdrh if( pSubst->isOuterJoin && pCopy->op!=TK_COLUMN ){ 375531d6fd55Sdrh memset(&ifNullRow, 0, sizeof(ifNullRow)); 375631d6fd55Sdrh ifNullRow.op = TK_IF_NULL_ROW; 375731d6fd55Sdrh ifNullRow.pLeft = pCopy; 375831d6fd55Sdrh ifNullRow.iTable = pSubst->iNewTable; 375946fe138dSdrh ifNullRow.flags = EP_IfNullRow; 376031d6fd55Sdrh pCopy = &ifNullRow; 376131d6fd55Sdrh } 376211df7d28Sdrh testcase( ExprHasProperty(pCopy, EP_Subquery) ); 376344c5604cSdan pNew = sqlite3ExprDup(db, pCopy, 0); 37648c6cb1bcSdrh if( db->mallocFailed ){ 37658c6cb1bcSdrh sqlite3ExprDelete(db, pNew); 37668c6cb1bcSdrh return pExpr; 37678c6cb1bcSdrh } 3768c133bab7Sdrh if( pSubst->isOuterJoin ){ 3769bd11a2acSdan ExprSetProperty(pNew, EP_CanBeNull); 3770bd11a2acSdan } 37713a6e4c59Sdrh if( ExprHasProperty(pExpr,EP_FromJoin|EP_InnerJoin) ){ 37723a6e4c59Sdrh sqlite3SetJoinExpr(pNew, pExpr->w.iJoin, 37733a6e4c59Sdrh pExpr->flags & (EP_FromJoin|EP_InnerJoin)); 377492ddb3bdSdan } 3775b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 3776b7916a78Sdrh pExpr = pNew; 3777e0866394Sdan 3778fa508349Sdan /* Ensure that the expression now has an implicit collation sequence, 3779fa508349Sdan ** just as it did when it was a column of a view or sub-query. */ 3780e0866394Sdan if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){ 3781e0866394Sdan CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr); 3782e0866394Sdan pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr, 3783e0866394Sdan (pColl ? pColl->zName : "BINARY") 3784e0866394Sdan ); 3785e0866394Sdan } 3786e0866394Sdan ExprClearProperty(pExpr, EP_Collate); 3787e0866394Sdan } 378850350a15Sdrh } 3789832508b7Sdrh }else{ 37907c1544e0Sdrh if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){ 37917c1544e0Sdrh pExpr->iTable = pSubst->iNewTable; 37927c1544e0Sdrh } 379346967de2Sdrh pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); 379446967de2Sdrh pExpr->pRight = substExpr(pSubst, pExpr->pRight); 3795a4eeccdfSdrh if( ExprUseXSelect(pExpr) ){ 379646967de2Sdrh substSelect(pSubst, pExpr->x.pSelect, 1); 37976ab3a2ecSdanielk1977 }else{ 379846967de2Sdrh substExprList(pSubst, pExpr->x.pList); 37996ab3a2ecSdanielk1977 } 38003703edf1Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 38013703edf1Sdan if( ExprHasProperty(pExpr, EP_WinFunc) ){ 38023703edf1Sdan Window *pWin = pExpr->y.pWin; 38033703edf1Sdan pWin->pFilter = substExpr(pSubst, pWin->pFilter); 38043703edf1Sdan substExprList(pSubst, pWin->pPartition); 38053703edf1Sdan substExprList(pSubst, pWin->pOrderBy); 38063703edf1Sdan } 38073703edf1Sdan #endif 3808832508b7Sdrh } 3809b7916a78Sdrh return pExpr; 3810832508b7Sdrh } 381117435752Sdrh static void substExprList( 381246967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 381346967de2Sdrh ExprList *pList /* List to scan and in which to make substitutes */ 381417435752Sdrh ){ 3815832508b7Sdrh int i; 3816832508b7Sdrh if( pList==0 ) return; 3817832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 381846967de2Sdrh pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); 3819832508b7Sdrh } 3820832508b7Sdrh } 382117435752Sdrh static void substSelect( 382246967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 382317435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 3824d12b6363Sdrh int doPrior /* Do substitutes on p->pPrior too */ 382517435752Sdrh ){ 3826588a9a1aSdrh SrcList *pSrc; 38277601294aSdrh SrcItem *pItem; 3828588a9a1aSdrh int i; 3829b3bce662Sdanielk1977 if( !p ) return; 3830d12b6363Sdrh do{ 383146967de2Sdrh substExprList(pSubst, p->pEList); 383246967de2Sdrh substExprList(pSubst, p->pGroupBy); 383346967de2Sdrh substExprList(pSubst, p->pOrderBy); 383446967de2Sdrh p->pHaving = substExpr(pSubst, p->pHaving); 383546967de2Sdrh p->pWhere = substExpr(pSubst, p->pWhere); 3836588a9a1aSdrh pSrc = p->pSrc; 38372906490bSdrh assert( pSrc!=0 ); 3838588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 383946967de2Sdrh substSelect(pSubst, pItem->pSelect, 1); 3840d12b6363Sdrh if( pItem->fg.isTabFunc ){ 384146967de2Sdrh substExprList(pSubst, pItem->u1.pFuncArg); 3842588a9a1aSdrh } 3843588a9a1aSdrh } 3844d12b6363Sdrh }while( doPrior && (p = p->pPrior)!=0 ); 3845b3bce662Sdanielk1977 } 38463514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3847832508b7Sdrh 38483514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3849832508b7Sdrh /* 38502aee514bSdrh ** pSelect is a SELECT statement and pSrcItem is one item in the FROM 38512aee514bSdrh ** clause of that SELECT. 38522aee514bSdrh ** 38532aee514bSdrh ** This routine scans the entire SELECT statement and recomputes the 38542aee514bSdrh ** pSrcItem->colUsed mask. 38552aee514bSdrh */ 38562aee514bSdrh static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){ 38577601294aSdrh SrcItem *pItem; 38582aee514bSdrh if( pExpr->op!=TK_COLUMN ) return WRC_Continue; 38592aee514bSdrh pItem = pWalker->u.pSrcItem; 38602aee514bSdrh if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue; 386174a07986Sdrh if( pExpr->iColumn<0 ) return WRC_Continue; 386274a07986Sdrh pItem->colUsed |= sqlite3ExprColUsed(pExpr); 38632aee514bSdrh return WRC_Continue; 38642aee514bSdrh } 38652aee514bSdrh static void recomputeColumnsUsed( 38662aee514bSdrh Select *pSelect, /* The complete SELECT statement */ 38677601294aSdrh SrcItem *pSrcItem /* Which FROM clause item to recompute */ 38682aee514bSdrh ){ 38692aee514bSdrh Walker w; 38702aee514bSdrh if( NEVER(pSrcItem->pTab==0) ) return; 38712aee514bSdrh memset(&w, 0, sizeof(w)); 38722aee514bSdrh w.xExprCallback = recomputeColumnsUsedExpr; 38732aee514bSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 38742aee514bSdrh w.u.pSrcItem = pSrcItem; 38752aee514bSdrh pSrcItem->colUsed = 0; 38762aee514bSdrh sqlite3WalkSelect(&w, pSelect); 38772aee514bSdrh } 38782aee514bSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 38792aee514bSdrh 38802aee514bSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 38812aee514bSdrh /* 3882964fa26eSdan ** Assign new cursor numbers to each of the items in pSrc. For each 3883964fa26eSdan ** new cursor number assigned, set an entry in the aCsrMap[] array 3884964fa26eSdan ** to map the old cursor number to the new: 3885964fa26eSdan ** 3886c8d21471Sdrh ** aCsrMap[iOld+1] = iNew; 3887964fa26eSdan ** 3888964fa26eSdan ** The array is guaranteed by the caller to be large enough for all 3889c8d21471Sdrh ** existing cursor numbers in pSrc. aCsrMap[0] is the array size. 3890964fa26eSdan ** 3891964fa26eSdan ** If pSrc contains any sub-selects, call this routine recursively 3892964fa26eSdan ** on the FROM clause of each such sub-select, with iExcept set to -1. 3893964fa26eSdan */ 3894964fa26eSdan static void srclistRenumberCursors( 3895964fa26eSdan Parse *pParse, /* Parse context */ 3896964fa26eSdan int *aCsrMap, /* Array to store cursor mappings in */ 3897964fa26eSdan SrcList *pSrc, /* FROM clause to renumber */ 3898964fa26eSdan int iExcept /* FROM clause item to skip */ 3899964fa26eSdan ){ 3900964fa26eSdan int i; 39017601294aSdrh SrcItem *pItem; 3902964fa26eSdan for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){ 3903964fa26eSdan if( i!=iExcept ){ 3904d131b51cSdan Select *p; 3905c8d21471Sdrh assert( pItem->iCursor < aCsrMap[0] ); 3906c8d21471Sdrh if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){ 3907c8d21471Sdrh aCsrMap[pItem->iCursor+1] = pParse->nTab++; 3908c7f5077eSdrh } 3909c8d21471Sdrh pItem->iCursor = aCsrMap[pItem->iCursor+1]; 3910d131b51cSdan for(p=pItem->pSelect; p; p=p->pPrior){ 3911d131b51cSdan srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1); 3912964fa26eSdan } 3913964fa26eSdan } 3914964fa26eSdan } 3915964fa26eSdan } 3916964fa26eSdan 3917964fa26eSdan /* 3918c8d21471Sdrh ** *piCursor is a cursor number. Change it if it needs to be mapped. 3919c8d21471Sdrh */ 3920c8d21471Sdrh static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){ 3921c8d21471Sdrh int *aCsrMap = pWalker->u.aiCol; 3922c8d21471Sdrh int iCsr = *piCursor; 3923c8d21471Sdrh if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){ 3924c8d21471Sdrh *piCursor = aCsrMap[iCsr+1]; 3925c8d21471Sdrh } 3926c8d21471Sdrh } 3927c8d21471Sdrh 3928c8d21471Sdrh /* 3929964fa26eSdan ** Expression walker callback used by renumberCursors() to update 3930964fa26eSdan ** Expr objects to match newly assigned cursor numbers. 3931964fa26eSdan */ 3932964fa26eSdan static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){ 3933e8f1490fSdan int op = pExpr->op; 3934c8d21471Sdrh if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){ 3935c8d21471Sdrh renumberCursorDoMapping(pWalker, &pExpr->iTable); 3936964fa26eSdan } 3937c8d21471Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) ){ 3938d1985262Sdrh renumberCursorDoMapping(pWalker, &pExpr->w.iJoin); 3939961a7260Sdan } 3940964fa26eSdan return WRC_Continue; 3941964fa26eSdan } 3942964fa26eSdan 3943964fa26eSdan /* 3944964fa26eSdan ** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc) 3945964fa26eSdan ** of the SELECT statement passed as the second argument, and to each 3946964fa26eSdan ** cursor in the FROM clause of any FROM clause sub-selects, recursively. 3947964fa26eSdan ** Except, do not assign a new cursor number to the iExcept'th element in 3948964fa26eSdan ** the FROM clause of (*p). Update all expressions and other references 3949964fa26eSdan ** to refer to the new cursor numbers. 3950964fa26eSdan ** 3951964fa26eSdan ** Argument aCsrMap is an array that may be used for temporary working 3952964fa26eSdan ** space. Two guarantees are made by the caller: 3953964fa26eSdan ** 3954964fa26eSdan ** * the array is larger than the largest cursor number used within the 3955964fa26eSdan ** select statement passed as an argument, and 3956964fa26eSdan ** 3957964fa26eSdan ** * the array entries for all cursor numbers that do *not* appear in 3958964fa26eSdan ** FROM clauses of the select statement as described above are 3959964fa26eSdan ** initialized to zero. 3960964fa26eSdan */ 3961964fa26eSdan static void renumberCursors( 3962964fa26eSdan Parse *pParse, /* Parse context */ 3963964fa26eSdan Select *p, /* Select to renumber cursors within */ 3964964fa26eSdan int iExcept, /* FROM clause item to skip */ 3965964fa26eSdan int *aCsrMap /* Working space */ 3966964fa26eSdan ){ 3967964fa26eSdan Walker w; 3968964fa26eSdan srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept); 3969964fa26eSdan memset(&w, 0, sizeof(w)); 3970964fa26eSdan w.u.aiCol = aCsrMap; 3971964fa26eSdan w.xExprCallback = renumberCursorsCb; 3972964fa26eSdan w.xSelectCallback = sqlite3SelectWalkNoop; 3973964fa26eSdan sqlite3WalkSelect(&w, p); 3974964fa26eSdan } 3975964fa26eSdan #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3976964fa26eSdan 3977964fa26eSdan #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3978964fa26eSdan /* 3979630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3980630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 39811350b030Sdrh ** 39821350b030Sdrh ** To understand the concept of flattening, consider the following 39831350b030Sdrh ** query: 39841350b030Sdrh ** 39851350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 39861350b030Sdrh ** 39871350b030Sdrh ** The default way of implementing this query is to execute the 39881350b030Sdrh ** subquery first and store the results in a temporary table, then 39891350b030Sdrh ** run the outer query on that temporary table. This requires two 39901350b030Sdrh ** passes over the data. Furthermore, because the temporary table 39911350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3992832508b7Sdrh ** optimized. 39931350b030Sdrh ** 3994832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 39951350b030Sdrh ** a single flat select, like this: 39961350b030Sdrh ** 39971350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 39981350b030Sdrh ** 399960ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 4000832508b7Sdrh ** but only has to scan the data once. And because indices might 4001832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 4002832508b7Sdrh ** avoided. 40031350b030Sdrh ** 4004d981e828Sdrh ** Flattening is subject to the following constraints: 40051350b030Sdrh ** 400625c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 400725c221ebSdrh ** The subquery and the outer query cannot both be aggregates. 40081350b030Sdrh ** 400925c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 4010d981e828Sdrh ** (2) If the subquery is an aggregate then 4011d981e828Sdrh ** (2a) the outer query must not be a join and 4012d981e828Sdrh ** (2b) the outer query must not use subqueries 4013d981e828Sdrh ** other than the one FROM-clause subquery that is a candidate 4014d981e828Sdrh ** for flattening. (This is due to ticket [2f7170d73bf9abf80] 4015d981e828Sdrh ** from 2015-02-09.) 4016832508b7Sdrh ** 4017d981e828Sdrh ** (3) If the subquery is the right operand of a LEFT JOIN then 4018d981e828Sdrh ** (3a) the subquery may not be a join and 4019d981e828Sdrh ** (3b) the FROM clause of the subquery may not contain a virtual 4020d981e828Sdrh ** table and 4021d981e828Sdrh ** (3c) the outer query may not be an aggregate. 4022396afe6fSdrh ** (3d) the outer query may not be DISTINCT. 402341798d5bSdrh ** See also (26) for restrictions on RIGHT JOIN. 4024832508b7Sdrh ** 4025d981e828Sdrh ** (4) The subquery can not be DISTINCT. 4026832508b7Sdrh ** 402749ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 402849ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 402949ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 4030832508b7Sdrh ** 403125c221ebSdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 403225c221ebSdrh ** If the subquery is aggregate, the outer query may not be DISTINCT. 4033832508b7Sdrh ** 4034d981e828Sdrh ** (7) The subquery must have a FROM clause. TODO: For subqueries without 403531d6fd55Sdrh ** A FROM clause, consider adding a FROM clause with the special 4036630d296cSdrh ** table sqlite_once that consists of a single row containing a 4037630d296cSdrh ** single NULL. 403808192d5fSdrh ** 4039d981e828Sdrh ** (8) If the subquery uses LIMIT then the outer query may not be a join. 4040df199a25Sdrh ** 4041d981e828Sdrh ** (9) If the subquery uses LIMIT then the outer query may not be aggregate. 4042df199a25Sdrh ** 40436092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 40446092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 4045d981e828Sdrh ** constraint: "If the subquery is aggregate then the outer query 4046d981e828Sdrh ** may not use LIMIT." 4047df199a25Sdrh ** 4048d981e828Sdrh ** (11) The subquery and the outer query may not both have ORDER BY clauses. 4049174b6195Sdrh ** 40507b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 40512b300d5dSdrh ** a separate restriction deriving from ticket #350. 40523fc673e6Sdrh ** 4053d981e828Sdrh ** (13) The subquery and outer query may not both use LIMIT. 4054ac83963aSdrh ** 4055d981e828Sdrh ** (14) The subquery may not use OFFSET. 4056ac83963aSdrh ** 4057d981e828Sdrh ** (15) If the outer query is part of a compound select, then the 4058d981e828Sdrh ** subquery may not use LIMIT. 4059f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 4060ad91c6cdSdrh ** 4061d981e828Sdrh ** (16) If the outer query is aggregate, then the subquery may not 4062d981e828Sdrh ** use ORDER BY. (Ticket #2942) This used to not matter 4063c52e355dSdrh ** until we introduced the group_concat() function. 4064c52e355dSdrh ** 4065d981e828Sdrh ** (17) If the subquery is a compound select, then 4066d981e828Sdrh ** (17a) all compound operators must be a UNION ALL, and 4067d981e828Sdrh ** (17b) no terms within the subquery compound may be aggregate 4068e76acc65Sdrh ** or DISTINCT, and 4069d981e828Sdrh ** (17c) every term within the subquery compound must have a FROM clause 4070d981e828Sdrh ** (17d) the outer query may not be 4071d981e828Sdrh ** (17d1) aggregate, or 40728daf5ae2Sdan ** (17d2) DISTINCT 40738daf5ae2Sdan ** (17e) the subquery may not contain window functions, and 40748daf5ae2Sdan ** (17f) the subquery must not be the RHS of a LEFT JOIN. 4075f23329a2Sdanielk1977 ** 40764914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 40774914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 4078630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 4079630d296cSdrh ** operator other than UNION ALL because all the other compound 4080630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 4081630d296cSdrh ** restriction (4). 4082f23329a2Sdanielk1977 ** 408367c70142Sdan ** Also, each component of the sub-query must return the same number 408467c70142Sdan ** of result columns. This is actually a requirement for any compound 408567c70142Sdan ** SELECT statement, but all the code here does is make sure that no 408667c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 408767c70142Sdan ** syntax error and return a detailed message. 408867c70142Sdan ** 408949fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 40909353beafSdan ** ORDER BY clause of the parent must be copies of a term returned 40919353beafSdan ** by the parent query. 409249fc1f60Sdanielk1977 ** 4093d981e828Sdrh ** (19) If the subquery uses LIMIT then the outer query may not 4094229cf702Sdrh ** have a WHERE clause. 4095229cf702Sdrh ** 4096fca23557Sdrh ** (20) If the sub-query is a compound select, then it must not use 4097fca23557Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 4098fca23557Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 4099fca23557Sdrh ** appear as unmodified result columns in the outer query. But we 4100fca23557Sdrh ** have other optimizations in mind to deal with that case. 4101e8902a70Sdrh ** 4102d981e828Sdrh ** (21) If the subquery uses LIMIT then the outer query may not be 4103a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 4104a91491e5Sshaneh ** 4105d981e828Sdrh ** (22) The subquery may not be a recursive CTE. 41068290c2adSdan ** 41078daf5ae2Sdan ** (23) If the outer query is a recursive CTE, then the sub-query may not be 41088daf5ae2Sdan ** a compound query. This restriction is because transforming the 41098290c2adSdan ** parent to a compound query confuses the code that handles 41108290c2adSdan ** recursive queries in multiSelect(). 41118290c2adSdan ** 4112508e2d00Sdrh ** (**) We no longer attempt to flatten aggregate subqueries. Was: 4113508e2d00Sdrh ** The subquery may not be an aggregate that uses the built-in min() or 41149588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 41159588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 41169588ad95Sdrh ** return the value X for which Y was maximal.) 41179588ad95Sdrh ** 41189a94722dSdan ** (25) If either the subquery or the parent query contains a window 41199a94722dSdan ** function in the select list or ORDER BY clause, flattening 41209a94722dSdan ** is not attempted. 41219a94722dSdan ** 412241798d5bSdrh ** (26) The subquery may not be the right operand of a RIGHT JOIN. 412341798d5bSdrh ** See also (3) for restrictions on LEFT JOIN. 412441798d5bSdrh ** 41251c2bf41aSdrh ** (27) The subquery may not contain a FULL or RIGHT JOIN unless it 41261c2bf41aSdrh ** is the first element of the parent query. 41271c2bf41aSdrh ** 41288290c2adSdan ** 4129832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 4130832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 413125c221ebSdrh ** uses aggregates. 4132832508b7Sdrh ** 4133665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 4134832508b7Sdrh ** If flattening is attempted this routine returns 1. 4135832508b7Sdrh ** 4136832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 4137832508b7Sdrh ** the subquery before this routine runs. 41381350b030Sdrh */ 41398c74a8caSdrh static int flattenSubquery( 4140524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 41418c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 41428c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 414325c221ebSdrh int isAgg /* True if outer SELECT uses aggregate functions */ 41448c74a8caSdrh ){ 4145524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 4146d12b6363Sdrh Select *pParent; /* Current UNION ALL term of the other query */ 41470bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 4148f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 4149ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 4150ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 41516a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 4152399c7e21Sdrh int iNewParent = -1;/* Replacement table for iParent */ 4153c133bab7Sdrh int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ 415491bb0eedSdrh int i; /* Loop counter */ 415591bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 41567601294aSdrh SrcItem *pSubitem; /* The subquery */ 4157524cc21eSdanielk1977 sqlite3 *db = pParse->db; 415889636628Sdrh Walker w; /* Walker to persist agginfo data */ 4159964fa26eSdan int *aCsrMap = 0; 41601350b030Sdrh 4161832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 4162832508b7Sdrh */ 4163a78c22c4Sdrh assert( p!=0 ); 4164d981e828Sdrh assert( p->pPrior==0 ); 41657e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 4166832508b7Sdrh pSrc = p->pSrc; 4167ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 416891bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 416949fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 417091bb0eedSdrh pSub = pSubitem->pSelect; 4171832508b7Sdrh assert( pSub!=0 ); 4172885a5b03Sdrh 417367a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 41749a94722dSdan if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */ 417567a9b8edSdan #endif 417686fb6e17Sdan 4177832508b7Sdrh pSubSrc = pSub->pSrc; 4178832508b7Sdrh assert( pSubSrc ); 4179ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 418060ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 4181ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 4182ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 4183ac83963aSdrh ** and (14). */ 4184ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 41858c0833fbSdrh if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */ 4186d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 4187ad91c6cdSdrh return 0; /* Restriction (15) */ 4188ad91c6cdSdrh } 4189ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 4190d981e828Sdrh if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */ 419149ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 419249ad330dSdan return 0; /* Restrictions (8)(9) */ 4193df199a25Sdrh } 41947d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 4195ac83963aSdrh return 0; /* Restriction (11) */ 4196ac83963aSdrh } 4197c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 4198229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 4199a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 4200a91491e5Sshaneh return 0; /* Restriction (21) */ 4201a91491e5Sshaneh } 4202508e2d00Sdrh if( pSub->selFlags & (SF_Recursive) ){ 4203508e2d00Sdrh return 0; /* Restrictions (22) */ 42049588ad95Sdrh } 4205832508b7Sdrh 4206399c7e21Sdrh /* 4207399c7e21Sdrh ** If the subquery is the right operand of a LEFT JOIN, then the 4208d981e828Sdrh ** subquery may not be a join itself (3a). Example of why this is not 4209d981e828Sdrh ** allowed: 42108af4d3acSdrh ** 42118af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 42128af4d3acSdrh ** 42138af4d3acSdrh ** If we flatten the above, we would get 42148af4d3acSdrh ** 42158af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 42168af4d3acSdrh ** 42178af4d3acSdrh ** which is not at all the same thing. 42182b300d5dSdrh ** 42193c790f2aSdrh ** If the subquery is the right operand of a LEFT JOIN, then the outer 4220d981e828Sdrh ** query cannot be an aggregate. (3c) This is an artifact of the way 4221d981e828Sdrh ** aggregates are processed - there is no mechanism to determine if 4222d981e828Sdrh ** the LEFT JOIN table should be all-NULL. 42233c790f2aSdrh ** 422431d6fd55Sdrh ** See also tickets #306, #350, and #3300. 42253fc673e6Sdrh */ 4226c133bab7Sdrh if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){ 4227396afe6fSdrh if( pSubSrc->nSrc>1 /* (3a) */ 4228396afe6fSdrh || isAgg /* (3b) */ 4229396afe6fSdrh || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */ 4230396afe6fSdrh || (p->selFlags & SF_Distinct)!=0 /* (3d) */ 423141798d5bSdrh || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */ 4232396afe6fSdrh ){ 4233d981e828Sdrh return 0; 4234399c7e21Sdrh } 4235c133bab7Sdrh isOuterJoin = 1; 42363fc673e6Sdrh } 4237dc6de479Sdrh #ifdef SQLITE_EXTRA_IFNULLROW 4238dc6de479Sdrh else if( iFrom>0 && !isAgg ){ 4239c133bab7Sdrh /* Setting isOuterJoin to -1 causes OP_IfNullRow opcodes to be generated for 42403d240d21Sdrh ** every reference to any result column from subquery in a join, even 42413d240d21Sdrh ** though they are not necessary. This will stress-test the OP_IfNullRow 42423d240d21Sdrh ** opcode. */ 4243c133bab7Sdrh isOuterJoin = -1; 4244dc6de479Sdrh } 4245dc6de479Sdrh #endif 42463fc673e6Sdrh 42471c2bf41aSdrh assert( pSubSrc->nSrc>0 ); /* True by restriction (7) */ 42481c2bf41aSdrh if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){ 42491c2bf41aSdrh return 0; /* Restriction (27) */ 42501c2bf41aSdrh } 42511c2bf41aSdrh 4252d981e828Sdrh /* Restriction (17): If the sub-query is a compound SELECT, then it must 4253f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 4254f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 4255f23329a2Sdanielk1977 ** queries. 4256f23329a2Sdanielk1977 */ 4257f23329a2Sdanielk1977 if( pSub->pPrior ){ 4258fca23557Sdrh if( pSub->pOrderBy ){ 4259fca23557Sdrh return 0; /* Restriction (20) */ 4260fca23557Sdrh } 4261c133bab7Sdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){ 42628daf5ae2Sdan return 0; /* (17d1), (17d2), or (17f) */ 4263f23329a2Sdanielk1977 } 4264f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 4265ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 4266ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 42674b3ac73cSdrh assert( pSub->pSrc!=0 ); 42688daf5ae2Sdan assert( (pSub->selFlags & SF_Recursive)==0 ); 42692ec18a3cSdrh assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); 4270d981e828Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */ 4271d981e828Sdrh || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */ 4272d981e828Sdrh || pSub1->pSrc->nSrc<1 /* (17c) */ 4273ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 42748d95ed78Sdrh || pSub1->pWin /* (17e) */ 4275ef9f719dSdrh #endif 427680b3c548Sdanielk1977 ){ 4277f23329a2Sdanielk1977 return 0; 4278f23329a2Sdanielk1977 } 42794b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 4280f23329a2Sdanielk1977 } 428149fc1f60Sdanielk1977 4282d981e828Sdrh /* Restriction (18). */ 428349fc1f60Sdanielk1977 if( p->pOrderBy ){ 428449fc1f60Sdanielk1977 int ii; 428549fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 4286c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 428749fc1f60Sdanielk1977 } 428849fc1f60Sdanielk1977 } 4289f23329a2Sdanielk1977 4290de9ed629Sdan /* Restriction (23) */ 4291de9ed629Sdan if( (p->selFlags & SF_Recursive) ) return 0; 4292964fa26eSdan 4293964fa26eSdan if( pSrc->nSrc>1 ){ 429451ddfef7Sdan if( pParse->nSelect>500 ) return 0; 4295913306a5Sdrh aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int)); 4296c8d21471Sdrh if( aCsrMap ) aCsrMap[0] = pParse->nTab; 4297964fa26eSdan } 4298de9ed629Sdan } 4299cdb2f607Sdrh 43007d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 4301fef37760Sdrh SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n", 4302fef37760Sdrh pSub->selId, pSub, iFrom)); 43037d10d5a6Sdrh 43047d10d5a6Sdrh /* Authorize the subquery */ 4305524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 4306a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 4307a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 4308524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 4309524cc21eSdanielk1977 4310de9ed629Sdan /* Delete the transient structures associated with thesubquery */ 4311de9ed629Sdan pSub1 = pSubitem->pSelect; 4312de9ed629Sdan sqlite3DbFree(db, pSubitem->zDatabase); 4313de9ed629Sdan sqlite3DbFree(db, pSubitem->zName); 4314de9ed629Sdan sqlite3DbFree(db, pSubitem->zAlias); 4315de9ed629Sdan pSubitem->zDatabase = 0; 4316de9ed629Sdan pSubitem->zName = 0; 4317de9ed629Sdan pSubitem->zAlias = 0; 4318de9ed629Sdan pSubitem->pSelect = 0; 4319d44f8b23Sdrh assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 ); 4320de9ed629Sdan 43217d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 43227d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 43237d10d5a6Sdrh ** be of the form: 4324f23329a2Sdanielk1977 ** 4325f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 4326f23329a2Sdanielk1977 ** 4327f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 4328a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 4329f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 4330f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 4331f23329a2Sdanielk1977 ** select statements in the compound sub-query. 4332a78c22c4Sdrh ** 4333a78c22c4Sdrh ** Example: 4334a78c22c4Sdrh ** 4335a78c22c4Sdrh ** SELECT a+1 FROM ( 4336a78c22c4Sdrh ** SELECT x FROM tab 4337a78c22c4Sdrh ** UNION ALL 4338a78c22c4Sdrh ** SELECT y FROM tab 4339a78c22c4Sdrh ** UNION ALL 4340a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 4341a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 4342a78c22c4Sdrh ** 4343a78c22c4Sdrh ** Transformed into: 4344a78c22c4Sdrh ** 4345a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 4346a78c22c4Sdrh ** UNION ALL 4347a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 4348a78c22c4Sdrh ** UNION ALL 4349a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 4350a78c22c4Sdrh ** ORDER BY 1 4351a78c22c4Sdrh ** 4352a78c22c4Sdrh ** We call this the "compound-subquery flattening". 4353f23329a2Sdanielk1977 */ 4354f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 4355f23329a2Sdanielk1977 Select *pNew; 4356f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 43574b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 4358f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 4359de9ed629Sdan Table *pItemTab = pSubitem->pTab; 4360de9ed629Sdan pSubitem->pTab = 0; 4361f23329a2Sdanielk1977 p->pOrderBy = 0; 4362f23329a2Sdanielk1977 p->pPrior = 0; 43634b86ef1dSdanielk1977 p->pLimit = 0; 43646ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 43654b86ef1dSdanielk1977 p->pLimit = pLimit; 4366a78c22c4Sdrh p->pOrderBy = pOrderBy; 4367a78c22c4Sdrh p->op = TK_ALL; 4368de9ed629Sdan pSubitem->pTab = pItemTab; 4369a78c22c4Sdrh if( pNew==0 ){ 4370d227a291Sdrh p->pPrior = pPrior; 4371a78c22c4Sdrh }else{ 437251ddfef7Sdan pNew->selId = ++pParse->nSelect; 43739da977f1Sdrh if( aCsrMap && ALWAYS(db->mallocFailed==0) ){ 4374964fa26eSdan renumberCursors(pParse, pNew, iFrom, aCsrMap); 4375964fa26eSdan } 4376a78c22c4Sdrh pNew->pPrior = pPrior; 4377d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 4378d227a291Sdrh pNew->pNext = p; 4379a78c22c4Sdrh p->pPrior = pNew; 4380e2243d26Sdrh SELECTTRACE(2,pParse,p,("compound-subquery flattener" 4381fef37760Sdrh " creates %u as peer\n",pNew->selId)); 4382d227a291Sdrh } 4383de9ed629Sdan assert( pSubitem->pSelect==0 ); 4384964fa26eSdan } 4385964fa26eSdan sqlite3DbFree(db, aCsrMap); 4386de9ed629Sdan if( db->mallocFailed ){ 4387de9ed629Sdan pSubitem->pSelect = pSub1; 4388de9ed629Sdan return 1; 4389a78c22c4Sdrh } 4390a78c22c4Sdrh 4391a78c22c4Sdrh /* Defer deleting the Table object associated with the 4392a78c22c4Sdrh ** subquery until code generation is 4393a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 4394a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 4395ccfcbceaSdrh ** 4396ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 4397a78c22c4Sdrh */ 4398ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 4399a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 440079df7782Sdrh if( pTabToDel->nTabRef==1 ){ 440165a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 4402cf3c078fSdrh sqlite3ParserAddCleanup(pToplevel, 4403cf3c078fSdrh (void(*)(sqlite3*,void*))sqlite3DeleteTable, 4404cf3c078fSdrh pTabToDel); 440521d4f5b5Sdrh testcase( pToplevel->earlyCleanup ); 4406a78c22c4Sdrh }else{ 440779df7782Sdrh pTabToDel->nTabRef--; 4408a78c22c4Sdrh } 4409a78c22c4Sdrh pSubitem->pTab = 0; 4410a78c22c4Sdrh } 4411a78c22c4Sdrh 4412a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 4413a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 4414a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 4415a78c22c4Sdrh ** then this loop only runs once. 4416a78c22c4Sdrh ** 4417a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 4418c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 4419c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 4420c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 4421c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 4422c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 4423c31c2eb8Sdrh ** elements we are now copying in. 4424c31c2eb8Sdrh */ 4425de9ed629Sdan pSub = pSub1; 4426a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 4427a78c22c4Sdrh int nSubSrc; 4428ea678832Sdrh u8 jointype = 0; 442979d26586Sdrh u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ; 443055f66b34Sdrh assert( pSub!=0 ); 4431a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 4432a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 4433a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 4434588a9a1aSdrh 4435de9ed629Sdan if( pParent==p ){ 4436de9ed629Sdan jointype = pSubitem->fg.jointype; /* First time through the loop */ 4437c31c2eb8Sdrh } 4438a78c22c4Sdrh 4439a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 4440a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 4441a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 4442a78c22c4Sdrh ** of the subquery. 4443a78c22c4Sdrh ** 4444a78c22c4Sdrh ** Example: 4445a78c22c4Sdrh ** 4446a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 4447a78c22c4Sdrh ** 4448a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 4449a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 4450d12b6363Sdrh ** block of code will expand the outer query FROM clause to 4 slots. 4451d12b6363Sdrh ** The middle slot is expanded to two slots in order to make space 4452d12b6363Sdrh ** for the two elements in the FROM clause of the subquery. 4453a78c22c4Sdrh */ 4454a78c22c4Sdrh if( nSubSrc>1 ){ 445529c992cbSdrh pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1); 445629c992cbSdrh if( pSrc==0 ) break; 445729c992cbSdrh pParent->pSrc = pSrc; 4458c31c2eb8Sdrh } 4459a78c22c4Sdrh 4460a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 4461a78c22c4Sdrh ** outer query. 4462a78c22c4Sdrh */ 4463c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 4464d44f8b23Sdrh SrcItem *pItem = &pSrc->a[i+iFrom]; 4465d44f8b23Sdrh if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing); 4466d44f8b23Sdrh assert( pItem->fg.isTabFunc==0 ); 4467d44f8b23Sdrh *pItem = pSubSrc->a[i]; 446879d26586Sdrh pItem->fg.jointype |= ltorj; 4469399c7e21Sdrh iNewParent = pSubSrc->a[i].iCursor; 4470c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 4471c31c2eb8Sdrh } 4472f7309bceSdrh pSrc->a[iFrom].fg.jointype &= JT_LTORJ; 4473f7309bceSdrh pSrc->a[iFrom].fg.jointype |= jointype | ltorj; 4474c31c2eb8Sdrh 4475c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 4476c31c2eb8Sdrh ** references to the iParent in the outer query. 4477c31c2eb8Sdrh ** 4478c31c2eb8Sdrh ** Example: 4479c31c2eb8Sdrh ** 4480c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 4481c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 4482c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 4483c31c2eb8Sdrh ** 4484c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 4485c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 4486c31c2eb8Sdrh */ 4487b7cbf5c1Sdrh if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){ 44887c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 44897c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 44907c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 44917c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 44927c0a4720Sdan ** zero them before transfering the ORDER BY clause. 44937c0a4720Sdan ** 44947c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 44957c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 44967c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 44977c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 44987c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 44997c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 45007c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 45017c0a4720Sdan } 4502f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 45037c0a4720Sdan pParent->pOrderBy = pOrderBy; 4504174b6195Sdrh pSub->pOrderBy = 0; 4505174b6195Sdrh } 450611df7d28Sdrh pWhere = pSub->pWhere; 450711df7d28Sdrh pSub->pWhere = 0; 4508c133bab7Sdrh if( isOuterJoin>0 ){ 45093a6e4c59Sdrh sqlite3SetJoinExpr(pWhere, iNewParent, EP_FromJoin); 4510399c7e21Sdrh } 4511cd653a32Sdan if( pWhere ){ 4512cd653a32Sdan if( pParent->pWhere ){ 4513cd653a32Sdan pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere); 4514cd653a32Sdan }else{ 4515cd653a32Sdan pParent->pWhere = pWhere; 4516cd653a32Sdan } 4517cd653a32Sdan } 4518c3becddbSdan if( db->mallocFailed==0 ){ 451946967de2Sdrh SubstContext x; 452046967de2Sdrh x.pParse = pParse; 452146967de2Sdrh x.iTable = iParent; 4522399c7e21Sdrh x.iNewTable = iNewParent; 4523c133bab7Sdrh x.isOuterJoin = isOuterJoin; 452446967de2Sdrh x.pEList = pSub->pEList; 452546967de2Sdrh substSelect(&x, pParent, 0); 4526c3becddbSdan } 4527c31c2eb8Sdrh 45287cd5e856Sdrh /* The flattened query is a compound if either the inner or the 45297cd5e856Sdrh ** outer query is a compound. */ 45307cd5e856Sdrh pParent->selFlags |= pSub->selFlags & SF_Compound; 45317cd5e856Sdrh assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */ 45328c74a8caSdrh 4533a58fdfb1Sdanielk1977 /* 4534a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 4535ac83963aSdrh ** 4536ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 4537ac83963aSdrh ** does not work if either limit is negative. 4538a58fdfb1Sdanielk1977 */ 4539a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 4540f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 4541a2dc3b1aSdanielk1977 pSub->pLimit = 0; 4542df199a25Sdrh } 45432aee514bSdrh 45442aee514bSdrh /* Recompute the SrcList_item.colUsed masks for the flattened 45452aee514bSdrh ** tables. */ 45462aee514bSdrh for(i=0; i<nSubSrc; i++){ 45472aee514bSdrh recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]); 45482aee514bSdrh } 4549f23329a2Sdanielk1977 } 45508c74a8caSdrh 4551c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 4552c31c2eb8Sdrh ** success. 4553c31c2eb8Sdrh */ 455489636628Sdrh sqlite3AggInfoPersistWalkerInit(&w, pParse); 455589636628Sdrh sqlite3WalkSelect(&w,pSub1); 4556633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 4557f23329a2Sdanielk1977 45585e431beaSdrh #if TREETRACE_ENABLED 45595e431beaSdrh if( sqlite3TreeTrace & 0x100 ){ 4560bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After flattening:\n")); 4561c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4562c90713d3Sdrh } 4563c90713d3Sdrh #endif 4564c90713d3Sdrh 4565832508b7Sdrh return 1; 45661350b030Sdrh } 45673514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 45681350b030Sdrh 4569660ee556Sdrh /* 45708e5bfeddSdrh ** A structure to keep track of all of the column values that are fixed to 4571efad2e23Sdrh ** a known value due to WHERE clause constraints of the form COLUMN=VALUE. 4572660ee556Sdrh */ 4573660ee556Sdrh typedef struct WhereConst WhereConst; 4574660ee556Sdrh struct WhereConst { 4575efad2e23Sdrh Parse *pParse; /* Parsing context */ 457675016050Sdrh u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */ 4577660ee556Sdrh int nConst; /* Number for COLUMN=CONSTANT terms */ 4578660ee556Sdrh int nChng; /* Number of times a constant is propagated */ 457940b82f9dSdan int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */ 4580efad2e23Sdrh Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */ 4581660ee556Sdrh }; 458269b72d5aSdrh 4583660ee556Sdrh /* 45848e5bfeddSdrh ** Add a new entry to the pConst object. Except, do not add duplicate 4585f8f76d67Sdrh ** pColumn entires. Also, do not add if doing so would not be appropriate. 4586f8f76d67Sdrh ** 4587f8f76d67Sdrh ** The caller guarantees the pColumn is a column and pValue is a constant. 4588f8f76d67Sdrh ** This routine has to do some additional checks before completing the 4589f8f76d67Sdrh ** insert. 4590660ee556Sdrh */ 4591660ee556Sdrh static void constInsert( 45928e5bfeddSdrh WhereConst *pConst, /* The WhereConst into which we are inserting */ 45938e5bfeddSdrh Expr *pColumn, /* The COLUMN part of the constraint */ 4594f8f76d67Sdrh Expr *pValue, /* The VALUE part of the constraint */ 4595f8f76d67Sdrh Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */ 4596660ee556Sdrh ){ 45978e5bfeddSdrh int i; 45988e5bfeddSdrh assert( pColumn->op==TK_COLUMN ); 4599f8f76d67Sdrh assert( sqlite3ExprIsConstant(pValue) ); 4600f8f76d67Sdrh 4601fdfd45aeSdrh if( ExprHasProperty(pColumn, EP_FixedCol) ) return; 4602fdfd45aeSdrh if( sqlite3ExprAffinity(pValue)!=0 ) return; 4603f8f76d67Sdrh if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){ 4604f8f76d67Sdrh return; 4605f8f76d67Sdrh } 46068e5bfeddSdrh 46078e5bfeddSdrh /* 2018-10-25 ticket [cf5ed20f] 46088e5bfeddSdrh ** Make sure the same pColumn is not inserted more than once */ 46098e5bfeddSdrh for(i=0; i<pConst->nConst; i++){ 46107be5e3ddSdrh const Expr *pE2 = pConst->apExpr[i*2]; 46117be5e3ddSdrh assert( pE2->op==TK_COLUMN ); 46127be5e3ddSdrh if( pE2->iTable==pColumn->iTable 46137be5e3ddSdrh && pE2->iColumn==pColumn->iColumn 46148e5bfeddSdrh ){ 46158e5bfeddSdrh return; /* Already present. Return without doing anything. */ 46168e5bfeddSdrh } 46178e5bfeddSdrh } 461840b82f9dSdan if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){ 461940b82f9dSdan pConst->bHasAffBlob = 1; 462040b82f9dSdan } 46219cbf4f35Sdrh 4622660ee556Sdrh pConst->nConst++; 4623efad2e23Sdrh pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr, 4624660ee556Sdrh pConst->nConst*2*sizeof(Expr*)); 4625660ee556Sdrh if( pConst->apExpr==0 ){ 4626660ee556Sdrh pConst->nConst = 0; 4627660ee556Sdrh }else{ 4628660ee556Sdrh pConst->apExpr[pConst->nConst*2-2] = pColumn; 4629660ee556Sdrh pConst->apExpr[pConst->nConst*2-1] = pValue; 4630660ee556Sdrh } 4631660ee556Sdrh } 4632660ee556Sdrh 4633660ee556Sdrh /* 4634efad2e23Sdrh ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE 4635efad2e23Sdrh ** is a constant expression and where the term must be true because it 4636efad2e23Sdrh ** is part of the AND-connected terms of the expression. For each term 4637efad2e23Sdrh ** found, add it to the pConst structure. 4638660ee556Sdrh */ 4639660ee556Sdrh static void findConstInWhere(WhereConst *pConst, Expr *pExpr){ 4640efad2e23Sdrh Expr *pRight, *pLeft; 4641b775c976Sdrh if( NEVER(pExpr==0) ) return; 4642660ee556Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) ) return; 4643660ee556Sdrh if( pExpr->op==TK_AND ){ 4644660ee556Sdrh findConstInWhere(pConst, pExpr->pRight); 4645660ee556Sdrh findConstInWhere(pConst, pExpr->pLeft); 4646660ee556Sdrh return; 4647660ee556Sdrh } 4648660ee556Sdrh if( pExpr->op!=TK_EQ ) return; 4649efad2e23Sdrh pRight = pExpr->pRight; 4650efad2e23Sdrh pLeft = pExpr->pLeft; 4651efad2e23Sdrh assert( pRight!=0 ); 4652efad2e23Sdrh assert( pLeft!=0 ); 4653f8f76d67Sdrh if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){ 4654f8f76d67Sdrh constInsert(pConst,pRight,pLeft,pExpr); 4655f8f76d67Sdrh } 4656f8f76d67Sdrh if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){ 4657f8f76d67Sdrh constInsert(pConst,pLeft,pRight,pExpr); 4658660ee556Sdrh } 4659660ee556Sdrh } 4660660ee556Sdrh 4661660ee556Sdrh /* 466240b82f9dSdan ** This is a helper function for Walker callback propagateConstantExprRewrite(). 466340b82f9dSdan ** 466440b82f9dSdan ** Argument pExpr is a candidate expression to be replaced by a value. If 466540b82f9dSdan ** pExpr is equivalent to one of the columns named in pWalker->u.pConst, 466640b82f9dSdan ** then overwrite it with the corresponding value. Except, do not do so 466740b82f9dSdan ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr 466840b82f9dSdan ** is SQLITE_AFF_BLOB. 4669660ee556Sdrh */ 467040b82f9dSdan static int propagateConstantExprRewriteOne( 467140b82f9dSdan WhereConst *pConst, 467240b82f9dSdan Expr *pExpr, 467340b82f9dSdan int bIgnoreAffBlob 467440b82f9dSdan ){ 4675660ee556Sdrh int i; 467675016050Sdrh if( pConst->pOomFault[0] ) return WRC_Prune; 4677660ee556Sdrh if( pExpr->op!=TK_COLUMN ) return WRC_Continue; 4678be0330e8Sdrh if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){ 4679be0330e8Sdrh testcase( ExprHasProperty(pExpr, EP_FixedCol) ); 4680be0330e8Sdrh testcase( ExprHasProperty(pExpr, EP_FromJoin) ); 4681be0330e8Sdrh return WRC_Continue; 4682be0330e8Sdrh } 4683660ee556Sdrh for(i=0; i<pConst->nConst; i++){ 4684660ee556Sdrh Expr *pColumn = pConst->apExpr[i*2]; 4685660ee556Sdrh if( pColumn==pExpr ) continue; 4686660ee556Sdrh if( pColumn->iTable!=pExpr->iTable ) continue; 4687660ee556Sdrh if( pColumn->iColumn!=pExpr->iColumn ) continue; 468840b82f9dSdan if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){ 468940b82f9dSdan break; 469040b82f9dSdan } 4691efad2e23Sdrh /* A match is found. Add the EP_FixedCol property */ 4692660ee556Sdrh pConst->nChng++; 4693660ee556Sdrh ExprClearProperty(pExpr, EP_Leaf); 4694efad2e23Sdrh ExprSetProperty(pExpr, EP_FixedCol); 4695efad2e23Sdrh assert( pExpr->pLeft==0 ); 4696efad2e23Sdrh pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0); 469775016050Sdrh if( pConst->pParse->db->mallocFailed ) return WRC_Prune; 4698660ee556Sdrh break; 4699660ee556Sdrh } 4700660ee556Sdrh return WRC_Prune; 4701660ee556Sdrh } 4702660ee556Sdrh 4703660ee556Sdrh /* 470440b82f9dSdan ** This is a Walker expression callback. pExpr is a node from the WHERE 470540b82f9dSdan ** clause of a SELECT statement. This function examines pExpr to see if 470640b82f9dSdan ** any substitutions based on the contents of pWalker->u.pConst should 470740b82f9dSdan ** be made to pExpr or its immediate children. 470840b82f9dSdan ** 470940b82f9dSdan ** A substitution is made if: 471040b82f9dSdan ** 471140b82f9dSdan ** + pExpr is a column with an affinity other than BLOB that matches 471240b82f9dSdan ** one of the columns in pWalker->u.pConst, or 471340b82f9dSdan ** 471440b82f9dSdan ** + pExpr is a binary comparison operator (=, <=, >=, <, >) that 471540b82f9dSdan ** uses an affinity other than TEXT and one of its immediate 471640b82f9dSdan ** children is a column that matches one of the columns in 471740b82f9dSdan ** pWalker->u.pConst. 471840b82f9dSdan */ 471940b82f9dSdan static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){ 472040b82f9dSdan WhereConst *pConst = pWalker->u.pConst; 4721a8ed5154Sdrh assert( TK_GT==TK_EQ+1 ); 4722a8ed5154Sdrh assert( TK_LE==TK_EQ+2 ); 4723a8ed5154Sdrh assert( TK_LT==TK_EQ+3 ); 4724a8ed5154Sdrh assert( TK_GE==TK_EQ+4 ); 472540b82f9dSdan if( pConst->bHasAffBlob ){ 4726a8ed5154Sdrh if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE) 472740b82f9dSdan || pExpr->op==TK_IS 472840b82f9dSdan ){ 472940b82f9dSdan propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0); 473075016050Sdrh if( pConst->pOomFault[0] ) return WRC_Prune; 473140b82f9dSdan if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){ 473240b82f9dSdan propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0); 473340b82f9dSdan } 473440b82f9dSdan } 473540b82f9dSdan } 473640b82f9dSdan return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob); 473740b82f9dSdan } 473840b82f9dSdan 473940b82f9dSdan /* 4740660ee556Sdrh ** The WHERE-clause constant propagation optimization. 4741660ee556Sdrh ** 4742660ee556Sdrh ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or 474397bffe67Sdrh ** CONSTANT=COLUMN that are top-level AND-connected terms that are not 474497bffe67Sdrh ** part of a ON clause from a LEFT JOIN, then throughout the query 474597bffe67Sdrh ** replace all other occurrences of COLUMN with CONSTANT. 4746660ee556Sdrh ** 4747660ee556Sdrh ** For example, the query: 4748660ee556Sdrh ** 4749660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b 4750660ee556Sdrh ** 4751660ee556Sdrh ** Is transformed into 4752660ee556Sdrh ** 4753660ee556Sdrh ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39 4754660ee556Sdrh ** 4755660ee556Sdrh ** Return true if any transformations where made and false if not. 4756efad2e23Sdrh ** 4757efad2e23Sdrh ** Implementation note: Constant propagation is tricky due to affinity 4758efad2e23Sdrh ** and collating sequence interactions. Consider this example: 4759efad2e23Sdrh ** 4760efad2e23Sdrh ** CREATE TABLE t1(a INT,b TEXT); 4761efad2e23Sdrh ** INSERT INTO t1 VALUES(123,'0123'); 4762efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=a; 4763efad2e23Sdrh ** SELECT * FROM t1 WHERE a=123 AND b=123; 4764efad2e23Sdrh ** 4765efad2e23Sdrh ** The two SELECT statements above should return different answers. b=a 4766efad2e23Sdrh ** is alway true because the comparison uses numeric affinity, but b=123 4767efad2e23Sdrh ** is false because it uses text affinity and '0123' is not the same as '123'. 4768efad2e23Sdrh ** To work around this, the expression tree is not actually changed from 4769efad2e23Sdrh ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol 4770efad2e23Sdrh ** and the "123" value is hung off of the pLeft pointer. Code generator 4771efad2e23Sdrh ** routines know to generate the constant "123" instead of looking up the 4772efad2e23Sdrh ** column value. Also, to avoid collation problems, this optimization is 4773efad2e23Sdrh ** only attempted if the "a=123" term uses the default BINARY collation. 4774342cb33bSdrh ** 4775342cb33bSdrh ** 2021-05-25 forum post 6a06202608: Another troublesome case is... 4776342cb33bSdrh ** 4777342cb33bSdrh ** CREATE TABLE t1(x); 4778342cb33bSdrh ** INSERT INTO t1 VALUES(10.0); 4779342cb33bSdrh ** SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10; 4780342cb33bSdrh ** 4781342cb33bSdrh ** The query should return no rows, because the t1.x value is '10.0' not '10' 4782342cb33bSdrh ** and '10.0' is not LIKE '10'. But if we are not careful, the first WHERE 4783342cb33bSdrh ** term "x=10" will cause the second WHERE term to become "10 LIKE 10", 4784342cb33bSdrh ** resulting in a false positive. To avoid this, constant propagation for 4785342cb33bSdrh ** columns with BLOB affinity is only allowed if the constant is used with 4786342cb33bSdrh ** operators ==, <=, <, >=, >, or IS in a way that will cause the correct 4787342cb33bSdrh ** type conversions to occur. See logic associated with the bHasAffBlob flag 4788342cb33bSdrh ** for details. 4789660ee556Sdrh */ 4790660ee556Sdrh static int propagateConstants( 4791660ee556Sdrh Parse *pParse, /* The parsing context */ 4792660ee556Sdrh Select *p /* The query in which to propagate constants */ 4793660ee556Sdrh ){ 4794660ee556Sdrh WhereConst x; 4795660ee556Sdrh Walker w; 4796660ee556Sdrh int nChng = 0; 4797efad2e23Sdrh x.pParse = pParse; 479875016050Sdrh x.pOomFault = &pParse->db->mallocFailed; 4799660ee556Sdrh do{ 4800660ee556Sdrh x.nConst = 0; 4801660ee556Sdrh x.nChng = 0; 4802660ee556Sdrh x.apExpr = 0; 480340b82f9dSdan x.bHasAffBlob = 0; 4804660ee556Sdrh findConstInWhere(&x, p->pWhere); 4805660ee556Sdrh if( x.nConst ){ 4806660ee556Sdrh memset(&w, 0, sizeof(w)); 4807660ee556Sdrh w.pParse = pParse; 4808660ee556Sdrh w.xExprCallback = propagateConstantExprRewrite; 4809660ee556Sdrh w.xSelectCallback = sqlite3SelectWalkNoop; 4810660ee556Sdrh w.xSelectCallback2 = 0; 4811660ee556Sdrh w.walkerDepth = 0; 4812660ee556Sdrh w.u.pConst = &x; 4813efad2e23Sdrh sqlite3WalkExpr(&w, p->pWhere); 4814efad2e23Sdrh sqlite3DbFree(x.pParse->db, x.apExpr); 4815660ee556Sdrh nChng += x.nChng; 4816660ee556Sdrh } 4817660ee556Sdrh }while( x.nChng ); 4818660ee556Sdrh return nChng; 4819660ee556Sdrh } 482069b72d5aSdrh 482169b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 4822903fdd48Sdan # if !defined(SQLITE_OMIT_WINDOWFUNC) 4823903fdd48Sdan /* 4824903fdd48Sdan ** This function is called to determine whether or not it is safe to 4825903fdd48Sdan ** push WHERE clause expression pExpr down to FROM clause sub-query 4826903fdd48Sdan ** pSubq, which contains at least one window function. Return 1 4827903fdd48Sdan ** if it is safe and the expression should be pushed down, or 0 4828903fdd48Sdan ** otherwise. 4829903fdd48Sdan ** 4830903fdd48Sdan ** It is only safe to push the expression down if it consists only 4831903fdd48Sdan ** of constants and copies of expressions that appear in the PARTITION 4832903fdd48Sdan ** BY clause of all window function used by the sub-query. It is safe 4833903fdd48Sdan ** to filter out entire partitions, but not rows within partitions, as 4834903fdd48Sdan ** this may change the results of the window functions. 4835903fdd48Sdan ** 4836903fdd48Sdan ** At the time this function is called it is guaranteed that 4837903fdd48Sdan ** 4838903fdd48Sdan ** * the sub-query uses only one distinct window frame, and 4839903fdd48Sdan ** * that the window frame has a PARTITION BY clase. 4840903fdd48Sdan */ 4841903fdd48Sdan static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){ 4842903fdd48Sdan assert( pSubq->pWin->pPartition ); 4843903fdd48Sdan assert( (pSubq->selFlags & SF_MultiPart)==0 ); 4844903fdd48Sdan assert( pSubq->pPrior==0 ); 4845903fdd48Sdan return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition); 4846903fdd48Sdan } 4847903fdd48Sdan # endif /* SQLITE_OMIT_WINDOWFUNC */ 4848903fdd48Sdan #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 4849903fdd48Sdan 4850903fdd48Sdan #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 485169b72d5aSdrh /* 485269b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into 485369b72d5aSdrh ** the WHERE clause of subquery. Example: 485469b72d5aSdrh ** 485569b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; 485669b72d5aSdrh ** 485769b72d5aSdrh ** Transformed into: 485869b72d5aSdrh ** 485969b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) 486069b72d5aSdrh ** WHERE x=5 AND y=10; 486169b72d5aSdrh ** 486269b72d5aSdrh ** The hope is that the terms added to the inner query will make it more 486369b72d5aSdrh ** efficient. 486469b72d5aSdrh ** 486569b72d5aSdrh ** Do not attempt this optimization if: 486669b72d5aSdrh ** 486725c221ebSdrh ** (1) (** This restriction was removed on 2017-09-29. We used to 486825c221ebSdrh ** disallow this optimization for aggregate subqueries, but now 486967cc51a4Sdrh ** it is allowed by putting the extra terms on the HAVING clause. 487067cc51a4Sdrh ** The added HAVING clause is pointless if the subquery lacks 487167cc51a4Sdrh ** a GROUP BY clause. But such a HAVING clause is also harmless 487267cc51a4Sdrh ** so there does not appear to be any reason to add extra logic 487367cc51a4Sdrh ** to suppress it. **) 487469b72d5aSdrh ** 487569b72d5aSdrh ** (2) The inner query is the recursive part of a common table expression. 487669b72d5aSdrh ** 487769b72d5aSdrh ** (3) The inner query has a LIMIT clause (since the changes to the WHERE 4878ce103735Sdan ** clause would change the meaning of the LIMIT). 487969b72d5aSdrh ** 48806a9b9527Sdrh ** (4) The inner query is the right operand of a LEFT JOIN and the 48816a9b9527Sdrh ** expression to be pushed down does not come from the ON clause 48826a9b9527Sdrh ** on that LEFT JOIN. 488369b72d5aSdrh ** 488438978dd4Sdrh ** (5) The WHERE clause expression originates in the ON or USING clause 48857fbb101cSdrh ** of a LEFT JOIN where iCursor is not the right-hand table of that 48867fbb101cSdrh ** left join. An example: 48877fbb101cSdrh ** 48887fbb101cSdrh ** SELECT * 48897fbb101cSdrh ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa 48907fbb101cSdrh ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2) 48917fbb101cSdrh ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2); 48927fbb101cSdrh ** 48937fbb101cSdrh ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9). 48947fbb101cSdrh ** But if the (b2=2) term were to be pushed down into the bb subquery, 48957fbb101cSdrh ** then the (1,1,NULL) row would be suppressed. 489638978dd4Sdrh ** 4897903fdd48Sdan ** (6) Window functions make things tricky as changes to the WHERE clause 4898903fdd48Sdan ** of the inner query could change the window over which window 4899903fdd48Sdan ** functions are calculated. Therefore, do not attempt the optimization 4900903fdd48Sdan ** if: 4901903fdd48Sdan ** 4902903fdd48Sdan ** (6a) The inner query uses multiple incompatible window partitions. 4903903fdd48Sdan ** 4904903fdd48Sdan ** (6b) The inner query is a compound and uses window-functions. 4905903fdd48Sdan ** 4906903fdd48Sdan ** (6c) The WHERE clause does not consist entirely of constants and 4907903fdd48Sdan ** copies of expressions found in the PARTITION BY clause of 4908903fdd48Sdan ** all window-functions used by the sub-query. It is safe to 4909903fdd48Sdan ** filter out entire partitions, as this does not change the 4910903fdd48Sdan ** window over which any window-function is calculated. 4911ce103735Sdan ** 4912745912efSdrh ** (7) The inner query is a Common Table Expression (CTE) that should 4913745912efSdrh ** be materialized. (This restriction is implemented in the calling 4914745912efSdrh ** routine.) 4915745912efSdrh ** 491669b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause 491769b72d5aSdrh ** terms are duplicated into the subquery. 491869b72d5aSdrh */ 491969b72d5aSdrh static int pushDownWhereTerms( 492044c5604cSdan Parse *pParse, /* Parse context (for malloc() and error reporting) */ 492169b72d5aSdrh Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ 492269b72d5aSdrh Expr *pWhere, /* The WHERE clause of the outer query */ 49236a9b9527Sdrh int iCursor, /* Cursor number of the subquery */ 49246a9b9527Sdrh int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */ 492569b72d5aSdrh ){ 492669b72d5aSdrh Expr *pNew; 492769b72d5aSdrh int nChng = 0; 492869b72d5aSdrh if( pWhere==0 ) return 0; 4929903fdd48Sdan if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ) return 0; 4930508e2d00Sdrh 4931ce103735Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 4932903fdd48Sdan if( pSubq->pPrior ){ 4933903fdd48Sdan Select *pSel; 4934f65e3799Sdan for(pSel=pSubq; pSel; pSel=pSel->pPrior){ 4935903fdd48Sdan if( pSel->pWin ) return 0; /* restriction (6b) */ 4936903fdd48Sdan } 4937903fdd48Sdan }else{ 4938903fdd48Sdan if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0; 4939f65e3799Sdan } 4940ce103735Sdan #endif 4941ce103735Sdan 4942508e2d00Sdrh #ifdef SQLITE_DEBUG 4943508e2d00Sdrh /* Only the first term of a compound can have a WITH clause. But make 4944508e2d00Sdrh ** sure no other terms are marked SF_Recursive in case something changes 4945508e2d00Sdrh ** in the future. 4946508e2d00Sdrh */ 4947508e2d00Sdrh { 4948508e2d00Sdrh Select *pX; 4949b1ec87afSdrh for(pX=pSubq; pX; pX=pX->pPrior){ 4950508e2d00Sdrh assert( (pX->selFlags & (SF_Recursive))==0 ); 495169b72d5aSdrh } 4952b1ec87afSdrh } 4953508e2d00Sdrh #endif 4954508e2d00Sdrh 495569b72d5aSdrh if( pSubq->pLimit!=0 ){ 495669b72d5aSdrh return 0; /* restriction (3) */ 495769b72d5aSdrh } 495869b72d5aSdrh while( pWhere->op==TK_AND ){ 49596a9b9527Sdrh nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, 49606a9b9527Sdrh iCursor, isLeftJoin); 496169b72d5aSdrh pWhere = pWhere->pLeft; 496269b72d5aSdrh } 49636a9b9527Sdrh if( isLeftJoin 49646a9b9527Sdrh && (ExprHasProperty(pWhere,EP_FromJoin)==0 4965d1985262Sdrh || pWhere->w.iJoin!=iCursor) 49666a9b9527Sdrh ){ 49676a9b9527Sdrh return 0; /* restriction (4) */ 49686a9b9527Sdrh } 4969796588aeSdrh if( ExprHasProperty(pWhere,EP_FromJoin) 4970d1985262Sdrh && pWhere->w.iJoin!=iCursor 4971796588aeSdrh ){ 49727fbb101cSdrh return 0; /* restriction (5) */ 49737fbb101cSdrh } 497469b72d5aSdrh if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ 497569b72d5aSdrh nChng++; 49768794c68aSdrh pSubq->selFlags |= SF_PushDown; 497769b72d5aSdrh while( pSubq ){ 497846967de2Sdrh SubstContext x; 497944c5604cSdan pNew = sqlite3ExprDup(pParse->db, pWhere, 0); 49807fbb101cSdrh unsetJoinExpr(pNew, -1); 498146967de2Sdrh x.pParse = pParse; 498246967de2Sdrh x.iTable = iCursor; 4983399c7e21Sdrh x.iNewTable = iCursor; 4984c133bab7Sdrh x.isOuterJoin = 0; 498546967de2Sdrh x.pEList = pSubq->pEList; 498646967de2Sdrh pNew = substExpr(&x, pNew); 4987903fdd48Sdan #ifndef SQLITE_OMIT_WINDOWFUNC 4988903fdd48Sdan if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){ 4989903fdd48Sdan /* Restriction 6c has prevented push-down in this case */ 4990903fdd48Sdan sqlite3ExprDelete(pParse->db, pNew); 4991903fdd48Sdan nChng--; 4992903fdd48Sdan break; 4993903fdd48Sdan } 4994903fdd48Sdan #endif 499525c221ebSdrh if( pSubq->selFlags & SF_Aggregate ){ 4996d5c851c1Sdrh pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew); 499725c221ebSdrh }else{ 4998d5c851c1Sdrh pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew); 499925c221ebSdrh } 500069b72d5aSdrh pSubq = pSubq->pPrior; 500169b72d5aSdrh } 500269b72d5aSdrh } 500369b72d5aSdrh return nChng; 500469b72d5aSdrh } 500569b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 500669b72d5aSdrh 50071350b030Sdrh /* 500847d9f839Sdrh ** The pFunc is the only aggregate function in the query. Check to see 500947d9f839Sdrh ** if the query is a candidate for the min/max optimization. 5010a9d1ccb9Sdanielk1977 ** 501147d9f839Sdrh ** If the query is a candidate for the min/max optimization, then set 501247d9f839Sdrh ** *ppMinMax to be an ORDER BY clause to be used for the optimization 501347d9f839Sdrh ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on 501447d9f839Sdrh ** whether pFunc is a min() or max() function. 5015738bdcfbSdanielk1977 ** 501647d9f839Sdrh ** If the query is not a candidate for the min/max optimization, return 501747d9f839Sdrh ** WHERE_ORDERBY_NORMAL (which must be zero). 50184ac391fcSdan ** 501947d9f839Sdrh ** This routine must be called after aggregate functions have been 502047d9f839Sdrh ** located but before their arguments have been subjected to aggregate 502147d9f839Sdrh ** analysis. 5022a9d1ccb9Sdanielk1977 */ 502347d9f839Sdrh static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){ 50244ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 5025a4eeccdfSdrh ExprList *pEList; /* Arguments to agg function */ 502647d9f839Sdrh const char *zFunc; /* Name of aggregate function pFunc */ 502747d9f839Sdrh ExprList *pOrderBy; 5028be284e4eSdrh u8 sortFlags = 0; 5029a9d1ccb9Sdanielk1977 503047d9f839Sdrh assert( *ppMinMax==0 ); 503147d9f839Sdrh assert( pFunc->op==TK_AGG_FUNCTION ); 50324f9adee2Sdan assert( !IsWindowFunc(pFunc) ); 5033a4eeccdfSdrh assert( ExprUseXList(pFunc) ); 5034a4eeccdfSdrh pEList = pFunc->x.pList; 5035af7b7653Sdrh if( pEList==0 5036af7b7653Sdrh || pEList->nExpr!=1 5037af7b7653Sdrh || ExprHasProperty(pFunc, EP_WinFunc) 5038af7b7653Sdrh || OptimizationDisabled(db, SQLITE_MinMaxOpt) 5039af7b7653Sdrh ){ 50406ba7ab0dSdan return eRet; 50416ba7ab0dSdan } 5042f9751074Sdrh assert( !ExprHasProperty(pFunc, EP_IntValue) ); 504347d9f839Sdrh zFunc = pFunc->u.zToken; 50444ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 50454ac391fcSdan eRet = WHERE_ORDERBY_MIN; 504667e2bb92Sdan if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){ 50475b32bdffSdan sortFlags = KEYINFO_ORDER_BIGNULL; 504867e2bb92Sdan } 50494ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 50504ac391fcSdan eRet = WHERE_ORDERBY_MAX; 50515b32bdffSdan sortFlags = KEYINFO_ORDER_DESC; 505247d9f839Sdrh }else{ 505347d9f839Sdrh return eRet; 5054a9d1ccb9Sdanielk1977 } 505547d9f839Sdrh *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0); 505647d9f839Sdrh assert( pOrderBy!=0 || db->mallocFailed ); 50575b32bdffSdan if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags; 50584ac391fcSdan return eRet; 5059a9d1ccb9Sdanielk1977 } 5060a9d1ccb9Sdanielk1977 5061a9d1ccb9Sdanielk1977 /* 5062a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 506360ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 5064a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 5065a5533162Sdanielk1977 ** 5066a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 5067a5533162Sdanielk1977 ** 5068a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 5069a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 5070a1c4c3c1Sdrh ** <tbl> is returned. Otherwise, NULL is returned. 5071a1c4c3c1Sdrh ** 5072e574a923Sdrh ** This routine checks to see if it is safe to use the count optimization. 5073e574a923Sdrh ** A correct answer is still obtained (though perhaps more slowly) if 5074e574a923Sdrh ** this routine returns NULL when it could have returned a table pointer. 5075e574a923Sdrh ** But returning the pointer when NULL should have been returned can 5076e574a923Sdrh ** result in incorrect answers and/or crashes. So, when in doubt, return NULL. 5077a5533162Sdanielk1977 */ 5078a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 5079a5533162Sdanielk1977 Table *pTab; 5080a5533162Sdanielk1977 Expr *pExpr; 5081a5533162Sdanielk1977 5082a5533162Sdanielk1977 assert( !p->pGroupBy ); 5083a5533162Sdanielk1977 5084a1c4c3c1Sdrh if( p->pWhere 5085a1c4c3c1Sdrh || p->pEList->nExpr!=1 5086a1c4c3c1Sdrh || p->pSrc->nSrc!=1 5087a1c4c3c1Sdrh || p->pSrc->a[0].pSelect 5088a1c4c3c1Sdrh || pAggInfo->nFunc!=1 5089a5533162Sdanielk1977 ){ 5090a5533162Sdanielk1977 return 0; 5091a5533162Sdanielk1977 } 5092a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 5093a1c4c3c1Sdrh assert( pTab!=0 ); 5094a1c4c3c1Sdrh assert( !IsView(pTab) ); 5095a1c4c3c1Sdrh if( !IsOrdinaryTable(pTab) ) return 0; 5096a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 5097a1c4c3c1Sdrh assert( pExpr!=0 ); 5098a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 50998745f8a3Sdan if( pExpr->pAggInfo!=pAggInfo ) return 0; 5100d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 5101a1c4c3c1Sdrh assert( pAggInfo->aFunc[0].pFExpr==pExpr ); 5102a1c4c3c1Sdrh testcase( ExprHasProperty(pExpr, EP_Distinct) ); 5103a1c4c3c1Sdrh testcase( ExprHasProperty(pExpr, EP_WinFunc) ); 51044f9adee2Sdan if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0; 5105a5533162Sdanielk1977 5106a5533162Sdanielk1977 return pTab; 5107a5533162Sdanielk1977 } 5108a5533162Sdanielk1977 5109a5533162Sdanielk1977 /* 5110b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 5111b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 5112b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 5113b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 5114b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 5115b1c685b0Sdanielk1977 */ 51167601294aSdrh int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){ 5117b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 51188a48b9c0Sdrh char *zIndexedBy = pFrom->u1.zIndexedBy; 5119b1c685b0Sdanielk1977 Index *pIdx; 51201862271fSdrh assert( pTab!=0 ); 51211862271fSdrh assert( pFrom->fg.isIndexedBy!=0 ); 51221862271fSdrh 5123b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 5124d62fbb50Sdrh pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 5125b1c685b0Sdanielk1977 pIdx=pIdx->pNext 5126b1c685b0Sdanielk1977 ); 5127b1c685b0Sdanielk1977 if( !pIdx ){ 5128d62fbb50Sdrh sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); 51291db95106Sdan pParse->checkSchema = 1; 5130b1c685b0Sdanielk1977 return SQLITE_ERROR; 5131b1c685b0Sdanielk1977 } 5132dbfbb5a0Sdrh assert( pFrom->fg.isCte==0 ); 5133a79e2a2dSdrh pFrom->u2.pIBIndex = pIdx; 5134b1c685b0Sdanielk1977 return SQLITE_OK; 5135b1c685b0Sdanielk1977 } 51361862271fSdrh 5137c01b7306Sdrh /* 5138c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 5139c01b7306Sdrh ** an alternative collating sequence. 5140c01b7306Sdrh ** 5141c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 5142c01b7306Sdrh ** 5143c01b7306Sdrh ** These are rewritten as a subquery: 5144c01b7306Sdrh ** 5145c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 5146c01b7306Sdrh ** ORDER BY ... COLLATE ... 5147c01b7306Sdrh ** 5148c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 5149c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 5150c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 5151c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 5152c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 5153c01b7306Sdrh ** 5154c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 5155c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 5156c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 5157c01b7306Sdrh */ 5158c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 5159c01b7306Sdrh int i; 5160c01b7306Sdrh Select *pNew; 5161c01b7306Sdrh Select *pX; 5162c01b7306Sdrh sqlite3 *db; 5163c01b7306Sdrh struct ExprList_item *a; 5164c01b7306Sdrh SrcList *pNewSrc; 5165c01b7306Sdrh Parse *pParse; 5166c01b7306Sdrh Token dummy; 5167c01b7306Sdrh 5168c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 5169c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 5170c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 5171c01b7306Sdrh if( pX==0 ) return WRC_Continue; 5172c01b7306Sdrh a = p->pOrderBy->a; 517346daa99bSdan #ifndef SQLITE_OMIT_WINDOWFUNC 517446daa99bSdan /* If iOrderByCol is already non-zero, then it has already been matched 517546daa99bSdan ** to a result column of the SELECT statement. This occurs when the 517646daa99bSdan ** SELECT is rewritten for window-functions processing and then passed 517746daa99bSdan ** to sqlite3SelectPrep() and similar a second time. The rewriting done 517846daa99bSdan ** by this function is not required in this case. */ 517946daa99bSdan if( a[0].u.x.iOrderByCol ) return WRC_Continue; 518046daa99bSdan #endif 5181c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 5182c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 5183c01b7306Sdrh } 5184c01b7306Sdrh if( i<0 ) return WRC_Continue; 5185c01b7306Sdrh 5186c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 5187c01b7306Sdrh 5188c01b7306Sdrh pParse = pWalker->pParse; 5189c01b7306Sdrh db = pParse->db; 5190c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 5191c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 5192c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 5193d44f8b23Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0); 5194c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 5195c01b7306Sdrh *pNew = *p; 5196c01b7306Sdrh p->pSrc = pNewSrc; 51971a1d3cd2Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); 5198c01b7306Sdrh p->op = TK_SELECT; 5199c01b7306Sdrh p->pWhere = 0; 5200c01b7306Sdrh pNew->pGroupBy = 0; 5201c01b7306Sdrh pNew->pHaving = 0; 5202c01b7306Sdrh pNew->pOrderBy = 0; 5203c01b7306Sdrh p->pPrior = 0; 52048af9ad95Sdrh p->pNext = 0; 5205f932f714Sdrh p->pWith = 0; 5206fcc057dbSdan #ifndef SQLITE_OMIT_WINDOWFUNC 5207fcc057dbSdan p->pWinDefn = 0; 5208fcc057dbSdan #endif 52098af9ad95Sdrh p->selFlags &= ~SF_Compound; 5210b33c50f2Sdan assert( (p->selFlags & SF_Converted)==0 ); 5211b33c50f2Sdan p->selFlags |= SF_Converted; 5212a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 5213a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 5214c01b7306Sdrh pNew->pLimit = 0; 5215c01b7306Sdrh return WRC_Continue; 5216c01b7306Sdrh } 5217b1c685b0Sdanielk1977 521820292310Sdrh /* 521920292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function 522020292310Sdrh ** arguments. If it does, leave an error message in pParse and return 522120292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function. 522220292310Sdrh */ 52237601294aSdrh static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){ 522420292310Sdrh if( pFrom->fg.isTabFunc ){ 522520292310Sdrh sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); 522620292310Sdrh return 1; 522720292310Sdrh } 522820292310Sdrh return 0; 522920292310Sdrh } 523020292310Sdrh 5231eede6a53Sdan #ifndef SQLITE_OMIT_CTE 5232eede6a53Sdan /* 5233eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 5234eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 5235eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 5236eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 5237eede6a53Sdan ** return NULL. 523898f45e53Sdan ** 523998f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 524098f45e53Sdan ** object that the returned CTE belongs to. 524160c1a2f0Sdrh */ 524298f45e53Sdan static struct Cte *searchWith( 52432476a6f2Sdrh With *pWith, /* Current innermost WITH clause */ 52447601294aSdrh SrcItem *pItem, /* FROM clause element to resolve */ 524598f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 524698f45e53Sdan ){ 52475abe1d3dSdrh const char *zName = pItem->zName; 5248eede6a53Sdan With *p; 52495abe1d3dSdrh assert( pItem->zDatabase==0 ); 52505abe1d3dSdrh assert( zName!=0 ); 5251eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 52524e9119d9Sdan int i; 5253eede6a53Sdan for(i=0; i<p->nCte; i++){ 5254eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 525598f45e53Sdan *ppContext = p; 5256eede6a53Sdan return &p->a[i]; 52574e9119d9Sdan } 52584e9119d9Sdan } 525990bc36fbSdan if( p->bView ) break; 52604e9119d9Sdan } 52614e9119d9Sdan return 0; 52624e9119d9Sdan } 52634e9119d9Sdan 5264c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 5265c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 5266c49832c2Sdrh ** 5267b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 5268b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 52697cc73b39Sdrh ** WITH clause will never be popped from the stack but should instead 52707cc73b39Sdrh ** be freed along with the Parse object. In other cases, when 5271b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 5272b290f117Sdan ** statement with which it is associated. 527324ce9446Sdrh ** 527424ce9446Sdrh ** This routine returns a copy of pWith. Or, if bFree is true and 527524ce9446Sdrh ** the pWith object is destroyed immediately due to an OOM condition, 527624ce9446Sdrh ** then this routine return NULL. 527724ce9446Sdrh ** 527824ce9446Sdrh ** If bFree is true, do not continue to use the pWith pointer after 527924ce9446Sdrh ** calling this routine, Instead, use only the return value. 5280c49832c2Sdrh */ 528124ce9446Sdrh With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 52824e9119d9Sdan if( pWith ){ 528324ce9446Sdrh if( bFree ){ 528424ce9446Sdrh pWith = (With*)sqlite3ParserAddCleanup(pParse, 528524ce9446Sdrh (void(*)(sqlite3*,void*))sqlite3WithDelete, 528624ce9446Sdrh pWith); 528724ce9446Sdrh if( pWith==0 ) return 0; 528824ce9446Sdrh } 52897cc73b39Sdrh if( pParse->nErr==0 ){ 52902476a6f2Sdrh assert( pParse->pWith!=pWith ); 52914e9119d9Sdan pWith->pOuter = pParse->pWith; 52924e9119d9Sdan pParse->pWith = pWith; 52937cc73b39Sdrh } 5294cf3c078fSdrh } 529524ce9446Sdrh return pWith; 52964e9119d9Sdan } 52974e9119d9Sdan 5298eede6a53Sdan /* 5299eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 53005abe1d3dSdrh ** a WITH clause on the stack currently maintained by the parser (on the 53015abe1d3dSdrh ** pParse->pWith linked list). And if currently processing a CTE 53025abe1d3dSdrh ** CTE expression, through routine checks to see if the reference is 53035abe1d3dSdrh ** a recursive reference to the CTE. 5304eede6a53Sdan ** 53055abe1d3dSdrh ** If pFrom matches a CTE according to either of these two above, pFrom->pTab 53065abe1d3dSdrh ** and other fields are populated accordingly. 5307eede6a53Sdan ** 53085abe1d3dSdrh ** Return 0 if no match is found. 53095abe1d3dSdrh ** Return 1 if a match is found. 53105abe1d3dSdrh ** Return 2 if an error condition is detected. 5311eede6a53Sdan */ 53125abe1d3dSdrh static int resolveFromTermToCte( 53135abe1d3dSdrh Parse *pParse, /* The parsing context */ 53145abe1d3dSdrh Walker *pWalker, /* Current tree walker */ 53157601294aSdrh SrcItem *pFrom /* The FROM clause term to check */ 53168ce7184bSdan ){ 53175abe1d3dSdrh Cte *pCte; /* Matched CTE (or NULL if no match) */ 53185abe1d3dSdrh With *pWith; /* The matching WITH */ 53198ce7184bSdan 53208ce7184bSdan assert( pFrom->pTab==0 ); 53215abe1d3dSdrh if( pParse->pWith==0 ){ 53225abe1d3dSdrh /* There are no WITH clauses in the stack. No match is possible */ 53235abe1d3dSdrh return 0; 532446a31cdfSdrh } 532593c8139cSdrh if( pParse->nErr ){ 532693c8139cSdrh /* Prior errors might have left pParse->pWith in a goofy state, so 532793c8139cSdrh ** go no further. */ 532893c8139cSdrh return 0; 532993c8139cSdrh } 53305abe1d3dSdrh if( pFrom->zDatabase!=0 ){ 53315abe1d3dSdrh /* The FROM term contains a schema qualifier (ex: main.t1) and so 53325abe1d3dSdrh ** it cannot possibly be a CTE reference. */ 53335abe1d3dSdrh return 0; 53345abe1d3dSdrh } 5335cd1499f4Sdrh if( pFrom->fg.notCte ){ 5336cd1499f4Sdrh /* The FROM term is specifically excluded from matching a CTE. 5337cd1499f4Sdrh ** (1) It is part of a trigger that used to have zDatabase but had 5338cd1499f4Sdrh ** zDatabase removed by sqlite3FixTriggerStep(). 5339cd1499f4Sdrh ** (2) This is the first term in the FROM clause of an UPDATE. 5340cd1499f4Sdrh */ 5341cd1499f4Sdrh return 0; 5342cd1499f4Sdrh } 534398f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 5344eae73fbfSdan if( pCte ){ 53455abe1d3dSdrh sqlite3 *db = pParse->db; 534698f45e53Sdan Table *pTab; 53478ce7184bSdan ExprList *pEList; 53488ce7184bSdan Select *pSel; 534960e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 535034055854Sdrh Select *pRecTerm; /* Left-most recursive term */ 5351f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 535298f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 535334055854Sdrh int iRecTab = -1; /* Cursor for recursive table */ 5354745912efSdrh CteUse *pCteUse; 5355f2655fe8Sdan 53560576bc59Sdrh /* If pCte->zCteErr is non-NULL at this point, then this is an illegal 5357f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 53580576bc59Sdrh ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. 5359f2655fe8Sdan ** In this case, proceed. */ 53600576bc59Sdrh if( pCte->zCteErr ){ 53610576bc59Sdrh sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); 53625abe1d3dSdrh return 2; 5363f2655fe8Sdan } 53645abe1d3dSdrh if( cannotBeFunction(pParse, pFrom) ) return 2; 53658ce7184bSdan 5366c25e2ebcSdrh assert( pFrom->pTab==0 ); 5367a79e2a2dSdrh pTab = sqlite3DbMallocZero(db, sizeof(Table)); 53685abe1d3dSdrh if( pTab==0 ) return 2; 5369745912efSdrh pCteUse = pCte->pUse; 5370745912efSdrh if( pCteUse==0 ){ 5371745912efSdrh pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0])); 5372745912efSdrh if( pCteUse==0 5373745912efSdrh || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0 5374a79e2a2dSdrh ){ 5375a79e2a2dSdrh sqlite3DbFree(db, pTab); 5376a79e2a2dSdrh return 2; 5377a79e2a2dSdrh } 5378745912efSdrh pCteUse->eM10d = pCte->eM10d; 5379a79e2a2dSdrh } 5380a79e2a2dSdrh pFrom->pTab = pTab; 538179df7782Sdrh pTab->nTabRef = 1; 53822d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 53838ce7184bSdan pTab->iPKey = -1; 5384cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 5385fccda8a1Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 53868ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 53875abe1d3dSdrh if( db->mallocFailed ) return 2; 5388ac67f567Sdan pFrom->pSelect->selFlags |= SF_CopyCte; 53898ce7184bSdan assert( pFrom->pSelect ); 53900c1da689Sdrh if( pFrom->fg.isIndexedBy ){ 53910c1da689Sdrh sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy); 53920c1da689Sdrh return 2; 53930c1da689Sdrh } 5394a79e2a2dSdrh pFrom->fg.isCte = 1; 5395745912efSdrh pFrom->u2.pCteUse = pCteUse; 5396745912efSdrh pCteUse->nUse++; 5397745912efSdrh if( pCteUse->nUse>=2 && pCteUse->eM10d==M10d_Any ){ 5398745912efSdrh pCteUse->eM10d = M10d_Yes; 5399745912efSdrh } 54008ce7184bSdan 5401eae73fbfSdan /* Check if this is a recursive CTE. */ 540234055854Sdrh pRecTerm = pSel = pFrom->pSelect; 5403f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 540434055854Sdrh while( bMayRecursive && pRecTerm->op==pSel->op ){ 5405eae73fbfSdan int i; 540634055854Sdrh SrcList *pSrc = pRecTerm->pSrc; 540734055854Sdrh assert( pRecTerm->pPrior!=0 ); 5408eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 54097601294aSdrh SrcItem *pItem = &pSrc->a[i]; 5410eae73fbfSdan if( pItem->zDatabase==0 5411eae73fbfSdan && pItem->zName!=0 5412eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 5413eae73fbfSdan ){ 5414eae73fbfSdan pItem->pTab = pTab; 541594d6f3f8Sdrh pTab->nTabRef++; 54168a48b9c0Sdrh pItem->fg.isRecursive = 1; 541734055854Sdrh if( pRecTerm->selFlags & SF_Recursive ){ 541834055854Sdrh sqlite3ErrorMsg(pParse, 541934055854Sdrh "multiple references to recursive table: %s", pCte->zName 5420eae73fbfSdan ); 54215abe1d3dSdrh return 2; 5422eae73fbfSdan } 542334055854Sdrh pRecTerm->selFlags |= SF_Recursive; 542434055854Sdrh if( iRecTab<0 ) iRecTab = pParse->nTab++; 542534055854Sdrh pItem->iCursor = iRecTab; 542634055854Sdrh } 542734055854Sdrh } 542834055854Sdrh if( (pRecTerm->selFlags & SF_Recursive)==0 ) break; 542934055854Sdrh pRecTerm = pRecTerm->pPrior; 543034055854Sdrh } 5431eae73fbfSdan 54320576bc59Sdrh pCte->zCteErr = "circular reference: %s"; 543398f45e53Sdan pSavedWith = pParse->pWith; 543498f45e53Sdan pParse->pWith = pWith; 543534055854Sdrh if( pSel->selFlags & SF_Recursive ){ 5436ca237a8bSdan int rc; 543734055854Sdrh assert( pRecTerm!=0 ); 543834055854Sdrh assert( (pRecTerm->selFlags & SF_Recursive)==0 ); 543934055854Sdrh assert( pRecTerm->pNext!=0 ); 544034055854Sdrh assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 ); 544134055854Sdrh assert( pRecTerm->pWith==0 ); 544234055854Sdrh pRecTerm->pWith = pSel->pWith; 5443ca237a8bSdan rc = sqlite3WalkSelect(pWalker, pRecTerm); 544434055854Sdrh pRecTerm->pWith = 0; 5445ca237a8bSdan if( rc ){ 5446ca237a8bSdan pParse->pWith = pSavedWith; 5447ca237a8bSdan return 2; 5448ca237a8bSdan } 5449067cd837Sdan }else{ 5450ca237a8bSdan if( sqlite3WalkSelect(pWalker, pSel) ){ 5451ca237a8bSdan pParse->pWith = pSavedWith; 5452ca237a8bSdan return 2; 5453ca237a8bSdan } 5454067cd837Sdan } 54556e772266Sdrh pParse->pWith = pWith; 54568ce7184bSdan 54578ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 54588ce7184bSdan pEList = pLeft->pEList; 545960e7068dSdan if( pCte->pCols ){ 54608f9d0b2bSdrh if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ 5461727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 546260e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 546360e7068dSdan ); 546498f45e53Sdan pParse->pWith = pSavedWith; 54655abe1d3dSdrh return 2; 54668ce7184bSdan } 546760e7068dSdan pEList = pCte->pCols; 546860e7068dSdan } 54698ce7184bSdan 54708981b904Sdrh sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 5471f2655fe8Sdan if( bMayRecursive ){ 5472f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 54730576bc59Sdrh pCte->zCteErr = "multiple recursive references: %s"; 5474f2655fe8Sdan }else{ 54750576bc59Sdrh pCte->zCteErr = "recursive reference in a subquery: %s"; 5476f2655fe8Sdan } 5477f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 5478f2655fe8Sdan } 54790576bc59Sdrh pCte->zCteErr = 0; 548098f45e53Sdan pParse->pWith = pSavedWith; 54815abe1d3dSdrh return 1; /* Success */ 54828ce7184bSdan } 54835abe1d3dSdrh return 0; /* No match */ 54848ce7184bSdan } 5485eede6a53Sdan #endif 54864e9119d9Sdan 5487b290f117Sdan #ifndef SQLITE_OMIT_CTE 548871856944Sdan /* 548971856944Sdan ** If the SELECT passed as the second argument has an associated WITH 549071856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 549171856944Sdan ** 549271856944Sdan ** This function is used as the xSelectCallback2() callback by 549371856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 549471856944Sdan ** names and other FROM clause elements. 549571856944Sdan */ 5496be12083bSdan void sqlite3SelectPopWith(Walker *pWalker, Select *p){ 5497b290f117Sdan Parse *pParse = pWalker->pParse; 54982f65b2f5Sdrh if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){ 5499d227a291Sdrh With *pWith = findRightmost(p)->pWith; 5500d227a291Sdrh if( pWith!=0 ){ 550170a32703Sdan assert( pParse->pWith==pWith || pParse->nErr ); 5502d227a291Sdrh pParse->pWith = pWith->pOuter; 5503b290f117Sdan } 5504b290f117Sdan } 5505067cd837Sdan } 5506b290f117Sdan #endif 5507b290f117Sdan 55089a94722dSdan /* 55099a94722dSdan ** The SrcList_item structure passed as the second argument represents a 55109a94722dSdan ** sub-query in the FROM clause of a SELECT statement. This function 55119a94722dSdan ** allocates and populates the SrcList_item.pTab object. If successful, 55129a94722dSdan ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered, 55139a94722dSdan ** SQLITE_NOMEM. 55149a94722dSdan */ 55157601294aSdrh int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){ 551686fb6e17Sdan Select *pSel = pFrom->pSelect; 551786fb6e17Sdan Table *pTab; 551886fb6e17Sdan 55199a94722dSdan assert( pSel ); 552086fb6e17Sdan pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table)); 55219a94722dSdan if( pTab==0 ) return SQLITE_NOMEM; 552286fb6e17Sdan pTab->nTabRef = 1; 552386fb6e17Sdan if( pFrom->zAlias ){ 552486fb6e17Sdan pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias); 552586fb6e17Sdan }else{ 5526fef37760Sdrh pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId); 552786fb6e17Sdan } 552886fb6e17Sdan while( pSel->pPrior ){ pSel = pSel->pPrior; } 552986fb6e17Sdan sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); 553086fb6e17Sdan pTab->iPKey = -1; 553186fb6e17Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 55326e5020e8Sdrh #ifndef SQLITE_ALLOW_ROWID_IN_VIEW 55336e5020e8Sdrh /* The usual case - do not allow ROWID on a subquery */ 55346e5020e8Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 55356e5020e8Sdrh #else 55366e5020e8Sdrh pTab->tabFlags |= TF_Ephemeral; /* Legacy compatibility mode */ 55376e5020e8Sdrh #endif 5538f4b33153Sdrh return pParse->nErr ? SQLITE_ERROR : SQLITE_OK; 553986fb6e17Sdan } 554086fb6e17Sdan 55414ce7bf91Sdrh 55424ce7bf91Sdrh /* 55434ce7bf91Sdrh ** Check the N SrcItem objects to the right of pBase. (N might be zero!) 55444ce7bf91Sdrh ** If any of those SrcItem objects have a USING clause containing zName 55454ce7bf91Sdrh ** then return true. 55464ce7bf91Sdrh ** 55474ce7bf91Sdrh ** If N is zero, or none of the N SrcItem objects to the right of pBase 55484ce7bf91Sdrh ** contains a USING clause, or if none of the USING clauses contain zName, 55494ce7bf91Sdrh ** then return false. 55504ce7bf91Sdrh */ 55514ce7bf91Sdrh static int inAnyUsingClause( 55524ce7bf91Sdrh const char *zName, /* Name we are looking for */ 55534ce7bf91Sdrh SrcItem *pBase, /* The base SrcItem. Looking at pBase[1] and following */ 55544ce7bf91Sdrh int N /* How many SrcItems to check */ 55554ce7bf91Sdrh ){ 55564ce7bf91Sdrh while( N>0 ){ 55574ce7bf91Sdrh N--; 55584ce7bf91Sdrh pBase++; 55594ce7bf91Sdrh if( pBase->fg.isUsing==0 ) continue; 5560e32d6a0bSdrh if( NEVER(pBase->u3.pUsing==0) ) continue; 55614ce7bf91Sdrh if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1; 55624ce7bf91Sdrh } 55634ce7bf91Sdrh return 0; 55644ce7bf91Sdrh } 55654ce7bf91Sdrh 55664ce7bf91Sdrh 5567b1c685b0Sdanielk1977 /* 55687d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 55697d10d5a6Sdrh ** "Expanding" means to do the following: 55707d10d5a6Sdrh ** 55717d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 55727d10d5a6Sdrh ** element of the FROM clause. 55737d10d5a6Sdrh ** 55747d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 55757d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 55767d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 55777d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 55787d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 557960ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 55807d10d5a6Sdrh ** of the view. 55817d10d5a6Sdrh ** 558260ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 55837d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 55847d10d5a6Sdrh ** 55857d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 55867d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 55877d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 55887d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 55897d10d5a6Sdrh ** 5590b3bce662Sdanielk1977 */ 55917d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 55927d10d5a6Sdrh Parse *pParse = pWalker->pParse; 55935abe1d3dSdrh int i, j, k, rc; 55947d10d5a6Sdrh SrcList *pTabList; 55957d10d5a6Sdrh ExprList *pEList; 55967601294aSdrh SrcItem *pFrom; 55977d10d5a6Sdrh sqlite3 *db = pParse->db; 55983e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 5599785097daSdrh u16 selFlags = p->selFlags; 5600fca23557Sdrh u32 elistFlags = 0; 56017d10d5a6Sdrh 5602785097daSdrh p->selFlags |= SF_Expanded; 56037d10d5a6Sdrh if( db->mallocFailed ){ 56047d10d5a6Sdrh return WRC_Abort; 56057d10d5a6Sdrh } 56069d9c41e2Sdrh assert( p->pSrc!=0 ); 56079d9c41e2Sdrh if( (selFlags & SF_Expanded)!=0 ){ 56087d10d5a6Sdrh return WRC_Prune; 56097d10d5a6Sdrh } 561059145813Sdrh if( pWalker->eCode ){ 561159145813Sdrh /* Renumber selId because it has been copied from a view */ 561259145813Sdrh p->selId = ++pParse->nSelect; 561359145813Sdrh } 56147d10d5a6Sdrh pTabList = p->pSrc; 56157d10d5a6Sdrh pEList = p->pEList; 561690bc36fbSdan if( pParse->pWith && (p->selFlags & SF_View) ){ 561790bc36fbSdan if( p->pWith==0 ){ 561890bc36fbSdan p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With)); 561990bc36fbSdan if( p->pWith==0 ){ 562090bc36fbSdan return WRC_Abort; 562190bc36fbSdan } 562290bc36fbSdan } 562390bc36fbSdan p->pWith->bView = 1; 562490bc36fbSdan } 5625067cd837Sdan sqlite3WithPush(pParse, p->pWith, 0); 56267d10d5a6Sdrh 56277d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 56287d10d5a6Sdrh ** the FROM clause of the SELECT statement. 56297d10d5a6Sdrh */ 56307d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 56317d10d5a6Sdrh 56327d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 56337d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 56347d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 56357d10d5a6Sdrh */ 56367d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 56377d10d5a6Sdrh Table *pTab; 5638e2b7d7a0Sdrh assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); 563969887c99Sdan if( pFrom->pTab ) continue; 564069887c99Sdan assert( pFrom->fg.isRecursive==0 ); 56417d10d5a6Sdrh if( pFrom->zName==0 ){ 56427d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 56437d10d5a6Sdrh Select *pSel = pFrom->pSelect; 56447d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 56457d10d5a6Sdrh assert( pSel!=0 ); 56467d10d5a6Sdrh assert( pFrom->pTab==0 ); 56472b8c5a00Sdrh if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; 5648dfa552f4Sdan if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort; 564986fb6e17Sdan #endif 56505abe1d3dSdrh #ifndef SQLITE_OMIT_CTE 56515abe1d3dSdrh }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){ 56525abe1d3dSdrh if( rc>1 ) return WRC_Abort; 56535abe1d3dSdrh pTab = pFrom->pTab; 56545abe1d3dSdrh assert( pTab!=0 ); 56555abe1d3dSdrh #endif 56567d10d5a6Sdrh }else{ 56577d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 56587d10d5a6Sdrh assert( pFrom->pTab==0 ); 565941fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 56607d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 566179df7782Sdrh if( pTab->nTabRef>=0xffff ){ 5662d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 5663d2a56238Sdrh pTab->zName); 5664d2a56238Sdrh pFrom->pTab = 0; 5665d2a56238Sdrh return WRC_Abort; 5666d2a56238Sdrh } 566779df7782Sdrh pTab->nTabRef++; 566820292310Sdrh if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ 566920292310Sdrh return WRC_Abort; 567020292310Sdrh } 56718c812f98Sdan #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 5672f38524d2Sdrh if( !IsOrdinaryTable(pTab) ){ 5673bfad7be7Sdrh i16 nCol; 567459145813Sdrh u8 eCodeOrig = pWalker->eCode; 56757d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 567643152cf8Sdrh assert( pFrom->pSelect==0 ); 5677f38524d2Sdrh if( IsView(pTab) ){ 5678f38524d2Sdrh if( (db->flags & SQLITE_EnableView)==0 567970149ba4Sdrh && pTab->pSchema!=db->aDb[1].pSchema 568070149ba4Sdrh ){ 568111d88e68Sdrh sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited", 568211d88e68Sdrh pTab->zName); 56833f68142bSdrh } 5684f38524d2Sdrh pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0); 5685afaa660aSdan } 56868c812f98Sdan #ifndef SQLITE_OMIT_VIRTUALTABLE 5687afaa660aSdan else if( ALWAYS(IsVirtual(pTab)) 56883f68142bSdrh && pFrom->fg.fromDDL 5689f38524d2Sdrh && ALWAYS(pTab->u.vtab.p!=0) 5690f38524d2Sdrh && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0) 56913f68142bSdrh ){ 569232266a10Sdrh sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"", 569332266a10Sdrh pTab->zName); 569411d88e68Sdrh } 5695f38524d2Sdrh assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 ); 56968c812f98Sdan #endif 5697bfad7be7Sdrh nCol = pTab->nCol; 5698bfad7be7Sdrh pTab->nCol = -1; 569959145813Sdrh pWalker->eCode = 1; /* Turn on Select.selId renumbering */ 57007d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 570159145813Sdrh pWalker->eCode = eCodeOrig; 5702bfad7be7Sdrh pTab->nCol = nCol; 57037d10d5a6Sdrh } 57047d10d5a6Sdrh #endif 57057d10d5a6Sdrh } 570685574e31Sdanielk1977 570785574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 57081862271fSdrh if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){ 570985574e31Sdanielk1977 return WRC_Abort; 571085574e31Sdanielk1977 } 57117d10d5a6Sdrh } 57127d10d5a6Sdrh 57137d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 57147d10d5a6Sdrh */ 57150c7d3d39Sdrh assert( db->mallocFailed==0 || pParse->nErr!=0 ); 5716358424aeSdrh if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){ 57177d10d5a6Sdrh return WRC_Abort; 57187d10d5a6Sdrh } 57197d10d5a6Sdrh 57207d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 57217d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 57227d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 57231a1d3cd2Sdrh ** with the TK_ASTERISK operator for each "*" that it found in the column 57241a1d3cd2Sdrh ** list. The following code just has to locate the TK_ASTERISK 57251a1d3cd2Sdrh ** expressions and expand each one to the list of all columns in 57261a1d3cd2Sdrh ** all tables. 57277d10d5a6Sdrh ** 57287d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 57297d10d5a6Sdrh ** that need expanding. 57307d10d5a6Sdrh */ 57317d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 57323e3f1a5bSdrh pE = pEList->a[k].pExpr; 57331a1d3cd2Sdrh if( pE->op==TK_ASTERISK ) break; 573443152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 573543152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 57361a1d3cd2Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; 5737fca23557Sdrh elistFlags |= pE->flags; 57387d10d5a6Sdrh } 57397d10d5a6Sdrh if( k<pEList->nExpr ){ 57407d10d5a6Sdrh /* 57417d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 57427d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 57437d10d5a6Sdrh ** in the result set and expand them one by one. 57447d10d5a6Sdrh */ 57457d10d5a6Sdrh struct ExprList_item *a = pEList->a; 57467d10d5a6Sdrh ExprList *pNew = 0; 57477d10d5a6Sdrh int flags = pParse->db->flags; 57487d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 574938b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 575038b384a0Sdrh 57517d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 57523e3f1a5bSdrh pE = a[k].pExpr; 5753fca23557Sdrh elistFlags |= pE->flags; 57543e3f1a5bSdrh pRight = pE->pRight; 57553e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 57561a1d3cd2Sdrh if( pE->op!=TK_ASTERISK 57571a1d3cd2Sdrh && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) 57581a1d3cd2Sdrh ){ 57597d10d5a6Sdrh /* This particular expression does not need to be expanded. 57607d10d5a6Sdrh */ 5761b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 57627d10d5a6Sdrh if( pNew ){ 576341cee668Sdrh pNew->a[pNew->nExpr-1].zEName = a[k].zEName; 5764cbb9da33Sdrh pNew->a[pNew->nExpr-1].eEName = a[k].eEName; 576541cee668Sdrh a[k].zEName = 0; 57667d10d5a6Sdrh } 57677d10d5a6Sdrh a[k].pExpr = 0; 57687d10d5a6Sdrh }else{ 57697d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 57707d10d5a6Sdrh ** expanded. */ 57717d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 57723e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 577343152cf8Sdrh if( pE->op==TK_DOT ){ 577443152cf8Sdrh assert( pE->pLeft!=0 ); 577533e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 577633e619fcSdrh zTName = pE->pLeft->u.zToken; 57777d10d5a6Sdrh } 57787d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 57797d10d5a6Sdrh Table *pTab = pFrom->pTab; 57803e3f1a5bSdrh Select *pSub = pFrom->pSelect; 57817d10d5a6Sdrh char *zTabName = pFrom->zAlias; 57823e3f1a5bSdrh const char *zSchemaName = 0; 5783c75e09c7Sdrh int iDb; 578443152cf8Sdrh if( zTabName==0 ){ 57857d10d5a6Sdrh zTabName = pTab->zName; 57867d10d5a6Sdrh } 57877d10d5a6Sdrh if( db->mallocFailed ) break; 57883e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 57893e3f1a5bSdrh pSub = 0; 57907d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 57917d10d5a6Sdrh continue; 57927d10d5a6Sdrh } 57933e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 579469c33826Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; 57953e3f1a5bSdrh } 57967d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 5797cf9d36d1Sdrh char *zName = pTab->aCol[j].zCnName; 5798b7916a78Sdrh char *zColname; /* The computed column name */ 5799b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 5800b7916a78Sdrh Token sColname; /* Computed column name as a token */ 58017d10d5a6Sdrh 5802c75e09c7Sdrh assert( zName ); 58033e3f1a5bSdrh if( zTName && pSub 5804c4938ea2Sdrh && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0 58053e3f1a5bSdrh ){ 58063e3f1a5bSdrh continue; 58073e3f1a5bSdrh } 58083e3f1a5bSdrh 580980090f92Sdrh /* If a column is marked as 'hidden', omit it from the expanded 581080090f92Sdrh ** result-set list unless the SELECT has the SF_IncludeHidden 581180090f92Sdrh ** bit set. 58127d10d5a6Sdrh */ 581380090f92Sdrh if( (p->selFlags & SF_IncludeHidden)==0 581480090f92Sdrh && IsHiddenColumn(&pTab->aCol[j]) 581580090f92Sdrh ){ 58167d10d5a6Sdrh continue; 58177d10d5a6Sdrh } 58183e3f1a5bSdrh tableSeen = 1; 58197d10d5a6Sdrh 5820da55c48aSdrh if( i>0 && zTName==0 ){ 5821d44f8b23Sdrh if( pFrom->fg.isUsing 5822d44f8b23Sdrh && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0 5823d44f8b23Sdrh ){ 58247d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 58257d10d5a6Sdrh ** using clause from the table on the right. */ 58267d10d5a6Sdrh continue; 58277d10d5a6Sdrh } 58287d10d5a6Sdrh } 5829b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 58304ce7bf91Sdrh if( longNames ){ 58314ce7bf91Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 58324ce7bf91Sdrh zToFree = zColname; 58334ce7bf91Sdrh }else{ 5834b7916a78Sdrh zColname = zName; 5835b7916a78Sdrh zToFree = 0; 58364ce7bf91Sdrh } 5837befbb40fSdrh if( (pTabList->nSrc>1 5838bdbda1ebSdrh && ( (pFrom->fg.jointype & JT_LTORJ)==0 5839befbb40fSdrh || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1) 5840befbb40fSdrh ) 5841befbb40fSdrh ) 5842befbb40fSdrh || IN_RENAME_OBJECT 58434ce7bf91Sdrh ){ 5844b7916a78Sdrh Expr *pLeft; 5845b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 5846abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); 5847*cbde37d8Sdan if( IN_RENAME_OBJECT && pE->pLeft ){ 5848*cbde37d8Sdan sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft); 5849*cbde37d8Sdan } 585038b384a0Sdrh if( zSchemaName ){ 5851c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 5852abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); 5853c75e09c7Sdrh } 58547d10d5a6Sdrh }else{ 58557d10d5a6Sdrh pExpr = pRight; 58567d10d5a6Sdrh } 5857b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 5858*cbde37d8Sdan 585940aced5cSdrh sqlite3TokenInit(&sColname, zColname); 5860b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 58610990c415Sdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){ 58623e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 5863cbb9da33Sdrh sqlite3DbFree(db, pX->zEName); 58643e3f1a5bSdrh if( pSub ){ 5865cbb9da33Sdrh pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName); 5866cbb9da33Sdrh testcase( pX->zEName==0 ); 58673e3f1a5bSdrh }else{ 5868cbb9da33Sdrh pX->zEName = sqlite3MPrintf(db, "%s.%s.%s", 58693e3f1a5bSdrh zSchemaName, zTabName, zColname); 5870cbb9da33Sdrh testcase( pX->zEName==0 ); 58713e3f1a5bSdrh } 5872cbb9da33Sdrh pX->eEName = ENAME_TAB; 58738f25d18bSdrh } 5874b7916a78Sdrh sqlite3DbFree(db, zToFree); 58757d10d5a6Sdrh } 58767d10d5a6Sdrh } 58777d10d5a6Sdrh if( !tableSeen ){ 58787d10d5a6Sdrh if( zTName ){ 58797d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 58807d10d5a6Sdrh }else{ 58817d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 58827d10d5a6Sdrh } 58837d10d5a6Sdrh } 58847d10d5a6Sdrh } 58857d10d5a6Sdrh } 58867d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 58877d10d5a6Sdrh p->pEList = pNew; 58887d10d5a6Sdrh } 5889fca23557Sdrh if( p->pEList ){ 5890fca23557Sdrh if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 58917d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 58928836cbbcSdan return WRC_Abort; 58937d10d5a6Sdrh } 5894fca23557Sdrh if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){ 5895fca23557Sdrh p->selFlags |= SF_ComplexResult; 5896fca23557Sdrh } 5897fca23557Sdrh } 5898cebc8009Sdrh #if TREETRACE_ENABLED 5899cebc8009Sdrh if( sqlite3TreeTrace & 0x100 ){ 5900cebc8009Sdrh SELECTTRACE(0x100,pParse,p,("After result-set wildcard expansion:\n")); 5901cebc8009Sdrh sqlite3TreeViewSelect(0, p, 0); 5902cebc8009Sdrh } 5903cebc8009Sdrh #endif 59047d10d5a6Sdrh return WRC_Continue; 59057d10d5a6Sdrh } 59067d10d5a6Sdrh 5907979dd1beSdrh #if SQLITE_DEBUG 5908979dd1beSdrh /* 5909979dd1beSdrh ** Always assert. This xSelectCallback2 implementation proves that the 5910979dd1beSdrh ** xSelectCallback2 is never invoked. 5911979dd1beSdrh */ 5912979dd1beSdrh void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){ 5913979dd1beSdrh UNUSED_PARAMETER2(NotUsed, NotUsed2); 5914979dd1beSdrh assert( 0 ); 5915979dd1beSdrh } 5916979dd1beSdrh #endif 5917979dd1beSdrh /* 59187d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 59197d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 59207d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 59217d10d5a6Sdrh ** 59227d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 59237d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 59247d10d5a6Sdrh ** name resolution is performed. 59257d10d5a6Sdrh ** 59267d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 59277d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 59287d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 59297d10d5a6Sdrh */ 59307d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 59317d10d5a6Sdrh Walker w; 59325b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 59337d10d5a6Sdrh w.pParse = pParse; 5934878fcf9dSdrh if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){ 5935d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 5936979dd1beSdrh w.xSelectCallback2 = 0; 59377d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 5938d58d3278Sdrh } 5939c01b7306Sdrh w.xSelectCallback = selectExpander; 5940be12083bSdan w.xSelectCallback2 = sqlite3SelectPopWith; 594159145813Sdrh w.eCode = 0; 5942c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 59437d10d5a6Sdrh } 59447d10d5a6Sdrh 59457d10d5a6Sdrh 59467d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 59477d10d5a6Sdrh /* 59487d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 59497d10d5a6Sdrh ** interface. 59507d10d5a6Sdrh ** 59517d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 59527d10d5a6Sdrh ** information to the Table structure that represents the result set 59537d10d5a6Sdrh ** of that subquery. 59547d10d5a6Sdrh ** 59557d10d5a6Sdrh ** The Table structure that represents the result set was constructed 59567d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 59577d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 59587d10d5a6Sdrh ** routine is called after identifier resolution. 59597d10d5a6Sdrh */ 5960b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 59617d10d5a6Sdrh Parse *pParse; 59627d10d5a6Sdrh int i; 59637d10d5a6Sdrh SrcList *pTabList; 59647601294aSdrh SrcItem *pFrom; 59657d10d5a6Sdrh 59669d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 5967cc464418Sdan if( p->selFlags & SF_HasTypeInfo ) return; 59687d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 59697d10d5a6Sdrh pParse = pWalker->pParse; 59707d10d5a6Sdrh pTabList = p->pSrc; 59717d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 59727d10d5a6Sdrh Table *pTab = pFrom->pTab; 5973e2b7d7a0Sdrh assert( pTab!=0 ); 5974e2b7d7a0Sdrh if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ 59757d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 59767d10d5a6Sdrh Select *pSel = pFrom->pSelect; 59778ce7184bSdan if( pSel ){ 59787d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 597996fb16eeSdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel, 598096fb16eeSdrh SQLITE_AFF_NONE); 59817d10d5a6Sdrh } 59827d10d5a6Sdrh } 59835a29d9cbSdrh } 59848ce7184bSdan } 59857d10d5a6Sdrh #endif 59867d10d5a6Sdrh 59877d10d5a6Sdrh 59887d10d5a6Sdrh /* 59897d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 59907d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 59917d10d5a6Sdrh ** SELECT statement. 59927d10d5a6Sdrh ** 59937d10d5a6Sdrh ** Use this routine after name resolution. 59947d10d5a6Sdrh */ 59957d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 59967d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 59977d10d5a6Sdrh Walker w; 5998979dd1beSdrh w.xSelectCallback = sqlite3SelectWalkNoop; 5999b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 60005b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 60017d10d5a6Sdrh w.pParse = pParse; 60027d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 60037d10d5a6Sdrh #endif 60047d10d5a6Sdrh } 60057d10d5a6Sdrh 60067d10d5a6Sdrh 60077d10d5a6Sdrh /* 6008030796dfSdrh ** This routine sets up a SELECT statement for processing. The 60097d10d5a6Sdrh ** following is accomplished: 60107d10d5a6Sdrh ** 60117d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 60127d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 60137d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 60147d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 60157d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 60167d10d5a6Sdrh ** 60177d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 60187d10d5a6Sdrh */ 60197d10d5a6Sdrh void sqlite3SelectPrep( 6020b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 6021b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 60227d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 6023b3bce662Sdanielk1977 ){ 6024e2463398Sdrh assert( p!=0 || pParse->db->mallocFailed ); 60250c7d3d39Sdrh assert( pParse->db->pParse==pParse ); 6026e2463398Sdrh if( pParse->db->mallocFailed ) return; 60277d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 60287d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 60290c7d3d39Sdrh if( pParse->nErr ) return; 60307d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 60310c7d3d39Sdrh if( pParse->nErr ) return; 60327d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 6033f6bbe022Sdrh } 6034b3bce662Sdanielk1977 6035b3bce662Sdanielk1977 /* 603613449892Sdrh ** Reset the aggregate accumulator. 603713449892Sdrh ** 603813449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 603913449892Sdrh ** intermediate results while calculating an aggregate. This 6040030796dfSdrh ** routine generates code that stores NULLs in all of those memory 6041030796dfSdrh ** cells. 6042b3bce662Sdanielk1977 */ 604313449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 604413449892Sdrh Vdbe *v = pParse->pVdbe; 604513449892Sdrh int i; 6046c99130fdSdrh struct AggInfo_func *pFunc; 60477e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 60480c7d3d39Sdrh assert( pParse->db->pParse==pParse ); 60490c7d3d39Sdrh assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 ); 60507e61d18eSdrh if( nReg==0 ) return; 60510c7d3d39Sdrh if( pParse->nErr ) return; 60527e61d18eSdrh #ifdef SQLITE_DEBUG 60537e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 60547e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 60557e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 605613449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 60577e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 60587e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 605913449892Sdrh } 60607e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 60617e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 60627e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 60637e61d18eSdrh } 60647e61d18eSdrh #endif 60657e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 6066c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 6067c99130fdSdrh if( pFunc->iDistinct>=0 ){ 606881185a51Sdrh Expr *pE = pFunc->pFExpr; 6069a4eeccdfSdrh assert( ExprUseXList(pE) ); 60706ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 60710daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 60720daa002cSdrh "argument"); 6073c99130fdSdrh pFunc->iDistinct = -1; 6074c99130fdSdrh }else{ 6075f9eae18bSdan KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0); 60764fcb30b7Sdan pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 60774fcb30b7Sdan pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO); 60789be1339fSdrh ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)", 60799be1339fSdrh pFunc->pFunc->zName)); 6080c99130fdSdrh } 6081c99130fdSdrh } 608213449892Sdrh } 6083b3bce662Sdanielk1977 } 6084b3bce662Sdanielk1977 6085b3bce662Sdanielk1977 /* 608613449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 608713449892Sdrh ** in the AggInfo structure. 6088b3bce662Sdanielk1977 */ 608913449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 609013449892Sdrh Vdbe *v = pParse->pVdbe; 609113449892Sdrh int i; 609213449892Sdrh struct AggInfo_func *pF; 609313449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 6094a4eeccdfSdrh ExprList *pList; 6095a4eeccdfSdrh assert( ExprUseXList(pF->pFExpr) ); 6096a4eeccdfSdrh pList = pF->pFExpr->x.pList; 60972700acaaSdrh sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); 60982700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 6099b3bce662Sdanielk1977 } 610013449892Sdrh } 610113449892Sdrh 6102280c894bSdan 610313449892Sdrh /* 610413449892Sdrh ** Update the accumulator memory cells for an aggregate based on 610513449892Sdrh ** the current cursor position. 6106280c894bSdan ** 6107280c894bSdan ** If regAcc is non-zero and there are no min() or max() aggregates 6108280c894bSdan ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator 610910cc16c9Sdrh ** registers if register regAcc contains 0. The caller will take care 6110280c894bSdan ** of setting and clearing regAcc. 611113449892Sdrh */ 61124fcb30b7Sdan static void updateAccumulator( 61134fcb30b7Sdan Parse *pParse, 61144fcb30b7Sdan int regAcc, 61154fcb30b7Sdan AggInfo *pAggInfo, 61164fcb30b7Sdan int eDistinctType 61174fcb30b7Sdan ){ 611813449892Sdrh Vdbe *v = pParse->pVdbe; 611913449892Sdrh int i; 61207a95789cSdrh int regHit = 0; 61217a95789cSdrh int addrHitTest = 0; 612213449892Sdrh struct AggInfo_func *pF; 612313449892Sdrh struct AggInfo_col *pC; 612413449892Sdrh 612513449892Sdrh pAggInfo->directMode = 1; 612613449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 612713449892Sdrh int nArg; 6128c99130fdSdrh int addrNext = 0; 612998757157Sdrh int regAgg; 6130a4eeccdfSdrh ExprList *pList; 6131a4eeccdfSdrh assert( ExprUseXList(pF->pFExpr) ); 613281185a51Sdrh assert( !IsWindowFunc(pF->pFExpr) ); 6133a4eeccdfSdrh pList = pF->pFExpr->x.pList; 613481185a51Sdrh if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){ 613581185a51Sdrh Expr *pFilter = pF->pFExpr->y.pWin->pFilter; 6136ed09dddeSdan if( pAggInfo->nAccumulator 6137ed09dddeSdan && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) 6138fa4b0d44Sdan && regAcc 6139ed09dddeSdan ){ 6140fa4b0d44Sdan /* If regAcc==0, there there exists some min() or max() function 6141fa4b0d44Sdan ** without a FILTER clause that will ensure the magnet registers 6142fa4b0d44Sdan ** are populated. */ 6143ed09dddeSdan if( regHit==0 ) regHit = ++pParse->nMem; 6144fa4b0d44Sdan /* If this is the first row of the group (regAcc contains 0), clear the 6145ed09dddeSdan ** "magnet" register regHit so that the accumulator registers 6146af9b58b3Sdan ** are populated if the FILTER clause jumps over the the 6147af9b58b3Sdan ** invocation of min() or max() altogether. Or, if this is not 6148fa4b0d44Sdan ** the first row (regAcc contains 1), set the magnet register so that 6149fa4b0d44Sdan ** the accumulators are not populated unless the min()/max() is invoked 6150fa4b0d44Sdan ** and indicates that they should be. */ 6151ed09dddeSdan sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit); 6152ed09dddeSdan } 61536ba7ab0dSdan addrNext = sqlite3VdbeMakeLabel(pParse); 61546ba7ab0dSdan sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL); 61556ba7ab0dSdan } 615613449892Sdrh if( pList ){ 615713449892Sdrh nArg = pList->nExpr; 6158892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 61595579d59fSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); 616013449892Sdrh }else{ 616113449892Sdrh nArg = 0; 616298757157Sdrh regAgg = 0; 616313449892Sdrh } 61644fcb30b7Sdan if( pF->iDistinct>=0 && pList ){ 61656ba7ab0dSdan if( addrNext==0 ){ 6166ec4ccdbcSdrh addrNext = sqlite3VdbeMakeLabel(pParse); 61676ba7ab0dSdan } 61685383db71Sdan pF->iDistinct = codeDistinct(pParse, eDistinctType, 61695383db71Sdan pF->iDistinct, addrNext, pList, regAgg); 6170c99130fdSdrh } 6171d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 617213449892Sdrh CollSeq *pColl = 0; 617313449892Sdrh struct ExprList_item *pItem; 617413449892Sdrh int j; 6175e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 617643617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 617713449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 617813449892Sdrh } 617913449892Sdrh if( !pColl ){ 618013449892Sdrh pColl = pParse->db->pDfltColl; 618113449892Sdrh } 61827a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 61837a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 618413449892Sdrh } 61858f26da6cSdrh sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem); 61862700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 6187ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 6188f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 6189c99130fdSdrh if( addrNext ){ 6190c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 6191c99130fdSdrh } 619213449892Sdrh } 6193280c894bSdan if( regHit==0 && pAggInfo->nAccumulator ){ 6194280c894bSdan regHit = regAcc; 6195280c894bSdan } 61967a95789cSdrh if( regHit ){ 6197688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 61987a95789cSdrh } 619913449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 620081185a51Sdrh sqlite3ExprCode(pParse, pC->pCExpr, pC->iMem); 620113449892Sdrh } 6202ed09dddeSdan 620313449892Sdrh pAggInfo->directMode = 0; 62047a95789cSdrh if( addrHitTest ){ 6205dc4f6fc0Sdrh sqlite3VdbeJumpHereOrPopInst(v, addrHitTest); 62067a95789cSdrh } 620713449892Sdrh } 620813449892Sdrh 6209b3bce662Sdanielk1977 /* 6210ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 6211ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 6212ef7075deSdan */ 6213ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 6214ef7075deSdan static void explainSimpleCount( 6215ef7075deSdan Parse *pParse, /* Parse context */ 6216ef7075deSdan Table *pTab, /* Table being queried */ 6217ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 6218ef7075deSdan ){ 6219ef7075deSdan if( pParse->explain==2 ){ 622048dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 62218210233cSdrh sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s", 6222ef7075deSdan pTab->zName, 6223e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 6224e96f2df3Sdan bCover ? pIdx->zName : "" 6225ef7075deSdan ); 6226ef7075deSdan } 6227ef7075deSdan } 6228ef7075deSdan #else 6229ef7075deSdan # define explainSimpleCount(a,b,c) 6230ef7075deSdan #endif 6231ef7075deSdan 6232ef7075deSdan /* 6233ab31a845Sdan ** sqlite3WalkExpr() callback used by havingToWhere(). 6234ab31a845Sdan ** 6235ab31a845Sdan ** If the node passed to the callback is a TK_AND node, return 6236ab31a845Sdan ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes. 6237ab31a845Sdan ** 6238ab31a845Sdan ** Otherwise, return WRC_Prune. In this case, also check if the 6239ab31a845Sdan ** sub-expression matches the criteria for being moved to the WHERE 6240ab31a845Sdan ** clause. If so, add it to the WHERE clause and replace the sub-expression 6241ab31a845Sdan ** within the HAVING expression with a constant "1". 6242ab31a845Sdan */ 6243ab31a845Sdan static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){ 6244ab31a845Sdan if( pExpr->op!=TK_AND ){ 6245cd0abc24Sdrh Select *pS = pWalker->u.pSelect; 6246d59f9835Sdan /* This routine is called before the HAVING clause of the current 6247d59f9835Sdan ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set 6248d59f9835Sdan ** here, it indicates that the expression is a correlated reference to a 6249d59f9835Sdan ** column from an outer aggregate query, or an aggregate function that 6250d59f9835Sdan ** belongs to an outer query. Do not move the expression to the WHERE 6251d59f9835Sdan ** clause in this obscure case, as doing so may corrupt the outer Select 6252d59f9835Sdan ** statements AggInfo structure. */ 6253f39168e4Sdan if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) 6254f39168e4Sdan && ExprAlwaysFalse(pExpr)==0 6255d59f9835Sdan && pExpr->pAggInfo==0 6256f39168e4Sdan ){ 6257ab31a845Sdan sqlite3 *db = pWalker->pParse->db; 62585776ee5cSdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1"); 6259ab31a845Sdan if( pNew ){ 6260cd0abc24Sdrh Expr *pWhere = pS->pWhere; 6261ab31a845Sdan SWAP(Expr, *pNew, *pExpr); 6262d5c851c1Sdrh pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew); 6263cd0abc24Sdrh pS->pWhere = pNew; 6264cd0abc24Sdrh pWalker->eCode = 1; 6265ab31a845Sdan } 6266ab31a845Sdan } 6267ab31a845Sdan return WRC_Prune; 6268ab31a845Sdan } 6269ab31a845Sdan return WRC_Continue; 6270ab31a845Sdan } 6271ab31a845Sdan 6272ab31a845Sdan /* 6273ab31a845Sdan ** Transfer eligible terms from the HAVING clause of a query, which is 6274ab31a845Sdan ** processed after grouping, to the WHERE clause, which is processed before 6275ab31a845Sdan ** grouping. For example, the query: 6276ab31a845Sdan ** 6277ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=? 6278ab31a845Sdan ** 6279ab31a845Sdan ** can be rewritten as: 6280ab31a845Sdan ** 6281ab31a845Sdan ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=? 6282ab31a845Sdan ** 6283ab31a845Sdan ** A term of the HAVING expression is eligible for transfer if it consists 6284ab31a845Sdan ** entirely of constants and expressions that are also GROUP BY terms that 6285ab31a845Sdan ** use the "BINARY" collation sequence. 6286ab31a845Sdan */ 6287cd0abc24Sdrh static void havingToWhere(Parse *pParse, Select *p){ 6288ab31a845Sdan Walker sWalker; 6289ab31a845Sdan memset(&sWalker, 0, sizeof(sWalker)); 6290ab31a845Sdan sWalker.pParse = pParse; 6291ab31a845Sdan sWalker.xExprCallback = havingToWhereExprCb; 6292cd0abc24Sdrh sWalker.u.pSelect = p; 6293cd0abc24Sdrh sqlite3WalkExpr(&sWalker, p->pHaving); 62945e431beaSdrh #if TREETRACE_ENABLED 62955e431beaSdrh if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){ 6296cd0abc24Sdrh SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n")); 6297cd0abc24Sdrh sqlite3TreeViewSelect(0, p, 0); 6298cd0abc24Sdrh } 6299cd0abc24Sdrh #endif 6300ab31a845Sdan } 6301ab31a845Sdan 6302ab31a845Sdan /* 6303e08e8d6bSdrh ** Check to see if the pThis entry of pTabList is a self-join of a prior view. 6304e08e8d6bSdrh ** If it is, then return the SrcList_item for the prior view. If it is not, 6305e08e8d6bSdrh ** then return 0. 6306e08e8d6bSdrh */ 63077601294aSdrh static SrcItem *isSelfJoinView( 6308e08e8d6bSdrh SrcList *pTabList, /* Search for self-joins in this FROM clause */ 63097601294aSdrh SrcItem *pThis /* Search for prior reference to this subquery */ 6310e08e8d6bSdrh ){ 63117601294aSdrh SrcItem *pItem; 63128794c68aSdrh assert( pThis->pSelect!=0 ); 63138794c68aSdrh if( pThis->pSelect->selFlags & SF_PushDown ) return 0; 6314e08e8d6bSdrh for(pItem = pTabList->a; pItem<pThis; pItem++){ 6315bdefaf08Sdrh Select *pS1; 6316e08e8d6bSdrh if( pItem->pSelect==0 ) continue; 6317e08e8d6bSdrh if( pItem->fg.viaCoroutine ) continue; 631833543c23Sdrh if( pItem->zName==0 ) continue; 631930ad79aeSdrh assert( pItem->pTab!=0 ); 632030ad79aeSdrh assert( pThis->pTab!=0 ); 632130ad79aeSdrh if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue; 6322ed712980Sdrh if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; 6323bdefaf08Sdrh pS1 = pItem->pSelect; 632430ad79aeSdrh if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){ 6325bdefaf08Sdrh /* The query flattener left two different CTE tables with identical 6326bdefaf08Sdrh ** names in the same FROM clause. */ 6327bdefaf08Sdrh continue; 6328bdefaf08Sdrh } 63298794c68aSdrh if( pItem->pSelect->selFlags & SF_PushDown ){ 6330ed712980Sdrh /* The view was modified by some other optimization such as 6331ed712980Sdrh ** pushDownWhereTerms() */ 6332ed712980Sdrh continue; 6333ed712980Sdrh } 6334ed712980Sdrh return pItem; 6335e08e8d6bSdrh } 6336e08e8d6bSdrh return 0; 6337e08e8d6bSdrh } 6338e08e8d6bSdrh 6339c54246ffSdrh /* 6340c54246ffSdrh ** Deallocate a single AggInfo object 6341c54246ffSdrh */ 6342c54246ffSdrh static void agginfoFree(sqlite3 *db, AggInfo *p){ 6343c54246ffSdrh sqlite3DbFree(db, p->aCol); 6344c54246ffSdrh sqlite3DbFree(db, p->aFunc); 6345c54246ffSdrh sqlite3DbFreeNN(db, p); 6346c54246ffSdrh } 6347c54246ffSdrh 6348269ba804Sdrh #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 6349269ba804Sdrh /* 6350269ba804Sdrh ** Attempt to transform a query of the form 6351269ba804Sdrh ** 6352269ba804Sdrh ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2) 6353269ba804Sdrh ** 6354269ba804Sdrh ** Into this: 6355269ba804Sdrh ** 6356269ba804Sdrh ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2) 6357269ba804Sdrh ** 6358269ba804Sdrh ** The transformation only works if all of the following are true: 6359269ba804Sdrh ** 6360269ba804Sdrh ** * The subquery is a UNION ALL of two or more terms 6361a4b5fb55Sdan ** * The subquery does not have a LIMIT clause 6362269ba804Sdrh ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries 636373c53b39Sdrh ** * The outer query is a simple count(*) with no WHERE clause or other 636473c53b39Sdrh ** extraneous syntax. 6365269ba804Sdrh ** 6366269ba804Sdrh ** Return TRUE if the optimization is undertaken. 6367269ba804Sdrh */ 6368269ba804Sdrh static int countOfViewOptimization(Parse *pParse, Select *p){ 6369269ba804Sdrh Select *pSub, *pPrior; 6370269ba804Sdrh Expr *pExpr; 6371269ba804Sdrh Expr *pCount; 6372269ba804Sdrh sqlite3 *db; 63733d240d21Sdrh if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */ 6374269ba804Sdrh if( p->pEList->nExpr!=1 ) return 0; /* Single result column */ 637573c53b39Sdrh if( p->pWhere ) return 0; 637673c53b39Sdrh if( p->pGroupBy ) return 0; 6377269ba804Sdrh pExpr = p->pEList->a[0].pExpr; 6378269ba804Sdrh if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */ 6379a4eeccdfSdrh assert( ExprUseUToken(pExpr) ); 63803d240d21Sdrh if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */ 6381a4eeccdfSdrh assert( ExprUseXList(pExpr) ); 6382269ba804Sdrh if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */ 63833d240d21Sdrh if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */ 6384269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 6385269ba804Sdrh if( pSub==0 ) return 0; /* The FROM is a subquery */ 63863d240d21Sdrh if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */ 6387269ba804Sdrh do{ 6388269ba804Sdrh if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */ 6389269ba804Sdrh if( pSub->pWhere ) return 0; /* No WHERE clause */ 6390a4b5fb55Sdan if( pSub->pLimit ) return 0; /* No LIMIT clause */ 6391269ba804Sdrh if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */ 63923d240d21Sdrh pSub = pSub->pPrior; /* Repeat over compound */ 6393269ba804Sdrh }while( pSub ); 6394269ba804Sdrh 63953d240d21Sdrh /* If we reach this point then it is OK to perform the transformation */ 6396269ba804Sdrh 6397269ba804Sdrh db = pParse->db; 6398269ba804Sdrh pCount = pExpr; 6399269ba804Sdrh pExpr = 0; 6400269ba804Sdrh pSub = p->pSrc->a[0].pSelect; 6401269ba804Sdrh p->pSrc->a[0].pSelect = 0; 6402269ba804Sdrh sqlite3SrcListDelete(db, p->pSrc); 6403269ba804Sdrh p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc)); 6404269ba804Sdrh while( pSub ){ 6405269ba804Sdrh Expr *pTerm; 6406269ba804Sdrh pPrior = pSub->pPrior; 6407269ba804Sdrh pSub->pPrior = 0; 6408269ba804Sdrh pSub->pNext = 0; 6409269ba804Sdrh pSub->selFlags |= SF_Aggregate; 6410269ba804Sdrh pSub->selFlags &= ~SF_Compound; 6411269ba804Sdrh pSub->nSelectRow = 0; 6412269ba804Sdrh sqlite3ExprListDelete(db, pSub->pEList); 6413269ba804Sdrh pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount; 6414269ba804Sdrh pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm); 6415269ba804Sdrh pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0); 6416269ba804Sdrh sqlite3PExprAddSelect(pParse, pTerm, pSub); 6417269ba804Sdrh if( pExpr==0 ){ 6418269ba804Sdrh pExpr = pTerm; 6419269ba804Sdrh }else{ 6420269ba804Sdrh pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr); 6421269ba804Sdrh } 6422269ba804Sdrh pSub = pPrior; 6423269ba804Sdrh } 6424269ba804Sdrh p->pEList->a[0].pExpr = pExpr; 6425269ba804Sdrh p->selFlags &= ~SF_Aggregate; 6426269ba804Sdrh 64275e431beaSdrh #if TREETRACE_ENABLED 64285e431beaSdrh if( sqlite3TreeTrace & 0x400 ){ 6429269ba804Sdrh SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n")); 6430269ba804Sdrh sqlite3TreeViewSelect(0, p, 0); 6431269ba804Sdrh } 6432269ba804Sdrh #endif 6433269ba804Sdrh return 1; 6434269ba804Sdrh } 6435269ba804Sdrh #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */ 6436269ba804Sdrh 6437e08e8d6bSdrh /* 64387d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 64399bb61fe7Sdrh ** 6440340309fdSdrh ** The results are returned according to the SelectDest structure. 6441340309fdSdrh ** See comments in sqliteInt.h for further information. 6442e78e8284Sdrh ** 64439bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 64449bb61fe7Sdrh ** encountered, then an appropriate error message is left in 64459bb61fe7Sdrh ** pParse->zErrMsg. 64469bb61fe7Sdrh ** 64479bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 64489bb61fe7Sdrh ** calling function needs to do that. 64499bb61fe7Sdrh */ 64504adee20fSdanielk1977 int sqlite3Select( 6451cce7d176Sdrh Parse *pParse, /* The parser context */ 64529bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 64537d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 6454cce7d176Sdrh ){ 645513449892Sdrh int i, j; /* Loop counters */ 645613449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 645713449892Sdrh Vdbe *v; /* The virtual machine under construction */ 6458b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 6459c29cbb0bSmistachkin ExprList *pEList = 0; /* List of columns to extract. */ 6460ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 64619bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 64622282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 64632282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 6464bf790973Sdrh AggInfo *pAggInfo = 0; /* Aggregate information */ 64651d83f052Sdrh int rc = 1; /* Value to return from this function */ 6466e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 6467079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 6468ec7429aeSdrh int iEnd; /* Address of the end of the query */ 646917435752Sdrh sqlite3 *db; /* The database connection */ 647047d9f839Sdrh ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */ 647147d9f839Sdrh u8 minMaxFlag; /* Flag for min/max queries */ 64729bb61fe7Sdrh 647317435752Sdrh db = pParse->db; 64740c7d3d39Sdrh assert( pParse==db->pParse ); 6475e2ca99c9Sdrh v = sqlite3GetVdbe(pParse); 64760c7d3d39Sdrh if( p==0 || pParse->nErr ){ 64776f7adc8aSdrh return 1; 64786f7adc8aSdrh } 64790c7d3d39Sdrh assert( db->mallocFailed==0 ); 64804adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 64815e431beaSdrh #if TREETRACE_ENABLED 6482e2ca99c9Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain)); 6483c2d0df95Sdrh if( sqlite3TreeTrace & 0x10100 ){ 6484c2d0df95Sdrh if( (sqlite3TreeTrace & 0x10001)==0x10000 ){ 6485c2d0df95Sdrh sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d", 6486c2d0df95Sdrh __FILE__, __LINE__); 6487c2d0df95Sdrh } 6488c2d0df95Sdrh sqlite3ShowSelect(p); 6489c90713d3Sdrh } 6490eb9b884cSdrh #endif 6491daffd0e5Sdrh 64928e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 64938e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 64949afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 64959afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 6496f1ea4255Sdrh if( IgnorableDistinct(pDest) ){ 64979ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 64989afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 6499f1ea4255Sdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo ); 6500f1ea4255Sdrh /* All of these destinations are also able to ignore the ORDER BY clause */ 6501fad1ad05Sdrh if( p->pOrderBy ){ 65025e431beaSdrh #if TREETRACE_ENABLED 6503fad1ad05Sdrh SELECTTRACE(1,pParse,p, ("dropping superfluous ORDER BY:\n")); 65045e431beaSdrh if( sqlite3TreeTrace & 0x100 ){ 6505fad1ad05Sdrh sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY"); 6506fad1ad05Sdrh } 6507fad1ad05Sdrh #endif 6508fad1ad05Sdrh sqlite3ParserAddCleanup(pParse, 6509fad1ad05Sdrh (void(*)(sqlite3*,void*))sqlite3ExprListDelete, 6510fad1ad05Sdrh p->pOrderBy); 65116d0053cfSdrh testcase( pParse->earlyCleanup ); 6512ccfcbceaSdrh p->pOrderBy = 0; 6513fad1ad05Sdrh } 65147d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 6515b7cbf5c1Sdrh p->selFlags |= SF_NoopOrderBy; 65169a99334dSdrh } 65177d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 65180c7d3d39Sdrh if( pParse->nErr ){ 65199a99334dSdrh goto select_end; 65209a99334dSdrh } 65210c7d3d39Sdrh assert( db->mallocFailed==0 ); 6522adc57f68Sdrh assert( p->pEList!=0 ); 65235e431beaSdrh #if TREETRACE_ENABLED 65245e431beaSdrh if( sqlite3TreeTrace & 0x104 ){ 6525e2243d26Sdrh SELECTTRACE(0x104,pParse,p, ("after name resolution:\n")); 652617645f5eSdrh sqlite3TreeViewSelect(0, p, 0); 652717645f5eSdrh } 652817645f5eSdrh #endif 6529cce7d176Sdrh 65305daf69e5Sdan /* If the SF_UFSrcCheck flag is set, then this function is being called 653107ca7d61Sdan ** as part of populating the temp table for an UPDATE...FROM statement. 653207ca7d61Sdan ** In this case, it is an error if the target object (pSrc->a[0]) name 65335daf69e5Sdan ** or alias is duplicated within FROM clause (pSrc->a[1..n]). 65345daf69e5Sdan ** 65355daf69e5Sdan ** Postgres disallows this case too. The reason is that some other 65365daf69e5Sdan ** systems handle this case differently, and not all the same way, 65375daf69e5Sdan ** which is just confusing. To avoid this, we follow PG's lead and 65385daf69e5Sdan ** disallow it altogether. */ 65395daf69e5Sdan if( p->selFlags & SF_UFSrcCheck ){ 65407601294aSdrh SrcItem *p0 = &p->pSrc->a[0]; 654107ca7d61Sdan for(i=1; i<p->pSrc->nSrc; i++){ 65427601294aSdrh SrcItem *p1 = &p->pSrc->a[i]; 654307ca7d61Sdan if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){ 654407ca7d61Sdan sqlite3ErrorMsg(pParse, 654507ca7d61Sdan "target object/alias may not appear in FROM clause: %s", 654607ca7d61Sdan p0->zAlias ? p0->zAlias : p0->pTab->zName 654707ca7d61Sdan ); 654807ca7d61Sdan goto select_end; 654907ca7d61Sdan } 655007ca7d61Sdan } 65515daf69e5Sdan 65525daf69e5Sdan /* Clear the SF_UFSrcCheck flag. The check has already been performed, 65535daf69e5Sdan ** and leaving this flag set can cause errors if a compound sub-query 65545daf69e5Sdan ** in p->pSrc is flattened into this query and this function called 65555daf69e5Sdan ** again as part of compound SELECT processing. */ 65565daf69e5Sdan p->selFlags &= ~SF_UFSrcCheck; 655707ca7d61Sdan } 655807ca7d61Sdan 6559f35f2f92Sdrh if( pDest->eDest==SRT_Output ){ 65609088186bSdrh sqlite3GenerateColumnNames(pParse, p); 6561f35f2f92Sdrh } 6562f35f2f92Sdrh 656367a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 656444918c74Sdan if( sqlite3WindowRewrite(pParse, p) ){ 65650c7d3d39Sdrh assert( pParse->nErr ); 656686fb6e17Sdan goto select_end; 656786fb6e17Sdan } 65685e431beaSdrh #if TREETRACE_ENABLED 65695e431beaSdrh if( p->pWin && (sqlite3TreeTrace & 0x108)!=0 ){ 6570dfa552f4Sdan SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n")); 6571dfa552f4Sdan sqlite3TreeViewSelect(0, p, 0); 6572dfa552f4Sdan } 6573dfa552f4Sdan #endif 657467a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 657586fb6e17Sdan pTabList = p->pSrc; 65767392569fSdan isAgg = (p->selFlags & SF_Aggregate)!=0; 6577f02cdd37Sdan memset(&sSort, 0, sizeof(sSort)); 6578f02cdd37Sdan sSort.pOrderBy = p->pOrderBy; 657986fb6e17Sdan 65809216de8aSdrh /* Try to do various optimizations (flattening subqueries, and strength 65812589787cSdrh ** reduction of join operators) in the FROM clause up into the main query 6582d820cb1bSdrh */ 658351522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 6584f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 65857601294aSdrh SrcItem *pItem = &pTabList->a[i]; 6586daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 65872679f14fSdrh Table *pTab = pItem->pTab; 65882589787cSdrh 6589b5aaee5eSdrh /* The expander should have already created transient Table objects 6590b5aaee5eSdrh ** even for FROM clause elements such as subqueries that do not correspond 6591b5aaee5eSdrh ** to a real table */ 6592b5aaee5eSdrh assert( pTab!=0 ); 6593b5aaee5eSdrh 65942589787cSdrh /* Convert LEFT JOIN into JOIN if there are terms of the right table 65952589787cSdrh ** of the LEFT JOIN used in the WHERE clause. 65962589787cSdrh */ 6597ff02ac7fSdrh if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==JT_LEFT 65982589787cSdrh && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor) 65992589787cSdrh && OptimizationEnabled(db, SQLITE_SimplifyJoin) 66002589787cSdrh ){ 66012589787cSdrh SELECTTRACE(0x100,pParse,p, 66022589787cSdrh ("LEFT-JOIN simplifies to JOIN on term %d\n",i)); 6603efce69deSdrh pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER); 66042589787cSdrh unsetJoinExpr(p->pWhere, pItem->iCursor); 66052589787cSdrh } 66062589787cSdrh 66072589787cSdrh /* No futher action if this term of the FROM clause is no a subquery */ 66084490c40bSdrh if( pSub==0 ) continue; 66092679f14fSdrh 66102679f14fSdrh /* Catch mismatch in the declared columns of a view and the number of 66112679f14fSdrh ** columns in the SELECT on the RHS */ 66122679f14fSdrh if( pTab->nCol!=pSub->pEList->nExpr ){ 66132679f14fSdrh sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", 66142679f14fSdrh pTab->nCol, pTab->zName, pSub->pEList->nExpr); 66152679f14fSdrh goto select_end; 66162679f14fSdrh } 66172679f14fSdrh 661825c221ebSdrh /* Do not try to flatten an aggregate subquery. 661925c221ebSdrh ** 662025c221ebSdrh ** Flattening an aggregate subquery is only possible if the outer query 662125c221ebSdrh ** is not a join. But if the outer query is not a join, then the subquery 662225c221ebSdrh ** will be implemented as a co-routine and there is no advantage to 662325c221ebSdrh ** flattening in that case. 662425c221ebSdrh */ 662525c221ebSdrh if( (pSub->selFlags & SF_Aggregate)!=0 ) continue; 662625c221ebSdrh assert( pSub->pGroupBy==0 ); 662725c221ebSdrh 6628bb301231Sdrh /* If a FROM-clause subquery has an ORDER BY clause that is not 6629bb301231Sdrh ** really doing anything, then delete it now so that it does not 66300fb78f0cSdrh ** interfere with query flattening. See the discussion at 66310fb78f0cSdrh ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a 6632bb301231Sdrh ** 6633bb301231Sdrh ** Beware of these cases where the ORDER BY clause may not be safely 6634bb301231Sdrh ** omitted: 6635bb301231Sdrh ** 6636bb301231Sdrh ** (1) There is also a LIMIT clause 6637bb301231Sdrh ** (2) The subquery was added to help with window-function 6638bb301231Sdrh ** processing 66390fb78f0cSdrh ** (3) The subquery is in the FROM clause of an UPDATE 66400fb78f0cSdrh ** (4) The outer query uses an aggregate function other than 6641bb301231Sdrh ** the built-in count(), min(), or max(). 66420fb78f0cSdrh ** (5) The ORDER BY isn't going to accomplish anything because 66430fb78f0cSdrh ** one of: 66440fb78f0cSdrh ** (a) The outer query has a different ORDER BY clause 66450fb78f0cSdrh ** (b) The subquery is part of a join 66460fb78f0cSdrh ** See forum post 062d576715d277c8 6647bb301231Sdrh */ 6648bb301231Sdrh if( pSub->pOrderBy!=0 66490fb78f0cSdrh && (p->pOrderBy!=0 || pTabList->nSrc>1) /* Condition (5) */ 6650bb301231Sdrh && pSub->pLimit==0 /* Condition (1) */ 6651bb301231Sdrh && (pSub->selFlags & SF_OrderByReqd)==0 /* Condition (2) */ 66520fb78f0cSdrh && (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */ 6653bb301231Sdrh && OptimizationEnabled(db, SQLITE_OmitOrderBy) 6654bb301231Sdrh ){ 6655bb301231Sdrh SELECTTRACE(0x100,pParse,p, 6656bb301231Sdrh ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1)); 6657bb301231Sdrh sqlite3ExprListDelete(db, pSub->pOrderBy); 6658bb301231Sdrh pSub->pOrderBy = 0; 6659bb301231Sdrh } 6660bb301231Sdrh 6661fca23557Sdrh /* If the outer query contains a "complex" result set (that is, 6662fca23557Sdrh ** if the result set of the outer query uses functions or subqueries) 6663fca23557Sdrh ** and if the subquery contains an ORDER BY clause and if 6664648fe49fSdrh ** it will be implemented as a co-routine, then do not flatten. This 6665648fe49fSdrh ** restriction allows SQL constructs like this: 6666648fe49fSdrh ** 6667648fe49fSdrh ** SELECT expensive_function(x) 6668648fe49fSdrh ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 6669648fe49fSdrh ** 6670648fe49fSdrh ** The expensive_function() is only computed on the 10 rows that 6671648fe49fSdrh ** are output, rather than every row of the table. 6672fca23557Sdrh ** 6673fca23557Sdrh ** The requirement that the outer query have a complex result set 6674fca23557Sdrh ** means that flattening does occur on simpler SQL constraints without 6675fca23557Sdrh ** the expensive_function() like: 6676fca23557Sdrh ** 6677fca23557Sdrh ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10); 6678648fe49fSdrh */ 667925c221ebSdrh if( pSub->pOrderBy!=0 6680648fe49fSdrh && i==0 6681fca23557Sdrh && (p->selFlags & SF_ComplexResult)!=0 6682648fe49fSdrh && (pTabList->nSrc==1 6683a76ac88aSdrh || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0) 6684648fe49fSdrh ){ 6685648fe49fSdrh continue; 6686648fe49fSdrh } 6687648fe49fSdrh 668825c221ebSdrh if( flattenSubquery(pParse, p, i, isAgg) ){ 66894acd754cSdrh if( pParse->nErr ) goto select_end; 66904490c40bSdrh /* This subquery can be absorbed into its parent. */ 66914490c40bSdrh i = -1; 66924490c40bSdrh } 66934490c40bSdrh pTabList = p->pSrc; 66944490c40bSdrh if( db->mallocFailed ) goto select_end; 66954490c40bSdrh if( !IgnorableOrderby(pDest) ){ 66964490c40bSdrh sSort.pOrderBy = p->pOrderBy; 66974490c40bSdrh } 66984490c40bSdrh } 66994490c40bSdrh #endif 67004490c40bSdrh 67014490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 67024490c40bSdrh /* Handle compound SELECT statements using the separate multiSelect() 67034490c40bSdrh ** procedure. 67044490c40bSdrh */ 67054490c40bSdrh if( p->pPrior ){ 67064490c40bSdrh rc = multiSelect(pParse, p, pDest); 67075e431beaSdrh #if TREETRACE_ENABLED 6708f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end compound-select processing\n")); 67095e431beaSdrh if( (sqlite3TreeTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 6710f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 6711f20609d1Sdrh } 67124490c40bSdrh #endif 6713c631ded5Sdrh if( p->pNext==0 ) ExplainQueryPlanPop(pParse); 67144490c40bSdrh return rc; 67154490c40bSdrh } 67164490c40bSdrh #endif 67174490c40bSdrh 67187810ab64Sdrh /* Do the WHERE-clause constant propagation optimization if this is 67197810ab64Sdrh ** a join. No need to speed time on this operation for non-join queries 67207810ab64Sdrh ** as the equivalent optimization will be handled by query planner in 67217810ab64Sdrh ** sqlite3WhereBegin(). 67227810ab64Sdrh */ 6723b775c976Sdrh if( p->pWhere!=0 6724b775c976Sdrh && p->pWhere->op==TK_AND 67257810ab64Sdrh && OptimizationEnabled(db, SQLITE_PropagateConst) 672624e1116eSdrh && propagateConstants(pParse, p) 672724e1116eSdrh ){ 67285e431beaSdrh #if TREETRACE_ENABLED 67295e431beaSdrh if( sqlite3TreeTrace & 0x100 ){ 673024e1116eSdrh SELECTTRACE(0x100,pParse,p,("After constant propagation:\n")); 673124e1116eSdrh sqlite3TreeViewSelect(0, p, 0); 673224e1116eSdrh } 673324e1116eSdrh #endif 673424e1116eSdrh }else{ 67357810ab64Sdrh SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n")); 673624e1116eSdrh } 673724e1116eSdrh 6738a4b5fb55Sdan #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION 6739a4b5fb55Sdan if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView) 6740a4b5fb55Sdan && countOfViewOptimization(pParse, p) 6741a4b5fb55Sdan ){ 6742a4b5fb55Sdan if( db->mallocFailed ) goto select_end; 6743a4b5fb55Sdan pEList = p->pEList; 6744a4b5fb55Sdan pTabList = p->pSrc; 6745a4b5fb55Sdan } 6746a4b5fb55Sdan #endif 6747a4b5fb55Sdan 6748701caf1eSdrh /* For each term in the FROM clause, do two things: 6749701caf1eSdrh ** (1) Authorized unreferenced tables 6750701caf1eSdrh ** (2) Generate code for all sub-queries 6751d820cb1bSdrh */ 67524490c40bSdrh for(i=0; i<pTabList->nSrc; i++){ 67537601294aSdrh SrcItem *pItem = &pTabList->a[i]; 6754a79e2a2dSdrh SrcItem *pPrior; 675513449892Sdrh SelectDest dest; 6756701caf1eSdrh Select *pSub; 6757824d21afSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 6758824d21afSdrh const char *zSavedAuthContext; 6759824d21afSdrh #endif 6760701caf1eSdrh 67613d240d21Sdrh /* Issue SQLITE_READ authorizations with a fake column name for any 67623d240d21Sdrh ** tables that are referenced but from which no values are extracted. 67633d240d21Sdrh ** Examples of where these kinds of null SQLITE_READ authorizations 67643d240d21Sdrh ** would occur: 6765701caf1eSdrh ** 67662336c935Sdrh ** SELECT count(*) FROM t1; -- SQLITE_READ t1."" 67672336c935Sdrh ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2."" 67682336c935Sdrh ** 67692336c935Sdrh ** The fake column name is an empty string. It is possible for a table to 67702336c935Sdrh ** have a column named by the empty string, in which case there is no way to 67712336c935Sdrh ** distinguish between an unreferenced table and an actual reference to the 67722336c935Sdrh ** "" column. The original design was for the fake column name to be a NULL, 67732336c935Sdrh ** which would be unambiguous. But legacy authorization callbacks might 67743d240d21Sdrh ** assume the column name is non-NULL and segfault. The use of an empty 67753d240d21Sdrh ** string for the fake column name seems safer. 6776701caf1eSdrh */ 677774c490e0Sdrh if( pItem->colUsed==0 && pItem->zName!=0 ){ 67782336c935Sdrh sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase); 6779701caf1eSdrh } 6780701caf1eSdrh 6781701caf1eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 6782701caf1eSdrh /* Generate code for all sub-queries in the FROM clause 6783701caf1eSdrh */ 6784701caf1eSdrh pSub = pItem->pSelect; 67855b6a9ed4Sdrh if( pSub==0 ) continue; 678621172c4cSdrh 678714c4d428Sdrh /* The code for a subquery should only be generated once. */ 678814c4d428Sdrh assert( pItem->addrFillSub==0 ); 6789daf79acbSdanielk1977 6790fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 6791f7b5496eSdrh ** tree referred to by this, the parent select. The child select 6792fc976065Sdanielk1977 ** may contain expression trees of at most 6793fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 6794fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 6795fc976065Sdanielk1977 ** an exact limit. 6796fc976065Sdanielk1977 */ 6797fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 6798daf79acbSdanielk1977 6799adc57f68Sdrh /* Make copies of constant WHERE-clause terms in the outer query down 6800adc57f68Sdrh ** inside the subquery. This can help the subquery to run more efficiently. 6801adc57f68Sdrh */ 68027fbb101cSdrh if( OptimizationEnabled(db, SQLITE_PushDown) 6803df67ec08Sdrh && (pItem->fg.isCte==0 6804df67ec08Sdrh || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2)) 680541798d5bSdrh && (pItem->fg.jointype & JT_RIGHT)==0 68066a9b9527Sdrh && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor, 68076a9b9527Sdrh (pItem->fg.jointype & JT_OUTER)!=0) 680869b72d5aSdrh ){ 68095e431beaSdrh #if TREETRACE_ENABLED 68105e431beaSdrh if( sqlite3TreeTrace & 0x100 ){ 6811d2a4401cSdrh SELECTTRACE(0x100,pParse,p, 6812d2a4401cSdrh ("After WHERE-clause push-down into subquery %d:\n", pSub->selId)); 681369b72d5aSdrh sqlite3TreeViewSelect(0, p, 0); 6814daf79acbSdanielk1977 } 681569b72d5aSdrh #endif 68168794c68aSdrh assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 ); 68172d277bb5Sdrh }else{ 68182d277bb5Sdrh SELECTTRACE(0x100,pParse,p,("Push-down not possible\n")); 681969b72d5aSdrh } 6820adc57f68Sdrh 6821824d21afSdrh zSavedAuthContext = pParse->zAuthContext; 6822824d21afSdrh pParse->zAuthContext = pItem->zName; 6823824d21afSdrh 6824adc57f68Sdrh /* Generate code to implement the subquery 68250ff47e9eSdrh ** 68269debb58eSdrh ** The subquery is implemented as a co-routine all of the following are 68279debb58eSdrh ** true: 68289debb58eSdrh ** 6829a79e2a2dSdrh ** (1) the subquery is guaranteed to be the outer loop (so that 6830a79e2a2dSdrh ** it does not need to be computed more than once), and 6831745912efSdrh ** (2) the subquery is not a CTE that should be materialized 68329debb58eSdrh ** (3) the subquery is not part of a left operand for a RIGHT JOIN 6833adc57f68Sdrh */ 68340ff47e9eSdrh if( i==0 68350ff47e9eSdrh && (pTabList->nSrc==1 6836a76ac88aSdrh || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0) /* (1) */ 6837745912efSdrh && (pItem->fg.isCte==0 || pItem->u2.pCteUse->eM10d!=M10d_Yes) /* (2) */ 68389debb58eSdrh && (pTabList->a[0].fg.jointype & JT_LTORJ)==0 /* (3) */ 6839a5759677Sdrh ){ 684021172c4cSdrh /* Implement a co-routine that will return a single row of the result 684121172c4cSdrh ** set on each invocation. 684221172c4cSdrh */ 6843725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 6844824d21afSdrh 684521172c4cSdrh pItem->regReturn = ++pParse->nMem; 6846725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 6847a979993bSdrh VdbeComment((v, "%!S", pItem)); 684821172c4cSdrh pItem->addrFillSub = addrTop; 684921172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 6850a979993bSdrh ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem)); 685121172c4cSdrh sqlite3Select(pParse, pSub, &dest); 6852c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 68538a48b9c0Sdrh pItem->fg.viaCoroutine = 1; 68545f612295Sdrh pItem->regResult = dest.iSdst; 68552fade2f7Sdrh sqlite3VdbeEndCoroutine(v, pItem->regReturn); 685621172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 685721172c4cSdrh sqlite3ClearTempRegCache(pParse); 6858a79e2a2dSdrh }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){ 6859a79e2a2dSdrh /* This is a CTE for which materialization code has already been 6860a79e2a2dSdrh ** generated. Invoke the subroutine to compute the materialization, 6861a79e2a2dSdrh ** the make the pItem->iCursor be a copy of the ephemerial table that 6862a79e2a2dSdrh ** holds the result of the materialization. */ 6863a79e2a2dSdrh CteUse *pCteUse = pItem->u2.pCteUse; 6864a79e2a2dSdrh sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e); 6865a79e2a2dSdrh if( pItem->iCursor!=pCteUse->iCur ){ 6866a79e2a2dSdrh sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur); 6867834c6881Sdrh VdbeComment((v, "%!S", pItem)); 6868a79e2a2dSdrh } 6869a79e2a2dSdrh pSub->nSelectRow = pCteUse->nRowEst; 6870a79e2a2dSdrh }else if( (pPrior = isSelfJoinView(pTabList, pItem))!=0 ){ 6871a79e2a2dSdrh /* This view has already been materialized by a prior entry in 6872a79e2a2dSdrh ** this same FROM clause. Reuse it. */ 6873a79e2a2dSdrh if( pPrior->addrFillSub ){ 6874a79e2a2dSdrh sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub); 6875a79e2a2dSdrh } 6876a79e2a2dSdrh sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor); 6877a79e2a2dSdrh pSub->nSelectRow = pPrior->pSelect->nSelectRow; 6878daf79acbSdanielk1977 }else{ 687914c4d428Sdrh /* Materialize the view. If the view is not correlated, generate a 6880d685dd6bSdrh ** subroutine to do the materialization so that subsequent uses of 6881d685dd6bSdrh ** the same view can reuse the materialization. */ 68827157e8eaSdrh int topAddr; 688348f2d3b1Sdrh int onceAddr = 0; 68847157e8eaSdrh int retAddr; 6885e08e8d6bSdrh 68865b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 68877157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 68887157e8eaSdrh pItem->addrFillSub = topAddr+1; 68898a48b9c0Sdrh if( pItem->fg.isCorrelated==0 ){ 6890ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 68915b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 68925b6a9ed4Sdrh ** once. */ 6893511f9e8dSdrh onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 6894a979993bSdrh VdbeComment((v, "materialize %!S", pItem)); 6895725de29aSdrh }else{ 6896a979993bSdrh VdbeNoopComment((v, "materialize %!S", pItem)); 68975b6a9ed4Sdrh } 68981013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 6899a979993bSdrh ExplainQueryPlan((pParse, 1, "MATERIALIZE %!S", pItem)); 69007d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 6901c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 690248f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 69037157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 6904a979993bSdrh VdbeComment((v, "end %!S", pItem)); 69057157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 6906cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 6907d685dd6bSdrh if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){ 6908a79e2a2dSdrh CteUse *pCteUse = pItem->u2.pCteUse; 6909a79e2a2dSdrh pCteUse->addrM9e = pItem->addrFillSub; 6910a79e2a2dSdrh pCteUse->regRtn = pItem->regReturn; 6911a79e2a2dSdrh pCteUse->iCur = pItem->iCursor; 6912a79e2a2dSdrh pCteUse->nRowEst = pSub->nSelectRow; 6913a79e2a2dSdrh } 6914daf79acbSdanielk1977 } 6915adc57f68Sdrh if( db->mallocFailed ) goto select_end; 6916fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 6917824d21afSdrh pParse->zAuthContext = zSavedAuthContext; 6918daf79acbSdanielk1977 #endif 6919701caf1eSdrh } 6920adc57f68Sdrh 692138b4149cSdrh /* Various elements of the SELECT copied into local variables for 692238b4149cSdrh ** convenience */ 6923adc57f68Sdrh pEList = p->pEList; 6924daf79acbSdanielk1977 pWhere = p->pWhere; 6925832508b7Sdrh pGroupBy = p->pGroupBy; 6926832508b7Sdrh pHaving = p->pHaving; 6927e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 6928832508b7Sdrh 69295e431beaSdrh #if TREETRACE_ENABLED 69305e431beaSdrh if( sqlite3TreeTrace & 0x400 ){ 6931bc8edba1Sdrh SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); 6932bc8edba1Sdrh sqlite3TreeViewSelect(0, p, 0); 6933f23329a2Sdanielk1977 } 6934f23329a2Sdanielk1977 #endif 6935f23329a2Sdanielk1977 693650118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 693750118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 693850118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 693950118cdfSdan ** 694050118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 694150118cdfSdan ** 694250118cdfSdan ** is transformed to: 694350118cdfSdan ** 6944dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 694550118cdfSdan ** 694650118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 694750118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 694850118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 694950118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 695050118cdfSdan */ 695150118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 6952adc57f68Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 6953ef9f719dSdrh #ifndef SQLITE_OMIT_WINDOWFUNC 6954e59c562bSdan && p->pWin==0 6955ef9f719dSdrh #endif 695650118cdfSdan ){ 695750118cdfSdan p->selFlags &= ~SF_Distinct; 6958adc57f68Sdrh pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); 69599e10f9abSdan p->selFlags |= SF_Aggregate; 6960e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 6961e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 6962e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 6963e8e4af76Sdrh assert( sDistinct.isTnct ); 6964ece092e7Sdan sDistinct.isTnct = 2; 69657512cb47Sdrh 69665e431beaSdrh #if TREETRACE_ENABLED 69675e431beaSdrh if( sqlite3TreeTrace & 0x400 ){ 69687512cb47Sdrh SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); 69697512cb47Sdrh sqlite3TreeViewSelect(0, p, 0); 69707512cb47Sdrh } 69717512cb47Sdrh #endif 697250118cdfSdan } 697350118cdfSdan 6974adc57f68Sdrh /* If there is an ORDER BY clause, then create an ephemeral index to 6975adc57f68Sdrh ** do the sorting. But this sorting ephemeral index might end up 6976adc57f68Sdrh ** being unused if the data can be extracted in pre-sorted order. 6977adc57f68Sdrh ** If that is the case, then the OP_OpenEphemeral instruction will be 6978adc57f68Sdrh ** changed to an OP_Noop once we figure out that the sorting index is 6979adc57f68Sdrh ** not needed. The sSort.addrSortIndex variable is used to facilitate 6980adc57f68Sdrh ** that change. 69817cedc8d4Sdanielk1977 */ 6982079a3072Sdrh if( sSort.pOrderBy ){ 69830342b1f5Sdrh KeyInfo *pKeyInfo; 6984f9eae18bSdan pKeyInfo = sqlite3KeyInfoFromExprList( 6985f9eae18bSdan pParse, sSort.pOrderBy, 0, pEList->nExpr); 6986079a3072Sdrh sSort.iECursor = pParse->nTab++; 6987079a3072Sdrh sSort.addrSortIndex = 698866a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 6989f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 6990f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 6991f45f2326Sdrh ); 69929d2985c7Sdrh }else{ 6993079a3072Sdrh sSort.addrSortIndex = -1; 69947cedc8d4Sdanielk1977 } 69957cedc8d4Sdanielk1977 69962d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 69972d0794e3Sdrh */ 69986c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 69992b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 70002d0794e3Sdrh } 70012d0794e3Sdrh 7002f42bacc2Sdrh /* Set the limiter. 7003f42bacc2Sdrh */ 7004ec4ccdbcSdrh iEnd = sqlite3VdbeMakeLabel(pParse); 700569b9383eSdan if( (p->selFlags & SF_FixedLimit)==0 ){ 7006c3489bbfSdrh p->nSelectRow = 320; /* 4 billion rows */ 700769b9383eSdan } 7008f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 7009079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 70100ff287fbSdrh sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); 7011079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 7012c6aff30cSdrh } 7013f42bacc2Sdrh 7014adc57f68Sdrh /* Open an ephemeral index to use for the distinct set. 7015cce7d176Sdrh */ 70162ce22453Sdan if( p->selFlags & SF_Distinct ){ 7017e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 7018e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 7019e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 7020f9eae18bSdan (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0), 70212ec2fb22Sdrh P4_KEYINFO); 7022d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 7023e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 7024832508b7Sdrh }else{ 7025e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 7026efb7251dSdrh } 7027832508b7Sdrh 702813449892Sdrh if( !isAgg && pGroupBy==0 ){ 7029e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 703067a9b8edSdan u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0) 703167a9b8edSdan | (p->selFlags & SF_FixedLimit); 703267a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 7033067b92baSdrh Window *pWin = p->pWin; /* Main window object (or NULL) */ 7034f9eae18bSdan if( pWin ){ 70354ea562eeSdan sqlite3WindowCodeInit(pParse, p); 703686fb6e17Sdan } 703767a9b8edSdan #endif 703867a9b8edSdan assert( WHERE_USE_LIMIT==SF_FixedLimit ); 703967a9b8edSdan 704086fb6e17Sdan 704138cc40c2Sdan /* Begin the database scan. */ 7042cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 7043079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 7044895bab33Sdrh p->pEList, p, wctrlFlags, p->nSelectRow); 70451d83f052Sdrh if( pWInfo==0 ) goto select_end; 70466f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 70476f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 70486f32848dSdrh } 70496457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 70506f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 70516f32848dSdrh } 7052079a3072Sdrh if( sSort.pOrderBy ){ 7053079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 70546ee5a7b4Sdrh sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo); 7055079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 7056079a3072Sdrh sSort.pOrderBy = 0; 7057079a3072Sdrh } 7058079a3072Sdrh } 705913162ef9Sdrh SELECTTRACE(1,pParse,p,("WhereBegin returns\n")); 7060cce7d176Sdrh 7061b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 7062b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 70639d2985c7Sdrh ** into an OP_Noop. 70649d2985c7Sdrh */ 7065079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 7066079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 70679d2985c7Sdrh } 70689d2985c7Sdrh 70692def2f7eSdrh assert( p->pEList==pEList ); 707067a9b8edSdan #ifndef SQLITE_OMIT_WINDOWFUNC 7071f9eae18bSdan if( pWin ){ 7072ec4ccdbcSdrh int addrGosub = sqlite3VdbeMakeLabel(pParse); 7073ec4ccdbcSdrh int iCont = sqlite3VdbeMakeLabel(pParse); 7074ec4ccdbcSdrh int iBreak = sqlite3VdbeMakeLabel(pParse); 7075f9eae18bSdan int regGosub = ++pParse->nMem; 707686fb6e17Sdan 7077dacf1de9Sdan sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub); 707886fb6e17Sdan 7079efa3a3c9Sdan sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak); 7080f9eae18bSdan sqlite3VdbeResolveLabel(v, addrGosub); 7081b0225bc5Sdrh VdbeNoopComment((v, "inner-loop subroutine")); 7082d4cb09e3Sdrh sSort.labelOBLopt = 0; 7083efa3a3c9Sdan selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak); 7084dacf1de9Sdan sqlite3VdbeResolveLabel(v, iCont); 708586fb6e17Sdan sqlite3VdbeAddOp1(v, OP_Return, regGosub); 70860b3b0dd1Sdrh VdbeComment((v, "end inner-loop subroutine")); 7087efa3a3c9Sdan sqlite3VdbeResolveLabel(v, iBreak); 708867a9b8edSdan }else 708967a9b8edSdan #endif /* SQLITE_OMIT_WINDOWFUNC */ 709067a9b8edSdan { 709186fb6e17Sdan /* Use the standard inner loop. */ 70922def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, 70936f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 70946f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 70952282792aSdrh 7096cce7d176Sdrh /* End the database scan loop. 7097cce7d176Sdrh */ 709813162ef9Sdrh SELECTTRACE(1,pParse,p,("WhereEnd\n")); 70994adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 710086fb6e17Sdan } 710113449892Sdrh }else{ 7102e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 7103e8e4af76Sdrh ** or both */ 710413449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 710513449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 710613449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 710713449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 710813449892Sdrh ** one row of the input to the aggregator has been 710913449892Sdrh ** processed */ 711013449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 711113449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 7112d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 71131c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 71141c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 7115374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 7116d176611bSdrh 7117d176611bSdrh /* Remove any and all aliases between the result set and the 7118d176611bSdrh ** GROUP BY clause. 7119d176611bSdrh */ 7120d176611bSdrh if( pGroupBy ){ 7121dc5ea5c7Sdrh int k; /* Loop counter */ 7122d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 7123d176611bSdrh 7124dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 7125c2acc4e4Sdrh pItem->u.x.iAlias = 0; 7126d176611bSdrh } 7127dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 7128c2acc4e4Sdrh pItem->u.x.iAlias = 0; 7129d176611bSdrh } 7130c3489bbfSdrh assert( 66==sqlite3LogEst(100) ); 7131c3489bbfSdrh if( p->nSelectRow>66 ) p->nSelectRow = 66; 7132cce7d176Sdrh 7133374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 7134374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 7135374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 7136adc57f68Sdrh ** in the correct order. It also may not - the GROUP BY might use a 7137374cd78cSdan ** database index that causes rows to be grouped together as required 7138374cd78cSdan ** but not actually sorted. Either way, record the fact that the 7139374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 7140374cd78cSdan ** variable. */ 71418c9bcb23Sdan if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){ 7142e39f388eSdrh int ii; 71438c9bcb23Sdan /* The GROUP BY processing doesn't care whether rows are delivered in 71448c9bcb23Sdan ** ASC or DESC order - only that each group is returned contiguously. 71458c9bcb23Sdan ** So set the ASC/DESC flags in the GROUP BY to match those in the 71468c9bcb23Sdan ** ORDER BY to maximize the chances of rows being delivered in an 71478c9bcb23Sdan ** order that makes the ORDER BY redundant. */ 7148e39f388eSdrh for(ii=0; ii<pGroupBy->nExpr; ii++){ 7149e39f388eSdrh u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC; 7150e39f388eSdrh pGroupBy->a[ii].sortFlags = sortFlags; 71518c9bcb23Sdan } 7152374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 7153374cd78cSdan orderByGrp = 1; 7154374cd78cSdan } 71558c9bcb23Sdan } 71568c9bcb23Sdan }else{ 71578c9bcb23Sdan assert( 0==sqlite3LogEst(1) ); 71588c9bcb23Sdan p->nSelectRow = 0; 71598c9bcb23Sdan } 716013449892Sdrh 7161d176611bSdrh /* Create a label to jump to when we want to abort the query */ 7162ec4ccdbcSdrh addrEnd = sqlite3VdbeMakeLabel(pParse); 716313449892Sdrh 716413449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 716513449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 716613449892Sdrh ** SELECT statement. 71672282792aSdrh */ 7168bf790973Sdrh pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) ); 7169c54246ffSdrh if( pAggInfo ){ 7170c54246ffSdrh sqlite3ParserAddCleanup(pParse, 7171c54246ffSdrh (void(*)(sqlite3*,void*))agginfoFree, pAggInfo); 71726d0053cfSdrh testcase( pParse->earlyCleanup ); 7173c54246ffSdrh } 7174c54246ffSdrh if( db->mallocFailed ){ 7175bf790973Sdrh goto select_end; 7176bf790973Sdrh } 7177e26d428aSdrh pAggInfo->selId = p->selId; 717813449892Sdrh memset(&sNC, 0, sizeof(sNC)); 717913449892Sdrh sNC.pParse = pParse; 718013449892Sdrh sNC.pSrcList = pTabList; 7181bf790973Sdrh sNC.uNC.pAggInfo = pAggInfo; 718225c3b8caSdrh VVA_ONLY( sNC.ncFlags = NC_UAggInfo; ) 7183bf790973Sdrh pAggInfo->mnReg = pParse->nMem+1; 7184bf790973Sdrh pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 7185bf790973Sdrh pAggInfo->pGroupBy = pGroupBy; 7186d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 7187079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 7188d2b3e23bSdrh if( pHaving ){ 7189ab31a845Sdan if( pGroupBy ){ 7190ab31a845Sdan assert( pWhere==p->pWhere ); 7191cd0abc24Sdrh assert( pHaving==p->pHaving ); 7192cd0abc24Sdrh assert( pGroupBy==p->pGroupBy ); 7193cd0abc24Sdrh havingToWhere(pParse, p); 7194ab31a845Sdan pWhere = p->pWhere; 7195ab31a845Sdan } 7196d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 719713449892Sdrh } 7198bf790973Sdrh pAggInfo->nAccumulator = pAggInfo->nColumn; 7199bf790973Sdrh if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){ 720081185a51Sdrh minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy); 720147d9f839Sdrh }else{ 720247d9f839Sdrh minMaxFlag = WHERE_ORDERBY_NORMAL; 720347d9f839Sdrh } 7204bf790973Sdrh for(i=0; i<pAggInfo->nFunc; i++){ 720581185a51Sdrh Expr *pExpr = pAggInfo->aFunc[i].pFExpr; 7206a4eeccdfSdrh assert( ExprUseXList(pExpr) ); 72073a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 72086ba7ab0dSdan sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList); 72096ba7ab0dSdan #ifndef SQLITE_OMIT_WINDOWFUNC 72104f9adee2Sdan assert( !IsWindowFunc(pExpr) ); 72114f9adee2Sdan if( ExprHasProperty(pExpr, EP_WinFunc) ){ 72124f9adee2Sdan sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter); 7213b28c4e56Sdan } 72146ba7ab0dSdan #endif 72153a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 721613449892Sdrh } 7217bf790973Sdrh pAggInfo->mxReg = pParse->nMem; 721817435752Sdrh if( db->mallocFailed ) goto select_end; 72195e431beaSdrh #if TREETRACE_ENABLED 72205e431beaSdrh if( sqlite3TreeTrace & 0x400 ){ 72217ea11066Sdrh int ii; 7222bf790973Sdrh SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", pAggInfo)); 72237ea11066Sdrh sqlite3TreeViewSelect(0, p, 0); 7224b9366f8eSdrh if( minMaxFlag ){ 7225b9366f8eSdrh sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag); 7226b9366f8eSdrh sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY"); 7227b9366f8eSdrh } 7228bf790973Sdrh for(ii=0; ii<pAggInfo->nColumn; ii++){ 72297ea11066Sdrh sqlite3DebugPrintf("agg-column[%d] iMem=%d\n", 7230bf790973Sdrh ii, pAggInfo->aCol[ii].iMem); 723181185a51Sdrh sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0); 72327ea11066Sdrh } 7233bf790973Sdrh for(ii=0; ii<pAggInfo->nFunc; ii++){ 72347ea11066Sdrh sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n", 7235bf790973Sdrh ii, pAggInfo->aFunc[ii].iMem); 723681185a51Sdrh sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0); 72377ea11066Sdrh } 72387ea11066Sdrh } 72397ea11066Sdrh #endif 72407ea11066Sdrh 724113449892Sdrh 724213449892Sdrh /* Processing for aggregates with GROUP BY is very different and 72433c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 724413449892Sdrh */ 724513449892Sdrh if( pGroupBy ){ 724613449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 7247728e0f91Sdrh int addr1; /* A-vs-B comparision jump */ 7248d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 7249d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 7250d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 7251d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 7252d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 7253d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 7254d176611bSdrh int regReset; /* Return address register for reset subroutine */ 72555383db71Sdan ExprList *pDistinct = 0; 72565383db71Sdan u16 distFlag = 0; 72575383db71Sdan int eDist = WHERE_DISTINCT_NOOP; 72585383db71Sdan 72595383db71Sdan if( pAggInfo->nFunc==1 72605383db71Sdan && pAggInfo->aFunc[0].iDistinct>=0 7261a4eeccdfSdrh && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0) 7262a4eeccdfSdrh && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr)) 7263a4eeccdfSdrh && pAggInfo->aFunc[0].pFExpr->x.pList!=0 72645383db71Sdan ){ 72655383db71Sdan Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr; 72665383db71Sdan pExpr = sqlite3ExprDup(db, pExpr, 0); 72675383db71Sdan pDistinct = sqlite3ExprListDup(db, pGroupBy, 0); 72685383db71Sdan pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr); 7269f330d53fSdan distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0; 72705383db71Sdan } 727113449892Sdrh 727213449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 727313449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 72741c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 727513449892Sdrh ** will be converted into a Noop. 727613449892Sdrh */ 7277bf790973Sdrh pAggInfo->sortingIdx = pParse->nTab++; 7278bf790973Sdrh pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy, 7279bf790973Sdrh 0, pAggInfo->nColumn); 72801c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 7281bf790973Sdrh pAggInfo->sortingIdx, pAggInfo->nSortingColumn, 72822ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 728313449892Sdrh 728413449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 728513449892Sdrh */ 72860a07c107Sdrh iUseFlag = ++pParse->nMem; 72870a07c107Sdrh iAbortFlag = ++pParse->nMem; 7288d176611bSdrh regOutputRow = ++pParse->nMem; 7289ec4ccdbcSdrh addrOutputRow = sqlite3VdbeMakeLabel(pParse); 7290d176611bSdrh regReset = ++pParse->nMem; 7291ec4ccdbcSdrh addrReset = sqlite3VdbeMakeLabel(pParse); 72920a07c107Sdrh iAMem = pParse->nMem + 1; 729313449892Sdrh pParse->nMem += pGroupBy->nExpr; 72940a07c107Sdrh iBMem = pParse->nMem + 1; 729513449892Sdrh pParse->nMem += pGroupBy->nExpr; 72964c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 7297d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 7298b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 7299e313382eSdrh 730013449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 730113449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 730213449892Sdrh ** it might be a single loop that uses an index to extract information 730313449892Sdrh ** in the right order to begin with. 730413449892Sdrh */ 73052eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 7306cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 73075383db71Sdan pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct, 7308ece092e7Sdan 0, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY) 7309ece092e7Sdan | (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0 7310374cd78cSdan ); 7311bfd6f1bcSdan if( pWInfo==0 ){ 7312b19a5812Sdan sqlite3ExprListDelete(db, pDistinct); 7313bfd6f1bcSdan goto select_end; 7314bfd6f1bcSdan } 731576075807Sdan eDist = sqlite3WhereIsDistinct(pWInfo); 731613162ef9Sdrh SELECTTRACE(1,pParse,p,("WhereBegin returns\n")); 7317ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 731813449892Sdrh /* The optimizer is able to deliver rows in group by order so 7319b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 732013449892Sdrh ** cancelled later because we still need to use the pKeyInfo 732113449892Sdrh */ 732213449892Sdrh groupBySort = 0; 732313449892Sdrh }else{ 732413449892Sdrh /* Rows are coming out in undetermined order. We have to push 732513449892Sdrh ** each row into a sorting index, terminate the first loop, 732613449892Sdrh ** then loop over the sorting index in order to get the output 732713449892Sdrh ** in sorted order 732813449892Sdrh */ 7329892d3179Sdrh int regBase; 7330892d3179Sdrh int regRecord; 7331892d3179Sdrh int nCol; 7332892d3179Sdrh int nGroupBy; 7333892d3179Sdrh 73342ce22453Sdan explainTempTable(pParse, 7335e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 7336e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 73372ce22453Sdan 733813449892Sdrh groupBySort = 1; 7339892d3179Sdrh nGroupBy = pGroupBy->nExpr; 7340dd23c6bfSdan nCol = nGroupBy; 7341dd23c6bfSdan j = nGroupBy; 7342bf790973Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 7343bf790973Sdrh if( pAggInfo->aCol[i].iSorterColumn>=j ){ 7344892d3179Sdrh nCol++; 734513449892Sdrh j++; 734613449892Sdrh } 7347892d3179Sdrh } 7348892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 73495579d59fSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); 7350dd23c6bfSdan j = nGroupBy; 7351bf790973Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 7352bf790973Sdrh struct AggInfo_col *pCol = &pAggInfo->aCol[i]; 7353892d3179Sdrh if( pCol->iSorterColumn>=j ){ 7354e55cbd72Sdrh int r1 = j + regBase; 73558c607191Sdrh sqlite3ExprCodeGetColumnOfTable(v, 73568c607191Sdrh pCol->pTab, pCol->iTable, pCol->iColumn, r1); 73576a012f04Sdrh j++; 7358892d3179Sdrh } 7359892d3179Sdrh } 7360892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 73611db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 7362bf790973Sdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord); 7363892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 7364892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 736513162ef9Sdrh SELECTTRACE(1,pParse,p,("WhereEnd\n")); 736613449892Sdrh sqlite3WhereEnd(pWInfo); 7367bf790973Sdrh pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++; 73681c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 73691c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 7370bf790973Sdrh sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd); 7371688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 7372bf790973Sdrh pAggInfo->useSortingIdx = 1; 7373374cd78cSdan } 7374374cd78cSdan 7375374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 7376374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 7377374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 7378374cd78cSdan ** 7379374cd78cSdan ** This is an optimization - the correct answer should result regardless. 7380374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 7381374cd78cSdan ** disable this optimization for testing purposes. */ 7382374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 7383374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 7384374cd78cSdan ){ 7385374cd78cSdan sSort.pOrderBy = 0; 7386374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 738713449892Sdrh } 738813449892Sdrh 738913449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 739013449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 739113449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 739213449892Sdrh ** from the previous row currently stored in a0, a1, a2... 739313449892Sdrh */ 739413449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 73951c9d835dSdrh if( groupBySort ){ 7396bf790973Sdrh sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx, 739738b4149cSdrh sortOut, sortPTab); 73981c9d835dSdrh } 739913449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 740013449892Sdrh if( groupBySort ){ 74011c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 740213449892Sdrh }else{ 7403bf790973Sdrh pAggInfo->directMode = 1; 74042dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 740513449892Sdrh } 740613449892Sdrh } 740716ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 74082ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 7409728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 7410728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); 741113449892Sdrh 741213449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 7413e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 741413449892Sdrh ** block. If there were no changes, this block is skipped. 741513449892Sdrh ** 741613449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 741713449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 741813449892Sdrh ** and resets the aggregate accumulator registers in preparation 741913449892Sdrh ** for the next GROUP BY batch. 742013449892Sdrh */ 7421b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 74222eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 7423d4e70ebdSdrh VdbeComment((v, "output one row")); 7424688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 7425d4e70ebdSdrh VdbeComment((v, "check abort flag")); 74262eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 7427d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 742813449892Sdrh 742913449892Sdrh /* Update the aggregate accumulators based on the content of 743013449892Sdrh ** the current row 743113449892Sdrh */ 7432728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 74335383db71Sdan updateAccumulator(pParse, iUseFlag, pAggInfo, eDist); 74344c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 7435d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 743613449892Sdrh 743713449892Sdrh /* End of the loop 743813449892Sdrh */ 743913449892Sdrh if( groupBySort ){ 7440bf790973Sdrh sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop); 7441688852abSdrh VdbeCoverage(v); 744213449892Sdrh }else{ 744313162ef9Sdrh SELECTTRACE(1,pParse,p,("WhereEnd\n")); 744413449892Sdrh sqlite3WhereEnd(pWInfo); 744548f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 744613449892Sdrh } 7447bfd6f1bcSdan sqlite3ExprListDelete(db, pDistinct); 744813449892Sdrh 744913449892Sdrh /* Output the final row of result 745013449892Sdrh */ 74512eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 7452d4e70ebdSdrh VdbeComment((v, "output final row")); 745313449892Sdrh 7454d176611bSdrh /* Jump over the subroutines 7455d176611bSdrh */ 7456076e85f5Sdrh sqlite3VdbeGoto(v, addrEnd); 7457d176611bSdrh 7458d176611bSdrh /* Generate a subroutine that outputs a single row of the result 7459d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 7460d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 7461d176611bSdrh ** the processing calls for the query to abort, this subroutine 7462d176611bSdrh ** increments the iAbortFlag memory location before returning in 7463d176611bSdrh ** order to signal the caller to abort. 7464d176611bSdrh */ 7465d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 7466d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 7467d176611bSdrh VdbeComment((v, "set abort flag")); 7468d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 7469d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 7470d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 7471d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 747238b4149cSdrh VdbeCoverage(v); 7473d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 7474d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 7475bf790973Sdrh finalizeAggFunctions(pParse, pAggInfo); 7476d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 74772def2f7eSdrh selectInnerLoop(pParse, p, -1, &sSort, 7478e8e4af76Sdrh &sDistinct, pDest, 7479d176611bSdrh addrOutputRow+1, addrSetAbort); 7480d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 7481d176611bSdrh VdbeComment((v, "end groupby result generator")); 7482d176611bSdrh 7483d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 7484d176611bSdrh */ 7485d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 7486bf790973Sdrh resetAccumulator(pParse, pAggInfo); 7487280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 7488280c894bSdan VdbeComment((v, "indicate accumulator empty")); 7489d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 7490d176611bSdrh 7491ece092e7Sdan if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){ 74925383db71Sdan struct AggInfo_func *pF = &pAggInfo->aFunc[0]; 74935383db71Sdan fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr); 74945383db71Sdan } 749543152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 749613449892Sdrh else { 7497a5533162Sdanielk1977 Table *pTab; 7498bf790973Sdrh if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){ 7499a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 7500a5533162Sdanielk1977 ** the SQL statement is of the form: 7501a5533162Sdanielk1977 ** 7502a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 7503a5533162Sdanielk1977 ** 7504a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 7505a5533162Sdanielk1977 ** 7506a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 7507a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 7508a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 7509a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 7510a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 7511a5533162Sdanielk1977 */ 7512a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 7513a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 7514a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 7515a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 7516a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 7517013e7bb7Sdrh Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */ 7518a9d1ccb9Sdanielk1977 7519a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 7520a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 7521a5533162Sdanielk1977 7522d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 7523a5533162Sdanielk1977 ** 75243e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 75253e9548b3Sdrh ** 7526abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 75275f33f375Sdrh ** 7528a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 7529a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 7530a5533162Sdanielk1977 */ 75315c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 753298aa1d73Sdrh if( !p->pSrc->a[0].fg.notIndexed ){ 7533a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 7534d9e3cad2Sdrh if( pIdx->bUnordered==0 7535e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 7536d3037a41Sdrh && pIdx->pPartIdxWhere==0 7537e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 7538d9e3cad2Sdrh ){ 7539a5533162Sdanielk1977 pBest = pIdx; 7540a5533162Sdanielk1977 } 7541a5533162Sdanielk1977 } 754298aa1d73Sdrh } 7543d9e3cad2Sdrh if( pBest ){ 7544a5533162Sdanielk1977 iRoot = pBest->tnum; 75452ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 7546a5533162Sdanielk1977 } 7547a5533162Sdanielk1977 7548a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 7549013e7bb7Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1); 7550a5533162Sdanielk1977 if( pKeyInfo ){ 75512ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 7552a5533162Sdanielk1977 } 7553bf790973Sdrh sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem); 7554a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 7555ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 7556e50478d7Sdrh }else{ 7557280c894bSdan int regAcc = 0; /* "populate accumulators" flag */ 75584fcb30b7Sdan ExprList *pDistinct = 0; 75594fcb30b7Sdan u16 distFlag = 0; 75605383db71Sdan int eDist; 7561280c894bSdan 7562ed09dddeSdan /* If there are accumulator registers but no min() or max() functions 7563ed09dddeSdan ** without FILTER clauses, allocate register regAcc. Register regAcc 7564ed09dddeSdan ** will contain 0 the first time the inner loop runs, and 1 thereafter. 7565ed09dddeSdan ** The code generated by updateAccumulator() uses this to ensure 7566ed09dddeSdan ** that the accumulator registers are (a) updated only once if 7567ed09dddeSdan ** there are no min() or max functions or (b) always updated for the 7568ed09dddeSdan ** first row visited by the aggregate, so that they are updated at 7569ed09dddeSdan ** least once even if the FILTER clause means the min() or max() 7570ed09dddeSdan ** function visits zero rows. */ 7571bf790973Sdrh if( pAggInfo->nAccumulator ){ 7572bf790973Sdrh for(i=0; i<pAggInfo->nFunc; i++){ 757381185a51Sdrh if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){ 7574bf790973Sdrh continue; 7575280c894bSdan } 7576bf790973Sdrh if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){ 7577bf790973Sdrh break; 7578bf790973Sdrh } 7579bf790973Sdrh } 7580bf790973Sdrh if( i==pAggInfo->nFunc ){ 7581280c894bSdan regAcc = ++pParse->nMem; 7582280c894bSdan sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc); 7583280c894bSdan } 75844fcb30b7Sdan }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){ 7585a4eeccdfSdrh assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) ); 75864fcb30b7Sdan pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList; 7587f330d53fSdan distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0; 7588280c894bSdan } 7589280c894bSdan 759013449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 759113449892Sdrh ** processing is much simpler since there is only a single row 759213449892Sdrh ** of output. 759313449892Sdrh */ 759447d9f839Sdrh assert( p->pGroupBy==0 ); 7595bf790973Sdrh resetAccumulator(pParse, pAggInfo); 759647d9f839Sdrh 759747d9f839Sdrh /* If this query is a candidate for the min/max optimization, then 759847d9f839Sdrh ** minMaxFlag will have been previously set to either 759947d9f839Sdrh ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will 760047d9f839Sdrh ** be an appropriate ORDER BY expression for the optimization. 760147d9f839Sdrh */ 760247d9f839Sdrh assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 ); 760347d9f839Sdrh assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 ); 760447d9f839Sdrh 7605cfd74700Sdrh SELECTTRACE(1,pParse,p,("WhereBegin\n")); 760647d9f839Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy, 7607895bab33Sdrh pDistinct, 0, minMaxFlag|distFlag, 0); 7608dba0137eSdanielk1977 if( pWInfo==0 ){ 7609dba0137eSdanielk1977 goto select_end; 7610dba0137eSdanielk1977 } 761113162ef9Sdrh SELECTTRACE(1,pParse,p,("WhereBegin returns\n")); 76125383db71Sdan eDist = sqlite3WhereIsDistinct(pWInfo); 76135383db71Sdan updateAccumulator(pParse, regAcc, pAggInfo, eDist); 76145383db71Sdan if( eDist!=WHERE_DISTINCT_NOOP ){ 76155383db71Sdan struct AggInfo_func *pF = &pAggInfo->aFunc[0]; 76163117b7b0Sdrh if( pF ){ 76175383db71Sdan fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr); 76185383db71Sdan } 76193117b7b0Sdrh } 76205383db71Sdan 7621280c894bSdan if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc); 7622d193057aSdrh if( minMaxFlag ){ 7623d193057aSdrh sqlite3WhereMinMaxOptEarlyOut(v, pWInfo); 7624a9d1ccb9Sdanielk1977 } 762513162ef9Sdrh SELECTTRACE(1,pParse,p,("WhereEnd\n")); 762613449892Sdrh sqlite3WhereEnd(pWInfo); 7627bf790973Sdrh finalizeAggFunctions(pParse, pAggInfo); 76287a895a80Sdanielk1977 } 76297a895a80Sdanielk1977 7630079a3072Sdrh sSort.pOrderBy = 0; 763135573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 76322def2f7eSdrh selectInnerLoop(pParse, p, -1, 0, 0, 7633a9671a22Sdrh pDest, addrEnd, addrEnd); 763413449892Sdrh } 763513449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 763613449892Sdrh 763713449892Sdrh } /* endif aggregate query */ 76382282792aSdrh 7639e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 76402ce22453Sdan explainTempTable(pParse, "DISTINCT"); 76412ce22453Sdan } 76422ce22453Sdan 7643cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 7644cce7d176Sdrh ** and send them to the callback one by one. 7645cce7d176Sdrh */ 7646079a3072Sdrh if( sSort.pOrderBy ){ 764738b4149cSdrh explainTempTable(pParse, 764838b4149cSdrh sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 764924e25d32Sdan assert( p->pEList==pEList ); 7650079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 7651cce7d176Sdrh } 76526a535340Sdrh 7653ec7429aeSdrh /* Jump here to skip this query 7654ec7429aeSdrh */ 7655ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 7656ec7429aeSdrh 76575b1c07e7Sdan /* The SELECT has been coded. If there is an error in the Parse structure, 76585b1c07e7Sdan ** set the return code to 1. Otherwise 0. */ 76595b1c07e7Sdan rc = (pParse->nErr>0); 76601d83f052Sdrh 76611d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 76621d83f052Sdrh ** successful coding of the SELECT. 76631d83f052Sdrh */ 76641d83f052Sdrh select_end: 766544918c74Sdan assert( db->mallocFailed==0 || db->mallocFailed==1 ); 76660c7d3d39Sdrh assert( db->mallocFailed==0 || pParse->nErr!=0 ); 766747d9f839Sdrh sqlite3ExprListDelete(db, pMinMaxOrderBy); 766889636628Sdrh #ifdef SQLITE_DEBUG 76697b4c4d4aSdrh if( pAggInfo && !db->mallocFailed ){ 7670bf790973Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 767181185a51Sdrh Expr *pExpr = pAggInfo->aCol[i].pCExpr; 767206ddb08fSdrh assert( pExpr!=0 ); 7673bf790973Sdrh assert( pExpr->pAggInfo==pAggInfo ); 767489636628Sdrh assert( pExpr->iAgg==i ); 767589636628Sdrh } 7676bf790973Sdrh for(i=0; i<pAggInfo->nFunc; i++){ 767781185a51Sdrh Expr *pExpr = pAggInfo->aFunc[i].pFExpr; 767806ddb08fSdrh assert( pExpr!=0 ); 7679bf790973Sdrh assert( pExpr->pAggInfo==pAggInfo ); 768089636628Sdrh assert( pExpr->iAgg==i ); 768189636628Sdrh } 768289636628Sdrh } 768389636628Sdrh #endif 768489636628Sdrh 76855e431beaSdrh #if TREETRACE_ENABLED 7686f20609d1Sdrh SELECTTRACE(0x1,pParse,p,("end processing\n")); 76875e431beaSdrh if( (sqlite3TreeTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){ 7688f20609d1Sdrh sqlite3TreeViewSelect(0, p, 0); 7689f20609d1Sdrh } 7690eb9b884cSdrh #endif 7691e2ca99c9Sdrh ExplainQueryPlanPop(pParse); 76921d83f052Sdrh return rc; 7693cce7d176Sdrh } 7694