1cce7d176Sdrh /* 2b19a2bc6Sdrh ** 2001 September 15 3cce7d176Sdrh ** 4b19a2bc6Sdrh ** The author disclaims copyright to this source code. In place of 5b19a2bc6Sdrh ** a legal notice, here is a blessing: 6cce7d176Sdrh ** 7b19a2bc6Sdrh ** May you do good and not evil. 8b19a2bc6Sdrh ** May you find forgiveness for yourself and forgive others. 9b19a2bc6Sdrh ** May you share freely, never taking more than you give. 10cce7d176Sdrh ** 11cce7d176Sdrh ************************************************************************* 12cce7d176Sdrh ** This file contains C code routines that are called by the parser 13b19a2bc6Sdrh ** to handle SELECT statements in SQLite. 14cce7d176Sdrh */ 15cce7d176Sdrh #include "sqliteInt.h" 16cce7d176Sdrh 17079a3072Sdrh /* 18abd4c723Sdrh ** Trace output macros 19abd4c723Sdrh */ 20abd4c723Sdrh #if SELECTTRACE_ENABLED 21abd4c723Sdrh /***/ int sqlite3SelectTrace = 0; 22eb9b884cSdrh # define SELECTTRACE(K,P,S,X) \ 23eb9b884cSdrh if(sqlite3SelectTrace&(K)) \ 2438b4149cSdrh sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\ 2538b4149cSdrh (S)->zSelName,(S)),\ 26eb9b884cSdrh sqlite3DebugPrintf X 27abd4c723Sdrh #else 28eb9b884cSdrh # define SELECTTRACE(K,P,S,X) 29abd4c723Sdrh #endif 30abd4c723Sdrh 31315555caSdrh 32cce7d176Sdrh /* 33079a3072Sdrh ** An instance of the following object is used to record information about 34079a3072Sdrh ** how to process the DISTINCT keyword, to simplify passing that information 35079a3072Sdrh ** into the selectInnerLoop() routine. 36eda639e1Sdrh */ 37079a3072Sdrh typedef struct DistinctCtx DistinctCtx; 38079a3072Sdrh struct DistinctCtx { 39079a3072Sdrh u8 isTnct; /* True if the DISTINCT keyword is present */ 40079a3072Sdrh u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */ 41079a3072Sdrh int tabTnct; /* Ephemeral table used for DISTINCT processing */ 42079a3072Sdrh int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */ 43079a3072Sdrh }; 44079a3072Sdrh 45079a3072Sdrh /* 46079a3072Sdrh ** An instance of the following object is used to record information about 47079a3072Sdrh ** the ORDER BY (or GROUP BY) clause of query is being coded. 48079a3072Sdrh */ 49079a3072Sdrh typedef struct SortCtx SortCtx; 50079a3072Sdrh struct SortCtx { 51079a3072Sdrh ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */ 52079a3072Sdrh int nOBSat; /* Number of ORDER BY terms satisfied by indices */ 53079a3072Sdrh int iECursor; /* Cursor number for the sorter */ 54079a3072Sdrh int regReturn; /* Register holding block-output return address */ 55079a3072Sdrh int labelBkOut; /* Start label for the block-output subroutine */ 56079a3072Sdrh int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */ 57a04a8be2Sdrh int labelDone; /* Jump here when done, ex: LIMIT reached */ 58079a3072Sdrh u8 sortFlags; /* Zero or more SORTFLAG_* bits */ 59a536df4eSdrh u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */ 60079a3072Sdrh }; 61079a3072Sdrh #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ 62cce7d176Sdrh 63cce7d176Sdrh /* 64b87fbed5Sdrh ** Delete all the content of a Select structure. Deallocate the structure 65b87fbed5Sdrh ** itself only if bFree is true. 66eda639e1Sdrh */ 67b87fbed5Sdrh static void clearSelect(sqlite3 *db, Select *p, int bFree){ 68b87fbed5Sdrh while( p ){ 69b87fbed5Sdrh Select *pPrior = p->pPrior; 70633e6d57Sdrh sqlite3ExprListDelete(db, p->pEList); 71633e6d57Sdrh sqlite3SrcListDelete(db, p->pSrc); 72633e6d57Sdrh sqlite3ExprDelete(db, p->pWhere); 73633e6d57Sdrh sqlite3ExprListDelete(db, p->pGroupBy); 74633e6d57Sdrh sqlite3ExprDelete(db, p->pHaving); 75633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 76633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 77633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 78f3c57ff5Sdrh if( p->pWith ) sqlite3WithDelete(db, p->pWith); 79dbd6a7dcSdrh if( bFree ) sqlite3DbFreeNN(db, p); 80b87fbed5Sdrh p = pPrior; 81b87fbed5Sdrh bFree = 1; 82b87fbed5Sdrh } 83eda639e1Sdrh } 84eda639e1Sdrh 851013c932Sdrh /* 861013c932Sdrh ** Initialize a SelectDest structure. 871013c932Sdrh */ 881013c932Sdrh void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ 89ea678832Sdrh pDest->eDest = (u8)eDest; 902b596da8Sdrh pDest->iSDParm = iParm; 9171c57db0Sdan pDest->zAffSdst = 0; 922b596da8Sdrh pDest->iSdst = 0; 932b596da8Sdrh pDest->nSdst = 0; 941013c932Sdrh } 951013c932Sdrh 96eda639e1Sdrh 97eda639e1Sdrh /* 989bb61fe7Sdrh ** Allocate a new Select structure and return a pointer to that 999bb61fe7Sdrh ** structure. 100cce7d176Sdrh */ 1014adee20fSdanielk1977 Select *sqlite3SelectNew( 10217435752Sdrh Parse *pParse, /* Parsing context */ 103daffd0e5Sdrh ExprList *pEList, /* which columns to include in the result */ 104ad3cab52Sdrh SrcList *pSrc, /* the FROM clause -- which tables to scan */ 105daffd0e5Sdrh Expr *pWhere, /* the WHERE clause */ 106daffd0e5Sdrh ExprList *pGroupBy, /* the GROUP BY clause */ 107daffd0e5Sdrh Expr *pHaving, /* the HAVING clause */ 108daffd0e5Sdrh ExprList *pOrderBy, /* the ORDER BY clause */ 109c3489bbfSdrh u32 selFlags, /* Flag parameters, such as SF_Distinct */ 110a2dc3b1aSdanielk1977 Expr *pLimit, /* LIMIT value. NULL means not used */ 111a2dc3b1aSdanielk1977 Expr *pOffset /* OFFSET value. NULL means no offset */ 1129bb61fe7Sdrh ){ 1139bb61fe7Sdrh Select *pNew; 114eda639e1Sdrh Select standin; 115ef90a6b8Sdrh pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) ); 116daffd0e5Sdrh if( pNew==0 ){ 117ef90a6b8Sdrh assert( pParse->db->mallocFailed ); 118eda639e1Sdrh pNew = &standin; 119eda639e1Sdrh } 120b733d037Sdrh if( pEList==0 ){ 121ef90a6b8Sdrh pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(pParse->db,TK_ASTERISK,0)); 122b733d037Sdrh } 1239bb61fe7Sdrh pNew->pEList = pEList; 124ca3862dcSdrh pNew->op = TK_SELECT; 125ca3862dcSdrh pNew->selFlags = selFlags; 126ca3862dcSdrh pNew->iLimit = 0; 127ca3862dcSdrh pNew->iOffset = 0; 1289ca33fa4Sdrh #if SELECTTRACE_ENABLED 1299ca33fa4Sdrh pNew->zSelName[0] = 0; 1309ca33fa4Sdrh #endif 131ca3862dcSdrh pNew->addrOpenEphm[0] = -1; 132ca3862dcSdrh pNew->addrOpenEphm[1] = -1; 133ca3862dcSdrh pNew->nSelectRow = 0; 134ef90a6b8Sdrh if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc)); 1359bb61fe7Sdrh pNew->pSrc = pSrc; 1369bb61fe7Sdrh pNew->pWhere = pWhere; 1379bb61fe7Sdrh pNew->pGroupBy = pGroupBy; 1389bb61fe7Sdrh pNew->pHaving = pHaving; 1399bb61fe7Sdrh pNew->pOrderBy = pOrderBy; 140ca3862dcSdrh pNew->pPrior = 0; 141ca3862dcSdrh pNew->pNext = 0; 142a2dc3b1aSdanielk1977 pNew->pLimit = pLimit; 143a2dc3b1aSdanielk1977 pNew->pOffset = pOffset; 144ca3862dcSdrh pNew->pWith = 0; 145ef90a6b8Sdrh assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || pParse->db->mallocFailed!=0 ); 146ef90a6b8Sdrh if( pParse->db->mallocFailed ) { 147ef90a6b8Sdrh clearSelect(pParse->db, pNew, pNew!=&standin); 148eda639e1Sdrh pNew = 0; 149a464c234Sdrh }else{ 150a464c234Sdrh assert( pNew->pSrc!=0 || pParse->nErr>0 ); 151daffd0e5Sdrh } 152338ec3e1Sdrh assert( pNew!=&standin ); 1539bb61fe7Sdrh return pNew; 1549bb61fe7Sdrh } 1559bb61fe7Sdrh 156eb9b884cSdrh #if SELECTTRACE_ENABLED 157eb9b884cSdrh /* 158eb9b884cSdrh ** Set the name of a Select object 159eb9b884cSdrh */ 160eb9b884cSdrh void sqlite3SelectSetName(Select *p, const char *zName){ 161eb9b884cSdrh if( p && zName ){ 162eb9b884cSdrh sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); 163eb9b884cSdrh } 164eb9b884cSdrh } 165eb9b884cSdrh #endif 166eb9b884cSdrh 167eb9b884cSdrh 1689bb61fe7Sdrh /* 169eda639e1Sdrh ** Delete the given Select structure and all of its substructures. 170eda639e1Sdrh */ 171633e6d57Sdrh void sqlite3SelectDelete(sqlite3 *db, Select *p){ 172f3c57ff5Sdrh if( p ) clearSelect(db, p, 1); 173eda639e1Sdrh } 174eda639e1Sdrh 175eda639e1Sdrh /* 176d227a291Sdrh ** Return a pointer to the right-most SELECT statement in a compound. 177d227a291Sdrh */ 178d227a291Sdrh static Select *findRightmost(Select *p){ 179d227a291Sdrh while( p->pNext ) p = p->pNext; 180d227a291Sdrh return p; 1819bb61fe7Sdrh } 1829bb61fe7Sdrh 1839bb61fe7Sdrh /* 184f7b5496eSdrh ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the 18501f3f253Sdrh ** type of join. Return an integer constant that expresses that type 18601f3f253Sdrh ** in terms of the following bit values: 18701f3f253Sdrh ** 18801f3f253Sdrh ** JT_INNER 1893dec223cSdrh ** JT_CROSS 19001f3f253Sdrh ** JT_OUTER 19101f3f253Sdrh ** JT_NATURAL 19201f3f253Sdrh ** JT_LEFT 19301f3f253Sdrh ** JT_RIGHT 19401f3f253Sdrh ** 19501f3f253Sdrh ** A full outer join is the combination of JT_LEFT and JT_RIGHT. 19601f3f253Sdrh ** 19701f3f253Sdrh ** If an illegal or unsupported join type is seen, then still return 19801f3f253Sdrh ** a join type, but put an error in the pParse structure. 19901f3f253Sdrh */ 2004adee20fSdanielk1977 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){ 20101f3f253Sdrh int jointype = 0; 20201f3f253Sdrh Token *apAll[3]; 20301f3f253Sdrh Token *p; 204373cc2ddSdrh /* 0123456789 123456789 123456789 123 */ 205373cc2ddSdrh static const char zKeyText[] = "naturaleftouterightfullinnercross"; 2065719628aSdrh static const struct { 207373cc2ddSdrh u8 i; /* Beginning of keyword text in zKeyText[] */ 208373cc2ddSdrh u8 nChar; /* Length of the keyword in characters */ 209373cc2ddSdrh u8 code; /* Join type mask */ 210373cc2ddSdrh } aKeyword[] = { 211373cc2ddSdrh /* natural */ { 0, 7, JT_NATURAL }, 212373cc2ddSdrh /* left */ { 6, 4, JT_LEFT|JT_OUTER }, 213373cc2ddSdrh /* outer */ { 10, 5, JT_OUTER }, 214373cc2ddSdrh /* right */ { 14, 5, JT_RIGHT|JT_OUTER }, 215373cc2ddSdrh /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER }, 216373cc2ddSdrh /* inner */ { 23, 5, JT_INNER }, 217373cc2ddSdrh /* cross */ { 28, 5, JT_INNER|JT_CROSS }, 21801f3f253Sdrh }; 21901f3f253Sdrh int i, j; 22001f3f253Sdrh apAll[0] = pA; 22101f3f253Sdrh apAll[1] = pB; 22201f3f253Sdrh apAll[2] = pC; 223195e6967Sdrh for(i=0; i<3 && apAll[i]; i++){ 22401f3f253Sdrh p = apAll[i]; 225373cc2ddSdrh for(j=0; j<ArraySize(aKeyword); j++){ 226373cc2ddSdrh if( p->n==aKeyword[j].nChar 227373cc2ddSdrh && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){ 228373cc2ddSdrh jointype |= aKeyword[j].code; 22901f3f253Sdrh break; 23001f3f253Sdrh } 23101f3f253Sdrh } 232373cc2ddSdrh testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 ); 233373cc2ddSdrh if( j>=ArraySize(aKeyword) ){ 23401f3f253Sdrh jointype |= JT_ERROR; 23501f3f253Sdrh break; 23601f3f253Sdrh } 23701f3f253Sdrh } 238ad2d8307Sdrh if( 239ad2d8307Sdrh (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || 240195e6967Sdrh (jointype & JT_ERROR)!=0 241ad2d8307Sdrh ){ 242a9671a22Sdrh const char *zSp = " "; 243a9671a22Sdrh assert( pB!=0 ); 244a9671a22Sdrh if( pC==0 ){ zSp++; } 245ae29ffbeSdrh sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " 246a9671a22Sdrh "%T %T%s%T", pA, pB, zSp, pC); 24701f3f253Sdrh jointype = JT_INNER; 248373cc2ddSdrh }else if( (jointype & JT_OUTER)!=0 249373cc2ddSdrh && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){ 2504adee20fSdanielk1977 sqlite3ErrorMsg(pParse, 251da93d238Sdrh "RIGHT and FULL OUTER JOINs are not currently supported"); 252195e6967Sdrh jointype = JT_INNER; 25301f3f253Sdrh } 25401f3f253Sdrh return jointype; 25501f3f253Sdrh } 25601f3f253Sdrh 25701f3f253Sdrh /* 258ad2d8307Sdrh ** Return the index of a column in a table. Return -1 if the column 259ad2d8307Sdrh ** is not contained in the table. 260ad2d8307Sdrh */ 261ad2d8307Sdrh static int columnIndex(Table *pTab, const char *zCol){ 262ad2d8307Sdrh int i; 263ad2d8307Sdrh for(i=0; i<pTab->nCol; i++){ 2644adee20fSdanielk1977 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; 265ad2d8307Sdrh } 266ad2d8307Sdrh return -1; 267ad2d8307Sdrh } 268ad2d8307Sdrh 269ad2d8307Sdrh /* 2702179b434Sdrh ** Search the first N tables in pSrc, from left to right, looking for a 2712179b434Sdrh ** table that has a column named zCol. 2722179b434Sdrh ** 2732179b434Sdrh ** When found, set *piTab and *piCol to the table index and column index 2742179b434Sdrh ** of the matching column and return TRUE. 2752179b434Sdrh ** 2762179b434Sdrh ** If not found, return FALSE. 2772179b434Sdrh */ 2782179b434Sdrh static int tableAndColumnIndex( 2792179b434Sdrh SrcList *pSrc, /* Array of tables to search */ 2802179b434Sdrh int N, /* Number of tables in pSrc->a[] to search */ 2812179b434Sdrh const char *zCol, /* Name of the column we are looking for */ 2822179b434Sdrh int *piTab, /* Write index of pSrc->a[] here */ 2832179b434Sdrh int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */ 2842179b434Sdrh ){ 2852179b434Sdrh int i; /* For looping over tables in pSrc */ 2862179b434Sdrh int iCol; /* Index of column matching zCol */ 2872179b434Sdrh 2882179b434Sdrh assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */ 2892179b434Sdrh for(i=0; i<N; i++){ 2902179b434Sdrh iCol = columnIndex(pSrc->a[i].pTab, zCol); 2912179b434Sdrh if( iCol>=0 ){ 2922179b434Sdrh if( piTab ){ 2932179b434Sdrh *piTab = i; 2942179b434Sdrh *piCol = iCol; 2952179b434Sdrh } 2962179b434Sdrh return 1; 2972179b434Sdrh } 2982179b434Sdrh } 2992179b434Sdrh return 0; 3002179b434Sdrh } 3012179b434Sdrh 3022179b434Sdrh /* 303f7b0b0adSdan ** This function is used to add terms implied by JOIN syntax to the 304f7b0b0adSdan ** WHERE clause expression of a SELECT statement. The new term, which 305f7b0b0adSdan ** is ANDed with the existing WHERE clause, is of the form: 306f7b0b0adSdan ** 307f7b0b0adSdan ** (tab1.col1 = tab2.col2) 308f7b0b0adSdan ** 309f7b0b0adSdan ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 310f7b0b0adSdan ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is 311f7b0b0adSdan ** column iColRight of tab2. 312ad2d8307Sdrh */ 313ad2d8307Sdrh static void addWhereTerm( 31417435752Sdrh Parse *pParse, /* Parsing context */ 315f7b0b0adSdan SrcList *pSrc, /* List of tables in FROM clause */ 3162179b434Sdrh int iLeft, /* Index of first table to join in pSrc */ 317f7b0b0adSdan int iColLeft, /* Index of column in first table */ 3182179b434Sdrh int iRight, /* Index of second table in pSrc */ 319f7b0b0adSdan int iColRight, /* Index of column in second table */ 320f7b0b0adSdan int isOuterJoin, /* True if this is an OUTER join */ 321f7b0b0adSdan Expr **ppWhere /* IN/OUT: The WHERE clause to add to */ 322ad2d8307Sdrh ){ 323f7b0b0adSdan sqlite3 *db = pParse->db; 324f7b0b0adSdan Expr *pE1; 325f7b0b0adSdan Expr *pE2; 326f7b0b0adSdan Expr *pEq; 327ad2d8307Sdrh 3282179b434Sdrh assert( iLeft<iRight ); 3292179b434Sdrh assert( pSrc->nSrc>iRight ); 3302179b434Sdrh assert( pSrc->a[iLeft].pTab ); 3312179b434Sdrh assert( pSrc->a[iRight].pTab ); 332f7b0b0adSdan 3332179b434Sdrh pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft); 3342179b434Sdrh pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight); 335f7b0b0adSdan 336abfd35eaSdrh pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2); 337f7b0b0adSdan if( pEq && isOuterJoin ){ 338f7b0b0adSdan ExprSetProperty(pEq, EP_FromJoin); 339c5cd1249Sdrh assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) ); 340ebb6a65dSdrh ExprSetVVAProperty(pEq, EP_NoReduce); 341f7b0b0adSdan pEq->iRightJoinTable = (i16)pE2->iTable; 342030530deSdrh } 343f7b0b0adSdan *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq); 344ad2d8307Sdrh } 345ad2d8307Sdrh 346ad2d8307Sdrh /* 3471f16230bSdrh ** Set the EP_FromJoin property on all terms of the given expression. 34822d6a53aSdrh ** And set the Expr.iRightJoinTable to iTable for every term in the 34922d6a53aSdrh ** expression. 3501cc093c2Sdrh ** 351e78e8284Sdrh ** The EP_FromJoin property is used on terms of an expression to tell 3521cc093c2Sdrh ** the LEFT OUTER JOIN processing logic that this term is part of the 3531f16230bSdrh ** join restriction specified in the ON or USING clause and not a part 3541f16230bSdrh ** of the more general WHERE clause. These terms are moved over to the 3551f16230bSdrh ** WHERE clause during join processing but we need to remember that they 3561f16230bSdrh ** originated in the ON or USING clause. 35722d6a53aSdrh ** 35822d6a53aSdrh ** The Expr.iRightJoinTable tells the WHERE clause processing that the 35922d6a53aSdrh ** expression depends on table iRightJoinTable even if that table is not 36022d6a53aSdrh ** explicitly mentioned in the expression. That information is needed 36122d6a53aSdrh ** for cases like this: 36222d6a53aSdrh ** 36322d6a53aSdrh ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 36422d6a53aSdrh ** 36522d6a53aSdrh ** The where clause needs to defer the handling of the t1.x=5 36622d6a53aSdrh ** term until after the t2 loop of the join. In that way, a 36722d6a53aSdrh ** NULL t2 row will be inserted whenever t1.x!=5. If we do not 36822d6a53aSdrh ** defer the handling of t1.x=5, it will be processed immediately 36922d6a53aSdrh ** after the t1 loop and rows with t1.x!=5 will never appear in 37022d6a53aSdrh ** the output, which is incorrect. 3711cc093c2Sdrh */ 37222d6a53aSdrh static void setJoinExpr(Expr *p, int iTable){ 3731cc093c2Sdrh while( p ){ 3741f16230bSdrh ExprSetProperty(p, EP_FromJoin); 375c5cd1249Sdrh assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 376ebb6a65dSdrh ExprSetVVAProperty(p, EP_NoReduce); 377cf697396Sshane p->iRightJoinTable = (i16)iTable; 378606f2344Sdrh if( p->op==TK_FUNCTION && p->x.pList ){ 379606f2344Sdrh int i; 380606f2344Sdrh for(i=0; i<p->x.pList->nExpr; i++){ 381606f2344Sdrh setJoinExpr(p->x.pList->a[i].pExpr, iTable); 382606f2344Sdrh } 383606f2344Sdrh } 38422d6a53aSdrh setJoinExpr(p->pLeft, iTable); 3851cc093c2Sdrh p = p->pRight; 3861cc093c2Sdrh } 3871cc093c2Sdrh } 3881cc093c2Sdrh 3891cc093c2Sdrh /* 390ad2d8307Sdrh ** This routine processes the join information for a SELECT statement. 391ad2d8307Sdrh ** ON and USING clauses are converted into extra terms of the WHERE clause. 392ad2d8307Sdrh ** NATURAL joins also create extra WHERE clause terms. 393ad2d8307Sdrh ** 39491bb0eedSdrh ** The terms of a FROM clause are contained in the Select.pSrc structure. 39591bb0eedSdrh ** The left most table is the first entry in Select.pSrc. The right-most 39691bb0eedSdrh ** table is the last entry. The join operator is held in the entry to 39791bb0eedSdrh ** the left. Thus entry 0 contains the join operator for the join between 39891bb0eedSdrh ** entries 0 and 1. Any ON or USING clauses associated with the join are 39991bb0eedSdrh ** also attached to the left entry. 40091bb0eedSdrh ** 401ad2d8307Sdrh ** This routine returns the number of errors encountered. 402ad2d8307Sdrh */ 403ad2d8307Sdrh static int sqliteProcessJoin(Parse *pParse, Select *p){ 40491bb0eedSdrh SrcList *pSrc; /* All tables in the FROM clause */ 40591bb0eedSdrh int i, j; /* Loop counters */ 40691bb0eedSdrh struct SrcList_item *pLeft; /* Left table being joined */ 40791bb0eedSdrh struct SrcList_item *pRight; /* Right table being joined */ 408ad2d8307Sdrh 40991bb0eedSdrh pSrc = p->pSrc; 41091bb0eedSdrh pLeft = &pSrc->a[0]; 41191bb0eedSdrh pRight = &pLeft[1]; 41291bb0eedSdrh for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){ 41391bb0eedSdrh Table *pLeftTab = pLeft->pTab; 41491bb0eedSdrh Table *pRightTab = pRight->pTab; 415ad27e761Sdrh int isOuter; 41691bb0eedSdrh 4171c767f0dSdrh if( NEVER(pLeftTab==0 || pRightTab==0) ) continue; 4188a48b9c0Sdrh isOuter = (pRight->fg.jointype & JT_OUTER)!=0; 419ad2d8307Sdrh 420ad2d8307Sdrh /* When the NATURAL keyword is present, add WHERE clause terms for 421ad2d8307Sdrh ** every column that the two tables have in common. 422ad2d8307Sdrh */ 4238a48b9c0Sdrh if( pRight->fg.jointype & JT_NATURAL ){ 42461dfc31dSdrh if( pRight->pOn || pRight->pUsing ){ 4254adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "a NATURAL join may not have " 426ad2d8307Sdrh "an ON or USING clause", 0); 427ad2d8307Sdrh return 1; 428ad2d8307Sdrh } 4292179b434Sdrh for(j=0; j<pRightTab->nCol; j++){ 4302179b434Sdrh char *zName; /* Name of column in the right table */ 4312179b434Sdrh int iLeft; /* Matching left table */ 4322179b434Sdrh int iLeftCol; /* Matching column in the left table */ 4332179b434Sdrh 4342179b434Sdrh zName = pRightTab->aCol[j].zName; 4352179b434Sdrh if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ 4362179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j, 4372179b434Sdrh isOuter, &p->pWhere); 438ad2d8307Sdrh } 439ad2d8307Sdrh } 440ad2d8307Sdrh } 441ad2d8307Sdrh 442ad2d8307Sdrh /* Disallow both ON and USING clauses in the same join 443ad2d8307Sdrh */ 44461dfc31dSdrh if( pRight->pOn && pRight->pUsing ){ 4454adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot have both ON and USING " 446da93d238Sdrh "clauses in the same join"); 447ad2d8307Sdrh return 1; 448ad2d8307Sdrh } 449ad2d8307Sdrh 450ad2d8307Sdrh /* Add the ON clause to the end of the WHERE clause, connected by 45191bb0eedSdrh ** an AND operator. 452ad2d8307Sdrh */ 45361dfc31dSdrh if( pRight->pOn ){ 454ad27e761Sdrh if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); 45517435752Sdrh p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); 45661dfc31dSdrh pRight->pOn = 0; 457ad2d8307Sdrh } 458ad2d8307Sdrh 459ad2d8307Sdrh /* Create extra terms on the WHERE clause for each column named 460ad2d8307Sdrh ** in the USING clause. Example: If the two tables to be joined are 461ad2d8307Sdrh ** A and B and the USING clause names X, Y, and Z, then add this 462ad2d8307Sdrh ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z 463ad2d8307Sdrh ** Report an error if any column mentioned in the USING clause is 464ad2d8307Sdrh ** not contained in both tables to be joined. 465ad2d8307Sdrh */ 46661dfc31dSdrh if( pRight->pUsing ){ 46761dfc31dSdrh IdList *pList = pRight->pUsing; 468ad2d8307Sdrh for(j=0; j<pList->nId; j++){ 4692179b434Sdrh char *zName; /* Name of the term in the USING clause */ 4702179b434Sdrh int iLeft; /* Table on the left with matching column name */ 4712179b434Sdrh int iLeftCol; /* Column number of matching column on the left */ 4722179b434Sdrh int iRightCol; /* Column number of matching column on the right */ 4732179b434Sdrh 4742179b434Sdrh zName = pList->a[j].zName; 4752179b434Sdrh iRightCol = columnIndex(pRightTab, zName); 4762179b434Sdrh if( iRightCol<0 4772179b434Sdrh || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) 4782179b434Sdrh ){ 4794adee20fSdanielk1977 sqlite3ErrorMsg(pParse, "cannot join using column %s - column " 48091bb0eedSdrh "not present in both tables", zName); 481ad2d8307Sdrh return 1; 482ad2d8307Sdrh } 4832179b434Sdrh addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol, 4842179b434Sdrh isOuter, &p->pWhere); 485ad2d8307Sdrh } 486ad2d8307Sdrh } 487ad2d8307Sdrh } 488ad2d8307Sdrh return 0; 489ad2d8307Sdrh } 490ad2d8307Sdrh 491079a3072Sdrh /* Forward reference */ 492079a3072Sdrh static KeyInfo *keyInfoFromExprList( 493079a3072Sdrh Parse *pParse, /* Parsing context */ 494079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 495079a3072Sdrh int iStart, /* Begin with this column of pList */ 496079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 497079a3072Sdrh ); 498079a3072Sdrh 499ad2d8307Sdrh /* 500f45f2326Sdrh ** Generate code that will push the record in registers regData 501f45f2326Sdrh ** through regData+nData-1 onto the sorter. 502c926afbcSdrh */ 503d59ba6ceSdrh static void pushOntoSorter( 504d59ba6ceSdrh Parse *pParse, /* Parser context */ 505079a3072Sdrh SortCtx *pSort, /* Information about the ORDER BY clause */ 506b7654111Sdrh Select *pSelect, /* The whole SELECT statement */ 507f45f2326Sdrh int regData, /* First register holding data to be sorted */ 5085579d59fSdrh int regOrigData, /* First register holding data before packing */ 509fd0a2f97Sdrh int nData, /* Number of elements in the data array */ 510fd0a2f97Sdrh int nPrefixReg /* No. of reg prior to regData available for use */ 511d59ba6ceSdrh ){ 512f45f2326Sdrh Vdbe *v = pParse->pVdbe; /* Stmt under construction */ 51378d58432Sdan int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0); 514f45f2326Sdrh int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */ 51578d58432Sdan int nBase = nExpr + bSeq + nData; /* Fields in sorter record */ 516fd0a2f97Sdrh int regBase; /* Regs for sorter record */ 517fb0d6e56Sdrh int regRecord = ++pParse->nMem; /* Assembled sorter record */ 51878d58432Sdan int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */ 519f45f2326Sdrh int op; /* Opcode to add sorter record to sorter */ 520a04a8be2Sdrh int iLimit; /* LIMIT counter */ 521f45f2326Sdrh 52278d58432Sdan assert( bSeq==0 || bSeq==1 ); 5239af90b72Sdan assert( nData==1 || regData==regOrigData || regOrigData==0 ); 524fd0a2f97Sdrh if( nPrefixReg ){ 52578d58432Sdan assert( nPrefixReg==nExpr+bSeq ); 52678d58432Sdan regBase = regData - nExpr - bSeq; 527fd0a2f97Sdrh }else{ 528fb0d6e56Sdrh regBase = pParse->nMem + 1; 529fb0d6e56Sdrh pParse->nMem += nBase; 530fd0a2f97Sdrh } 531a04a8be2Sdrh assert( pSelect->iOffset==0 || pSelect->iLimit!=0 ); 532a04a8be2Sdrh iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit; 533a04a8be2Sdrh pSort->labelDone = sqlite3VdbeMakeLabel(v); 5345579d59fSdrh sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData, 5359af90b72Sdan SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0)); 53678d58432Sdan if( bSeq ){ 537079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr); 538fd0a2f97Sdrh } 539257c13faSdan if( nPrefixReg==0 && nData>0 ){ 540236241aeSdrh sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData); 54178d58432Sdan } 542f45f2326Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); 543079a3072Sdrh if( nOBSat>0 ){ 544079a3072Sdrh int regPrevKey; /* The first nOBSat columns of the previous row */ 545079a3072Sdrh int addrFirst; /* Address of the OP_IfNot opcode */ 546079a3072Sdrh int addrJmp; /* Address of the OP_Jump opcode */ 547079a3072Sdrh VdbeOp *pOp; /* Opcode that opens the sorter */ 548079a3072Sdrh int nKey; /* Number of sorting key columns, including OP_Sequence */ 549dbfca2b7Sdrh KeyInfo *pKI; /* Original KeyInfo on the sorter table */ 550079a3072Sdrh 55126d7e7c6Sdrh regPrevKey = pParse->nMem+1; 55226d7e7c6Sdrh pParse->nMem += pSort->nOBSat; 55378d58432Sdan nKey = nExpr - pSort->nOBSat + bSeq; 55478d58432Sdan if( bSeq ){ 55578d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 55678d58432Sdan }else{ 55778d58432Sdan addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor); 55878d58432Sdan } 55978d58432Sdan VdbeCoverage(v); 56026d7e7c6Sdrh sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat); 561079a3072Sdrh pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex); 56259b8f2e1Sdrh if( pParse->db->mallocFailed ) return; 563fb0d6e56Sdrh pOp->p2 = nKey + nData; 564dbfca2b7Sdrh pKI = pOp->p4.pKeyInfo; 565dbfca2b7Sdrh memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */ 566dbfca2b7Sdrh sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); 567fe201effSdrh testcase( pKI->nXField>2 ); 568fe201effSdrh pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 569fe201effSdrh pKI->nXField-1); 570079a3072Sdrh addrJmp = sqlite3VdbeCurrentAddr(v); 571079a3072Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); 572079a3072Sdrh pSort->labelBkOut = sqlite3VdbeMakeLabel(v); 573079a3072Sdrh pSort->regReturn = ++pParse->nMem; 574079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 57565ea12cbSdrh sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor); 576a04a8be2Sdrh if( iLimit ){ 577a04a8be2Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone); 578a04a8be2Sdrh VdbeCoverage(v); 579a04a8be2Sdrh } 580079a3072Sdrh sqlite3VdbeJumpHere(v, addrFirst); 581236241aeSdrh sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat); 582079a3072Sdrh sqlite3VdbeJumpHere(v, addrJmp); 583079a3072Sdrh } 584079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 585c6aff30cSdrh op = OP_SorterInsert; 586c6aff30cSdrh }else{ 587c6aff30cSdrh op = OP_IdxInsert; 588c6aff30cSdrh } 5894a8b013eSdrh sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, 5904a8b013eSdrh regBase+nOBSat, nBase-nOBSat); 591a04a8be2Sdrh if( iLimit ){ 59216897072Sdrh int addr; 593a536df4eSdrh int r1 = 0; 594a536df4eSdrh /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit 595a536df4eSdrh ** register is initialized with value of LIMIT+OFFSET.) After the sorter 596a536df4eSdrh ** fills up, delete the least entry in the sorter after each insert. 597a536df4eSdrh ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */ 598f99dd359Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v); 599079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); 600a536df4eSdrh if( pSort->bOrderedInnerLoop ){ 601a536df4eSdrh r1 = ++pParse->nMem; 602a536df4eSdrh sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1); 603a536df4eSdrh VdbeComment((v, "seq")); 604a536df4eSdrh } 605079a3072Sdrh sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); 606a536df4eSdrh if( pSort->bOrderedInnerLoop ){ 607a536df4eSdrh /* If the inner loop is driven by an index such that values from 608a536df4eSdrh ** the same iteration of the inner loop are in sorted order, then 609a536df4eSdrh ** immediately jump to the next iteration of an inner loop if the 610a536df4eSdrh ** entry from the current iteration does not fit into the top 611a536df4eSdrh ** LIMIT+OFFSET entries of the sorter. */ 612a536df4eSdrh int iBrk = sqlite3VdbeCurrentAddr(v) + 2; 613a536df4eSdrh sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1); 6146326d9f6Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 615a536df4eSdrh VdbeCoverage(v); 616a536df4eSdrh } 61716897072Sdrh sqlite3VdbeJumpHere(v, addr); 618d59ba6ceSdrh } 619c926afbcSdrh } 620c926afbcSdrh 621c926afbcSdrh /* 622ec7429aeSdrh ** Add code to implement the OFFSET 623ea48eb2eSdrh */ 624ec7429aeSdrh static void codeOffset( 625bab39e13Sdrh Vdbe *v, /* Generate code into this VM */ 626aa9ce707Sdrh int iOffset, /* Register holding the offset counter */ 627b7654111Sdrh int iContinue /* Jump here to skip the current record */ 628ea48eb2eSdrh ){ 629a22a75e5Sdrh if( iOffset>0 ){ 6308b0cf38aSdrh sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v); 6318b0cf38aSdrh VdbeComment((v, "OFFSET")); 632ea48eb2eSdrh } 633ea48eb2eSdrh } 634ea48eb2eSdrh 635ea48eb2eSdrh /* 63698757157Sdrh ** Add code that will check to make sure the N registers starting at iMem 63798757157Sdrh ** form a distinct entry. iTab is a sorting index that holds previously 638a2a49dc9Sdrh ** seen combinations of the N values. A new entry is made in iTab 639a2a49dc9Sdrh ** if the current N values are new. 640a2a49dc9Sdrh ** 641a2a49dc9Sdrh ** A jump to addrRepeat is made and the N+1 values are popped from the 642a2a49dc9Sdrh ** stack if the top N elements are not distinct. 643a2a49dc9Sdrh */ 644a2a49dc9Sdrh static void codeDistinct( 6452dcef11bSdrh Parse *pParse, /* Parsing and code generating context */ 646a2a49dc9Sdrh int iTab, /* A sorting index used to test for distinctness */ 647a2a49dc9Sdrh int addrRepeat, /* Jump to here if not distinct */ 648477df4b3Sdrh int N, /* Number of elements */ 649a2a49dc9Sdrh int iMem /* First element */ 650a2a49dc9Sdrh ){ 6512dcef11bSdrh Vdbe *v; 6522dcef11bSdrh int r1; 6532dcef11bSdrh 6542dcef11bSdrh v = pParse->pVdbe; 6552dcef11bSdrh r1 = sqlite3GetTempReg(pParse); 656688852abSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v); 6571db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); 6589b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N); 659a67b5cb6Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 6602dcef11bSdrh sqlite3ReleaseTempReg(pParse, r1); 661a2a49dc9Sdrh } 662a2a49dc9Sdrh 663c99130fdSdrh /* 6642282792aSdrh ** This routine generates the code for the inside of the inner loop 6652282792aSdrh ** of a SELECT. 66682c3d636Sdrh ** 667340309fdSdrh ** If srcTab is negative, then the pEList expressions 668340309fdSdrh ** are evaluated in order to get the data for this row. If srcTab is 669340309fdSdrh ** zero or more, then data is pulled from srcTab and pEList is used only 670257c13faSdan ** to get the number of columns and the collation sequence for each column. 6712282792aSdrh */ 672d2b3e23bSdrh static void selectInnerLoop( 6732282792aSdrh Parse *pParse, /* The parser context */ 674df199a25Sdrh Select *p, /* The complete select statement being coded */ 6752282792aSdrh ExprList *pEList, /* List of values being extracted */ 67682c3d636Sdrh int srcTab, /* Pull data from this table */ 677079a3072Sdrh SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */ 678e8e4af76Sdrh DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */ 6796c8c8ce0Sdanielk1977 SelectDest *pDest, /* How to dispose of the results */ 6802282792aSdrh int iContinue, /* Jump here to continue with next row */ 681a9671a22Sdrh int iBreak /* Jump here to break out of the inner loop */ 6822282792aSdrh ){ 6832282792aSdrh Vdbe *v = pParse->pVdbe; 684d847eaadSdrh int i; 685ea48eb2eSdrh int hasDistinct; /* True if the DISTINCT keyword is present */ 686d847eaadSdrh int eDest = pDest->eDest; /* How to dispose of results */ 6872b596da8Sdrh int iParm = pDest->iSDParm; /* First argument to disposal method */ 688d847eaadSdrh int nResultCol; /* Number of result columns */ 689fd0a2f97Sdrh int nPrefixReg = 0; /* Number of extra registers before regResult */ 69038640e15Sdrh 6919af90b72Sdan /* Usually, regResult is the first cell in an array of memory cells 6929af90b72Sdan ** containing the current result row. In this case regOrig is set to the 6939af90b72Sdan ** same value. However, if the results are being sent to the sorter, the 6949af90b72Sdan ** values for any expressions that are also part of the sort-key are omitted 6959af90b72Sdan ** from this array. In this case regOrig is set to zero. */ 6969af90b72Sdan int regResult; /* Start of memory holding current results */ 6979af90b72Sdan int regOrig; /* Start of memory holding full result (or 0) */ 6989af90b72Sdan 6991c767f0dSdrh assert( v ); 70038640e15Sdrh assert( pEList!=0 ); 701e8e4af76Sdrh hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP; 702079a3072Sdrh if( pSort && pSort->pOrderBy==0 ) pSort = 0; 703079a3072Sdrh if( pSort==0 && !hasDistinct ){ 704a22a75e5Sdrh assert( iContinue!=0 ); 705aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 706df199a25Sdrh } 707df199a25Sdrh 708967e8b73Sdrh /* Pull the requested columns. 7092282792aSdrh */ 710d847eaadSdrh nResultCol = pEList->nExpr; 71105a86c5cSdrh 7122b596da8Sdrh if( pDest->iSdst==0 ){ 713fd0a2f97Sdrh if( pSort ){ 71478d58432Sdan nPrefixReg = pSort->pOrderBy->nExpr; 71578d58432Sdan if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++; 716fd0a2f97Sdrh pParse->nMem += nPrefixReg; 7171013c932Sdrh } 718a2a49dc9Sdrh pDest->iSdst = pParse->nMem+1; 719477df4b3Sdrh pParse->nMem += nResultCol; 72005a86c5cSdrh }else if( pDest->iSdst+nResultCol > pParse->nMem ){ 72105a86c5cSdrh /* This is an error condition that can result, for example, when a SELECT 72205a86c5cSdrh ** on the right-hand side of an INSERT contains more result columns than 72305a86c5cSdrh ** there are columns in the table on the left. The error will be caught 72405a86c5cSdrh ** and reported later. But we need to make sure enough memory is allocated 72505a86c5cSdrh ** to avoid other spurious errors in the meantime. */ 72605a86c5cSdrh pParse->nMem += nResultCol; 7274c583128Sdrh } 72805a86c5cSdrh pDest->nSdst = nResultCol; 7299af90b72Sdan regOrig = regResult = pDest->iSdst; 730340309fdSdrh if( srcTab>=0 ){ 731340309fdSdrh for(i=0; i<nResultCol; i++){ 732d847eaadSdrh sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); 733340309fdSdrh VdbeComment((v, "%s", pEList->a[i].zName)); 73482c3d636Sdrh } 7359ed1dfa8Sdanielk1977 }else if( eDest!=SRT_Exists ){ 7369ed1dfa8Sdanielk1977 /* If the destination is an EXISTS(...) expression, the actual 7379ed1dfa8Sdanielk1977 ** values returned by the SELECT are not required. 7389ed1dfa8Sdanielk1977 */ 739df553659Sdrh u8 ecelFlags; 740df553659Sdrh if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){ 741df553659Sdrh ecelFlags = SQLITE_ECEL_DUP; 742df553659Sdrh }else{ 743df553659Sdrh ecelFlags = 0; 744a2a49dc9Sdrh } 745ac56ab7eSdan if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){ 746257c13faSdan /* For each expression in pEList that is a copy of an expression in 747257c13faSdan ** the ORDER BY clause (pSort->pOrderBy), set the associated 748257c13faSdan ** iOrderByCol value to one more than the index of the ORDER BY 749257c13faSdan ** expression within the sort-key that pushOntoSorter() will generate. 750257c13faSdan ** This allows the pEList field to be omitted from the sorted record, 751257c13faSdan ** saving space and CPU cycles. */ 752257c13faSdan ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF); 753257c13faSdan for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){ 754257c13faSdan int j; 755257c13faSdan if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){ 756257c13faSdan pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat; 757257c13faSdan } 758257c13faSdan } 7599af90b72Sdan regOrig = 0; 760257c13faSdan assert( eDest==SRT_Set || eDest==SRT_Mem 761257c13faSdan || eDest==SRT_Coroutine || eDest==SRT_Output ); 762257c13faSdan } 763257c13faSdan nResultCol = sqlite3ExprCodeExprList(pParse,pEList,regResult,0,ecelFlags); 764a2a49dc9Sdrh } 7652282792aSdrh 766daffd0e5Sdrh /* If the DISTINCT keyword was present on the SELECT statement 767daffd0e5Sdrh ** and this row has been seen before, then do not make this row 768daffd0e5Sdrh ** part of the result. 7692282792aSdrh */ 770ea48eb2eSdrh if( hasDistinct ){ 771e8e4af76Sdrh switch( pDistinct->eTnctType ){ 772e8e4af76Sdrh case WHERE_DISTINCT_ORDERED: { 773e8e4af76Sdrh VdbeOp *pOp; /* No longer required OpenEphemeral instr. */ 774e8e4af76Sdrh int iJump; /* Jump destination */ 775e8e4af76Sdrh int regPrev; /* Previous row content */ 776e8e4af76Sdrh 777e8e4af76Sdrh /* Allocate space for the previous row */ 778e8e4af76Sdrh regPrev = pParse->nMem+1; 779340309fdSdrh pParse->nMem += nResultCol; 780e8e4af76Sdrh 781e8e4af76Sdrh /* Change the OP_OpenEphemeral coded earlier to an OP_Null 782e8e4af76Sdrh ** sets the MEM_Cleared bit on the first register of the 783e8e4af76Sdrh ** previous value. This will cause the OP_Ne below to always 784e8e4af76Sdrh ** fail on the first iteration of the loop even if the first 785e8e4af76Sdrh ** row is all NULLs. 786e8e4af76Sdrh */ 787e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 788e8e4af76Sdrh pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct); 789e8e4af76Sdrh pOp->opcode = OP_Null; 790e8e4af76Sdrh pOp->p1 = 1; 791e8e4af76Sdrh pOp->p2 = regPrev; 792e8e4af76Sdrh 793340309fdSdrh iJump = sqlite3VdbeCurrentAddr(v) + nResultCol; 794340309fdSdrh for(i=0; i<nResultCol; i++){ 795e8e4af76Sdrh CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr); 796340309fdSdrh if( i<nResultCol-1 ){ 797e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i); 798688852abSdrh VdbeCoverage(v); 799e8e4af76Sdrh }else{ 800e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i); 801688852abSdrh VdbeCoverage(v); 802e8e4af76Sdrh } 803e8e4af76Sdrh sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ); 804e8e4af76Sdrh sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); 805e8e4af76Sdrh } 806fcf2a775Sdrh assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed ); 807340309fdSdrh sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1); 808e8e4af76Sdrh break; 809e8e4af76Sdrh } 810e8e4af76Sdrh 811e8e4af76Sdrh case WHERE_DISTINCT_UNIQUE: { 812e8e4af76Sdrh sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct); 813e8e4af76Sdrh break; 814e8e4af76Sdrh } 815e8e4af76Sdrh 816e8e4af76Sdrh default: { 817e8e4af76Sdrh assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED ); 81838b4149cSdrh codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, 81938b4149cSdrh regResult); 820e8e4af76Sdrh break; 821e8e4af76Sdrh } 822e8e4af76Sdrh } 823079a3072Sdrh if( pSort==0 ){ 824aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 825ea48eb2eSdrh } 8262282792aSdrh } 82782c3d636Sdrh 828c926afbcSdrh switch( eDest ){ 82982c3d636Sdrh /* In this mode, write each query result to the key of the temporary 83082c3d636Sdrh ** table iParm. 8312282792aSdrh */ 83213449892Sdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 833c926afbcSdrh case SRT_Union: { 8349cbf3425Sdrh int r1; 8359cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 836340309fdSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1); 8379b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 8389cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 839c926afbcSdrh break; 840c926afbcSdrh } 84182c3d636Sdrh 84282c3d636Sdrh /* Construct a record from the query result, but instead of 84382c3d636Sdrh ** saving that record, use it as a key to delete elements from 84482c3d636Sdrh ** the temporary table iParm. 84582c3d636Sdrh */ 846c926afbcSdrh case SRT_Except: { 847340309fdSdrh sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol); 848c926afbcSdrh break; 849c926afbcSdrh } 850781def29Sdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 8515338a5f7Sdanielk1977 8525338a5f7Sdanielk1977 /* Store the result as data using a unique key. 8535338a5f7Sdanielk1977 */ 8548e1ee88cSdrh case SRT_Fifo: 8558e1ee88cSdrh case SRT_DistFifo: 8565338a5f7Sdanielk1977 case SRT_Table: 857b9bb7c18Sdrh case SRT_EphemTab: { 858fd0a2f97Sdrh int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1); 859373cc2ddSdrh testcase( eDest==SRT_Table ); 860373cc2ddSdrh testcase( eDest==SRT_EphemTab ); 861e2248cfdSdrh testcase( eDest==SRT_Fifo ); 862e2248cfdSdrh testcase( eDest==SRT_DistFifo ); 863fd0a2f97Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg); 8648ce7184bSdan #ifndef SQLITE_OMIT_CTE 8658e1ee88cSdrh if( eDest==SRT_DistFifo ){ 8668e1ee88cSdrh /* If the destination is DistFifo, then cursor (iParm+1) is open 8678ce7184bSdan ** on an ephemeral index. If the current row is already present 8688ce7184bSdan ** in the index, do not write it to the output. If not, add the 8698ce7184bSdan ** current row to the index and proceed with writing it to the 8708ce7184bSdan ** output table as well. */ 8718ce7184bSdan int addr = sqlite3VdbeCurrentAddr(v) + 4; 87238b4149cSdrh sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); 87338b4149cSdrh VdbeCoverage(v); 8749b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol); 875079a3072Sdrh assert( pSort==0 ); 8768ce7184bSdan } 8778ce7184bSdan #endif 878079a3072Sdrh if( pSort ){ 8795579d59fSdrh pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg); 8805338a5f7Sdanielk1977 }else{ 881b7654111Sdrh int r2 = sqlite3GetTempReg(pParse); 882b7654111Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); 883b7654111Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); 884b7654111Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 885b7654111Sdrh sqlite3ReleaseTempReg(pParse, r2); 8865338a5f7Sdanielk1977 } 887fd0a2f97Sdrh sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1); 8885338a5f7Sdanielk1977 break; 8895338a5f7Sdanielk1977 } 8902282792aSdrh 89193758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 8922282792aSdrh /* If we are creating a set for an "expr IN (SELECT ...)" construct, 8932282792aSdrh ** then there should be a single item on the stack. Write this 8942282792aSdrh ** item into the set table with bogus data. 8952282792aSdrh */ 896c926afbcSdrh case SRT_Set: { 897079a3072Sdrh if( pSort ){ 898de941c60Sdrh /* At first glance you would think we could optimize out the 899de941c60Sdrh ** ORDER BY in this case since the order of entries in the set 900de941c60Sdrh ** does not matter. But there might be a LIMIT clause, in which 901de941c60Sdrh ** case the order does matter */ 90251d82d1dSdan pushOntoSorter( 9039af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 904c926afbcSdrh }else{ 905b7654111Sdrh int r1 = sqlite3GetTempReg(pParse); 90671c57db0Sdan assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol ); 90771c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 908553168c7Sdan r1, pDest->zAffSdst, nResultCol); 90971c57db0Sdan sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 9109b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol); 911b7654111Sdrh sqlite3ReleaseTempReg(pParse, r1); 912c926afbcSdrh } 913c926afbcSdrh break; 914c926afbcSdrh } 91582c3d636Sdrh 916504b6989Sdrh /* If any row exist in the result set, record that fact and abort. 917ec7429aeSdrh */ 918ec7429aeSdrh case SRT_Exists: { 9194c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); 920ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 921ec7429aeSdrh break; 922ec7429aeSdrh } 923ec7429aeSdrh 9242282792aSdrh /* If this is a scalar select that is part of an expression, then 925870a0705Sdan ** store the results in the appropriate memory cell or array of 926870a0705Sdan ** memory cells and break out of the scan loop. 9272282792aSdrh */ 928c926afbcSdrh case SRT_Mem: { 929079a3072Sdrh if( pSort ){ 930257c13faSdan assert( nResultCol<=pDest->nSdst ); 931870a0705Sdan pushOntoSorter( 9329af90b72Sdan pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg); 933c926afbcSdrh }else{ 934257c13faSdan assert( nResultCol==pDest->nSdst ); 93553932ce8Sdrh assert( regResult==iParm ); 936ec7429aeSdrh /* The LIMIT clause will jump out of the loop for us */ 937c926afbcSdrh } 938c926afbcSdrh break; 939c926afbcSdrh } 94093758c8dSdanielk1977 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 9412282792aSdrh 94281cf13ecSdrh case SRT_Coroutine: /* Send data to a co-routine */ 94381cf13ecSdrh case SRT_Output: { /* Return the results */ 944373cc2ddSdrh testcase( eDest==SRT_Coroutine ); 945373cc2ddSdrh testcase( eDest==SRT_Output ); 946079a3072Sdrh if( pSort ){ 9479af90b72Sdan pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol, 9485579d59fSdrh nPrefixReg); 949e00ee6ebSdrh }else if( eDest==SRT_Coroutine ){ 9502b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 951c182d163Sdrh }else{ 952340309fdSdrh sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol); 953340309fdSdrh sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol); 954ac82fcf5Sdrh } 955142e30dfSdrh break; 956142e30dfSdrh } 957142e30dfSdrh 958fe1c6bb9Sdrh #ifndef SQLITE_OMIT_CTE 959fe1c6bb9Sdrh /* Write the results into a priority queue that is order according to 960fe1c6bb9Sdrh ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an 961fe1c6bb9Sdrh ** index with pSO->nExpr+2 columns. Build a key using pSO for the first 962fe1c6bb9Sdrh ** pSO->nExpr columns, then make sure all keys are unique by adding a 963fe1c6bb9Sdrh ** final OP_Sequence column. The last column is the record as a blob. 964fe1c6bb9Sdrh */ 965fe1c6bb9Sdrh case SRT_DistQueue: 966fe1c6bb9Sdrh case SRT_Queue: { 967fe1c6bb9Sdrh int nKey; 968fe1c6bb9Sdrh int r1, r2, r3; 969fe1c6bb9Sdrh int addrTest = 0; 970fe1c6bb9Sdrh ExprList *pSO; 971fe1c6bb9Sdrh pSO = pDest->pOrderBy; 972fe1c6bb9Sdrh assert( pSO ); 973fe1c6bb9Sdrh nKey = pSO->nExpr; 974fe1c6bb9Sdrh r1 = sqlite3GetTempReg(pParse); 975fe1c6bb9Sdrh r2 = sqlite3GetTempRange(pParse, nKey+2); 976fe1c6bb9Sdrh r3 = r2+nKey+1; 977fe1c6bb9Sdrh if( eDest==SRT_DistQueue ){ 978fe1c6bb9Sdrh /* If the destination is DistQueue, then cursor (iParm+1) is open 979fe1c6bb9Sdrh ** on a second ephemeral index that holds all values every previously 9807e4efaecSdrh ** added to the queue. */ 9817e4efaecSdrh addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 9827e4efaecSdrh regResult, nResultCol); 983688852abSdrh VdbeCoverage(v); 9847e4efaecSdrh } 9857e4efaecSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3); 9867e4efaecSdrh if( eDest==SRT_DistQueue ){ 987fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3); 988cfe24586Sdan sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 989fe1c6bb9Sdrh } 990fe1c6bb9Sdrh for(i=0; i<nKey; i++){ 991fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_SCopy, 992fe1c6bb9Sdrh regResult + pSO->a[i].u.x.iOrderByCol - 1, 993fe1c6bb9Sdrh r2+i); 994fe1c6bb9Sdrh } 995fe1c6bb9Sdrh sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey); 996fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1); 9979b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2); 998fe1c6bb9Sdrh if( addrTest ) sqlite3VdbeJumpHere(v, addrTest); 999fe1c6bb9Sdrh sqlite3ReleaseTempReg(pParse, r1); 1000fe1c6bb9Sdrh sqlite3ReleaseTempRange(pParse, r2, nKey+2); 1001fe1c6bb9Sdrh break; 1002fe1c6bb9Sdrh } 1003fe1c6bb9Sdrh #endif /* SQLITE_OMIT_CTE */ 1004fe1c6bb9Sdrh 1005fe1c6bb9Sdrh 1006fe1c6bb9Sdrh 10076a67fe8eSdanielk1977 #if !defined(SQLITE_OMIT_TRIGGER) 1008d7489c39Sdrh /* Discard the results. This is used for SELECT statements inside 1009d7489c39Sdrh ** the body of a TRIGGER. The purpose of such selects is to call 1010d7489c39Sdrh ** user-defined functions that have side effects. We do not care 1011d7489c39Sdrh ** about the actual results of the select. 1012d7489c39Sdrh */ 1013c926afbcSdrh default: { 1014f46f905aSdrh assert( eDest==SRT_Discard ); 1015c926afbcSdrh break; 1016c926afbcSdrh } 101793758c8dSdanielk1977 #endif 1018c926afbcSdrh } 1019ec7429aeSdrh 10205e87be87Sdrh /* Jump to the end of the loop if the LIMIT is reached. Except, if 10215e87be87Sdrh ** there is a sorter, in which case the sorter has already limited 10225e87be87Sdrh ** the output for us. 1023ec7429aeSdrh */ 1024079a3072Sdrh if( pSort==0 && p->iLimit ){ 102516897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 1026ec7429aeSdrh } 102782c3d636Sdrh } 102882c3d636Sdrh 102982c3d636Sdrh /* 1030ad124329Sdrh ** Allocate a KeyInfo object sufficient for an index of N key columns and 1031ad124329Sdrh ** X extra columns. 1032323df790Sdrh */ 1033ad124329Sdrh KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){ 1034c263f7c4Sdrh int nExtra = (N+X)*(sizeof(CollSeq*)+1); 1035d8e4b132Sdrh KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra); 1036323df790Sdrh if( p ){ 1037ad124329Sdrh p->aSortOrder = (u8*)&p->aColl[N+X]; 1038323df790Sdrh p->nField = (u16)N; 1039ad124329Sdrh p->nXField = (u16)X; 1040323df790Sdrh p->enc = ENC(db); 1041323df790Sdrh p->db = db; 10422ec2fb22Sdrh p->nRef = 1; 1043c263f7c4Sdrh memset(&p[1], 0, nExtra); 10442ec2fb22Sdrh }else{ 10454a642b60Sdrh sqlite3OomFault(db); 1046323df790Sdrh } 1047323df790Sdrh return p; 1048323df790Sdrh } 1049323df790Sdrh 1050323df790Sdrh /* 10512ec2fb22Sdrh ** Deallocate a KeyInfo object 10522ec2fb22Sdrh */ 10532ec2fb22Sdrh void sqlite3KeyInfoUnref(KeyInfo *p){ 10542ec2fb22Sdrh if( p ){ 10552ec2fb22Sdrh assert( p->nRef>0 ); 10562ec2fb22Sdrh p->nRef--; 1057dbd6a7dcSdrh if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p); 10582ec2fb22Sdrh } 10592ec2fb22Sdrh } 10602ec2fb22Sdrh 10612ec2fb22Sdrh /* 10622ec2fb22Sdrh ** Make a new pointer to a KeyInfo object 10632ec2fb22Sdrh */ 10642ec2fb22Sdrh KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){ 10652ec2fb22Sdrh if( p ){ 10662ec2fb22Sdrh assert( p->nRef>0 ); 10672ec2fb22Sdrh p->nRef++; 10682ec2fb22Sdrh } 10692ec2fb22Sdrh return p; 10702ec2fb22Sdrh } 10712ec2fb22Sdrh 10722ec2fb22Sdrh #ifdef SQLITE_DEBUG 10732ec2fb22Sdrh /* 10742ec2fb22Sdrh ** Return TRUE if a KeyInfo object can be change. The KeyInfo object 10752ec2fb22Sdrh ** can only be changed if this is just a single reference to the object. 10762ec2fb22Sdrh ** 10772ec2fb22Sdrh ** This routine is used only inside of assert() statements. 10782ec2fb22Sdrh */ 10792ec2fb22Sdrh int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; } 10802ec2fb22Sdrh #endif /* SQLITE_DEBUG */ 10812ec2fb22Sdrh 10822ec2fb22Sdrh /* 1083dece1a84Sdrh ** Given an expression list, generate a KeyInfo structure that records 1084dece1a84Sdrh ** the collating sequence for each expression in that expression list. 1085dece1a84Sdrh ** 10860342b1f5Sdrh ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting 10870342b1f5Sdrh ** KeyInfo structure is appropriate for initializing a virtual index to 10880342b1f5Sdrh ** implement that clause. If the ExprList is the result set of a SELECT 10890342b1f5Sdrh ** then the KeyInfo structure is appropriate for initializing a virtual 10900342b1f5Sdrh ** index to implement a DISTINCT test. 10910342b1f5Sdrh ** 109260ec914cSpeter.d.reid ** Space to hold the KeyInfo structure is obtained from malloc. The calling 1093dece1a84Sdrh ** function is responsible for seeing that this structure is eventually 10942ec2fb22Sdrh ** freed. 1095dece1a84Sdrh */ 1096079a3072Sdrh static KeyInfo *keyInfoFromExprList( 1097079a3072Sdrh Parse *pParse, /* Parsing context */ 1098079a3072Sdrh ExprList *pList, /* Form the KeyInfo object from this ExprList */ 1099079a3072Sdrh int iStart, /* Begin with this column of pList */ 1100079a3072Sdrh int nExtra /* Add this many extra columns to the end */ 1101079a3072Sdrh ){ 1102dece1a84Sdrh int nExpr; 1103dece1a84Sdrh KeyInfo *pInfo; 1104dece1a84Sdrh struct ExprList_item *pItem; 1105323df790Sdrh sqlite3 *db = pParse->db; 1106dece1a84Sdrh int i; 1107dece1a84Sdrh 1108dece1a84Sdrh nExpr = pList->nExpr; 11093f39bcf5Sdrh pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1); 1110dece1a84Sdrh if( pInfo ){ 11112ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pInfo) ); 11126284db90Sdrh for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){ 1113dece1a84Sdrh CollSeq *pColl; 1114dece1a84Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 1115323df790Sdrh if( !pColl ) pColl = db->pDfltColl; 11166284db90Sdrh pInfo->aColl[i-iStart] = pColl; 11176284db90Sdrh pInfo->aSortOrder[i-iStart] = pItem->sortOrder; 1118dece1a84Sdrh } 1119dece1a84Sdrh } 1120dece1a84Sdrh return pInfo; 1121dece1a84Sdrh } 1122dece1a84Sdrh 11237f61e92cSdan /* 11247f61e92cSdan ** Name of the connection operator, used for error messages. 11257f61e92cSdan */ 11267f61e92cSdan static const char *selectOpName(int id){ 11277f61e92cSdan char *z; 11287f61e92cSdan switch( id ){ 11297f61e92cSdan case TK_ALL: z = "UNION ALL"; break; 11307f61e92cSdan case TK_INTERSECT: z = "INTERSECT"; break; 11317f61e92cSdan case TK_EXCEPT: z = "EXCEPT"; break; 11327f61e92cSdan default: z = "UNION"; break; 11337f61e92cSdan } 11347f61e92cSdan return z; 11357f61e92cSdan } 11367f61e92cSdan 11372ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 113817c0bc0cSdan /* 113917c0bc0cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 114017c0bc0cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 114117c0bc0cSdan ** where the caption is of the form: 114217c0bc0cSdan ** 114317c0bc0cSdan ** "USE TEMP B-TREE FOR xxx" 114417c0bc0cSdan ** 114517c0bc0cSdan ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which 114617c0bc0cSdan ** is determined by the zUsage argument. 114717c0bc0cSdan */ 11482ce22453Sdan static void explainTempTable(Parse *pParse, const char *zUsage){ 11492ce22453Sdan if( pParse->explain==2 ){ 11502ce22453Sdan Vdbe *v = pParse->pVdbe; 11512ce22453Sdan char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); 11522ce22453Sdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 11532ce22453Sdan } 11542ce22453Sdan } 115517c0bc0cSdan 115617c0bc0cSdan /* 1157bb2b4418Sdan ** Assign expression b to lvalue a. A second, no-op, version of this macro 1158bb2b4418Sdan ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code 1159bb2b4418Sdan ** in sqlite3Select() to assign values to structure member variables that 1160bb2b4418Sdan ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the 1161bb2b4418Sdan ** code with #ifndef directives. 1162bb2b4418Sdan */ 1163bb2b4418Sdan # define explainSetInteger(a, b) a = b 1164bb2b4418Sdan 1165bb2b4418Sdan #else 1166bb2b4418Sdan /* No-op versions of the explainXXX() functions and macros. */ 1167bb2b4418Sdan # define explainTempTable(y,z) 1168bb2b4418Sdan # define explainSetInteger(y,z) 1169bb2b4418Sdan #endif 1170bb2b4418Sdan 1171bb2b4418Sdan #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) 1172bb2b4418Sdan /* 11737f61e92cSdan ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function 11747f61e92cSdan ** is a no-op. Otherwise, it adds a single row of output to the EQP result, 11757f61e92cSdan ** where the caption is of one of the two forms: 11767f61e92cSdan ** 11777f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" 11787f61e92cSdan ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" 11797f61e92cSdan ** 11807f61e92cSdan ** where iSub1 and iSub2 are the integers passed as the corresponding 11817f61e92cSdan ** function parameters, and op is the text representation of the parameter 11827f61e92cSdan ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, 11837f61e92cSdan ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 11847f61e92cSdan ** false, or the second form if it is true. 11857f61e92cSdan */ 11867f61e92cSdan static void explainComposite( 11877f61e92cSdan Parse *pParse, /* Parse context */ 11887f61e92cSdan int op, /* One of TK_UNION, TK_EXCEPT etc. */ 11897f61e92cSdan int iSub1, /* Subquery id 1 */ 11907f61e92cSdan int iSub2, /* Subquery id 2 */ 11917f61e92cSdan int bUseTmp /* True if a temp table was used */ 11927f61e92cSdan ){ 11937f61e92cSdan assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); 11947f61e92cSdan if( pParse->explain==2 ){ 11957f61e92cSdan Vdbe *v = pParse->pVdbe; 11967f61e92cSdan char *zMsg = sqlite3MPrintf( 119730969d3fSdan pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, 11987f61e92cSdan bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) 11997f61e92cSdan ); 12007f61e92cSdan sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); 12017f61e92cSdan } 12027f61e92cSdan } 12032ce22453Sdan #else 120417c0bc0cSdan /* No-op versions of the explainXXX() functions and macros. */ 12057f61e92cSdan # define explainComposite(v,w,x,y,z) 12062ce22453Sdan #endif 1207dece1a84Sdrh 1208dece1a84Sdrh /* 1209d8bc7086Sdrh ** If the inner loop was generated using a non-null pOrderBy argument, 1210d8bc7086Sdrh ** then the results were placed in a sorter. After the loop is terminated 1211d8bc7086Sdrh ** we need to run the sorter and output the results. The following 1212d8bc7086Sdrh ** routine generates the code needed to do that. 1213d8bc7086Sdrh */ 1214c926afbcSdrh static void generateSortTail( 1215cdd536f0Sdrh Parse *pParse, /* Parsing context */ 1216c926afbcSdrh Select *p, /* The SELECT statement */ 1217079a3072Sdrh SortCtx *pSort, /* Information on the ORDER BY clause */ 1218c926afbcSdrh int nColumn, /* Number of columns of data */ 12196c8c8ce0Sdanielk1977 SelectDest *pDest /* Write the sorted results here */ 1220c926afbcSdrh ){ 1221ddba0c22Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement */ 1222a04a8be2Sdrh int addrBreak = pSort->labelDone; /* Jump here to exit loop */ 1223dc5ea5c7Sdrh int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */ 1224d8bc7086Sdrh int addr; 1225079a3072Sdrh int addrOnce = 0; 12260342b1f5Sdrh int iTab; 1227079a3072Sdrh ExprList *pOrderBy = pSort->pOrderBy; 12286c8c8ce0Sdanielk1977 int eDest = pDest->eDest; 12292b596da8Sdrh int iParm = pDest->iSDParm; 12302d401ab8Sdrh int regRow; 12312d401ab8Sdrh int regRowid; 1232257c13faSdan int iCol; 1233079a3072Sdrh int nKey; 1234f45f2326Sdrh int iSortTab; /* Sorter cursor to read from */ 1235f45f2326Sdrh int nSortData; /* Trailing values to read from sorter */ 1236f45f2326Sdrh int i; 123778d58432Sdan int bSeq; /* True if sorter record includes seq. no. */ 123870f624c3Sdrh struct ExprList_item *aOutEx = p->pEList->a; 12392d401ab8Sdrh 1240a04a8be2Sdrh assert( addrBreak<0 ); 1241079a3072Sdrh if( pSort->labelBkOut ){ 1242079a3072Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut); 1243076e85f5Sdrh sqlite3VdbeGoto(v, addrBreak); 1244079a3072Sdrh sqlite3VdbeResolveLabel(v, pSort->labelBkOut); 1245079a3072Sdrh } 1246079a3072Sdrh iTab = pSort->iECursor; 124771c57db0Sdan if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ 12483e9ca094Sdrh regRowid = 0; 1249f45f2326Sdrh regRow = pDest->iSdst; 1250f45f2326Sdrh nSortData = nColumn; 1251ed24da4bSdrh }else{ 125251d82d1dSdan regRowid = sqlite3GetTempReg(pParse); 125351d82d1dSdan regRow = sqlite3GetTempRange(pParse, nColumn); 125451d82d1dSdan nSortData = nColumn; 1255cdd536f0Sdrh } 1256079a3072Sdrh nKey = pOrderBy->nExpr - pSort->nOBSat; 1257079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1258c2bb3282Sdrh int regSortOut = ++pParse->nMem; 1259f45f2326Sdrh iSortTab = pParse->nTab++; 126083553eefSdrh if( pSort->labelBkOut ){ 1261511f9e8dSdrh addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 126283553eefSdrh } 1263f45f2326Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData); 1264079a3072Sdrh if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce); 1265c6aff30cSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak); 1266688852abSdrh VdbeCoverage(v); 1267aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 12686cf4a7dfSdrh sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab); 126978d58432Sdan bSeq = 0; 1270c6aff30cSdrh }else{ 1271688852abSdrh addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v); 1272aa9ce707Sdrh codeOffset(v, p->iOffset, addrContinue); 1273f45f2326Sdrh iSortTab = iTab; 127478d58432Sdan bSeq = 1; 1275f45f2326Sdrh } 1276257c13faSdan for(i=0, iCol=nKey+bSeq; i<nSortData; i++){ 1277257c13faSdan int iRead; 1278257c13faSdan if( aOutEx[i].u.x.iOrderByCol ){ 1279257c13faSdan iRead = aOutEx[i].u.x.iOrderByCol-1; 1280257c13faSdan }else{ 1281257c13faSdan iRead = iCol++; 1282257c13faSdan } 1283257c13faSdan sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i); 128470f624c3Sdrh VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan)); 1285c6aff30cSdrh } 1286c926afbcSdrh switch( eDest ){ 1287ac56ab7eSdan case SRT_Table: 1288b9bb7c18Sdrh case SRT_EphemTab: { 12892d401ab8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); 12902d401ab8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); 12912d401ab8Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 1292c926afbcSdrh break; 1293c926afbcSdrh } 129493758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 1295c926afbcSdrh case SRT_Set: { 129671c57db0Sdan assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) ); 129771c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, 1298553168c7Sdan pDest->zAffSdst, nColumn); 129971c57db0Sdan sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn); 13009b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); 1301c926afbcSdrh break; 1302c926afbcSdrh } 1303c926afbcSdrh case SRT_Mem: { 1304ec7429aeSdrh /* The LIMIT clause will terminate the loop for us */ 1305c926afbcSdrh break; 1306c926afbcSdrh } 130793758c8dSdanielk1977 #endif 1308373cc2ddSdrh default: { 1309373cc2ddSdrh assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 13101c767f0dSdrh testcase( eDest==SRT_Output ); 13111c767f0dSdrh testcase( eDest==SRT_Coroutine ); 13127d10d5a6Sdrh if( eDest==SRT_Output ){ 13132b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn); 13142b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn); 1315a9671a22Sdrh }else{ 13162b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 1317ce665cf6Sdrh } 1318ac82fcf5Sdrh break; 1319ac82fcf5Sdrh } 1320c926afbcSdrh } 1321f45f2326Sdrh if( regRowid ){ 132251d82d1dSdan if( eDest==SRT_Set ){ 132351d82d1dSdan sqlite3ReleaseTempRange(pParse, regRow, nColumn); 132451d82d1dSdan }else{ 13252d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRow); 132651d82d1dSdan } 13272d401ab8Sdrh sqlite3ReleaseTempReg(pParse, regRowid); 1328f45f2326Sdrh } 1329ec7429aeSdrh /* The bottom of the loop 1330ec7429aeSdrh */ 1331dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrContinue); 1332079a3072Sdrh if( pSort->sortFlags & SORTFLAG_UseSorter ){ 1333688852abSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v); 1334c6aff30cSdrh }else{ 1335688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v); 1336c6aff30cSdrh } 1337079a3072Sdrh if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn); 1338dc5ea5c7Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 1339d8bc7086Sdrh } 1340d8bc7086Sdrh 1341d8bc7086Sdrh /* 1342517eb646Sdanielk1977 ** Return a pointer to a string containing the 'declaration type' of the 1343517eb646Sdanielk1977 ** expression pExpr. The string may be treated as static by the caller. 1344e78e8284Sdrh ** 13455f3e5e74Sdrh ** Also try to estimate the size of the returned value and return that 13465f3e5e74Sdrh ** result in *pEstWidth. 13475f3e5e74Sdrh ** 1348955de52cSdanielk1977 ** The declaration type is the exact datatype definition extracted from the 1349955de52cSdanielk1977 ** original CREATE TABLE statement if the expression is a column. The 1350955de52cSdanielk1977 ** declaration type for a ROWID field is INTEGER. Exactly when an expression 1351955de52cSdanielk1977 ** is considered a column can be complex in the presence of subqueries. The 1352955de52cSdanielk1977 ** result-set expression in all of the following SELECT statements is 1353955de52cSdanielk1977 ** considered a column by this function. 1354e78e8284Sdrh ** 1355955de52cSdanielk1977 ** SELECT col FROM tbl; 1356955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl; 1357955de52cSdanielk1977 ** SELECT (SELECT col FROM tbl); 1358955de52cSdanielk1977 ** SELECT abc FROM (SELECT col AS abc FROM tbl); 1359955de52cSdanielk1977 ** 1360955de52cSdanielk1977 ** The declaration type for any expression other than a column is NULL. 13615f3e5e74Sdrh ** 13625f3e5e74Sdrh ** This routine has either 3 or 6 parameters depending on whether or not 13635f3e5e74Sdrh ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used. 1364fcb78a49Sdrh */ 13655f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 13665f3e5e74Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F) 1367b121dd14Sdrh #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */ 1368b121dd14Sdrh # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F) 1369b121dd14Sdrh #endif 13705f3e5e74Sdrh static const char *columnTypeImpl( 1371955de52cSdanielk1977 NameContext *pNC, 1372955de52cSdanielk1977 Expr *pExpr, 1373b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 13745f3e5e74Sdrh const char **pzOrigDb, 13755f3e5e74Sdrh const char **pzOrigTab, 13765f3e5e74Sdrh const char **pzOrigCol, 1377b121dd14Sdrh #endif 13785f3e5e74Sdrh u8 *pEstWidth 1379955de52cSdanielk1977 ){ 1380955de52cSdanielk1977 char const *zType = 0; 1381517eb646Sdanielk1977 int j; 13825f3e5e74Sdrh u8 estWidth = 1; 1383b121dd14Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1384b121dd14Sdrh char const *zOrigDb = 0; 1385b121dd14Sdrh char const *zOrigTab = 0; 1386b121dd14Sdrh char const *zOrigCol = 0; 1387b121dd14Sdrh #endif 13885338a5f7Sdanielk1977 1389f7ce4291Sdrh assert( pExpr!=0 ); 1390f7ce4291Sdrh assert( pNC->pSrcList!=0 ); 139100e279d9Sdanielk1977 switch( pExpr->op ){ 139230bcf5dbSdrh case TK_AGG_COLUMN: 139300e279d9Sdanielk1977 case TK_COLUMN: { 1394955de52cSdanielk1977 /* The expression is a column. Locate the table the column is being 1395955de52cSdanielk1977 ** extracted from in NameContext.pSrcList. This table may be real 1396955de52cSdanielk1977 ** database table or a subquery. 1397955de52cSdanielk1977 */ 1398955de52cSdanielk1977 Table *pTab = 0; /* Table structure column is extracted from */ 1399955de52cSdanielk1977 Select *pS = 0; /* Select the column is extracted from */ 1400955de52cSdanielk1977 int iCol = pExpr->iColumn; /* Index of column in pTab */ 1401373cc2ddSdrh testcase( pExpr->op==TK_AGG_COLUMN ); 1402373cc2ddSdrh testcase( pExpr->op==TK_COLUMN ); 140343bc88bbSdan while( pNC && !pTab ){ 1404b3bce662Sdanielk1977 SrcList *pTabList = pNC->pSrcList; 1405b3bce662Sdanielk1977 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++); 1406b3bce662Sdanielk1977 if( j<pTabList->nSrc ){ 14076a3ea0e6Sdrh pTab = pTabList->a[j].pTab; 1408955de52cSdanielk1977 pS = pTabList->a[j].pSelect; 1409b3bce662Sdanielk1977 }else{ 1410b3bce662Sdanielk1977 pNC = pNC->pNext; 1411b3bce662Sdanielk1977 } 1412b3bce662Sdanielk1977 } 1413955de52cSdanielk1977 141443bc88bbSdan if( pTab==0 ){ 1415417168adSdrh /* At one time, code such as "SELECT new.x" within a trigger would 1416417168adSdrh ** cause this condition to run. Since then, we have restructured how 1417417168adSdrh ** trigger code is generated and so this condition is no longer 141843bc88bbSdan ** possible. However, it can still be true for statements like 141943bc88bbSdan ** the following: 142043bc88bbSdan ** 142143bc88bbSdan ** CREATE TABLE t1(col INTEGER); 142243bc88bbSdan ** SELECT (SELECT t1.col) FROM FROM t1; 142343bc88bbSdan ** 142443bc88bbSdan ** when columnType() is called on the expression "t1.col" in the 142543bc88bbSdan ** sub-select. In this case, set the column type to NULL, even 142643bc88bbSdan ** though it should really be "INTEGER". 142743bc88bbSdan ** 142843bc88bbSdan ** This is not a problem, as the column type of "t1.col" is never 142943bc88bbSdan ** used. When columnType() is called on the expression 143043bc88bbSdan ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT 143143bc88bbSdan ** branch below. */ 14327e62779aSdrh break; 14337e62779aSdrh } 1434955de52cSdanielk1977 143543bc88bbSdan assert( pTab && pExpr->pTab==pTab ); 1436955de52cSdanielk1977 if( pS ){ 1437955de52cSdanielk1977 /* The "table" is actually a sub-select or a view in the FROM clause 1438955de52cSdanielk1977 ** of the SELECT statement. Return the declaration type and origin 1439955de52cSdanielk1977 ** data for the result-set column of the sub-select. 1440955de52cSdanielk1977 */ 14417b688edeSdrh if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){ 1442955de52cSdanielk1977 /* If iCol is less than zero, then the expression requests the 1443955de52cSdanielk1977 ** rowid of the sub-select or view. This expression is legal (see 1444955de52cSdanielk1977 ** test case misc2.2.2) - it always evaluates to NULL. 14452ec18a3cSdrh ** 14462ec18a3cSdrh ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been 14472ec18a3cSdrh ** caught already by name resolution. 1448955de52cSdanielk1977 */ 1449955de52cSdanielk1977 NameContext sNC; 1450955de52cSdanielk1977 Expr *p = pS->pEList->a[iCol].pExpr; 1451955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 145243bc88bbSdan sNC.pNext = pNC; 1453955de52cSdanielk1977 sNC.pParse = pNC->pParse; 14545f3e5e74Sdrh zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 1455955de52cSdanielk1977 } 145693c36bb3Sdrh }else if( pTab->pSchema ){ 1457955de52cSdanielk1977 /* A real table */ 1458955de52cSdanielk1977 assert( !pS ); 1459fcb78a49Sdrh if( iCol<0 ) iCol = pTab->iPKey; 1460fcb78a49Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 14615f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1462fcb78a49Sdrh if( iCol<0 ){ 1463fcb78a49Sdrh zType = "INTEGER"; 14645f3e5e74Sdrh zOrigCol = "rowid"; 1465fcb78a49Sdrh }else{ 14665f3e5e74Sdrh zOrigCol = pTab->aCol[iCol].zName; 1467d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 14685f3e5e74Sdrh estWidth = pTab->aCol[iCol].szEst; 1469955de52cSdanielk1977 } 14705f3e5e74Sdrh zOrigTab = pTab->zName; 1471955de52cSdanielk1977 if( pNC->pParse ){ 1472955de52cSdanielk1977 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema); 1473e59be010Sdrh zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName; 1474955de52cSdanielk1977 } 14755f3e5e74Sdrh #else 14765f3e5e74Sdrh if( iCol<0 ){ 14775f3e5e74Sdrh zType = "INTEGER"; 14785f3e5e74Sdrh }else{ 1479d7564865Sdrh zType = sqlite3ColumnType(&pTab->aCol[iCol],0); 14805f3e5e74Sdrh estWidth = pTab->aCol[iCol].szEst; 14815f3e5e74Sdrh } 14825f3e5e74Sdrh #endif 1483fcb78a49Sdrh } 148400e279d9Sdanielk1977 break; 1485736c22b8Sdrh } 148693758c8dSdanielk1977 #ifndef SQLITE_OMIT_SUBQUERY 148700e279d9Sdanielk1977 case TK_SELECT: { 1488955de52cSdanielk1977 /* The expression is a sub-select. Return the declaration type and 1489955de52cSdanielk1977 ** origin info for the single column in the result set of the SELECT 1490955de52cSdanielk1977 ** statement. 1491955de52cSdanielk1977 */ 1492b3bce662Sdanielk1977 NameContext sNC; 14936ab3a2ecSdanielk1977 Select *pS = pExpr->x.pSelect; 1494955de52cSdanielk1977 Expr *p = pS->pEList->a[0].pExpr; 14956ab3a2ecSdanielk1977 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1496955de52cSdanielk1977 sNC.pSrcList = pS->pSrc; 1497b3bce662Sdanielk1977 sNC.pNext = pNC; 1498955de52cSdanielk1977 sNC.pParse = pNC->pParse; 14995f3e5e74Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); 150000e279d9Sdanielk1977 break; 1501fcb78a49Sdrh } 150293758c8dSdanielk1977 #endif 150300e279d9Sdanielk1977 } 150400e279d9Sdanielk1977 15055f3e5e74Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 15065f3e5e74Sdrh if( pzOrigDb ){ 15075f3e5e74Sdrh assert( pzOrigTab && pzOrigCol ); 15085f3e5e74Sdrh *pzOrigDb = zOrigDb; 15095f3e5e74Sdrh *pzOrigTab = zOrigTab; 15105f3e5e74Sdrh *pzOrigCol = zOrigCol; 1511955de52cSdanielk1977 } 15125f3e5e74Sdrh #endif 15135f3e5e74Sdrh if( pEstWidth ) *pEstWidth = estWidth; 1514517eb646Sdanielk1977 return zType; 1515517eb646Sdanielk1977 } 1516517eb646Sdanielk1977 1517517eb646Sdanielk1977 /* 1518517eb646Sdanielk1977 ** Generate code that will tell the VDBE the declaration types of columns 1519517eb646Sdanielk1977 ** in the result set. 1520517eb646Sdanielk1977 */ 1521517eb646Sdanielk1977 static void generateColumnTypes( 1522517eb646Sdanielk1977 Parse *pParse, /* Parser context */ 1523517eb646Sdanielk1977 SrcList *pTabList, /* List of tables */ 1524517eb646Sdanielk1977 ExprList *pEList /* Expressions defining the result set */ 1525517eb646Sdanielk1977 ){ 15263f913576Sdrh #ifndef SQLITE_OMIT_DECLTYPE 1527517eb646Sdanielk1977 Vdbe *v = pParse->pVdbe; 1528517eb646Sdanielk1977 int i; 1529b3bce662Sdanielk1977 NameContext sNC; 1530b3bce662Sdanielk1977 sNC.pSrcList = pTabList; 1531955de52cSdanielk1977 sNC.pParse = pParse; 1532eac5fc04Sdrh sNC.pNext = 0; 1533517eb646Sdanielk1977 for(i=0; i<pEList->nExpr; i++){ 1534517eb646Sdanielk1977 Expr *p = pEList->a[i].pExpr; 15353f913576Sdrh const char *zType; 15363f913576Sdrh #ifdef SQLITE_ENABLE_COLUMN_METADATA 1537955de52cSdanielk1977 const char *zOrigDb = 0; 1538955de52cSdanielk1977 const char *zOrigTab = 0; 1539955de52cSdanielk1977 const char *zOrigCol = 0; 15405f3e5e74Sdrh zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0); 1541955de52cSdanielk1977 154285b623f2Sdrh /* The vdbe must make its own copy of the column-type and other 15434b1ae99dSdanielk1977 ** column specific strings, in case the schema is reset before this 15444b1ae99dSdanielk1977 ** virtual machine is deleted. 1545fbcd585fSdanielk1977 */ 154610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT); 154710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT); 154810fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT); 15493f913576Sdrh #else 15505f3e5e74Sdrh zType = columnType(&sNC, p, 0, 0, 0, 0); 15513f913576Sdrh #endif 155210fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT); 1553fcb78a49Sdrh } 15545f3e5e74Sdrh #endif /* !defined(SQLITE_OMIT_DECLTYPE) */ 1555fcb78a49Sdrh } 1556fcb78a49Sdrh 1557fcb78a49Sdrh /* 1558eac5fc04Sdrh ** Return the Table objecct in the SrcList that has cursor iCursor. 1559eac5fc04Sdrh ** Or return NULL if no such Table object exists in the SrcList. 1560eac5fc04Sdrh */ 1561eac5fc04Sdrh static Table *tableWithCursor(SrcList *pList, int iCursor){ 1562eac5fc04Sdrh int j; 1563eac5fc04Sdrh for(j=0; j<pList->nSrc; j++){ 1564eac5fc04Sdrh if( pList->a[j].iCursor==iCursor ) return pList->a[j].pTab; 1565eac5fc04Sdrh } 1566eac5fc04Sdrh return 0; 1567eac5fc04Sdrh } 1568eac5fc04Sdrh 1569eac5fc04Sdrh 1570eac5fc04Sdrh /* 1571fcb78a49Sdrh ** Generate code that will tell the VDBE the names of columns 1572fcb78a49Sdrh ** in the result set. This information is used to provide the 1573fcabd464Sdrh ** azCol[] values in the callback. 157482c3d636Sdrh */ 1575832508b7Sdrh static void generateColumnNames( 1576832508b7Sdrh Parse *pParse, /* Parser context */ 1577ad3cab52Sdrh SrcList *pTabList, /* List of tables */ 1578832508b7Sdrh ExprList *pEList /* Expressions defining the result set */ 1579832508b7Sdrh ){ 1580d8bc7086Sdrh Vdbe *v = pParse->pVdbe; 1581eac5fc04Sdrh int i; 1582eac5fc04Sdrh Table *pTab; 15839bb575fdSdrh sqlite3 *db = pParse->db; 1584fcabd464Sdrh int fullNames, shortNames; 1585fcabd464Sdrh 1586fe2093d7Sdrh #ifndef SQLITE_OMIT_EXPLAIN 15873cf86063Sdanielk1977 /* If this is an EXPLAIN, skip this step */ 15883cf86063Sdanielk1977 if( pParse->explain ){ 158961de0d1bSdanielk1977 return; 15903cf86063Sdanielk1977 } 15915338a5f7Sdanielk1977 #endif 15923cf86063Sdanielk1977 15939802947fSdrh if( pParse->colNamesSet || db->mallocFailed ) return; 15949802947fSdrh assert( v!=0 ); 1595f7ce4291Sdrh assert( pTabList!=0 ); 1596d8bc7086Sdrh pParse->colNamesSet = 1; 1597fcabd464Sdrh fullNames = (db->flags & SQLITE_FullColNames)!=0; 1598fcabd464Sdrh shortNames = (db->flags & SQLITE_ShortColNames)!=0; 159922322fd4Sdanielk1977 sqlite3VdbeSetNumCols(v, pEList->nExpr); 160082c3d636Sdrh for(i=0; i<pEList->nExpr; i++){ 160182c3d636Sdrh Expr *p; 16025a38705eSdrh p = pEList->a[i].pExpr; 1603373cc2ddSdrh if( NEVER(p==0) ) continue; 160482c3d636Sdrh if( pEList->a[i].zName ){ 160582c3d636Sdrh char *zName = pEList->a[i].zName; 160610fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); 1607eac5fc04Sdrh }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) 1608eac5fc04Sdrh && (pTab = tableWithCursor(pTabList, p->iTable))!=0 1609eac5fc04Sdrh ){ 161097665873Sdrh char *zCol; 16118aff1015Sdrh int iCol = p->iColumn; 16128aff1015Sdrh if( iCol<0 ) iCol = pTab->iPKey; 161397665873Sdrh assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) ); 1614b1363206Sdrh if( iCol<0 ){ 161547a6db2bSdrh zCol = "rowid"; 1616b1363206Sdrh }else{ 1617b1363206Sdrh zCol = pTab->aCol[iCol].zName; 1618b1363206Sdrh } 1619e49b146fSdrh if( !shortNames && !fullNames ){ 162010fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, 1621b7916a78Sdrh sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC); 16221c767f0dSdrh }else if( fullNames ){ 162382c3d636Sdrh char *zName = 0; 16241c767f0dSdrh zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol); 162510fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC); 162682c3d636Sdrh }else{ 162710fb749bSdanielk1977 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT); 162882c3d636Sdrh } 16291bee3d7bSdrh }else{ 1630859bc542Sdrh const char *z = pEList->a[i].zSpan; 1631859bc542Sdrh z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z); 1632859bc542Sdrh sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC); 163382c3d636Sdrh } 163482c3d636Sdrh } 163576d505baSdanielk1977 generateColumnTypes(pParse, pTabList, pEList); 16365080aaa7Sdrh } 163782c3d636Sdrh 1638d8bc7086Sdrh /* 163960ec914cSpeter.d.reid ** Given an expression list (which is really the list of expressions 16407d10d5a6Sdrh ** that form the result set of a SELECT statement) compute appropriate 16417d10d5a6Sdrh ** column names for a table that would hold the expression list. 16427d10d5a6Sdrh ** 16437d10d5a6Sdrh ** All column names will be unique. 16447d10d5a6Sdrh ** 16457d10d5a6Sdrh ** Only the column names are computed. Column.zType, Column.zColl, 16467d10d5a6Sdrh ** and other fields of Column are zeroed. 16477d10d5a6Sdrh ** 16487d10d5a6Sdrh ** Return SQLITE_OK on success. If a memory allocation error occurs, 16497d10d5a6Sdrh ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM. 1650315555caSdrh */ 16518981b904Sdrh int sqlite3ColumnsFromExprList( 16527d10d5a6Sdrh Parse *pParse, /* Parsing context */ 16537d10d5a6Sdrh ExprList *pEList, /* Expr list from which to derive column names */ 1654d815f17dSdrh i16 *pnCol, /* Write the number of columns here */ 16557d10d5a6Sdrh Column **paCol /* Write the new column list here */ 16567d10d5a6Sdrh ){ 1657dc5ea5c7Sdrh sqlite3 *db = pParse->db; /* Database connection */ 1658dc5ea5c7Sdrh int i, j; /* Loop counters */ 1659ebed3fa3Sdrh u32 cnt; /* Index added to make the name unique */ 1660dc5ea5c7Sdrh Column *aCol, *pCol; /* For looping over result columns */ 1661dc5ea5c7Sdrh int nCol; /* Number of columns in the result set */ 1662dc5ea5c7Sdrh Expr *p; /* Expression for a single result column */ 1663dc5ea5c7Sdrh char *zName; /* Column name */ 1664dc5ea5c7Sdrh int nName; /* Size of name in zName[] */ 16650315e3ccSdrh Hash ht; /* Hash table of column names */ 166679d5f63fSdrh 16670315e3ccSdrh sqlite3HashInit(&ht); 16688c2e0f02Sdan if( pEList ){ 16698c2e0f02Sdan nCol = pEList->nExpr; 16708c2e0f02Sdan aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol); 16718c2e0f02Sdan testcase( aCol==0 ); 16728c2e0f02Sdan }else{ 16738c2e0f02Sdan nCol = 0; 16748c2e0f02Sdan aCol = 0; 16758c2e0f02Sdan } 16768836cbbcSdan assert( nCol==(i16)nCol ); 16778c2e0f02Sdan *pnCol = nCol; 16788c2e0f02Sdan *paCol = aCol; 16798c2e0f02Sdan 16800315e3ccSdrh for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){ 168179d5f63fSdrh /* Get an appropriate name for the column 168279d5f63fSdrh */ 1683580c8c18Sdrh p = sqlite3ExprSkipCollate(pEList->a[i].pExpr); 168491bb0eedSdrh if( (zName = pEList->a[i].zName)!=0 ){ 168579d5f63fSdrh /* If the column contains an "AS <name>" phrase, use <name> as the name */ 16867d10d5a6Sdrh }else{ 1687dc5ea5c7Sdrh Expr *pColExpr = p; /* The expression that is the result column name */ 1688dc5ea5c7Sdrh Table *pTab; /* Table associated with this expression */ 1689b07028f7Sdrh while( pColExpr->op==TK_DOT ){ 1690b07028f7Sdrh pColExpr = pColExpr->pRight; 1691b07028f7Sdrh assert( pColExpr!=0 ); 1692b07028f7Sdrh } 16937c88bcd4Sdrh if( pColExpr->op==TK_COLUMN && pColExpr->pTab!=0 ){ 169493a960a0Sdrh /* For columns use the column name name */ 1695dc5ea5c7Sdrh int iCol = pColExpr->iColumn; 1696373cc2ddSdrh pTab = pColExpr->pTab; 1697f0209f74Sdrh if( iCol<0 ) iCol = pTab->iPKey; 169896ceaf86Sdrh zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid"; 1699b7916a78Sdrh }else if( pColExpr->op==TK_ID ){ 170033e619fcSdrh assert( !ExprHasProperty(pColExpr, EP_IntValue) ); 170196ceaf86Sdrh zName = pColExpr->u.zToken; 170293a960a0Sdrh }else{ 170379d5f63fSdrh /* Use the original text of the column expression as its name */ 170496ceaf86Sdrh zName = pEList->a[i].zSpan; 17057d10d5a6Sdrh } 170622f70c32Sdrh } 170796ceaf86Sdrh zName = sqlite3MPrintf(db, "%s", zName); 170879d5f63fSdrh 170979d5f63fSdrh /* Make sure the column name is unique. If the name is not unique, 171060ec914cSpeter.d.reid ** append an integer to the name so that it becomes unique. 171179d5f63fSdrh */ 17120315e3ccSdrh cnt = 0; 17130315e3ccSdrh while( zName && sqlite3HashFind(&ht, zName)!=0 ){ 17140315e3ccSdrh nName = sqlite3Strlen30(zName); 1715f7ee8965Sdrh if( nName>0 ){ 17160315e3ccSdrh for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){} 17170315e3ccSdrh if( zName[j]==':' ) nName = j; 1718f7ee8965Sdrh } 171996ceaf86Sdrh zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt); 1720ebed3fa3Sdrh if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt); 172179d5f63fSdrh } 172291bb0eedSdrh pCol->zName = zName; 1723ba68f8f3Sdan sqlite3ColumnPropertiesFromName(0, pCol); 172403d69a68Sdrh if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){ 17254a642b60Sdrh sqlite3OomFault(db); 17267d10d5a6Sdrh } 17270315e3ccSdrh } 17280315e3ccSdrh sqlite3HashClear(&ht); 17297d10d5a6Sdrh if( db->mallocFailed ){ 17307d10d5a6Sdrh for(j=0; j<i; j++){ 17317d10d5a6Sdrh sqlite3DbFree(db, aCol[j].zName); 17327d10d5a6Sdrh } 17337d10d5a6Sdrh sqlite3DbFree(db, aCol); 17347d10d5a6Sdrh *paCol = 0; 17357d10d5a6Sdrh *pnCol = 0; 1736fad3039cSmistachkin return SQLITE_NOMEM_BKPT; 17377d10d5a6Sdrh } 17387d10d5a6Sdrh return SQLITE_OK; 17397d10d5a6Sdrh } 1740e014a838Sdanielk1977 17417d10d5a6Sdrh /* 17427d10d5a6Sdrh ** Add type and collation information to a column list based on 17437d10d5a6Sdrh ** a SELECT statement. 17447d10d5a6Sdrh ** 17457d10d5a6Sdrh ** The column list presumably came from selectColumnNamesFromExprList(). 17467d10d5a6Sdrh ** The column list has only names, not types or collations. This 17477d10d5a6Sdrh ** routine goes through and adds the types and collations. 17487d10d5a6Sdrh ** 1749b08a67a7Sshane ** This routine requires that all identifiers in the SELECT 17507d10d5a6Sdrh ** statement be resolved. 175179d5f63fSdrh */ 1752ed06a131Sdrh void sqlite3SelectAddColumnTypeAndCollation( 17537d10d5a6Sdrh Parse *pParse, /* Parsing contexts */ 1754186ad8ccSdrh Table *pTab, /* Add column type information to this table */ 17557d10d5a6Sdrh Select *pSelect /* SELECT used to determine types and collations */ 17567d10d5a6Sdrh ){ 17577d10d5a6Sdrh sqlite3 *db = pParse->db; 17587d10d5a6Sdrh NameContext sNC; 17597d10d5a6Sdrh Column *pCol; 17607d10d5a6Sdrh CollSeq *pColl; 17617d10d5a6Sdrh int i; 17627d10d5a6Sdrh Expr *p; 17637d10d5a6Sdrh struct ExprList_item *a; 1764186ad8ccSdrh u64 szAll = 0; 17657d10d5a6Sdrh 17667d10d5a6Sdrh assert( pSelect!=0 ); 17677d10d5a6Sdrh assert( (pSelect->selFlags & SF_Resolved)!=0 ); 1768186ad8ccSdrh assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed ); 17697d10d5a6Sdrh if( db->mallocFailed ) return; 1770c43e8be8Sdrh memset(&sNC, 0, sizeof(sNC)); 1771b3bce662Sdanielk1977 sNC.pSrcList = pSelect->pSrc; 17727d10d5a6Sdrh a = pSelect->pEList->a; 1773186ad8ccSdrh for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ 1774ed06a131Sdrh const char *zType; 1775ed06a131Sdrh int n, m; 17767d10d5a6Sdrh p = a[i].pExpr; 1777ed06a131Sdrh zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst); 1778186ad8ccSdrh szAll += pCol->szEst; 1779c60e9b82Sdanielk1977 pCol->affinity = sqlite3ExprAffinity(p); 1780ed06a131Sdrh if( zType && (m = sqlite3Strlen30(zType))>0 ){ 1781ed06a131Sdrh n = sqlite3Strlen30(pCol->zName); 1782ed06a131Sdrh pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2); 1783ed06a131Sdrh if( pCol->zName ){ 1784ed06a131Sdrh memcpy(&pCol->zName[n+1], zType, m+1); 1785ed06a131Sdrh pCol->colFlags |= COLFLAG_HASTYPE; 1786ed06a131Sdrh } 1787ed06a131Sdrh } 178805883a34Sdrh if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB; 1789b3bf556eSdanielk1977 pColl = sqlite3ExprCollSeq(pParse, p); 17901cb50c88Sdrh if( pColl && pCol->zColl==0 ){ 179117435752Sdrh pCol->zColl = sqlite3DbStrDup(db, pColl->zName); 17920202b29eSdanielk1977 } 179322f70c32Sdrh } 1794186ad8ccSdrh pTab->szTabRow = sqlite3LogEst(szAll*4); 17957d10d5a6Sdrh } 17967d10d5a6Sdrh 17977d10d5a6Sdrh /* 17987d10d5a6Sdrh ** Given a SELECT statement, generate a Table structure that describes 17997d10d5a6Sdrh ** the result set of that SELECT. 18007d10d5a6Sdrh */ 18017d10d5a6Sdrh Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){ 18027d10d5a6Sdrh Table *pTab; 18037d10d5a6Sdrh sqlite3 *db = pParse->db; 18047d10d5a6Sdrh int savedFlags; 18057d10d5a6Sdrh 18067d10d5a6Sdrh savedFlags = db->flags; 18077d10d5a6Sdrh db->flags &= ~SQLITE_FullColNames; 18087d10d5a6Sdrh db->flags |= SQLITE_ShortColNames; 18097d10d5a6Sdrh sqlite3SelectPrep(pParse, pSelect, 0); 18107d10d5a6Sdrh if( pParse->nErr ) return 0; 18117d10d5a6Sdrh while( pSelect->pPrior ) pSelect = pSelect->pPrior; 18127d10d5a6Sdrh db->flags = savedFlags; 18137d10d5a6Sdrh pTab = sqlite3DbMallocZero(db, sizeof(Table) ); 18147d10d5a6Sdrh if( pTab==0 ){ 18157d10d5a6Sdrh return 0; 18167d10d5a6Sdrh } 1817373cc2ddSdrh /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside 1818b2468954Sdrh ** is disabled */ 18194a642b60Sdrh assert( db->lookaside.bDisable ); 182079df7782Sdrh pTab->nTabRef = 1; 18217d10d5a6Sdrh pTab->zName = 0; 1822cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 18238981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol); 1824ed06a131Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect); 182522f70c32Sdrh pTab->iPKey = -1; 18267ce72f69Sdrh if( db->mallocFailed ){ 18271feeaed2Sdan sqlite3DeleteTable(db, pTab); 18287ce72f69Sdrh return 0; 18297ce72f69Sdrh } 183022f70c32Sdrh return pTab; 183122f70c32Sdrh } 183222f70c32Sdrh 183322f70c32Sdrh /* 1834d8bc7086Sdrh ** Get a VDBE for the given parser context. Create a new one if necessary. 1835d8bc7086Sdrh ** If an error occurs, return NULL and leave a message in pParse. 1836d8bc7086Sdrh */ 18376f077343Sdrh static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){ 18386f077343Sdrh Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse); 18394910a76dSdrh if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1); 1840e0e261a4Sdrh if( pParse->pToplevel==0 1841e0e261a4Sdrh && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst) 1842e0e261a4Sdrh ){ 1843e0e261a4Sdrh pParse->okConstFactor = 1; 1844949f9cd5Sdrh } 1845d8bc7086Sdrh return v; 1846d8bc7086Sdrh } 18476f077343Sdrh Vdbe *sqlite3GetVdbe(Parse *pParse){ 18486f077343Sdrh Vdbe *v = pParse->pVdbe; 18496f077343Sdrh return v ? v : allocVdbe(pParse); 18506f077343Sdrh } 1851d8bc7086Sdrh 185215007a99Sdrh 1853d8bc7086Sdrh /* 18547b58daeaSdrh ** Compute the iLimit and iOffset fields of the SELECT based on the 1855ec7429aeSdrh ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions 18567b58daeaSdrh ** that appear in the original SQL statement after the LIMIT and OFFSET 1857a2dc3b1aSdanielk1977 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset 1858a2dc3b1aSdanielk1977 ** are the integer memory register numbers for counters used to compute 1859a2dc3b1aSdanielk1977 ** the limit and offset. If there is no limit and/or offset, then 1860a2dc3b1aSdanielk1977 ** iLimit and iOffset are negative. 18617b58daeaSdrh ** 1862d59ba6ceSdrh ** This routine changes the values of iLimit and iOffset only if 1863ec7429aeSdrh ** a limit or offset is defined by pLimit and pOffset. iLimit and 1864aa9ce707Sdrh ** iOffset should have been preset to appropriate default values (zero) 1865aa9ce707Sdrh ** prior to calling this routine. 1866aa9ce707Sdrh ** 1867aa9ce707Sdrh ** The iOffset register (if it exists) is initialized to the value 1868aa9ce707Sdrh ** of the OFFSET. The iLimit register is initialized to LIMIT. Register 1869aa9ce707Sdrh ** iOffset+1 is initialized to LIMIT+OFFSET. 1870aa9ce707Sdrh ** 1871ec7429aeSdrh ** Only if pLimit!=0 or pOffset!=0 do the limit registers get 18727b58daeaSdrh ** redefined. The UNION ALL operator uses this property to force 18737b58daeaSdrh ** the reuse of the same limit and offset registers across multiple 18747b58daeaSdrh ** SELECT statements. 18757b58daeaSdrh */ 1876ec7429aeSdrh static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ 187702afc861Sdrh Vdbe *v = 0; 187802afc861Sdrh int iLimit = 0; 187915007a99Sdrh int iOffset; 18808b0cf38aSdrh int n; 18810acb7e48Sdrh if( p->iLimit ) return; 188215007a99Sdrh 18837b58daeaSdrh /* 18847b58daeaSdrh ** "LIMIT -1" always shows all rows. There is some 1885f7b5496eSdrh ** controversy about what the correct behavior should be. 18867b58daeaSdrh ** The current implementation interprets "LIMIT 0" to mean 18877b58daeaSdrh ** no rows. 18887b58daeaSdrh */ 1889ceea3321Sdrh sqlite3ExprCacheClear(pParse); 1890373cc2ddSdrh assert( p->pOffset==0 || p->pLimit!=0 ); 1891a2dc3b1aSdanielk1977 if( p->pLimit ){ 18920a07c107Sdrh p->iLimit = iLimit = ++pParse->nMem; 189315007a99Sdrh v = sqlite3GetVdbe(pParse); 1894aa9ce707Sdrh assert( v!=0 ); 18959b918ed1Sdrh if( sqlite3ExprIsInteger(p->pLimit, &n) ){ 18969b918ed1Sdrh sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit); 18979b918ed1Sdrh VdbeComment((v, "LIMIT counter")); 1898456e4e4fSdrh if( n==0 ){ 1899076e85f5Sdrh sqlite3VdbeGoto(v, iBreak); 1900c3489bbfSdrh }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){ 1901c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)n); 1902c3489bbfSdrh p->selFlags |= SF_FixedLimit; 19039b918ed1Sdrh } 19049b918ed1Sdrh }else{ 1905b7654111Sdrh sqlite3ExprCode(pParse, p->pLimit, iLimit); 1906688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); 1907d4e70ebdSdrh VdbeComment((v, "LIMIT counter")); 190816897072Sdrh sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); 19099b918ed1Sdrh } 1910a2dc3b1aSdanielk1977 if( p->pOffset ){ 19110a07c107Sdrh p->iOffset = iOffset = ++pParse->nMem; 1912b7654111Sdrh pParse->nMem++; /* Allocate an extra register for limit+offset */ 1913b7654111Sdrh sqlite3ExprCode(pParse, p->pOffset, iOffset); 1914688852abSdrh sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v); 1915d4e70ebdSdrh VdbeComment((v, "OFFSET counter")); 1916cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset); 1917d4e70ebdSdrh VdbeComment((v, "LIMIT+OFFSET")); 1918b7654111Sdrh } 1919d59ba6ceSdrh } 19207b58daeaSdrh } 19217b58daeaSdrh 1922b7f9164eSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 1923fbc4ee7bSdrh /* 1924fbc4ee7bSdrh ** Return the appropriate collating sequence for the iCol-th column of 1925fbc4ee7bSdrh ** the result set for the compound-select statement "p". Return NULL if 1926fbc4ee7bSdrh ** the column has no default collating sequence. 1927fbc4ee7bSdrh ** 1928fbc4ee7bSdrh ** The collating sequence for the compound select is taken from the 1929fbc4ee7bSdrh ** left-most term of the select that has a collating sequence. 1930fbc4ee7bSdrh */ 1931dc1bdc4fSdanielk1977 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ 1932fbc4ee7bSdrh CollSeq *pRet; 1933dc1bdc4fSdanielk1977 if( p->pPrior ){ 1934dc1bdc4fSdanielk1977 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol); 1935fbc4ee7bSdrh }else{ 1936fbc4ee7bSdrh pRet = 0; 1937dc1bdc4fSdanielk1977 } 193810c081adSdrh assert( iCol>=0 ); 19392ec18a3cSdrh /* iCol must be less than p->pEList->nExpr. Otherwise an error would 19402ec18a3cSdrh ** have been thrown during name resolution and we would not have gotten 19412ec18a3cSdrh ** this far */ 19422ec18a3cSdrh if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){ 1943dc1bdc4fSdanielk1977 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr); 1944dc1bdc4fSdanielk1977 } 1945dc1bdc4fSdanielk1977 return pRet; 1946d3d39e93Sdrh } 1947d3d39e93Sdrh 194853bed45eSdan /* 194953bed45eSdan ** The select statement passed as the second parameter is a compound SELECT 195053bed45eSdan ** with an ORDER BY clause. This function allocates and returns a KeyInfo 195153bed45eSdan ** structure suitable for implementing the ORDER BY. 195253bed45eSdan ** 195353bed45eSdan ** Space to hold the KeyInfo structure is obtained from malloc. The calling 195453bed45eSdan ** function is responsible for ensuring that this structure is eventually 195553bed45eSdan ** freed. 195653bed45eSdan */ 195753bed45eSdan static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){ 195853bed45eSdan ExprList *pOrderBy = p->pOrderBy; 195953bed45eSdan int nOrderBy = p->pOrderBy->nExpr; 196053bed45eSdan sqlite3 *db = pParse->db; 196153bed45eSdan KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1); 196253bed45eSdan if( pRet ){ 196353bed45eSdan int i; 196453bed45eSdan for(i=0; i<nOrderBy; i++){ 196553bed45eSdan struct ExprList_item *pItem = &pOrderBy->a[i]; 196653bed45eSdan Expr *pTerm = pItem->pExpr; 196753bed45eSdan CollSeq *pColl; 196853bed45eSdan 196953bed45eSdan if( pTerm->flags & EP_Collate ){ 197053bed45eSdan pColl = sqlite3ExprCollSeq(pParse, pTerm); 197153bed45eSdan }else{ 197253bed45eSdan pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1); 197353bed45eSdan if( pColl==0 ) pColl = db->pDfltColl; 197453bed45eSdan pOrderBy->a[i].pExpr = 197553bed45eSdan sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName); 197653bed45eSdan } 197753bed45eSdan assert( sqlite3KeyInfoIsWriteable(pRet) ); 197853bed45eSdan pRet->aColl[i] = pColl; 197953bed45eSdan pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder; 198053bed45eSdan } 198153bed45eSdan } 198253bed45eSdan 198353bed45eSdan return pRet; 198453bed45eSdan } 1985d3d39e93Sdrh 1986781def29Sdrh #ifndef SQLITE_OMIT_CTE 1987781def29Sdrh /* 1988781def29Sdrh ** This routine generates VDBE code to compute the content of a WITH RECURSIVE 1989781def29Sdrh ** query of the form: 1990781def29Sdrh ** 1991781def29Sdrh ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>) 1992781def29Sdrh ** \___________/ \_______________/ 1993781def29Sdrh ** p->pPrior p 1994781def29Sdrh ** 1995781def29Sdrh ** 1996781def29Sdrh ** There is exactly one reference to the recursive-table in the FROM clause 19978a48b9c0Sdrh ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag. 1998781def29Sdrh ** 1999781def29Sdrh ** The setup-query runs once to generate an initial set of rows that go 2000781def29Sdrh ** into a Queue table. Rows are extracted from the Queue table one by 2001fe1c6bb9Sdrh ** one. Each row extracted from Queue is output to pDest. Then the single 2002fe1c6bb9Sdrh ** extracted row (now in the iCurrent table) becomes the content of the 2003fe1c6bb9Sdrh ** recursive-table for a recursive-query run. The output of the recursive-query 2004781def29Sdrh ** is added back into the Queue table. Then another row is extracted from Queue 2005781def29Sdrh ** and the iteration continues until the Queue table is empty. 2006781def29Sdrh ** 2007781def29Sdrh ** If the compound query operator is UNION then no duplicate rows are ever 2008781def29Sdrh ** inserted into the Queue table. The iDistinct table keeps a copy of all rows 2009781def29Sdrh ** that have ever been inserted into Queue and causes duplicates to be 2010781def29Sdrh ** discarded. If the operator is UNION ALL, then duplicates are allowed. 2011781def29Sdrh ** 2012781def29Sdrh ** If the query has an ORDER BY, then entries in the Queue table are kept in 2013781def29Sdrh ** ORDER BY order and the first entry is extracted for each cycle. Without 2014781def29Sdrh ** an ORDER BY, the Queue table is just a FIFO. 2015781def29Sdrh ** 2016781def29Sdrh ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows 2017781def29Sdrh ** have been output to pDest. A LIMIT of zero means to output no rows and a 2018781def29Sdrh ** negative LIMIT means to output all rows. If there is also an OFFSET clause 2019781def29Sdrh ** with a positive value, then the first OFFSET outputs are discarded rather 2020781def29Sdrh ** than being sent to pDest. The LIMIT count does not begin until after OFFSET 2021781def29Sdrh ** rows have been skipped. 2022781def29Sdrh */ 2023781def29Sdrh static void generateWithRecursiveQuery( 2024781def29Sdrh Parse *pParse, /* Parsing context */ 2025781def29Sdrh Select *p, /* The recursive SELECT to be coded */ 2026781def29Sdrh SelectDest *pDest /* What to do with query results */ 2027781def29Sdrh ){ 2028781def29Sdrh SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */ 2029781def29Sdrh int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */ 2030781def29Sdrh Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */ 2031781def29Sdrh Select *pSetup = p->pPrior; /* The setup query */ 2032781def29Sdrh int addrTop; /* Top of the loop */ 2033781def29Sdrh int addrCont, addrBreak; /* CONTINUE and BREAK addresses */ 2034edf83d1eSdrh int iCurrent = 0; /* The Current table */ 2035781def29Sdrh int regCurrent; /* Register holding Current table */ 2036781def29Sdrh int iQueue; /* The Queue table */ 2037781def29Sdrh int iDistinct = 0; /* To ensure unique results if UNION */ 20388e1ee88cSdrh int eDest = SRT_Fifo; /* How to write to Queue */ 2039781def29Sdrh SelectDest destQueue; /* SelectDest targetting the Queue table */ 2040781def29Sdrh int i; /* Loop counter */ 2041781def29Sdrh int rc; /* Result code */ 2042fe1c6bb9Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 2043aa9ce707Sdrh Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */ 2044aa9ce707Sdrh int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ 2045781def29Sdrh 2046781def29Sdrh /* Obtain authorization to do a recursive query */ 2047781def29Sdrh if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return; 2048781def29Sdrh 2049aa9ce707Sdrh /* Process the LIMIT and OFFSET clauses, if they exist */ 2050aa9ce707Sdrh addrBreak = sqlite3VdbeMakeLabel(v); 205169b9383eSdan p->nSelectRow = 320; /* 4 billion rows */ 2052aa9ce707Sdrh computeLimitRegisters(pParse, p, addrBreak); 2053aa9ce707Sdrh pLimit = p->pLimit; 2054aa9ce707Sdrh pOffset = p->pOffset; 2055aa9ce707Sdrh regLimit = p->iLimit; 2056aa9ce707Sdrh regOffset = p->iOffset; 2057aa9ce707Sdrh p->pLimit = p->pOffset = 0; 2058aa9ce707Sdrh p->iLimit = p->iOffset = 0; 205953bed45eSdan pOrderBy = p->pOrderBy; 2060781def29Sdrh 2061781def29Sdrh /* Locate the cursor number of the Current table */ 2062781def29Sdrh for(i=0; ALWAYS(i<pSrc->nSrc); i++){ 20638a48b9c0Sdrh if( pSrc->a[i].fg.isRecursive ){ 2064781def29Sdrh iCurrent = pSrc->a[i].iCursor; 2065781def29Sdrh break; 2066781def29Sdrh } 2067781def29Sdrh } 2068781def29Sdrh 2069fe1c6bb9Sdrh /* Allocate cursors numbers for Queue and Distinct. The cursor number for 2070781def29Sdrh ** the Distinct table must be exactly one greater than Queue in order 20718e1ee88cSdrh ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */ 2072781def29Sdrh iQueue = pParse->nTab++; 2073781def29Sdrh if( p->op==TK_UNION ){ 20748e1ee88cSdrh eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo; 2075781def29Sdrh iDistinct = pParse->nTab++; 2076fe1c6bb9Sdrh }else{ 20778e1ee88cSdrh eDest = pOrderBy ? SRT_Queue : SRT_Fifo; 2078781def29Sdrh } 2079781def29Sdrh sqlite3SelectDestInit(&destQueue, eDest, iQueue); 2080781def29Sdrh 2081781def29Sdrh /* Allocate cursors for Current, Queue, and Distinct. */ 2082781def29Sdrh regCurrent = ++pParse->nMem; 2083781def29Sdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol); 2084fe1c6bb9Sdrh if( pOrderBy ){ 208553bed45eSdan KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1); 2086fe1c6bb9Sdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0, 2087fe1c6bb9Sdrh (char*)pKeyInfo, P4_KEYINFO); 2088fe1c6bb9Sdrh destQueue.pOrderBy = pOrderBy; 2089fe1c6bb9Sdrh }else{ 2090781def29Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol); 2091fe1c6bb9Sdrh } 2092fe1c6bb9Sdrh VdbeComment((v, "Queue table")); 2093781def29Sdrh if( iDistinct ){ 2094781def29Sdrh p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0); 2095781def29Sdrh p->selFlags |= SF_UsesEphemeral; 2096781def29Sdrh } 2097781def29Sdrh 209853bed45eSdan /* Detach the ORDER BY clause from the compound SELECT */ 209953bed45eSdan p->pOrderBy = 0; 210053bed45eSdan 2101781def29Sdrh /* Store the results of the setup-query in Queue. */ 2102d227a291Sdrh pSetup->pNext = 0; 2103781def29Sdrh rc = sqlite3Select(pParse, pSetup, &destQueue); 2104d227a291Sdrh pSetup->pNext = p; 2105fe1c6bb9Sdrh if( rc ) goto end_of_recursive_query; 2106781def29Sdrh 2107781def29Sdrh /* Find the next row in the Queue and output that row */ 2108688852abSdrh addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v); 2109781def29Sdrh 2110781def29Sdrh /* Transfer the next row in Queue over to Current */ 2111781def29Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */ 2112fe1c6bb9Sdrh if( pOrderBy ){ 2113fe1c6bb9Sdrh sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent); 2114fe1c6bb9Sdrh }else{ 2115781def29Sdrh sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent); 2116fe1c6bb9Sdrh } 2117781def29Sdrh sqlite3VdbeAddOp1(v, OP_Delete, iQueue); 2118781def29Sdrh 2119fe1c6bb9Sdrh /* Output the single row in Current */ 2120fe1c6bb9Sdrh addrCont = sqlite3VdbeMakeLabel(v); 2121aa9ce707Sdrh codeOffset(v, regOffset, addrCont); 2122fe1c6bb9Sdrh selectInnerLoop(pParse, p, p->pEList, iCurrent, 2123079a3072Sdrh 0, 0, pDest, addrCont, addrBreak); 2124688852abSdrh if( regLimit ){ 212516897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak); 2126688852abSdrh VdbeCoverage(v); 2127688852abSdrh } 2128fe1c6bb9Sdrh sqlite3VdbeResolveLabel(v, addrCont); 2129fe1c6bb9Sdrh 2130781def29Sdrh /* Execute the recursive SELECT taking the single row in Current as 2131781def29Sdrh ** the value for the recursive-table. Store the results in the Queue. 2132781def29Sdrh */ 2133b63ce02fSdrh if( p->selFlags & SF_Aggregate ){ 2134b63ce02fSdrh sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported"); 2135b63ce02fSdrh }else{ 2136781def29Sdrh p->pPrior = 0; 2137781def29Sdrh sqlite3Select(pParse, p, &destQueue); 2138781def29Sdrh assert( p->pPrior==0 ); 2139781def29Sdrh p->pPrior = pSetup; 2140b63ce02fSdrh } 2141781def29Sdrh 2142781def29Sdrh /* Keep running the loop until the Queue is empty */ 2143076e85f5Sdrh sqlite3VdbeGoto(v, addrTop); 2144781def29Sdrh sqlite3VdbeResolveLabel(v, addrBreak); 2145fe1c6bb9Sdrh 2146fe1c6bb9Sdrh end_of_recursive_query: 21479afccba2Sdan sqlite3ExprListDelete(pParse->db, p->pOrderBy); 2148fe1c6bb9Sdrh p->pOrderBy = pOrderBy; 2149aa9ce707Sdrh p->pLimit = pLimit; 2150aa9ce707Sdrh p->pOffset = pOffset; 2151fe1c6bb9Sdrh return; 2152781def29Sdrh } 2153b68b9778Sdan #endif /* SQLITE_OMIT_CTE */ 2154781def29Sdrh 2155781def29Sdrh /* Forward references */ 2156b21e7c70Sdrh static int multiSelectOrderBy( 2157b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2158b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2159a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2160b21e7c70Sdrh ); 2161b21e7c70Sdrh 216245f54a57Sdrh /* 216345f54a57Sdrh ** Handle the special case of a compound-select that originates from a 216445f54a57Sdrh ** VALUES clause. By handling this as a special case, we avoid deep 216545f54a57Sdrh ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT 216645f54a57Sdrh ** on a VALUES clause. 216745f54a57Sdrh ** 216845f54a57Sdrh ** Because the Select object originates from a VALUES clause: 216945f54a57Sdrh ** (1) It has no LIMIT or OFFSET 217045f54a57Sdrh ** (2) All terms are UNION ALL 217145f54a57Sdrh ** (3) There is no ORDER BY clause 217245f54a57Sdrh */ 217345f54a57Sdrh static int multiSelectValues( 217445f54a57Sdrh Parse *pParse, /* Parsing context */ 217545f54a57Sdrh Select *p, /* The right-most of SELECTs to be coded */ 217645f54a57Sdrh SelectDest *pDest /* What to do with query results */ 217745f54a57Sdrh ){ 217845f54a57Sdrh Select *pPrior; 217945f54a57Sdrh int nRow = 1; 218045f54a57Sdrh int rc = 0; 2181772460fdSdrh assert( p->selFlags & SF_MultiValue ); 218245f54a57Sdrh do{ 218345f54a57Sdrh assert( p->selFlags & SF_Values ); 218445f54a57Sdrh assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) ); 218545f54a57Sdrh assert( p->pLimit==0 ); 218645f54a57Sdrh assert( p->pOffset==0 ); 2187923cadb1Sdan assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); 218845f54a57Sdrh if( p->pPrior==0 ) break; 218945f54a57Sdrh assert( p->pPrior->pNext==p ); 219045f54a57Sdrh p = p->pPrior; 219145f54a57Sdrh nRow++; 219245f54a57Sdrh }while(1); 219345f54a57Sdrh while( p ){ 219445f54a57Sdrh pPrior = p->pPrior; 219545f54a57Sdrh p->pPrior = 0; 219645f54a57Sdrh rc = sqlite3Select(pParse, p, pDest); 219745f54a57Sdrh p->pPrior = pPrior; 219845f54a57Sdrh if( rc ) break; 219945f54a57Sdrh p->nSelectRow = nRow; 220045f54a57Sdrh p = p->pNext; 220145f54a57Sdrh } 220245f54a57Sdrh return rc; 220345f54a57Sdrh } 2204b21e7c70Sdrh 2205d3d39e93Sdrh /* 220616ee60ffSdrh ** This routine is called to process a compound query form from 220716ee60ffSdrh ** two or more separate queries using UNION, UNION ALL, EXCEPT, or 220816ee60ffSdrh ** INTERSECT 2209c926afbcSdrh ** 2210e78e8284Sdrh ** "p" points to the right-most of the two queries. the query on the 2211e78e8284Sdrh ** left is p->pPrior. The left query could also be a compound query 2212e78e8284Sdrh ** in which case this routine will be called recursively. 2213e78e8284Sdrh ** 2214e78e8284Sdrh ** The results of the total query are to be written into a destination 2215e78e8284Sdrh ** of type eDest with parameter iParm. 2216e78e8284Sdrh ** 2217e78e8284Sdrh ** Example 1: Consider a three-way compound SQL statement. 2218e78e8284Sdrh ** 2219e78e8284Sdrh ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3 2220e78e8284Sdrh ** 2221e78e8284Sdrh ** This statement is parsed up as follows: 2222e78e8284Sdrh ** 2223e78e8284Sdrh ** SELECT c FROM t3 2224e78e8284Sdrh ** | 2225e78e8284Sdrh ** `-----> SELECT b FROM t2 2226e78e8284Sdrh ** | 22274b11c6d3Sjplyon ** `------> SELECT a FROM t1 2228e78e8284Sdrh ** 2229e78e8284Sdrh ** The arrows in the diagram above represent the Select.pPrior pointer. 2230e78e8284Sdrh ** So if this routine is called with p equal to the t3 query, then 2231e78e8284Sdrh ** pPrior will be the t2 query. p->op will be TK_UNION in this case. 2232e78e8284Sdrh ** 2233e78e8284Sdrh ** Notice that because of the way SQLite parses compound SELECTs, the 2234e78e8284Sdrh ** individual selects always group from left to right. 223582c3d636Sdrh */ 223684ac9d02Sdanielk1977 static int multiSelect( 2237fbc4ee7bSdrh Parse *pParse, /* Parsing context */ 2238fbc4ee7bSdrh Select *p, /* The right-most of SELECTs to be coded */ 2239a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 224084ac9d02Sdanielk1977 ){ 224184ac9d02Sdanielk1977 int rc = SQLITE_OK; /* Success code from a subroutine */ 224210e5e3cfSdrh Select *pPrior; /* Another SELECT immediately to our left */ 224310e5e3cfSdrh Vdbe *v; /* Generate code to this VDBE */ 22441013c932Sdrh SelectDest dest; /* Alternative data destination */ 2245eca7e01aSdanielk1977 Select *pDelete = 0; /* Chain of simple selects to delete */ 2246633e6d57Sdrh sqlite3 *db; /* Database connection */ 22477f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 2248edf83d1eSdrh int iSub1 = 0; /* EQP id of left-hand query */ 2249edf83d1eSdrh int iSub2 = 0; /* EQP id of right-hand query */ 22507f61e92cSdan #endif 225182c3d636Sdrh 22527b58daeaSdrh /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only 2253fbc4ee7bSdrh ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. 225482c3d636Sdrh */ 2255701bb3b4Sdrh assert( p && p->pPrior ); /* Calling function guarantees this much */ 2256eae73fbfSdan assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); 2257633e6d57Sdrh db = pParse->db; 2258d8bc7086Sdrh pPrior = p->pPrior; 2259bc10377aSdrh dest = *pDest; 2260d8bc7086Sdrh if( pPrior->pOrderBy ){ 22614adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before", 2262da93d238Sdrh selectOpName(p->op)); 226384ac9d02Sdanielk1977 rc = 1; 226484ac9d02Sdanielk1977 goto multi_select_end; 226582c3d636Sdrh } 2266a2dc3b1aSdanielk1977 if( pPrior->pLimit ){ 22674adee20fSdanielk1977 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before", 22687b58daeaSdrh selectOpName(p->op)); 226984ac9d02Sdanielk1977 rc = 1; 227084ac9d02Sdanielk1977 goto multi_select_end; 22717b58daeaSdrh } 227282c3d636Sdrh 22734adee20fSdanielk1977 v = sqlite3GetVdbe(pParse); 2274701bb3b4Sdrh assert( v!=0 ); /* The VDBE already created by calling function */ 2275d8bc7086Sdrh 22761cc3d75fSdrh /* Create the destination temporary table if necessary 22771cc3d75fSdrh */ 22786c8c8ce0Sdanielk1977 if( dest.eDest==SRT_EphemTab ){ 2279b4964b72Sdanielk1977 assert( p->pEList ); 22802b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr); 22816c8c8ce0Sdanielk1977 dest.eDest = SRT_Table; 22821cc3d75fSdrh } 22831cc3d75fSdrh 228445f54a57Sdrh /* Special handling for a compound-select that originates as a VALUES clause. 228545f54a57Sdrh */ 2286772460fdSdrh if( p->selFlags & SF_MultiValue ){ 228745f54a57Sdrh rc = multiSelectValues(pParse, p, &dest); 228845f54a57Sdrh goto multi_select_end; 228945f54a57Sdrh } 229045f54a57Sdrh 2291f6e369a1Sdrh /* Make sure all SELECTs in the statement have the same number of elements 2292f6e369a1Sdrh ** in their result sets. 2293f6e369a1Sdrh */ 2294f6e369a1Sdrh assert( p->pEList && pPrior->pEList ); 2295923cadb1Sdan assert( p->pEList->nExpr==pPrior->pEList->nExpr ); 2296f6e369a1Sdrh 2297eede6a53Sdan #ifndef SQLITE_OMIT_CTE 2298eae73fbfSdan if( p->selFlags & SF_Recursive ){ 2299781def29Sdrh generateWithRecursiveQuery(pParse, p, &dest); 23008ce7184bSdan }else 23018ce7184bSdan #endif 2302f6e369a1Sdrh 2303a9671a22Sdrh /* Compound SELECTs that have an ORDER BY clause are handled separately. 2304a9671a22Sdrh */ 2305f6e369a1Sdrh if( p->pOrderBy ){ 2306a9671a22Sdrh return multiSelectOrderBy(pParse, p, pDest); 2307eede6a53Sdan }else 2308f6e369a1Sdrh 2309f46f905aSdrh /* Generate code for the left and right SELECT statements. 2310d8bc7086Sdrh */ 231182c3d636Sdrh switch( p->op ){ 2312f46f905aSdrh case TK_ALL: { 2313ec7429aeSdrh int addr = 0; 231495aa47b1Sdrh int nLimit; 2315a2dc3b1aSdanielk1977 assert( !pPrior->pLimit ); 2316547180baSdrh pPrior->iLimit = p->iLimit; 2317547180baSdrh pPrior->iOffset = p->iOffset; 2318a2dc3b1aSdanielk1977 pPrior->pLimit = p->pLimit; 2319a2dc3b1aSdanielk1977 pPrior->pOffset = p->pOffset; 23207f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 23217d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &dest); 2322ad68cb6bSdanielk1977 p->pLimit = 0; 2323ad68cb6bSdanielk1977 p->pOffset = 0; 232484ac9d02Sdanielk1977 if( rc ){ 232584ac9d02Sdanielk1977 goto multi_select_end; 232684ac9d02Sdanielk1977 } 2327f46f905aSdrh p->pPrior = 0; 23287b58daeaSdrh p->iLimit = pPrior->iLimit; 23297b58daeaSdrh p->iOffset = pPrior->iOffset; 233092b01d53Sdrh if( p->iLimit ){ 233116897072Sdrh addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v); 2332d4e70ebdSdrh VdbeComment((v, "Jump ahead if LIMIT reached")); 23339f1ef45fSdrh if( p->iOffset ){ 2334cc2fa4cfSdrh sqlite3VdbeAddOp3(v, OP_OffsetLimit, 2335cc2fa4cfSdrh p->iLimit, p->iOffset+1, p->iOffset); 23369f1ef45fSdrh } 2337ec7429aeSdrh } 23387f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 23397d10d5a6Sdrh rc = sqlite3Select(pParse, p, &dest); 2340373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2341eca7e01aSdanielk1977 pDelete = p->pPrior; 2342f46f905aSdrh p->pPrior = pPrior; 2343c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 234495aa47b1Sdrh if( pPrior->pLimit 234595aa47b1Sdrh && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit) 2346c3489bbfSdrh && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 234795aa47b1Sdrh ){ 2348c3489bbfSdrh p->nSelectRow = sqlite3LogEst((u64)nLimit); 234995aa47b1Sdrh } 2350ec7429aeSdrh if( addr ){ 2351ec7429aeSdrh sqlite3VdbeJumpHere(v, addr); 2352ec7429aeSdrh } 2353f46f905aSdrh break; 2354f46f905aSdrh } 235582c3d636Sdrh case TK_EXCEPT: 235682c3d636Sdrh case TK_UNION: { 2357d8bc7086Sdrh int unionTab; /* Cursor number of the temporary table holding result */ 2358ea678832Sdrh u8 op = 0; /* One of the SRT_ operations to apply to self */ 2359d8bc7086Sdrh int priorOp; /* The SRT_ operation to apply to prior selects */ 2360a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ 2361dc1bdc4fSdanielk1977 int addr; 23626c8c8ce0Sdanielk1977 SelectDest uniondest; 236382c3d636Sdrh 2364373cc2ddSdrh testcase( p->op==TK_EXCEPT ); 2365373cc2ddSdrh testcase( p->op==TK_UNION ); 236693a960a0Sdrh priorOp = SRT_Union; 2367d227a291Sdrh if( dest.eDest==priorOp ){ 2368d8bc7086Sdrh /* We can reuse a temporary table generated by a SELECT to our 2369c926afbcSdrh ** right. 2370d8bc7086Sdrh */ 2371e2f02bacSdrh assert( p->pLimit==0 ); /* Not allowed on leftward elements */ 2372e2f02bacSdrh assert( p->pOffset==0 ); /* Not allowed on leftward elements */ 23732b596da8Sdrh unionTab = dest.iSDParm; 237482c3d636Sdrh }else{ 2375d8bc7086Sdrh /* We will need to create our own temporary table to hold the 2376d8bc7086Sdrh ** intermediate results. 2377d8bc7086Sdrh */ 237882c3d636Sdrh unionTab = pParse->nTab++; 237993a960a0Sdrh assert( p->pOrderBy==0 ); 238066a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); 2381b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2382b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2383d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 238484ac9d02Sdanielk1977 assert( p->pEList ); 2385d8bc7086Sdrh } 2386d8bc7086Sdrh 2387d8bc7086Sdrh /* Code the SELECT statements to our left 2388d8bc7086Sdrh */ 2389b3bce662Sdanielk1977 assert( !pPrior->pOrderBy ); 23901013c932Sdrh sqlite3SelectDestInit(&uniondest, priorOp, unionTab); 23917f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 23927d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &uniondest); 239384ac9d02Sdanielk1977 if( rc ){ 239484ac9d02Sdanielk1977 goto multi_select_end; 239584ac9d02Sdanielk1977 } 2396d8bc7086Sdrh 2397d8bc7086Sdrh /* Code the current SELECT statement 2398d8bc7086Sdrh */ 23994cfb22f7Sdrh if( p->op==TK_EXCEPT ){ 24004cfb22f7Sdrh op = SRT_Except; 24014cfb22f7Sdrh }else{ 24024cfb22f7Sdrh assert( p->op==TK_UNION ); 24034cfb22f7Sdrh op = SRT_Union; 2404d8bc7086Sdrh } 240582c3d636Sdrh p->pPrior = 0; 2406a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2407a2dc3b1aSdanielk1977 p->pLimit = 0; 2408a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2409a2dc3b1aSdanielk1977 p->pOffset = 0; 24106c8c8ce0Sdanielk1977 uniondest.eDest = op; 24117f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 24127d10d5a6Sdrh rc = sqlite3Select(pParse, p, &uniondest); 2413373cc2ddSdrh testcase( rc!=SQLITE_OK ); 24145bd1bf2eSdrh /* Query flattening in sqlite3Select() might refill p->pOrderBy. 24155bd1bf2eSdrh ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ 2416633e6d57Sdrh sqlite3ExprListDelete(db, p->pOrderBy); 2417eca7e01aSdanielk1977 pDelete = p->pPrior; 241882c3d636Sdrh p->pPrior = pPrior; 2419a9671a22Sdrh p->pOrderBy = 0; 2420c3489bbfSdrh if( p->op==TK_UNION ){ 2421c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 2422c3489bbfSdrh } 2423633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2424a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2425a2dc3b1aSdanielk1977 p->pOffset = pOffset; 242692b01d53Sdrh p->iLimit = 0; 242792b01d53Sdrh p->iOffset = 0; 2428d8bc7086Sdrh 2429d8bc7086Sdrh /* Convert the data in the temporary table into whatever form 2430d8bc7086Sdrh ** it is that we currently need. 2431d8bc7086Sdrh */ 24322b596da8Sdrh assert( unionTab==dest.iSDParm || dest.eDest!=priorOp ); 2433373cc2ddSdrh if( dest.eDest!=priorOp ){ 24346b56344dSdrh int iCont, iBreak, iStart; 243582c3d636Sdrh assert( p->pEList ); 24367d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 243792378253Sdrh Select *pFirst = p; 243892378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 24399a8941fcSdan generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); 244041202ccaSdrh } 24414adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 24424adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2443ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2444688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v); 24454adee20fSdanielk1977 iStart = sqlite3VdbeCurrentAddr(v); 2446340309fdSdrh selectInnerLoop(pParse, p, p->pEList, unionTab, 2447e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 24484adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2449688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v); 24504adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 245166a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); 245282c3d636Sdrh } 245382c3d636Sdrh break; 245482c3d636Sdrh } 2455373cc2ddSdrh default: assert( p->op==TK_INTERSECT ); { 245682c3d636Sdrh int tab1, tab2; 24576b56344dSdrh int iCont, iBreak, iStart; 2458a2dc3b1aSdanielk1977 Expr *pLimit, *pOffset; 2459dc1bdc4fSdanielk1977 int addr; 24601013c932Sdrh SelectDest intersectdest; 24619cbf3425Sdrh int r1; 246282c3d636Sdrh 2463d8bc7086Sdrh /* INTERSECT is different from the others since it requires 24646206d50aSdrh ** two temporary tables. Hence it has its own case. Begin 2465d8bc7086Sdrh ** by allocating the tables we will need. 2466d8bc7086Sdrh */ 246782c3d636Sdrh tab1 = pParse->nTab++; 246882c3d636Sdrh tab2 = pParse->nTab++; 246993a960a0Sdrh assert( p->pOrderBy==0 ); 2470dc1bdc4fSdanielk1977 247166a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); 2472b9bb7c18Sdrh assert( p->addrOpenEphm[0] == -1 ); 2473b9bb7c18Sdrh p->addrOpenEphm[0] = addr; 2474d227a291Sdrh findRightmost(p)->selFlags |= SF_UsesEphemeral; 247584ac9d02Sdanielk1977 assert( p->pEList ); 2476d8bc7086Sdrh 2477d8bc7086Sdrh /* Code the SELECTs to our left into temporary table "tab1". 2478d8bc7086Sdrh */ 24791013c932Sdrh sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); 24807f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 24817d10d5a6Sdrh rc = sqlite3Select(pParse, pPrior, &intersectdest); 248284ac9d02Sdanielk1977 if( rc ){ 248384ac9d02Sdanielk1977 goto multi_select_end; 248484ac9d02Sdanielk1977 } 2485d8bc7086Sdrh 2486d8bc7086Sdrh /* Code the current SELECT into temporary table "tab2" 2487d8bc7086Sdrh */ 248866a5167bSdrh addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); 2489b9bb7c18Sdrh assert( p->addrOpenEphm[1] == -1 ); 2490b9bb7c18Sdrh p->addrOpenEphm[1] = addr; 249182c3d636Sdrh p->pPrior = 0; 2492a2dc3b1aSdanielk1977 pLimit = p->pLimit; 2493a2dc3b1aSdanielk1977 p->pLimit = 0; 2494a2dc3b1aSdanielk1977 pOffset = p->pOffset; 2495a2dc3b1aSdanielk1977 p->pOffset = 0; 24962b596da8Sdrh intersectdest.iSDParm = tab2; 24977f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 24987d10d5a6Sdrh rc = sqlite3Select(pParse, p, &intersectdest); 2499373cc2ddSdrh testcase( rc!=SQLITE_OK ); 2500eca7e01aSdanielk1977 pDelete = p->pPrior; 250182c3d636Sdrh p->pPrior = pPrior; 250295aa47b1Sdrh if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 2503633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 2504a2dc3b1aSdanielk1977 p->pLimit = pLimit; 2505a2dc3b1aSdanielk1977 p->pOffset = pOffset; 2506d8bc7086Sdrh 2507d8bc7086Sdrh /* Generate code to take the intersection of the two temporary 2508d8bc7086Sdrh ** tables. 2509d8bc7086Sdrh */ 251082c3d636Sdrh assert( p->pEList ); 25117d10d5a6Sdrh if( dest.eDest==SRT_Output ){ 251292378253Sdrh Select *pFirst = p; 251392378253Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 25149a8941fcSdan generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); 251541202ccaSdrh } 25164adee20fSdanielk1977 iBreak = sqlite3VdbeMakeLabel(v); 25174adee20fSdanielk1977 iCont = sqlite3VdbeMakeLabel(v); 2518ec7429aeSdrh computeLimitRegisters(pParse, p, iBreak); 2519688852abSdrh sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v); 25209cbf3425Sdrh r1 = sqlite3GetTempReg(pParse); 25219057fc7cSdrh iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1); 2522688852abSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v); 25239cbf3425Sdrh sqlite3ReleaseTempReg(pParse, r1); 2524340309fdSdrh selectInnerLoop(pParse, p, p->pEList, tab1, 2525e8e4af76Sdrh 0, 0, &dest, iCont, iBreak); 25264adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iCont); 2527688852abSdrh sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v); 25284adee20fSdanielk1977 sqlite3VdbeResolveLabel(v, iBreak); 252966a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); 253066a5167bSdrh sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); 253182c3d636Sdrh break; 253282c3d636Sdrh } 253382c3d636Sdrh } 25348cdbf836Sdrh 25357f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); 25367f61e92cSdan 2537a9671a22Sdrh /* Compute collating sequences used by 2538a9671a22Sdrh ** temporary tables needed to implement the compound select. 2539a9671a22Sdrh ** Attach the KeyInfo structure to all temporary tables. 25408cdbf836Sdrh ** 25418cdbf836Sdrh ** This section is run by the right-most SELECT statement only. 25428cdbf836Sdrh ** SELECT statements to the left always skip this part. The right-most 25438cdbf836Sdrh ** SELECT might also skip this part if it has no ORDER BY clause and 25448cdbf836Sdrh ** no temp tables are required. 2545fbc4ee7bSdrh */ 25467d10d5a6Sdrh if( p->selFlags & SF_UsesEphemeral ){ 2547fbc4ee7bSdrh int i; /* Loop counter */ 2548fbc4ee7bSdrh KeyInfo *pKeyInfo; /* Collating sequence for the result set */ 25490342b1f5Sdrh Select *pLoop; /* For looping through SELECT statements */ 2550f68d7d17Sdrh CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ 255193a960a0Sdrh int nCol; /* Number of columns in result set */ 2552fbc4ee7bSdrh 2553d227a291Sdrh assert( p->pNext==0 ); 255493a960a0Sdrh nCol = p->pEList->nExpr; 2555ad124329Sdrh pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1); 2556dc1bdc4fSdanielk1977 if( !pKeyInfo ){ 2557fad3039cSmistachkin rc = SQLITE_NOMEM_BKPT; 2558dc1bdc4fSdanielk1977 goto multi_select_end; 2559dc1bdc4fSdanielk1977 } 25600342b1f5Sdrh for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){ 25610342b1f5Sdrh *apColl = multiSelectCollSeq(pParse, p, i); 25620342b1f5Sdrh if( 0==*apColl ){ 2563633e6d57Sdrh *apColl = db->pDfltColl; 2564dc1bdc4fSdanielk1977 } 2565dc1bdc4fSdanielk1977 } 2566dc1bdc4fSdanielk1977 25670342b1f5Sdrh for(pLoop=p; pLoop; pLoop=pLoop->pPrior){ 25680342b1f5Sdrh for(i=0; i<2; i++){ 2569b9bb7c18Sdrh int addr = pLoop->addrOpenEphm[i]; 25700342b1f5Sdrh if( addr<0 ){ 25710342b1f5Sdrh /* If [0] is unused then [1] is also unused. So we can 25720342b1f5Sdrh ** always safely abort as soon as the first unused slot is found */ 2573b9bb7c18Sdrh assert( pLoop->addrOpenEphm[1]<0 ); 25740342b1f5Sdrh break; 25750342b1f5Sdrh } 25760342b1f5Sdrh sqlite3VdbeChangeP2(v, addr, nCol); 25772ec2fb22Sdrh sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo), 25782ec2fb22Sdrh P4_KEYINFO); 25790ee5a1e7Sdrh pLoop->addrOpenEphm[i] = -1; 25800342b1f5Sdrh } 2581dc1bdc4fSdanielk1977 } 25822ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyInfo); 2583dc1bdc4fSdanielk1977 } 2584dc1bdc4fSdanielk1977 2585dc1bdc4fSdanielk1977 multi_select_end: 25862b596da8Sdrh pDest->iSdst = dest.iSdst; 25872b596da8Sdrh pDest->nSdst = dest.nSdst; 2588633e6d57Sdrh sqlite3SelectDelete(db, pDelete); 258984ac9d02Sdanielk1977 return rc; 25902282792aSdrh } 2591b7f9164eSdrh #endif /* SQLITE_OMIT_COMPOUND_SELECT */ 25922282792aSdrh 2593b21e7c70Sdrh /* 259489b31d73Smistachkin ** Error message for when two or more terms of a compound select have different 259589b31d73Smistachkin ** size result sets. 259689b31d73Smistachkin */ 259789b31d73Smistachkin void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){ 259889b31d73Smistachkin if( p->selFlags & SF_Values ){ 259989b31d73Smistachkin sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms"); 260089b31d73Smistachkin }else{ 260189b31d73Smistachkin sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s" 260289b31d73Smistachkin " do not have the same number of result columns", selectOpName(p->op)); 260389b31d73Smistachkin } 260489b31d73Smistachkin } 260589b31d73Smistachkin 260689b31d73Smistachkin /* 2607b21e7c70Sdrh ** Code an output subroutine for a coroutine implementation of a 2608b21e7c70Sdrh ** SELECT statment. 26090acb7e48Sdrh ** 26102b596da8Sdrh ** The data to be output is contained in pIn->iSdst. There are 26112b596da8Sdrh ** pIn->nSdst columns to be output. pDest is where the output should 26120acb7e48Sdrh ** be sent. 26130acb7e48Sdrh ** 26140acb7e48Sdrh ** regReturn is the number of the register holding the subroutine 26150acb7e48Sdrh ** return address. 26160acb7e48Sdrh ** 2617f053d5b6Sdrh ** If regPrev>0 then it is the first register in a vector that 26180acb7e48Sdrh ** records the previous output. mem[regPrev] is a flag that is false 26190acb7e48Sdrh ** if there has been no previous output. If regPrev>0 then code is 26200acb7e48Sdrh ** generated to suppress duplicates. pKeyInfo is used for comparing 26210acb7e48Sdrh ** keys. 26220acb7e48Sdrh ** 26230acb7e48Sdrh ** If the LIMIT found in p->iLimit is reached, jump immediately to 26240acb7e48Sdrh ** iBreak. 2625b21e7c70Sdrh */ 26260acb7e48Sdrh static int generateOutputSubroutine( 262792b01d53Sdrh Parse *pParse, /* Parsing context */ 262892b01d53Sdrh Select *p, /* The SELECT statement */ 262992b01d53Sdrh SelectDest *pIn, /* Coroutine supplying data */ 263092b01d53Sdrh SelectDest *pDest, /* Where to send the data */ 263192b01d53Sdrh int regReturn, /* The return address register */ 26320acb7e48Sdrh int regPrev, /* Previous result register. No uniqueness if 0 */ 26330acb7e48Sdrh KeyInfo *pKeyInfo, /* For comparing with previous entry */ 263492b01d53Sdrh int iBreak /* Jump here if we hit the LIMIT */ 2635b21e7c70Sdrh ){ 2636b21e7c70Sdrh Vdbe *v = pParse->pVdbe; 263792b01d53Sdrh int iContinue; 263892b01d53Sdrh int addr; 2639b21e7c70Sdrh 264092b01d53Sdrh addr = sqlite3VdbeCurrentAddr(v); 264192b01d53Sdrh iContinue = sqlite3VdbeMakeLabel(v); 26420acb7e48Sdrh 26430acb7e48Sdrh /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 26440acb7e48Sdrh */ 26450acb7e48Sdrh if( regPrev ){ 2646728e0f91Sdrh int addr1, addr2; 2647728e0f91Sdrh addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v); 2648728e0f91Sdrh addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst, 26492ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 2650728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v); 2651728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 2652e8e4af76Sdrh sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1); 2653ec86c724Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); 26540acb7e48Sdrh } 26551f9caa41Sdanielk1977 if( pParse->db->mallocFailed ) return 0; 26560acb7e48Sdrh 2657d5578433Smistachkin /* Suppress the first OFFSET entries if there is an OFFSET clause 26580acb7e48Sdrh */ 2659aa9ce707Sdrh codeOffset(v, p->iOffset, iContinue); 2660b21e7c70Sdrh 2661e2248cfdSdrh assert( pDest->eDest!=SRT_Exists ); 2662e2248cfdSdrh assert( pDest->eDest!=SRT_Table ); 2663b21e7c70Sdrh switch( pDest->eDest ){ 2664b21e7c70Sdrh /* Store the result as data using a unique key. 2665b21e7c70Sdrh */ 2666b21e7c70Sdrh case SRT_EphemTab: { 2667b21e7c70Sdrh int r1 = sqlite3GetTempReg(pParse); 2668b21e7c70Sdrh int r2 = sqlite3GetTempReg(pParse); 26692b596da8Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1); 26702b596da8Sdrh sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2); 26712b596da8Sdrh sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2); 2672b21e7c70Sdrh sqlite3VdbeChangeP5(v, OPFLAG_APPEND); 2673b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r2); 2674b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2675b21e7c70Sdrh break; 2676b21e7c70Sdrh } 2677b21e7c70Sdrh 2678b21e7c70Sdrh #ifndef SQLITE_OMIT_SUBQUERY 26791431807aSdrh /* If we are creating a set for an "expr IN (SELECT ...)". 2680b21e7c70Sdrh */ 2681b21e7c70Sdrh case SRT_Set: { 26826fccc35aSdrh int r1; 268363cecc41Sdrh testcase( pIn->nSdst>1 ); 2684b21e7c70Sdrh r1 = sqlite3GetTempReg(pParse); 268571c57db0Sdan sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 26861431807aSdrh r1, pDest->zAffSdst, pIn->nSdst); 26871431807aSdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 26889b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1, 26899b4eaebcSdrh pIn->iSdst, pIn->nSdst); 2690b21e7c70Sdrh sqlite3ReleaseTempReg(pParse, r1); 2691b21e7c70Sdrh break; 2692b21e7c70Sdrh } 2693b21e7c70Sdrh 2694b21e7c70Sdrh /* If this is a scalar select that is part of an expression, then 2695b21e7c70Sdrh ** store the results in the appropriate memory cell and break out 2696b21e7c70Sdrh ** of the scan loop. 2697b21e7c70Sdrh */ 2698b21e7c70Sdrh case SRT_Mem: { 2699a276e3fdSdrh assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); 27002b596da8Sdrh sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); 2701b21e7c70Sdrh /* The LIMIT clause will jump out of the loop for us */ 2702b21e7c70Sdrh break; 2703b21e7c70Sdrh } 2704b21e7c70Sdrh #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ 2705b21e7c70Sdrh 27067d10d5a6Sdrh /* The results are stored in a sequence of registers 27072b596da8Sdrh ** starting at pDest->iSdst. Then the co-routine yields. 2708b21e7c70Sdrh */ 270992b01d53Sdrh case SRT_Coroutine: { 27102b596da8Sdrh if( pDest->iSdst==0 ){ 27112b596da8Sdrh pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst); 27122b596da8Sdrh pDest->nSdst = pIn->nSdst; 2713b21e7c70Sdrh } 27144b79bde7Sdan sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst); 27152b596da8Sdrh sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm); 271692b01d53Sdrh break; 271792b01d53Sdrh } 271892b01d53Sdrh 2719ccfcbceaSdrh /* If none of the above, then the result destination must be 2720ccfcbceaSdrh ** SRT_Output. This routine is never called with any other 2721ccfcbceaSdrh ** destination other than the ones handled above or SRT_Output. 2722ccfcbceaSdrh ** 2723ccfcbceaSdrh ** For SRT_Output, results are stored in a sequence of registers. 2724ccfcbceaSdrh ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to 2725ccfcbceaSdrh ** return the next row of result. 27267d10d5a6Sdrh */ 2727ccfcbceaSdrh default: { 2728ccfcbceaSdrh assert( pDest->eDest==SRT_Output ); 27292b596da8Sdrh sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst); 27302b596da8Sdrh sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst); 2731b21e7c70Sdrh break; 2732b21e7c70Sdrh } 2733b21e7c70Sdrh } 273492b01d53Sdrh 273592b01d53Sdrh /* Jump to the end of the loop if the LIMIT is reached. 273692b01d53Sdrh */ 273792b01d53Sdrh if( p->iLimit ){ 273816897072Sdrh sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v); 273992b01d53Sdrh } 274092b01d53Sdrh 274192b01d53Sdrh /* Generate the subroutine return 274292b01d53Sdrh */ 27430acb7e48Sdrh sqlite3VdbeResolveLabel(v, iContinue); 274492b01d53Sdrh sqlite3VdbeAddOp1(v, OP_Return, regReturn); 274592b01d53Sdrh 274692b01d53Sdrh return addr; 2747b21e7c70Sdrh } 2748b21e7c70Sdrh 2749b21e7c70Sdrh /* 2750b21e7c70Sdrh ** Alternative compound select code generator for cases when there 2751b21e7c70Sdrh ** is an ORDER BY clause. 2752b21e7c70Sdrh ** 2753b21e7c70Sdrh ** We assume a query of the following form: 2754b21e7c70Sdrh ** 2755b21e7c70Sdrh ** <selectA> <operator> <selectB> ORDER BY <orderbylist> 2756b21e7c70Sdrh ** 2757b21e7c70Sdrh ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea 2758b21e7c70Sdrh ** is to code both <selectA> and <selectB> with the ORDER BY clause as 2759b21e7c70Sdrh ** co-routines. Then run the co-routines in parallel and merge the results 2760b21e7c70Sdrh ** into the output. In addition to the two coroutines (called selectA and 2761b21e7c70Sdrh ** selectB) there are 7 subroutines: 2762b21e7c70Sdrh ** 2763b21e7c70Sdrh ** outA: Move the output of the selectA coroutine into the output 2764b21e7c70Sdrh ** of the compound query. 2765b21e7c70Sdrh ** 2766b21e7c70Sdrh ** outB: Move the output of the selectB coroutine into the output 2767b21e7c70Sdrh ** of the compound query. (Only generated for UNION and 2768b21e7c70Sdrh ** UNION ALL. EXCEPT and INSERTSECT never output a row that 2769b21e7c70Sdrh ** appears only in B.) 2770b21e7c70Sdrh ** 2771b21e7c70Sdrh ** AltB: Called when there is data from both coroutines and A<B. 2772b21e7c70Sdrh ** 2773b21e7c70Sdrh ** AeqB: Called when there is data from both coroutines and A==B. 2774b21e7c70Sdrh ** 2775b21e7c70Sdrh ** AgtB: Called when there is data from both coroutines and A>B. 2776b21e7c70Sdrh ** 2777b21e7c70Sdrh ** EofA: Called when data is exhausted from selectA. 2778b21e7c70Sdrh ** 2779b21e7c70Sdrh ** EofB: Called when data is exhausted from selectB. 2780b21e7c70Sdrh ** 2781b21e7c70Sdrh ** The implementation of the latter five subroutines depend on which 2782b21e7c70Sdrh ** <operator> is used: 2783b21e7c70Sdrh ** 2784b21e7c70Sdrh ** 2785b21e7c70Sdrh ** UNION ALL UNION EXCEPT INTERSECT 2786b21e7c70Sdrh ** ------------- ----------------- -------------- ----------------- 2787b21e7c70Sdrh ** AltB: outA, nextA outA, nextA outA, nextA nextA 2788b21e7c70Sdrh ** 27890acb7e48Sdrh ** AeqB: outA, nextA nextA nextA outA, nextA 2790b21e7c70Sdrh ** 2791b21e7c70Sdrh ** AgtB: outB, nextB outB, nextB nextB nextB 2792b21e7c70Sdrh ** 27930acb7e48Sdrh ** EofA: outB, nextB outB, nextB halt halt 2794b21e7c70Sdrh ** 27950acb7e48Sdrh ** EofB: outA, nextA outA, nextA outA, nextA halt 27960acb7e48Sdrh ** 27970acb7e48Sdrh ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA 27980acb7e48Sdrh ** causes an immediate jump to EofA and an EOF on B following nextB causes 27990acb7e48Sdrh ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or 28000acb7e48Sdrh ** following nextX causes a jump to the end of the select processing. 28010acb7e48Sdrh ** 28020acb7e48Sdrh ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled 28030acb7e48Sdrh ** within the output subroutine. The regPrev register set holds the previously 28040acb7e48Sdrh ** output value. A comparison is made against this value and the output 28050acb7e48Sdrh ** is skipped if the next results would be the same as the previous. 2806b21e7c70Sdrh ** 2807b21e7c70Sdrh ** The implementation plan is to implement the two coroutines and seven 2808b21e7c70Sdrh ** subroutines first, then put the control logic at the bottom. Like this: 2809b21e7c70Sdrh ** 2810b21e7c70Sdrh ** goto Init 2811b21e7c70Sdrh ** coA: coroutine for left query (A) 2812b21e7c70Sdrh ** coB: coroutine for right query (B) 2813b21e7c70Sdrh ** outA: output one row of A 2814b21e7c70Sdrh ** outB: output one row of B (UNION and UNION ALL only) 2815b21e7c70Sdrh ** EofA: ... 2816b21e7c70Sdrh ** EofB: ... 2817b21e7c70Sdrh ** AltB: ... 2818b21e7c70Sdrh ** AeqB: ... 2819b21e7c70Sdrh ** AgtB: ... 2820b21e7c70Sdrh ** Init: initialize coroutine registers 2821b21e7c70Sdrh ** yield coA 2822b21e7c70Sdrh ** if eof(A) goto EofA 2823b21e7c70Sdrh ** yield coB 2824b21e7c70Sdrh ** if eof(B) goto EofB 2825b21e7c70Sdrh ** Cmpr: Compare A, B 2826b21e7c70Sdrh ** Jump AltB, AeqB, AgtB 2827b21e7c70Sdrh ** End: ... 2828b21e7c70Sdrh ** 2829b21e7c70Sdrh ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not 2830b21e7c70Sdrh ** actually called using Gosub and they do not Return. EofA and EofB loop 2831b21e7c70Sdrh ** until all data is exhausted then jump to the "end" labe. AltB, AeqB, 2832b21e7c70Sdrh ** and AgtB jump to either L2 or to one of EofA or EofB. 2833b21e7c70Sdrh */ 2834de3e41e3Sdanielk1977 #ifndef SQLITE_OMIT_COMPOUND_SELECT 2835b21e7c70Sdrh static int multiSelectOrderBy( 2836b21e7c70Sdrh Parse *pParse, /* Parsing context */ 2837b21e7c70Sdrh Select *p, /* The right-most of SELECTs to be coded */ 2838a9671a22Sdrh SelectDest *pDest /* What to do with query results */ 2839b21e7c70Sdrh ){ 28400acb7e48Sdrh int i, j; /* Loop counters */ 2841b21e7c70Sdrh Select *pPrior; /* Another SELECT immediately to our left */ 2842b21e7c70Sdrh Vdbe *v; /* Generate code to this VDBE */ 2843b21e7c70Sdrh SelectDest destA; /* Destination for coroutine A */ 2844b21e7c70Sdrh SelectDest destB; /* Destination for coroutine B */ 284592b01d53Sdrh int regAddrA; /* Address register for select-A coroutine */ 284692b01d53Sdrh int regAddrB; /* Address register for select-B coroutine */ 284792b01d53Sdrh int addrSelectA; /* Address of the select-A coroutine */ 284892b01d53Sdrh int addrSelectB; /* Address of the select-B coroutine */ 284992b01d53Sdrh int regOutA; /* Address register for the output-A subroutine */ 285092b01d53Sdrh int regOutB; /* Address register for the output-B subroutine */ 285192b01d53Sdrh int addrOutA; /* Address of the output-A subroutine */ 2852b27b7f5dSdrh int addrOutB = 0; /* Address of the output-B subroutine */ 285392b01d53Sdrh int addrEofA; /* Address of the select-A-exhausted subroutine */ 285481cf13ecSdrh int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */ 285592b01d53Sdrh int addrEofB; /* Address of the select-B-exhausted subroutine */ 285692b01d53Sdrh int addrAltB; /* Address of the A<B subroutine */ 285792b01d53Sdrh int addrAeqB; /* Address of the A==B subroutine */ 285892b01d53Sdrh int addrAgtB; /* Address of the A>B subroutine */ 285992b01d53Sdrh int regLimitA; /* Limit register for select-A */ 286092b01d53Sdrh int regLimitB; /* Limit register for select-A */ 28610acb7e48Sdrh int regPrev; /* A range of registers to hold previous output */ 286292b01d53Sdrh int savedLimit; /* Saved value of p->iLimit */ 286392b01d53Sdrh int savedOffset; /* Saved value of p->iOffset */ 286492b01d53Sdrh int labelCmpr; /* Label for the start of the merge algorithm */ 286592b01d53Sdrh int labelEnd; /* Label for the end of the overall SELECT stmt */ 2866728e0f91Sdrh int addr1; /* Jump instructions that get retargetted */ 286792b01d53Sdrh int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ 286896067816Sdrh KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */ 28690acb7e48Sdrh KeyInfo *pKeyMerge; /* Comparison information for merging rows */ 28700acb7e48Sdrh sqlite3 *db; /* Database connection */ 28710acb7e48Sdrh ExprList *pOrderBy; /* The ORDER BY clause */ 28720acb7e48Sdrh int nOrderBy; /* Number of terms in the ORDER BY clause */ 28730acb7e48Sdrh int *aPermute; /* Mapping from ORDER BY terms to result set columns */ 28747f61e92cSdan #ifndef SQLITE_OMIT_EXPLAIN 28757f61e92cSdan int iSub1; /* EQP id of left-hand query */ 28767f61e92cSdan int iSub2; /* EQP id of right-hand query */ 28777f61e92cSdan #endif 2878b21e7c70Sdrh 287992b01d53Sdrh assert( p->pOrderBy!=0 ); 288096067816Sdrh assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */ 28810acb7e48Sdrh db = pParse->db; 288292b01d53Sdrh v = pParse->pVdbe; 2883ccfcbceaSdrh assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */ 288492b01d53Sdrh labelEnd = sqlite3VdbeMakeLabel(v); 288592b01d53Sdrh labelCmpr = sqlite3VdbeMakeLabel(v); 28860acb7e48Sdrh 2887b21e7c70Sdrh 288892b01d53Sdrh /* Patch up the ORDER BY clause 288992b01d53Sdrh */ 289092b01d53Sdrh op = p->op; 2891b21e7c70Sdrh pPrior = p->pPrior; 289292b01d53Sdrh assert( pPrior->pOrderBy==0 ); 28930acb7e48Sdrh pOrderBy = p->pOrderBy; 289493a960a0Sdrh assert( pOrderBy ); 28950acb7e48Sdrh nOrderBy = pOrderBy->nExpr; 289693a960a0Sdrh 28970acb7e48Sdrh /* For operators other than UNION ALL we have to make sure that 28980acb7e48Sdrh ** the ORDER BY clause covers every term of the result set. Add 28990acb7e48Sdrh ** terms to the ORDER BY clause as necessary. 29000acb7e48Sdrh */ 29010acb7e48Sdrh if( op!=TK_ALL ){ 29020acb7e48Sdrh for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ 29037d10d5a6Sdrh struct ExprList_item *pItem; 29047d10d5a6Sdrh for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){ 2905c2acc4e4Sdrh assert( pItem->u.x.iOrderByCol>0 ); 2906c2acc4e4Sdrh if( pItem->u.x.iOrderByCol==i ) break; 29070acb7e48Sdrh } 29080acb7e48Sdrh if( j==nOrderBy ){ 2909b7916a78Sdrh Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 2910fad3039cSmistachkin if( pNew==0 ) return SQLITE_NOMEM_BKPT; 29110acb7e48Sdrh pNew->flags |= EP_IntValue; 291233e619fcSdrh pNew->u.iValue = i; 291343606175Sdrh p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew); 2914c2acc4e4Sdrh if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i; 29150acb7e48Sdrh } 29160acb7e48Sdrh } 29170acb7e48Sdrh } 29180acb7e48Sdrh 29190acb7e48Sdrh /* Compute the comparison permutation and keyinfo that is used with 292010c081adSdrh ** the permutation used to determine if the next 29210acb7e48Sdrh ** row of results comes from selectA or selectB. Also add explicit 29220acb7e48Sdrh ** collations to the ORDER BY clause terms so that when the subqueries 29230acb7e48Sdrh ** to the right and the left are evaluated, they use the correct 29240acb7e48Sdrh ** collation. 29250acb7e48Sdrh */ 2926575fad65Sdrh aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1)); 29270acb7e48Sdrh if( aPermute ){ 29287d10d5a6Sdrh struct ExprList_item *pItem; 2929b1702026Sdrh aPermute[0] = nOrderBy; 2930b1702026Sdrh for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){ 29316736618aSdrh assert( pItem->u.x.iOrderByCol>0 ); 29322ec18a3cSdrh assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ); 2933c2acc4e4Sdrh aPermute[i] = pItem->u.x.iOrderByCol - 1; 29340acb7e48Sdrh } 293553bed45eSdan pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1); 29360acb7e48Sdrh }else{ 29370acb7e48Sdrh pKeyMerge = 0; 29380acb7e48Sdrh } 29390acb7e48Sdrh 29400acb7e48Sdrh /* Reattach the ORDER BY clause to the query. 29410acb7e48Sdrh */ 29420acb7e48Sdrh p->pOrderBy = pOrderBy; 29436ab3a2ecSdanielk1977 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0); 29440acb7e48Sdrh 29450acb7e48Sdrh /* Allocate a range of temporary registers and the KeyInfo needed 29460acb7e48Sdrh ** for the logic that removes duplicate result rows when the 29470acb7e48Sdrh ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). 29480acb7e48Sdrh */ 29490acb7e48Sdrh if( op==TK_ALL ){ 29500acb7e48Sdrh regPrev = 0; 29510acb7e48Sdrh }else{ 29520acb7e48Sdrh int nExpr = p->pEList->nExpr; 29531c0dc825Sdrh assert( nOrderBy>=nExpr || db->mallocFailed ); 2954c8ac0d16Sdrh regPrev = pParse->nMem+1; 2955c8ac0d16Sdrh pParse->nMem += nExpr+1; 29560acb7e48Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); 2957ad124329Sdrh pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1); 29580acb7e48Sdrh if( pKeyDup ){ 29592ec2fb22Sdrh assert( sqlite3KeyInfoIsWriteable(pKeyDup) ); 29600acb7e48Sdrh for(i=0; i<nExpr; i++){ 29610acb7e48Sdrh pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i); 29620acb7e48Sdrh pKeyDup->aSortOrder[i] = 0; 29630acb7e48Sdrh } 29640acb7e48Sdrh } 29650acb7e48Sdrh } 296692b01d53Sdrh 296792b01d53Sdrh /* Separate the left and the right query from one another 296892b01d53Sdrh */ 296992b01d53Sdrh p->pPrior = 0; 2970d227a291Sdrh pPrior->pNext = 0; 29717d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER"); 29720acb7e48Sdrh if( pPrior->pPrior==0 ){ 29737d10d5a6Sdrh sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER"); 29740acb7e48Sdrh } 297592b01d53Sdrh 297692b01d53Sdrh /* Compute the limit registers */ 297792b01d53Sdrh computeLimitRegisters(pParse, p, labelEnd); 29780acb7e48Sdrh if( p->iLimit && op==TK_ALL ){ 297992b01d53Sdrh regLimitA = ++pParse->nMem; 298092b01d53Sdrh regLimitB = ++pParse->nMem; 298192b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, 298292b01d53Sdrh regLimitA); 298392b01d53Sdrh sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); 298492b01d53Sdrh }else{ 298592b01d53Sdrh regLimitA = regLimitB = 0; 298692b01d53Sdrh } 2987633e6d57Sdrh sqlite3ExprDelete(db, p->pLimit); 29880acb7e48Sdrh p->pLimit = 0; 2989633e6d57Sdrh sqlite3ExprDelete(db, p->pOffset); 29900acb7e48Sdrh p->pOffset = 0; 299192b01d53Sdrh 2992b21e7c70Sdrh regAddrA = ++pParse->nMem; 2993b21e7c70Sdrh regAddrB = ++pParse->nMem; 2994b21e7c70Sdrh regOutA = ++pParse->nMem; 2995b21e7c70Sdrh regOutB = ++pParse->nMem; 2996b21e7c70Sdrh sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); 2997b21e7c70Sdrh sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); 2998b21e7c70Sdrh 299992b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement to the 30000acb7e48Sdrh ** left of the compound operator - the "A" select. 30010acb7e48Sdrh */ 3002ed71a839Sdrh addrSelectA = sqlite3VdbeCurrentAddr(v) + 1; 3003728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA); 3004ed71a839Sdrh VdbeComment((v, "left SELECT")); 300592b01d53Sdrh pPrior->iLimit = regLimitA; 30067f61e92cSdan explainSetInteger(iSub1, pParse->iNextSelectId); 30077d10d5a6Sdrh sqlite3Select(pParse, pPrior, &destA); 30082fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrA); 3009728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3010b21e7c70Sdrh 301192b01d53Sdrh /* Generate a coroutine to evaluate the SELECT statement on 301292b01d53Sdrh ** the right - the "B" select 301392b01d53Sdrh */ 3014ed71a839Sdrh addrSelectB = sqlite3VdbeCurrentAddr(v) + 1; 3015728e0f91Sdrh addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB); 3016ed71a839Sdrh VdbeComment((v, "right SELECT")); 301792b01d53Sdrh savedLimit = p->iLimit; 301892b01d53Sdrh savedOffset = p->iOffset; 301992b01d53Sdrh p->iLimit = regLimitB; 302092b01d53Sdrh p->iOffset = 0; 30217f61e92cSdan explainSetInteger(iSub2, pParse->iNextSelectId); 30227d10d5a6Sdrh sqlite3Select(pParse, p, &destB); 302392b01d53Sdrh p->iLimit = savedLimit; 302492b01d53Sdrh p->iOffset = savedOffset; 30252fade2f7Sdrh sqlite3VdbeEndCoroutine(v, regAddrB); 3026b21e7c70Sdrh 302792b01d53Sdrh /* Generate a subroutine that outputs the current row of the A 30280acb7e48Sdrh ** select as the next output row of the compound select. 302992b01d53Sdrh */ 3030b21e7c70Sdrh VdbeNoopComment((v, "Output routine for A")); 30310acb7e48Sdrh addrOutA = generateOutputSubroutine(pParse, 30320acb7e48Sdrh p, &destA, pDest, regOutA, 30332ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 3034b21e7c70Sdrh 303592b01d53Sdrh /* Generate a subroutine that outputs the current row of the B 30360acb7e48Sdrh ** select as the next output row of the compound select. 303792b01d53Sdrh */ 30380acb7e48Sdrh if( op==TK_ALL || op==TK_UNION ){ 3039b21e7c70Sdrh VdbeNoopComment((v, "Output routine for B")); 30400acb7e48Sdrh addrOutB = generateOutputSubroutine(pParse, 30410acb7e48Sdrh p, &destB, pDest, regOutB, 30422ec2fb22Sdrh regPrev, pKeyDup, labelEnd); 30430acb7e48Sdrh } 30442ec2fb22Sdrh sqlite3KeyInfoUnref(pKeyDup); 3045b21e7c70Sdrh 304692b01d53Sdrh /* Generate a subroutine to run when the results from select A 304792b01d53Sdrh ** are exhausted and only data in select B remains. 304892b01d53Sdrh */ 304992b01d53Sdrh if( op==TK_EXCEPT || op==TK_INTERSECT ){ 305081cf13ecSdrh addrEofA_noB = addrEofA = labelEnd; 305192b01d53Sdrh }else{ 305281cf13ecSdrh VdbeNoopComment((v, "eof-A subroutine")); 305381cf13ecSdrh addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 305481cf13ecSdrh addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd); 3055688852abSdrh VdbeCoverage(v); 3056076e85f5Sdrh sqlite3VdbeGoto(v, addrEofA); 3057c3489bbfSdrh p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow); 3058b21e7c70Sdrh } 3059b21e7c70Sdrh 306092b01d53Sdrh /* Generate a subroutine to run when the results from select B 306192b01d53Sdrh ** are exhausted and only data in select A remains. 306292b01d53Sdrh */ 3063b21e7c70Sdrh if( op==TK_INTERSECT ){ 306492b01d53Sdrh addrEofB = addrEofA; 306595aa47b1Sdrh if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow; 3066b21e7c70Sdrh }else{ 306792b01d53Sdrh VdbeNoopComment((v, "eof-B subroutine")); 306881cf13ecSdrh addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3069688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v); 3070076e85f5Sdrh sqlite3VdbeGoto(v, addrEofB); 3071b21e7c70Sdrh } 3072b21e7c70Sdrh 307392b01d53Sdrh /* Generate code to handle the case of A<B 307492b01d53Sdrh */ 3075b21e7c70Sdrh VdbeNoopComment((v, "A-lt-B subroutine")); 30760acb7e48Sdrh addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); 3077688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3078076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3079b21e7c70Sdrh 308092b01d53Sdrh /* Generate code to handle the case of A==B 308192b01d53Sdrh */ 3082b21e7c70Sdrh if( op==TK_ALL ){ 3083b21e7c70Sdrh addrAeqB = addrAltB; 30840acb7e48Sdrh }else if( op==TK_INTERSECT ){ 30850acb7e48Sdrh addrAeqB = addrAltB; 30860acb7e48Sdrh addrAltB++; 308792b01d53Sdrh }else{ 3088b21e7c70Sdrh VdbeNoopComment((v, "A-eq-B subroutine")); 30890acb7e48Sdrh addrAeqB = 3090688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v); 3091076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 309292b01d53Sdrh } 3093b21e7c70Sdrh 309492b01d53Sdrh /* Generate code to handle the case of A>B 309592b01d53Sdrh */ 3096b21e7c70Sdrh VdbeNoopComment((v, "A-gt-B subroutine")); 3097b21e7c70Sdrh addrAgtB = sqlite3VdbeCurrentAddr(v); 3098b21e7c70Sdrh if( op==TK_ALL || op==TK_UNION ){ 3099b21e7c70Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); 310092b01d53Sdrh } 3101688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 3102076e85f5Sdrh sqlite3VdbeGoto(v, labelCmpr); 3103b21e7c70Sdrh 310492b01d53Sdrh /* This code runs once to initialize everything. 310592b01d53Sdrh */ 3106728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 3107688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v); 3108688852abSdrh sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v); 310992b01d53Sdrh 311092b01d53Sdrh /* Implement the main merge loop 311192b01d53Sdrh */ 311292b01d53Sdrh sqlite3VdbeResolveLabel(v, labelCmpr); 31130acb7e48Sdrh sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); 31142b596da8Sdrh sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy, 31152ec2fb22Sdrh (char*)pKeyMerge, P4_KEYINFO); 3116953f7611Sdrh sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE); 3117688852abSdrh sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v); 311892b01d53Sdrh 311992b01d53Sdrh /* Jump to the this point in order to terminate the query. 312092b01d53Sdrh */ 3121b21e7c70Sdrh sqlite3VdbeResolveLabel(v, labelEnd); 3122b21e7c70Sdrh 312392b01d53Sdrh /* Set the number of output columns 312492b01d53Sdrh */ 31257d10d5a6Sdrh if( pDest->eDest==SRT_Output ){ 31260acb7e48Sdrh Select *pFirst = pPrior; 312792b01d53Sdrh while( pFirst->pPrior ) pFirst = pFirst->pPrior; 31289a8941fcSdan generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList); 3129b21e7c70Sdrh } 313092b01d53Sdrh 31310acb7e48Sdrh /* Reassembly the compound query so that it will be freed correctly 31320acb7e48Sdrh ** by the calling function */ 31335e7ad508Sdanielk1977 if( p->pPrior ){ 3134633e6d57Sdrh sqlite3SelectDelete(db, p->pPrior); 31355e7ad508Sdanielk1977 } 31360acb7e48Sdrh p->pPrior = pPrior; 3137d227a291Sdrh pPrior->pNext = p; 313892b01d53Sdrh 313992b01d53Sdrh /*** TBD: Insert subroutine calls to close cursors on incomplete 314092b01d53Sdrh **** subqueries ****/ 31417f61e92cSdan explainComposite(pParse, p->op, iSub1, iSub2, 0); 31423dc4cc66Sdrh return pParse->nErr!=0; 314392b01d53Sdrh } 3144de3e41e3Sdanielk1977 #endif 3145b21e7c70Sdrh 31463514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 314746967de2Sdrh 314846967de2Sdrh /* An instance of the SubstContext object describes an substitution edit 314946967de2Sdrh ** to be performed on a parse tree. 315046967de2Sdrh ** 315146967de2Sdrh ** All references to columns in table iTable are to be replaced by corresponding 315246967de2Sdrh ** expressions in pEList. 315346967de2Sdrh */ 315446967de2Sdrh typedef struct SubstContext { 315546967de2Sdrh Parse *pParse; /* The parsing context */ 315646967de2Sdrh int iTable; /* Replace references to this table */ 315731d6fd55Sdrh int iNewTable; /* New table number */ 315831d6fd55Sdrh int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */ 315946967de2Sdrh ExprList *pEList; /* Replacement expressions */ 316046967de2Sdrh } SubstContext; 316146967de2Sdrh 316217435752Sdrh /* Forward Declarations */ 316346967de2Sdrh static void substExprList(SubstContext*, ExprList*); 316446967de2Sdrh static void substSelect(SubstContext*, Select*, int); 316517435752Sdrh 31662282792aSdrh /* 3167832508b7Sdrh ** Scan through the expression pExpr. Replace every reference to 31686a3ea0e6Sdrh ** a column in table number iTable with a copy of the iColumn-th 316984e59207Sdrh ** entry in pEList. (But leave references to the ROWID column 31706a3ea0e6Sdrh ** unchanged.) 3171832508b7Sdrh ** 3172832508b7Sdrh ** This routine is part of the flattening procedure. A subquery 3173832508b7Sdrh ** whose result set is defined by pEList appears as entry in the 3174832508b7Sdrh ** FROM clause of a SELECT such that the VDBE cursor assigned to that 3175aca19e19Sdrh ** FORM clause entry is iTable. This routine makes the necessary 3176832508b7Sdrh ** changes to pExpr so that it refers directly to the source table 3177832508b7Sdrh ** of the subquery rather the result set of the subquery. 3178832508b7Sdrh */ 3179b7916a78Sdrh static Expr *substExpr( 318046967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 318146967de2Sdrh Expr *pExpr /* Expr in which substitution occurs */ 318217435752Sdrh ){ 3183b7916a78Sdrh if( pExpr==0 ) return 0; 3184399c7e21Sdrh if( ExprHasProperty(pExpr, EP_FromJoin) && pExpr->iRightJoinTable==pSubst->iTable ){ 3185399c7e21Sdrh pExpr->iRightJoinTable = pSubst->iNewTable; 3186399c7e21Sdrh } 318746967de2Sdrh if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){ 318850350a15Sdrh if( pExpr->iColumn<0 ){ 318950350a15Sdrh pExpr->op = TK_NULL; 319050350a15Sdrh }else{ 3191832508b7Sdrh Expr *pNew; 319246967de2Sdrh Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr; 319331d6fd55Sdrh Expr ifNullRow; 319446967de2Sdrh assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr ); 31956ab3a2ecSdanielk1977 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 319644c5604cSdan if( sqlite3ExprIsVector(pCopy) ){ 319746967de2Sdrh sqlite3VectorErrorMsg(pSubst->pParse, pCopy); 319844c5604cSdan }else{ 319946967de2Sdrh sqlite3 *db = pSubst->pParse->db; 320031d6fd55Sdrh if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){ 320131d6fd55Sdrh memset(&ifNullRow, 0, sizeof(ifNullRow)); 320231d6fd55Sdrh ifNullRow.op = TK_IF_NULL_ROW; 320331d6fd55Sdrh ifNullRow.pLeft = pCopy; 320431d6fd55Sdrh ifNullRow.iTable = pSubst->iNewTable; 320531d6fd55Sdrh pCopy = &ifNullRow; 320631d6fd55Sdrh } 320744c5604cSdan pNew = sqlite3ExprDup(db, pCopy, 0); 320892ddb3bdSdan if( pNew && (pExpr->flags & EP_FromJoin) ){ 320992ddb3bdSdan pNew->iRightJoinTable = pExpr->iRightJoinTable; 321092ddb3bdSdan pNew->flags |= EP_FromJoin; 321192ddb3bdSdan } 3212b7916a78Sdrh sqlite3ExprDelete(db, pExpr); 3213b7916a78Sdrh pExpr = pNew; 321450350a15Sdrh } 321544c5604cSdan } 3216832508b7Sdrh }else{ 321746967de2Sdrh pExpr->pLeft = substExpr(pSubst, pExpr->pLeft); 321846967de2Sdrh pExpr->pRight = substExpr(pSubst, pExpr->pRight); 32196ab3a2ecSdanielk1977 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 322046967de2Sdrh substSelect(pSubst, pExpr->x.pSelect, 1); 32216ab3a2ecSdanielk1977 }else{ 322246967de2Sdrh substExprList(pSubst, pExpr->x.pList); 32236ab3a2ecSdanielk1977 } 3224832508b7Sdrh } 3225b7916a78Sdrh return pExpr; 3226832508b7Sdrh } 322717435752Sdrh static void substExprList( 322846967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 322946967de2Sdrh ExprList *pList /* List to scan and in which to make substitutes */ 323017435752Sdrh ){ 3231832508b7Sdrh int i; 3232832508b7Sdrh if( pList==0 ) return; 3233832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 323446967de2Sdrh pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr); 3235832508b7Sdrh } 3236832508b7Sdrh } 323717435752Sdrh static void substSelect( 323846967de2Sdrh SubstContext *pSubst, /* Description of the substitution */ 323917435752Sdrh Select *p, /* SELECT statement in which to make substitutions */ 3240d12b6363Sdrh int doPrior /* Do substitutes on p->pPrior too */ 324117435752Sdrh ){ 3242588a9a1aSdrh SrcList *pSrc; 3243588a9a1aSdrh struct SrcList_item *pItem; 3244588a9a1aSdrh int i; 3245b3bce662Sdanielk1977 if( !p ) return; 3246d12b6363Sdrh do{ 324746967de2Sdrh substExprList(pSubst, p->pEList); 324846967de2Sdrh substExprList(pSubst, p->pGroupBy); 324946967de2Sdrh substExprList(pSubst, p->pOrderBy); 325046967de2Sdrh p->pHaving = substExpr(pSubst, p->pHaving); 325146967de2Sdrh p->pWhere = substExpr(pSubst, p->pWhere); 3252588a9a1aSdrh pSrc = p->pSrc; 32532906490bSdrh assert( pSrc!=0 ); 3254588a9a1aSdrh for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){ 325546967de2Sdrh substSelect(pSubst, pItem->pSelect, 1); 3256d12b6363Sdrh if( pItem->fg.isTabFunc ){ 325746967de2Sdrh substExprList(pSubst, pItem->u1.pFuncArg); 3258588a9a1aSdrh } 3259588a9a1aSdrh } 3260d12b6363Sdrh }while( doPrior && (p = p->pPrior)!=0 ); 3261b3bce662Sdanielk1977 } 32623514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 3263832508b7Sdrh 32643514b6f7Sshane #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 3265832508b7Sdrh /* 3266630d296cSdrh ** This routine attempts to flatten subqueries as a performance optimization. 3267630d296cSdrh ** This routine returns 1 if it makes changes and 0 if no flattening occurs. 32681350b030Sdrh ** 32691350b030Sdrh ** To understand the concept of flattening, consider the following 32701350b030Sdrh ** query: 32711350b030Sdrh ** 32721350b030Sdrh ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5 32731350b030Sdrh ** 32741350b030Sdrh ** The default way of implementing this query is to execute the 32751350b030Sdrh ** subquery first and store the results in a temporary table, then 32761350b030Sdrh ** run the outer query on that temporary table. This requires two 32771350b030Sdrh ** passes over the data. Furthermore, because the temporary table 32781350b030Sdrh ** has no indices, the WHERE clause on the outer query cannot be 3279832508b7Sdrh ** optimized. 32801350b030Sdrh ** 3281832508b7Sdrh ** This routine attempts to rewrite queries such as the above into 32821350b030Sdrh ** a single flat select, like this: 32831350b030Sdrh ** 32841350b030Sdrh ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5 32851350b030Sdrh ** 328660ec914cSpeter.d.reid ** The code generated for this simplification gives the same result 3287832508b7Sdrh ** but only has to scan the data once. And because indices might 3288832508b7Sdrh ** exist on the table t1, a complete scan of the data might be 3289832508b7Sdrh ** avoided. 32901350b030Sdrh ** 3291832508b7Sdrh ** Flattening is only attempted if all of the following are true: 32921350b030Sdrh ** 3293832508b7Sdrh ** (1) The subquery and the outer query do not both use aggregates. 32941350b030Sdrh ** 3295885a5b03Sdrh ** (2) The subquery is not an aggregate or (2a) the outer query is not a join 3296885a5b03Sdrh ** and (2b) the outer query does not use subqueries other than the one 3297885a5b03Sdrh ** FROM-clause subquery that is a candidate for flattening. (2b is 3298885a5b03Sdrh ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.) 3299832508b7Sdrh ** 330031d6fd55Sdrh ** (3) The subquery is not the right operand of a LEFT JOIN 330131d6fd55Sdrh ** or the subquery is not itself a join. 3302832508b7Sdrh ** 330349ad330dSdan ** (4) The subquery is not DISTINCT. 3304832508b7Sdrh ** 330549ad330dSdan ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT 330649ad330dSdan ** sub-queries that were excluded from this optimization. Restriction 330749ad330dSdan ** (4) has since been expanded to exclude all DISTINCT subqueries. 3308832508b7Sdrh ** 3309832508b7Sdrh ** (6) The subquery does not use aggregates or the outer query is not 3310832508b7Sdrh ** DISTINCT. 3311832508b7Sdrh ** 3312630d296cSdrh ** (7) The subquery has a FROM clause. TODO: For subqueries without 331331d6fd55Sdrh ** A FROM clause, consider adding a FROM clause with the special 3314630d296cSdrh ** table sqlite_once that consists of a single row containing a 3315630d296cSdrh ** single NULL. 331608192d5fSdrh ** 3317df199a25Sdrh ** (8) The subquery does not use LIMIT or the outer query is not a join. 3318df199a25Sdrh ** 3319df199a25Sdrh ** (9) The subquery does not use LIMIT or the outer query does not use 3320df199a25Sdrh ** aggregates. 3321df199a25Sdrh ** 33226092d2bcSdrh ** (**) Restriction (10) was removed from the code on 2005-02-05 but we 33236092d2bcSdrh ** accidently carried the comment forward until 2014-09-15. Original 332438b4149cSdrh ** text: "The subquery does not use aggregates or the outer query 332538b4149cSdrh ** does not use LIMIT." 3326df199a25Sdrh ** 3327174b6195Sdrh ** (11) The subquery and the outer query do not both have ORDER BY clauses. 3328174b6195Sdrh ** 33297b688edeSdrh ** (**) Not implemented. Subsumed into restriction (3). Was previously 33302b300d5dSdrh ** a separate restriction deriving from ticket #350. 33313fc673e6Sdrh ** 333249ad330dSdan ** (13) The subquery and outer query do not both use LIMIT. 3333ac83963aSdrh ** 333449ad330dSdan ** (14) The subquery does not use OFFSET. 3335ac83963aSdrh ** 3336ad91c6cdSdrh ** (15) The outer query is not part of a compound select or the 3337f3913278Sdrh ** subquery does not have a LIMIT clause. 3338f3913278Sdrh ** (See ticket #2339 and ticket [02a8e81d44]). 3339ad91c6cdSdrh ** 3340c52e355dSdrh ** (16) The outer query is not an aggregate or the subquery does 3341c52e355dSdrh ** not contain ORDER BY. (Ticket #2942) This used to not matter 3342c52e355dSdrh ** until we introduced the group_concat() function. 3343c52e355dSdrh ** 3344f23329a2Sdanielk1977 ** (17) The sub-query is not a compound select, or it is a UNION ALL 33454914cf92Sdanielk1977 ** compound clause made up entirely of non-aggregate queries, and 3346f23329a2Sdanielk1977 ** the parent query: 3347f23329a2Sdanielk1977 ** 3348f23329a2Sdanielk1977 ** * is not itself part of a compound select, 3349f23329a2Sdanielk1977 ** * is not an aggregate or DISTINCT query, and 3350630d296cSdrh ** * is not a join 3351f23329a2Sdanielk1977 ** 33524914cf92Sdanielk1977 ** The parent and sub-query may contain WHERE clauses. Subject to 33534914cf92Sdanielk1977 ** rules (11), (13) and (14), they may also contain ORDER BY, 3354630d296cSdrh ** LIMIT and OFFSET clauses. The subquery cannot use any compound 3355630d296cSdrh ** operator other than UNION ALL because all the other compound 3356630d296cSdrh ** operators have an implied DISTINCT which is disallowed by 3357630d296cSdrh ** restriction (4). 3358f23329a2Sdanielk1977 ** 335967c70142Sdan ** Also, each component of the sub-query must return the same number 336067c70142Sdan ** of result columns. This is actually a requirement for any compound 336167c70142Sdan ** SELECT statement, but all the code here does is make sure that no 336267c70142Sdan ** such (illegal) sub-query is flattened. The caller will detect the 336367c70142Sdan ** syntax error and return a detailed message. 336467c70142Sdan ** 336549fc1f60Sdanielk1977 ** (18) If the sub-query is a compound select, then all terms of the 336649fc1f60Sdanielk1977 ** ORDER by clause of the parent must be simple references to 336749fc1f60Sdanielk1977 ** columns of the sub-query. 336849fc1f60Sdanielk1977 ** 3369229cf702Sdrh ** (19) The subquery does not use LIMIT or the outer query does not 3370229cf702Sdrh ** have a WHERE clause. 3371229cf702Sdrh ** 3372e8902a70Sdrh ** (20) If the sub-query is a compound select, then it must not use 3373e8902a70Sdrh ** an ORDER BY clause. Ticket #3773. We could relax this constraint 3374e8902a70Sdrh ** somewhat by saying that the terms of the ORDER BY clause must 3375630d296cSdrh ** appear as unmodified result columns in the outer query. But we 3376e8902a70Sdrh ** have other optimizations in mind to deal with that case. 3377e8902a70Sdrh ** 3378a91491e5Sshaneh ** (21) The subquery does not use LIMIT or the outer query is not 3379a91491e5Sshaneh ** DISTINCT. (See ticket [752e1646fc]). 3380a91491e5Sshaneh ** 33818290c2adSdan ** (22) The subquery is not a recursive CTE. 33828290c2adSdan ** 33838290c2adSdan ** (23) The parent is not a recursive CTE, or the sub-query is not a 33848290c2adSdan ** compound query. This restriction is because transforming the 33858290c2adSdan ** parent to a compound query confuses the code that handles 33868290c2adSdan ** recursive queries in multiSelect(). 33878290c2adSdan ** 33889588ad95Sdrh ** (24) The subquery is not an aggregate that uses the built-in min() or 33899588ad95Sdrh ** or max() functions. (Without this restriction, a query like: 33909588ad95Sdrh ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily 33919588ad95Sdrh ** return the value X for which Y was maximal.) 33929588ad95Sdrh ** 33938290c2adSdan ** 3394832508b7Sdrh ** In this routine, the "p" parameter is a pointer to the outer query. 3395832508b7Sdrh ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query 3396832508b7Sdrh ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. 3397832508b7Sdrh ** 3398665de47aSdrh ** If flattening is not attempted, this routine is a no-op and returns 0. 3399832508b7Sdrh ** If flattening is attempted this routine returns 1. 3400832508b7Sdrh ** 3401832508b7Sdrh ** All of the expression analysis must occur on both the outer query and 3402832508b7Sdrh ** the subquery before this routine runs. 34031350b030Sdrh */ 34048c74a8caSdrh static int flattenSubquery( 3405524cc21eSdanielk1977 Parse *pParse, /* Parsing context */ 34068c74a8caSdrh Select *p, /* The parent or outer SELECT statement */ 34078c74a8caSdrh int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ 34088c74a8caSdrh int isAgg, /* True if outer SELECT uses aggregate functions */ 34098c74a8caSdrh int subqueryIsAgg /* True if the subquery uses aggregate functions */ 34108c74a8caSdrh ){ 3411524cc21eSdanielk1977 const char *zSavedAuthContext = pParse->zAuthContext; 3412d12b6363Sdrh Select *pParent; /* Current UNION ALL term of the other query */ 34130bb28106Sdrh Select *pSub; /* The inner query or "subquery" */ 3414f23329a2Sdanielk1977 Select *pSub1; /* Pointer to the rightmost select in sub-query */ 3415ad3cab52Sdrh SrcList *pSrc; /* The FROM clause of the outer query */ 3416ad3cab52Sdrh SrcList *pSubSrc; /* The FROM clause of the subquery */ 34170bb28106Sdrh ExprList *pList; /* The result set of the outer query */ 34186a3ea0e6Sdrh int iParent; /* VDBE cursor number of the pSub result set temp table */ 3419399c7e21Sdrh int iNewParent = -1;/* Replacement table for iParent */ 3420399c7e21Sdrh int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */ 342191bb0eedSdrh int i; /* Loop counter */ 342291bb0eedSdrh Expr *pWhere; /* The WHERE clause */ 342391bb0eedSdrh struct SrcList_item *pSubitem; /* The subquery */ 3424524cc21eSdanielk1977 sqlite3 *db = pParse->db; 34251350b030Sdrh 3426832508b7Sdrh /* Check to see if flattening is permitted. Return 0 if not. 3427832508b7Sdrh */ 3428a78c22c4Sdrh assert( p!=0 ); 3429a78c22c4Sdrh assert( p->pPrior==0 ); /* Unable to flatten compound queries */ 34307e5418e4Sdrh if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0; 3431832508b7Sdrh pSrc = p->pSrc; 3432ad3cab52Sdrh assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc ); 343391bb0eedSdrh pSubitem = &pSrc->a[iFrom]; 343449fc1f60Sdanielk1977 iParent = pSubitem->iCursor; 343591bb0eedSdrh pSub = pSubitem->pSelect; 3436832508b7Sdrh assert( pSub!=0 ); 3437885a5b03Sdrh if( subqueryIsAgg ){ 3438885a5b03Sdrh if( isAgg ) return 0; /* Restriction (1) */ 3439885a5b03Sdrh if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */ 3440885a5b03Sdrh if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery)) 34412308ed38Sdrh || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0 34422308ed38Sdrh || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0 3443885a5b03Sdrh ){ 3444885a5b03Sdrh return 0; /* Restriction (2b) */ 3445885a5b03Sdrh } 3446885a5b03Sdrh } 3447885a5b03Sdrh 3448832508b7Sdrh pSubSrc = pSub->pSrc; 3449832508b7Sdrh assert( pSubSrc ); 3450ac83963aSdrh /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants, 345160ec914cSpeter.d.reid ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET 3452ac83963aSdrh ** because they could be computed at compile-time. But when LIMIT and OFFSET 3453ac83963aSdrh ** became arbitrary expressions, we were forced to add restrictions (13) 3454ac83963aSdrh ** and (14). */ 3455ac83963aSdrh if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */ 3456ac83963aSdrh if( pSub->pOffset ) return 0; /* Restriction (14) */ 3457d227a291Sdrh if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){ 3458ad91c6cdSdrh return 0; /* Restriction (15) */ 3459ad91c6cdSdrh } 3460ac83963aSdrh if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */ 346149ad330dSdan if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */ 346249ad330dSdan if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){ 346349ad330dSdan return 0; /* Restrictions (8)(9) */ 3464df199a25Sdrh } 34657d10d5a6Sdrh if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){ 34667d10d5a6Sdrh return 0; /* Restriction (6) */ 34677d10d5a6Sdrh } 34687d10d5a6Sdrh if( p->pOrderBy && pSub->pOrderBy ){ 3469ac83963aSdrh return 0; /* Restriction (11) */ 3470ac83963aSdrh } 3471c52e355dSdrh if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ 3472229cf702Sdrh if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */ 3473a91491e5Sshaneh if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){ 3474a91491e5Sshaneh return 0; /* Restriction (21) */ 3475a91491e5Sshaneh } 34769588ad95Sdrh testcase( pSub->selFlags & SF_Recursive ); 34779588ad95Sdrh testcase( pSub->selFlags & SF_MinMaxAgg ); 34789588ad95Sdrh if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){ 34799588ad95Sdrh return 0; /* Restrictions (22) and (24) */ 34809588ad95Sdrh } 34819588ad95Sdrh if( (p->selFlags & SF_Recursive) && pSub->pPrior ){ 34829588ad95Sdrh return 0; /* Restriction (23) */ 34839588ad95Sdrh } 3484832508b7Sdrh 3485399c7e21Sdrh /* 3486399c7e21Sdrh ** If the subquery is the right operand of a LEFT JOIN, then the 3487399c7e21Sdrh ** subquery may not be a join itself. Example of why this is not allowed: 34888af4d3acSdrh ** 34898af4d3acSdrh ** t1 LEFT OUTER JOIN (t2 JOIN t3) 34908af4d3acSdrh ** 34918af4d3acSdrh ** If we flatten the above, we would get 34928af4d3acSdrh ** 34938af4d3acSdrh ** (t1 LEFT OUTER JOIN t2) JOIN t3 34948af4d3acSdrh ** 34958af4d3acSdrh ** which is not at all the same thing. 34962b300d5dSdrh ** 349731d6fd55Sdrh ** See also tickets #306, #350, and #3300. 34983fc673e6Sdrh */ 34998a48b9c0Sdrh if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){ 3500399c7e21Sdrh isLeftJoin = 1; 3501399c7e21Sdrh if( pSubSrc->nSrc>1 ){ 350231d6fd55Sdrh return 0; /* Restriction (3) */ 3503399c7e21Sdrh } 35043fc673e6Sdrh } 35053fc673e6Sdrh 3506f23329a2Sdanielk1977 /* Restriction 17: If the sub-query is a compound SELECT, then it must 3507f23329a2Sdanielk1977 ** use only the UNION ALL operator. And none of the simple select queries 3508f23329a2Sdanielk1977 ** that make up the compound SELECT are allowed to be aggregate or distinct 3509f23329a2Sdanielk1977 ** queries. 3510f23329a2Sdanielk1977 */ 3511f23329a2Sdanielk1977 if( pSub->pPrior ){ 3512e8902a70Sdrh if( pSub->pOrderBy ){ 3513e8902a70Sdrh return 0; /* Restriction 20 */ 3514e8902a70Sdrh } 3515e2f02bacSdrh if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){ 3516f23329a2Sdanielk1977 return 0; 3517f23329a2Sdanielk1977 } 3518f23329a2Sdanielk1977 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ 3519ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 3520ccfcbceaSdrh testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 35214b3ac73cSdrh assert( pSub->pSrc!=0 ); 35222ec18a3cSdrh assert( pSub->pEList->nExpr==pSub1->pEList->nExpr ); 35237d10d5a6Sdrh if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 352480b3c548Sdanielk1977 || (pSub1->pPrior && pSub1->op!=TK_ALL) 35254b3ac73cSdrh || pSub1->pSrc->nSrc<1 352680b3c548Sdanielk1977 ){ 3527f23329a2Sdanielk1977 return 0; 3528f23329a2Sdanielk1977 } 35294b3ac73cSdrh testcase( pSub1->pSrc->nSrc>1 ); 3530f23329a2Sdanielk1977 } 353149fc1f60Sdanielk1977 353249fc1f60Sdanielk1977 /* Restriction 18. */ 353349fc1f60Sdanielk1977 if( p->pOrderBy ){ 353449fc1f60Sdanielk1977 int ii; 353549fc1f60Sdanielk1977 for(ii=0; ii<p->pOrderBy->nExpr; ii++){ 3536c2acc4e4Sdrh if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0; 353749fc1f60Sdanielk1977 } 353849fc1f60Sdanielk1977 } 3539f23329a2Sdanielk1977 } 3540f23329a2Sdanielk1977 35417d10d5a6Sdrh /***** If we reach this point, flattening is permitted. *****/ 3542eb9b884cSdrh SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", 3543eb9b884cSdrh pSub->zSelName, pSub, iFrom)); 35447d10d5a6Sdrh 35457d10d5a6Sdrh /* Authorize the subquery */ 3546524cc21eSdanielk1977 pParse->zAuthContext = pSubitem->zName; 3547a2acb0d7Sdrh TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); 3548a2acb0d7Sdrh testcase( i==SQLITE_DENY ); 3549524cc21eSdanielk1977 pParse->zAuthContext = zSavedAuthContext; 3550524cc21eSdanielk1977 35517d10d5a6Sdrh /* If the sub-query is a compound SELECT statement, then (by restrictions 35527d10d5a6Sdrh ** 17 and 18 above) it must be a UNION ALL and the parent query must 35537d10d5a6Sdrh ** be of the form: 3554f23329a2Sdanielk1977 ** 3555f23329a2Sdanielk1977 ** SELECT <expr-list> FROM (<sub-query>) <where-clause> 3556f23329a2Sdanielk1977 ** 3557f23329a2Sdanielk1977 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block 3558a78c22c4Sdrh ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 3559f23329a2Sdanielk1977 ** OFFSET clauses and joins them to the left-hand-side of the original 3560f23329a2Sdanielk1977 ** using UNION ALL operators. In this case N is the number of simple 3561f23329a2Sdanielk1977 ** select statements in the compound sub-query. 3562a78c22c4Sdrh ** 3563a78c22c4Sdrh ** Example: 3564a78c22c4Sdrh ** 3565a78c22c4Sdrh ** SELECT a+1 FROM ( 3566a78c22c4Sdrh ** SELECT x FROM tab 3567a78c22c4Sdrh ** UNION ALL 3568a78c22c4Sdrh ** SELECT y FROM tab 3569a78c22c4Sdrh ** UNION ALL 3570a78c22c4Sdrh ** SELECT abs(z*2) FROM tab2 3571a78c22c4Sdrh ** ) WHERE a!=5 ORDER BY 1 3572a78c22c4Sdrh ** 3573a78c22c4Sdrh ** Transformed into: 3574a78c22c4Sdrh ** 3575a78c22c4Sdrh ** SELECT x+1 FROM tab WHERE x+1!=5 3576a78c22c4Sdrh ** UNION ALL 3577a78c22c4Sdrh ** SELECT y+1 FROM tab WHERE y+1!=5 3578a78c22c4Sdrh ** UNION ALL 3579a78c22c4Sdrh ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5 3580a78c22c4Sdrh ** ORDER BY 1 3581a78c22c4Sdrh ** 3582a78c22c4Sdrh ** We call this the "compound-subquery flattening". 3583f23329a2Sdanielk1977 */ 3584f23329a2Sdanielk1977 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ 3585f23329a2Sdanielk1977 Select *pNew; 3586f23329a2Sdanielk1977 ExprList *pOrderBy = p->pOrderBy; 35874b86ef1dSdanielk1977 Expr *pLimit = p->pLimit; 3588547180baSdrh Expr *pOffset = p->pOffset; 3589f23329a2Sdanielk1977 Select *pPrior = p->pPrior; 3590f23329a2Sdanielk1977 p->pOrderBy = 0; 3591f23329a2Sdanielk1977 p->pSrc = 0; 3592f23329a2Sdanielk1977 p->pPrior = 0; 35934b86ef1dSdanielk1977 p->pLimit = 0; 3594547180baSdrh p->pOffset = 0; 35956ab3a2ecSdanielk1977 pNew = sqlite3SelectDup(db, p, 0); 3596eb9b884cSdrh sqlite3SelectSetName(pNew, pSub->zSelName); 3597547180baSdrh p->pOffset = pOffset; 35984b86ef1dSdanielk1977 p->pLimit = pLimit; 3599a78c22c4Sdrh p->pOrderBy = pOrderBy; 3600a78c22c4Sdrh p->pSrc = pSrc; 3601a78c22c4Sdrh p->op = TK_ALL; 3602a78c22c4Sdrh if( pNew==0 ){ 3603d227a291Sdrh p->pPrior = pPrior; 3604a78c22c4Sdrh }else{ 3605a78c22c4Sdrh pNew->pPrior = pPrior; 3606d227a291Sdrh if( pPrior ) pPrior->pNext = pNew; 3607d227a291Sdrh pNew->pNext = p; 3608a78c22c4Sdrh p->pPrior = pNew; 3609eb9b884cSdrh SELECTTRACE(2,pParse,p, 3610eb9b884cSdrh ("compound-subquery flattener creates %s.%p as peer\n", 3611eb9b884cSdrh pNew->zSelName, pNew)); 3612d227a291Sdrh } 3613a78c22c4Sdrh if( db->mallocFailed ) return 1; 3614a78c22c4Sdrh } 3615f23329a2Sdanielk1977 36167d10d5a6Sdrh /* Begin flattening the iFrom-th entry of the FROM clause 36177d10d5a6Sdrh ** in the outer query. 3618832508b7Sdrh */ 3619f23329a2Sdanielk1977 pSub = pSub1 = pSubitem->pSelect; 3620c31c2eb8Sdrh 3621a78c22c4Sdrh /* Delete the transient table structure associated with the 3622a78c22c4Sdrh ** subquery 3623a78c22c4Sdrh */ 3624a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zDatabase); 3625a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zName); 3626a78c22c4Sdrh sqlite3DbFree(db, pSubitem->zAlias); 3627a78c22c4Sdrh pSubitem->zDatabase = 0; 3628a78c22c4Sdrh pSubitem->zName = 0; 3629a78c22c4Sdrh pSubitem->zAlias = 0; 3630a78c22c4Sdrh pSubitem->pSelect = 0; 3631a78c22c4Sdrh 3632a78c22c4Sdrh /* Defer deleting the Table object associated with the 3633a78c22c4Sdrh ** subquery until code generation is 3634a78c22c4Sdrh ** complete, since there may still exist Expr.pTab entries that 3635a78c22c4Sdrh ** refer to the subquery even after flattening. Ticket #3346. 3636ccfcbceaSdrh ** 3637ccfcbceaSdrh ** pSubitem->pTab is always non-NULL by test restrictions and tests above. 3638a78c22c4Sdrh */ 3639ccfcbceaSdrh if( ALWAYS(pSubitem->pTab!=0) ){ 3640a78c22c4Sdrh Table *pTabToDel = pSubitem->pTab; 364179df7782Sdrh if( pTabToDel->nTabRef==1 ){ 364265a7cd16Sdan Parse *pToplevel = sqlite3ParseToplevel(pParse); 364365a7cd16Sdan pTabToDel->pNextZombie = pToplevel->pZombieTab; 364465a7cd16Sdan pToplevel->pZombieTab = pTabToDel; 3645a78c22c4Sdrh }else{ 364679df7782Sdrh pTabToDel->nTabRef--; 3647a78c22c4Sdrh } 3648a78c22c4Sdrh pSubitem->pTab = 0; 3649a78c22c4Sdrh } 3650a78c22c4Sdrh 3651a78c22c4Sdrh /* The following loop runs once for each term in a compound-subquery 3652a78c22c4Sdrh ** flattening (as described above). If we are doing a different kind 3653a78c22c4Sdrh ** of flattening - a flattening other than a compound-subquery flattening - 3654a78c22c4Sdrh ** then this loop only runs once. 3655a78c22c4Sdrh ** 3656a78c22c4Sdrh ** This loop moves all of the FROM elements of the subquery into the 3657c31c2eb8Sdrh ** the FROM clause of the outer query. Before doing this, remember 3658c31c2eb8Sdrh ** the cursor number for the original outer query FROM element in 3659c31c2eb8Sdrh ** iParent. The iParent cursor will never be used. Subsequent code 3660c31c2eb8Sdrh ** will scan expressions looking for iParent references and replace 3661c31c2eb8Sdrh ** those references with expressions that resolve to the subquery FROM 3662c31c2eb8Sdrh ** elements we are now copying in. 3663c31c2eb8Sdrh */ 3664a78c22c4Sdrh for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ 3665a78c22c4Sdrh int nSubSrc; 3666ea678832Sdrh u8 jointype = 0; 3667a78c22c4Sdrh pSubSrc = pSub->pSrc; /* FROM clause of subquery */ 3668a78c22c4Sdrh nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */ 3669a78c22c4Sdrh pSrc = pParent->pSrc; /* FROM clause of the outer query */ 3670588a9a1aSdrh 3671a78c22c4Sdrh if( pSrc ){ 3672a78c22c4Sdrh assert( pParent==p ); /* First time through the loop */ 36738a48b9c0Sdrh jointype = pSubitem->fg.jointype; 3674588a9a1aSdrh }else{ 3675a78c22c4Sdrh assert( pParent!=p ); /* 2nd and subsequent times through the loop */ 3676a78c22c4Sdrh pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); 3677cfa063b3Sdrh if( pSrc==0 ){ 3678a78c22c4Sdrh assert( db->mallocFailed ); 3679a78c22c4Sdrh break; 3680cfa063b3Sdrh } 3681c31c2eb8Sdrh } 3682a78c22c4Sdrh 3683a78c22c4Sdrh /* The subquery uses a single slot of the FROM clause of the outer 3684a78c22c4Sdrh ** query. If the subquery has more than one element in its FROM clause, 3685a78c22c4Sdrh ** then expand the outer query to make space for it to hold all elements 3686a78c22c4Sdrh ** of the subquery. 3687a78c22c4Sdrh ** 3688a78c22c4Sdrh ** Example: 3689a78c22c4Sdrh ** 3690a78c22c4Sdrh ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; 3691a78c22c4Sdrh ** 3692a78c22c4Sdrh ** The outer query has 3 slots in its FROM clause. One slot of the 3693a78c22c4Sdrh ** outer query (the middle slot) is used by the subquery. The next 3694d12b6363Sdrh ** block of code will expand the outer query FROM clause to 4 slots. 3695d12b6363Sdrh ** The middle slot is expanded to two slots in order to make space 3696d12b6363Sdrh ** for the two elements in the FROM clause of the subquery. 3697a78c22c4Sdrh */ 3698a78c22c4Sdrh if( nSubSrc>1 ){ 3699a78c22c4Sdrh pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); 3700a78c22c4Sdrh if( db->mallocFailed ){ 3701a78c22c4Sdrh break; 3702c31c2eb8Sdrh } 3703c31c2eb8Sdrh } 3704a78c22c4Sdrh 3705a78c22c4Sdrh /* Transfer the FROM clause terms from the subquery into the 3706a78c22c4Sdrh ** outer query. 3707a78c22c4Sdrh */ 3708c31c2eb8Sdrh for(i=0; i<nSubSrc; i++){ 3709c3a8402aSdrh sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing); 371020292310Sdrh assert( pSrc->a[i+iFrom].fg.isTabFunc==0 ); 3711c31c2eb8Sdrh pSrc->a[i+iFrom] = pSubSrc->a[i]; 3712399c7e21Sdrh iNewParent = pSubSrc->a[i].iCursor; 3713c31c2eb8Sdrh memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); 3714c31c2eb8Sdrh } 37158a48b9c0Sdrh pSrc->a[iFrom].fg.jointype = jointype; 3716c31c2eb8Sdrh 3717c31c2eb8Sdrh /* Now begin substituting subquery result set expressions for 3718c31c2eb8Sdrh ** references to the iParent in the outer query. 3719c31c2eb8Sdrh ** 3720c31c2eb8Sdrh ** Example: 3721c31c2eb8Sdrh ** 3722c31c2eb8Sdrh ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; 3723c31c2eb8Sdrh ** \ \_____________ subquery __________/ / 3724c31c2eb8Sdrh ** \_____________________ outer query ______________________________/ 3725c31c2eb8Sdrh ** 3726c31c2eb8Sdrh ** We look at every expression in the outer query and every place we see 3727c31c2eb8Sdrh ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". 3728c31c2eb8Sdrh */ 3729f23329a2Sdanielk1977 pList = pParent->pEList; 3730832508b7Sdrh for(i=0; i<pList->nExpr; i++){ 3731ccfcbceaSdrh if( pList->a[i].zName==0 ){ 373242fbf321Sdrh char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan); 373342fbf321Sdrh sqlite3Dequote(zName); 373442fbf321Sdrh pList->a[i].zName = zName; 3735832508b7Sdrh } 3736ccfcbceaSdrh } 3737174b6195Sdrh if( pSub->pOrderBy ){ 37387c0a4720Sdan /* At this point, any non-zero iOrderByCol values indicate that the 37397c0a4720Sdan ** ORDER BY column expression is identical to the iOrderByCol'th 37407c0a4720Sdan ** expression returned by SELECT statement pSub. Since these values 37417c0a4720Sdan ** do not necessarily correspond to columns in SELECT statement pParent, 37427c0a4720Sdan ** zero them before transfering the ORDER BY clause. 37437c0a4720Sdan ** 37447c0a4720Sdan ** Not doing this may cause an error if a subsequent call to this 37457c0a4720Sdan ** function attempts to flatten a compound sub-query into pParent 37467c0a4720Sdan ** (the only way this can happen is if the compound sub-query is 37477c0a4720Sdan ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */ 37487c0a4720Sdan ExprList *pOrderBy = pSub->pOrderBy; 37497c0a4720Sdan for(i=0; i<pOrderBy->nExpr; i++){ 37507c0a4720Sdan pOrderBy->a[i].u.x.iOrderByCol = 0; 37517c0a4720Sdan } 3752f23329a2Sdanielk1977 assert( pParent->pOrderBy==0 ); 37537c0a4720Sdan assert( pSub->pPrior==0 ); 37547c0a4720Sdan pParent->pOrderBy = pOrderBy; 3755174b6195Sdrh pSub->pOrderBy = 0; 3756174b6195Sdrh } 37576ab3a2ecSdanielk1977 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); 3758399c7e21Sdrh if( isLeftJoin ){ 3759399c7e21Sdrh setJoinExpr(pWhere, iNewParent); 3760399c7e21Sdrh } 3761832508b7Sdrh if( subqueryIsAgg ){ 3762f23329a2Sdanielk1977 assert( pParent->pHaving==0 ); 3763f23329a2Sdanielk1977 pParent->pHaving = pParent->pWhere; 3764f23329a2Sdanielk1977 pParent->pWhere = pWhere; 37654c5ebee0Sdan pParent->pHaving = sqlite3ExprAnd(db, 37664c5ebee0Sdan sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving 37674c5ebee0Sdan ); 3768f23329a2Sdanielk1977 assert( pParent->pGroupBy==0 ); 37696ab3a2ecSdanielk1977 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0); 3770832508b7Sdrh }else{ 37714c5ebee0Sdan pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere); 3772832508b7Sdrh } 3773c3becddbSdan if( db->mallocFailed==0 ){ 377446967de2Sdrh SubstContext x; 377546967de2Sdrh x.pParse = pParse; 377646967de2Sdrh x.iTable = iParent; 3777399c7e21Sdrh x.iNewTable = iNewParent; 377831d6fd55Sdrh x.isLeftJoin = isLeftJoin; 377946967de2Sdrh x.pEList = pSub->pEList; 378046967de2Sdrh substSelect(&x, pParent, 0); 3781c3becddbSdan } 3782c31c2eb8Sdrh 3783c31c2eb8Sdrh /* The flattened query is distinct if either the inner or the 3784c31c2eb8Sdrh ** outer query is distinct. 3785c31c2eb8Sdrh */ 37867d10d5a6Sdrh pParent->selFlags |= pSub->selFlags & SF_Distinct; 37878c74a8caSdrh 3788a58fdfb1Sdanielk1977 /* 3789a58fdfb1Sdanielk1977 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; 3790ac83963aSdrh ** 3791ac83963aSdrh ** One is tempted to try to add a and b to combine the limits. But this 3792ac83963aSdrh ** does not work if either limit is negative. 3793a58fdfb1Sdanielk1977 */ 3794a2dc3b1aSdanielk1977 if( pSub->pLimit ){ 3795f23329a2Sdanielk1977 pParent->pLimit = pSub->pLimit; 3796a2dc3b1aSdanielk1977 pSub->pLimit = 0; 3797df199a25Sdrh } 3798f23329a2Sdanielk1977 } 37998c74a8caSdrh 3800c31c2eb8Sdrh /* Finially, delete what is left of the subquery and return 3801c31c2eb8Sdrh ** success. 3802c31c2eb8Sdrh */ 3803633e6d57Sdrh sqlite3SelectDelete(db, pSub1); 3804f23329a2Sdanielk1977 3805c90713d3Sdrh #if SELECTTRACE_ENABLED 3806c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 3807bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After flattening:\n")); 3808c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 3809c90713d3Sdrh } 3810c90713d3Sdrh #endif 3811c90713d3Sdrh 3812832508b7Sdrh return 1; 38131350b030Sdrh } 38143514b6f7Sshane #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 38151350b030Sdrh 381669b72d5aSdrh 381769b72d5aSdrh 381869b72d5aSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 381969b72d5aSdrh /* 382069b72d5aSdrh ** Make copies of relevant WHERE clause terms of the outer query into 382169b72d5aSdrh ** the WHERE clause of subquery. Example: 382269b72d5aSdrh ** 382369b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10; 382469b72d5aSdrh ** 382569b72d5aSdrh ** Transformed into: 382669b72d5aSdrh ** 382769b72d5aSdrh ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10) 382869b72d5aSdrh ** WHERE x=5 AND y=10; 382969b72d5aSdrh ** 383069b72d5aSdrh ** The hope is that the terms added to the inner query will make it more 383169b72d5aSdrh ** efficient. 383269b72d5aSdrh ** 383369b72d5aSdrh ** Do not attempt this optimization if: 383469b72d5aSdrh ** 383569b72d5aSdrh ** (1) The inner query is an aggregate. (In that case, we'd really want 383669b72d5aSdrh ** to copy the outer WHERE-clause terms onto the HAVING clause of the 383769b72d5aSdrh ** inner query. But they probably won't help there so do not bother.) 383869b72d5aSdrh ** 383969b72d5aSdrh ** (2) The inner query is the recursive part of a common table expression. 384069b72d5aSdrh ** 384169b72d5aSdrh ** (3) The inner query has a LIMIT clause (since the changes to the WHERE 384269b72d5aSdrh ** close would change the meaning of the LIMIT). 384369b72d5aSdrh ** 384469b72d5aSdrh ** (4) The inner query is the right operand of a LEFT JOIN. (The caller 384569b72d5aSdrh ** enforces this restriction since this routine does not have enough 384669b72d5aSdrh ** information to know.) 384769b72d5aSdrh ** 384838978dd4Sdrh ** (5) The WHERE clause expression originates in the ON or USING clause 384938978dd4Sdrh ** of a LEFT JOIN. 385038978dd4Sdrh ** 385169b72d5aSdrh ** Return 0 if no changes are made and non-zero if one or more WHERE clause 385269b72d5aSdrh ** terms are duplicated into the subquery. 385369b72d5aSdrh */ 385469b72d5aSdrh static int pushDownWhereTerms( 385544c5604cSdan Parse *pParse, /* Parse context (for malloc() and error reporting) */ 385669b72d5aSdrh Select *pSubq, /* The subquery whose WHERE clause is to be augmented */ 385769b72d5aSdrh Expr *pWhere, /* The WHERE clause of the outer query */ 385869b72d5aSdrh int iCursor /* Cursor number of the subquery */ 385969b72d5aSdrh ){ 386069b72d5aSdrh Expr *pNew; 386169b72d5aSdrh int nChng = 0; 3862b1ec87afSdrh Select *pX; /* For looping over compound SELECTs in pSubq */ 386369b72d5aSdrh if( pWhere==0 ) return 0; 3864b1ec87afSdrh for(pX=pSubq; pX; pX=pX->pPrior){ 3865b1ec87afSdrh if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){ 3866b1ec87afSdrh testcase( pX->selFlags & SF_Aggregate ); 3867b1ec87afSdrh testcase( pX->selFlags & SF_Recursive ); 3868b1ec87afSdrh testcase( pX!=pSubq ); 386969b72d5aSdrh return 0; /* restrictions (1) and (2) */ 387069b72d5aSdrh } 3871b1ec87afSdrh } 387269b72d5aSdrh if( pSubq->pLimit!=0 ){ 387369b72d5aSdrh return 0; /* restriction (3) */ 387469b72d5aSdrh } 387569b72d5aSdrh while( pWhere->op==TK_AND ){ 387644c5604cSdan nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor); 387769b72d5aSdrh pWhere = pWhere->pLeft; 387869b72d5aSdrh } 387938978dd4Sdrh if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */ 388069b72d5aSdrh if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ 388169b72d5aSdrh nChng++; 388269b72d5aSdrh while( pSubq ){ 388346967de2Sdrh SubstContext x; 388444c5604cSdan pNew = sqlite3ExprDup(pParse->db, pWhere, 0); 388546967de2Sdrh x.pParse = pParse; 388646967de2Sdrh x.iTable = iCursor; 3887399c7e21Sdrh x.iNewTable = iCursor; 388831d6fd55Sdrh x.isLeftJoin = 0; 388946967de2Sdrh x.pEList = pSubq->pEList; 389046967de2Sdrh pNew = substExpr(&x, pNew); 389144c5604cSdan pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew); 389269b72d5aSdrh pSubq = pSubq->pPrior; 389369b72d5aSdrh } 389469b72d5aSdrh } 389569b72d5aSdrh return nChng; 389669b72d5aSdrh } 389769b72d5aSdrh #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ 389869b72d5aSdrh 38991350b030Sdrh /* 39004ac391fcSdan ** Based on the contents of the AggInfo structure indicated by the first 39014ac391fcSdan ** argument, this function checks if the following are true: 3902a9d1ccb9Sdanielk1977 ** 39034ac391fcSdan ** * the query contains just a single aggregate function, 39044ac391fcSdan ** * the aggregate function is either min() or max(), and 39054ac391fcSdan ** * the argument to the aggregate function is a column value. 3906738bdcfbSdanielk1977 ** 39074ac391fcSdan ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX 39084ac391fcSdan ** is returned as appropriate. Also, *ppMinMax is set to point to the 39094ac391fcSdan ** list of arguments passed to the aggregate before returning. 39104ac391fcSdan ** 39114ac391fcSdan ** Or, if the conditions above are not met, *ppMinMax is set to 0 and 39124ac391fcSdan ** WHERE_ORDERBY_NORMAL is returned. 3913a9d1ccb9Sdanielk1977 */ 39144ac391fcSdan static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ 39154ac391fcSdan int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ 3916a9d1ccb9Sdanielk1977 39174ac391fcSdan *ppMinMax = 0; 39184ac391fcSdan if( pAggInfo->nFunc==1 ){ 39194ac391fcSdan Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ 39204ac391fcSdan ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ 39214ac391fcSdan 39224ac391fcSdan assert( pExpr->op==TK_AGG_FUNCTION ); 39234ac391fcSdan if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ 39244ac391fcSdan const char *zFunc = pExpr->u.zToken; 39254ac391fcSdan if( sqlite3StrICmp(zFunc, "min")==0 ){ 39264ac391fcSdan eRet = WHERE_ORDERBY_MIN; 39274ac391fcSdan *ppMinMax = pEList; 39284ac391fcSdan }else if( sqlite3StrICmp(zFunc, "max")==0 ){ 39294ac391fcSdan eRet = WHERE_ORDERBY_MAX; 39304ac391fcSdan *ppMinMax = pEList; 3931a9d1ccb9Sdanielk1977 } 39324ac391fcSdan } 39334ac391fcSdan } 39344ac391fcSdan 39354ac391fcSdan assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); 39364ac391fcSdan return eRet; 3937a9d1ccb9Sdanielk1977 } 3938a9d1ccb9Sdanielk1977 3939a9d1ccb9Sdanielk1977 /* 3940a5533162Sdanielk1977 ** The select statement passed as the first argument is an aggregate query. 394160ec914cSpeter.d.reid ** The second argument is the associated aggregate-info object. This 3942a5533162Sdanielk1977 ** function tests if the SELECT is of the form: 3943a5533162Sdanielk1977 ** 3944a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 3945a5533162Sdanielk1977 ** 3946a5533162Sdanielk1977 ** where table is a database table, not a sub-select or view. If the query 3947a5533162Sdanielk1977 ** does match this pattern, then a pointer to the Table object representing 3948a5533162Sdanielk1977 ** <tbl> is returned. Otherwise, 0 is returned. 3949a5533162Sdanielk1977 */ 3950a5533162Sdanielk1977 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){ 3951a5533162Sdanielk1977 Table *pTab; 3952a5533162Sdanielk1977 Expr *pExpr; 3953a5533162Sdanielk1977 3954a5533162Sdanielk1977 assert( !p->pGroupBy ); 3955a5533162Sdanielk1977 39567a895a80Sdanielk1977 if( p->pWhere || p->pEList->nExpr!=1 3957a5533162Sdanielk1977 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect 3958a5533162Sdanielk1977 ){ 3959a5533162Sdanielk1977 return 0; 3960a5533162Sdanielk1977 } 3961a5533162Sdanielk1977 pTab = p->pSrc->a[0].pTab; 3962a5533162Sdanielk1977 pExpr = p->pEList->a[0].pExpr; 396302f33725Sdanielk1977 assert( pTab && !pTab->pSelect && pExpr ); 396402f33725Sdanielk1977 396502f33725Sdanielk1977 if( IsVirtual(pTab) ) return 0; 3966a5533162Sdanielk1977 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; 3967fb0a6081Sdrh if( NEVER(pAggInfo->nFunc==0) ) return 0; 3968d36e1041Sdrh if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0; 3969a5533162Sdanielk1977 if( pExpr->flags&EP_Distinct ) return 0; 3970a5533162Sdanielk1977 3971a5533162Sdanielk1977 return pTab; 3972a5533162Sdanielk1977 } 3973a5533162Sdanielk1977 3974a5533162Sdanielk1977 /* 3975b1c685b0Sdanielk1977 ** If the source-list item passed as an argument was augmented with an 3976b1c685b0Sdanielk1977 ** INDEXED BY clause, then try to locate the specified index. If there 3977b1c685b0Sdanielk1977 ** was such a clause and the named index cannot be found, return 3978b1c685b0Sdanielk1977 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 3979b1c685b0Sdanielk1977 ** pFrom->pIndex and return SQLITE_OK. 3980b1c685b0Sdanielk1977 */ 3981b1c685b0Sdanielk1977 int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){ 39828a48b9c0Sdrh if( pFrom->pTab && pFrom->fg.isIndexedBy ){ 3983b1c685b0Sdanielk1977 Table *pTab = pFrom->pTab; 39848a48b9c0Sdrh char *zIndexedBy = pFrom->u1.zIndexedBy; 3985b1c685b0Sdanielk1977 Index *pIdx; 3986b1c685b0Sdanielk1977 for(pIdx=pTab->pIndex; 3987d62fbb50Sdrh pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 3988b1c685b0Sdanielk1977 pIdx=pIdx->pNext 3989b1c685b0Sdanielk1977 ); 3990b1c685b0Sdanielk1977 if( !pIdx ){ 3991d62fbb50Sdrh sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0); 39921db95106Sdan pParse->checkSchema = 1; 3993b1c685b0Sdanielk1977 return SQLITE_ERROR; 3994b1c685b0Sdanielk1977 } 39958a48b9c0Sdrh pFrom->pIBIndex = pIdx; 3996b1c685b0Sdanielk1977 } 3997b1c685b0Sdanielk1977 return SQLITE_OK; 3998b1c685b0Sdanielk1977 } 3999c01b7306Sdrh /* 4000c01b7306Sdrh ** Detect compound SELECT statements that use an ORDER BY clause with 4001c01b7306Sdrh ** an alternative collating sequence. 4002c01b7306Sdrh ** 4003c01b7306Sdrh ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ... 4004c01b7306Sdrh ** 4005c01b7306Sdrh ** These are rewritten as a subquery: 4006c01b7306Sdrh ** 4007c01b7306Sdrh ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2) 4008c01b7306Sdrh ** ORDER BY ... COLLATE ... 4009c01b7306Sdrh ** 4010c01b7306Sdrh ** This transformation is necessary because the multiSelectOrderBy() routine 4011c01b7306Sdrh ** above that generates the code for a compound SELECT with an ORDER BY clause 4012c01b7306Sdrh ** uses a merge algorithm that requires the same collating sequence on the 4013c01b7306Sdrh ** result columns as on the ORDER BY clause. See ticket 4014c01b7306Sdrh ** http://www.sqlite.org/src/info/6709574d2a 4015c01b7306Sdrh ** 4016c01b7306Sdrh ** This transformation is only needed for EXCEPT, INTERSECT, and UNION. 4017c01b7306Sdrh ** The UNION ALL operator works fine with multiSelectOrderBy() even when 4018c01b7306Sdrh ** there are COLLATE terms in the ORDER BY. 4019c01b7306Sdrh */ 4020c01b7306Sdrh static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){ 4021c01b7306Sdrh int i; 4022c01b7306Sdrh Select *pNew; 4023c01b7306Sdrh Select *pX; 4024c01b7306Sdrh sqlite3 *db; 4025c01b7306Sdrh struct ExprList_item *a; 4026c01b7306Sdrh SrcList *pNewSrc; 4027c01b7306Sdrh Parse *pParse; 4028c01b7306Sdrh Token dummy; 4029c01b7306Sdrh 4030c01b7306Sdrh if( p->pPrior==0 ) return WRC_Continue; 4031c01b7306Sdrh if( p->pOrderBy==0 ) return WRC_Continue; 4032c01b7306Sdrh for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){} 4033c01b7306Sdrh if( pX==0 ) return WRC_Continue; 4034c01b7306Sdrh a = p->pOrderBy->a; 4035c01b7306Sdrh for(i=p->pOrderBy->nExpr-1; i>=0; i--){ 4036c01b7306Sdrh if( a[i].pExpr->flags & EP_Collate ) break; 4037c01b7306Sdrh } 4038c01b7306Sdrh if( i<0 ) return WRC_Continue; 4039c01b7306Sdrh 4040c01b7306Sdrh /* If we reach this point, that means the transformation is required. */ 4041c01b7306Sdrh 4042c01b7306Sdrh pParse = pWalker->pParse; 4043c01b7306Sdrh db = pParse->db; 4044c01b7306Sdrh pNew = sqlite3DbMallocZero(db, sizeof(*pNew) ); 4045c01b7306Sdrh if( pNew==0 ) return WRC_Abort; 4046c01b7306Sdrh memset(&dummy, 0, sizeof(dummy)); 4047c01b7306Sdrh pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0); 4048c01b7306Sdrh if( pNewSrc==0 ) return WRC_Abort; 4049c01b7306Sdrh *pNew = *p; 4050c01b7306Sdrh p->pSrc = pNewSrc; 40511a1d3cd2Sdrh p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0)); 4052c01b7306Sdrh p->op = TK_SELECT; 4053c01b7306Sdrh p->pWhere = 0; 4054c01b7306Sdrh pNew->pGroupBy = 0; 4055c01b7306Sdrh pNew->pHaving = 0; 4056c01b7306Sdrh pNew->pOrderBy = 0; 4057c01b7306Sdrh p->pPrior = 0; 40588af9ad95Sdrh p->pNext = 0; 4059f932f714Sdrh p->pWith = 0; 40608af9ad95Sdrh p->selFlags &= ~SF_Compound; 4061b33c50f2Sdan assert( (p->selFlags & SF_Converted)==0 ); 4062b33c50f2Sdan p->selFlags |= SF_Converted; 4063a6e3a8c9Sdrh assert( pNew->pPrior!=0 ); 4064a6e3a8c9Sdrh pNew->pPrior->pNext = pNew; 4065c01b7306Sdrh pNew->pLimit = 0; 4066c01b7306Sdrh pNew->pOffset = 0; 4067c01b7306Sdrh return WRC_Continue; 4068c01b7306Sdrh } 4069b1c685b0Sdanielk1977 407020292310Sdrh /* 407120292310Sdrh ** Check to see if the FROM clause term pFrom has table-valued function 407220292310Sdrh ** arguments. If it does, leave an error message in pParse and return 407320292310Sdrh ** non-zero, since pFrom is not allowed to be a table-valued function. 407420292310Sdrh */ 407520292310Sdrh static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){ 407620292310Sdrh if( pFrom->fg.isTabFunc ){ 407720292310Sdrh sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName); 407820292310Sdrh return 1; 407920292310Sdrh } 408020292310Sdrh return 0; 408120292310Sdrh } 408220292310Sdrh 4083eede6a53Sdan #ifndef SQLITE_OMIT_CTE 4084eede6a53Sdan /* 4085eede6a53Sdan ** Argument pWith (which may be NULL) points to a linked list of nested 4086eede6a53Sdan ** WITH contexts, from inner to outermost. If the table identified by 4087eede6a53Sdan ** FROM clause element pItem is really a common-table-expression (CTE) 4088eede6a53Sdan ** then return a pointer to the CTE definition for that table. Otherwise 4089eede6a53Sdan ** return NULL. 409098f45e53Sdan ** 409198f45e53Sdan ** If a non-NULL value is returned, set *ppContext to point to the With 409298f45e53Sdan ** object that the returned CTE belongs to. 409360c1a2f0Sdrh */ 409498f45e53Sdan static struct Cte *searchWith( 40952476a6f2Sdrh With *pWith, /* Current innermost WITH clause */ 409698f45e53Sdan struct SrcList_item *pItem, /* FROM clause element to resolve */ 409798f45e53Sdan With **ppContext /* OUT: WITH clause return value belongs to */ 409898f45e53Sdan ){ 40997b19f252Sdrh const char *zName; 41007b19f252Sdrh if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){ 4101eede6a53Sdan With *p; 4102eede6a53Sdan for(p=pWith; p; p=p->pOuter){ 41034e9119d9Sdan int i; 4104eede6a53Sdan for(i=0; i<p->nCte; i++){ 4105eede6a53Sdan if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){ 410698f45e53Sdan *ppContext = p; 4107eede6a53Sdan return &p->a[i]; 41084e9119d9Sdan } 41094e9119d9Sdan } 41104e9119d9Sdan } 41114e9119d9Sdan } 41124e9119d9Sdan return 0; 41134e9119d9Sdan } 41144e9119d9Sdan 4115c49832c2Sdrh /* The code generator maintains a stack of active WITH clauses 4116c49832c2Sdrh ** with the inner-most WITH clause being at the top of the stack. 4117c49832c2Sdrh ** 4118b290f117Sdan ** This routine pushes the WITH clause passed as the second argument 4119b290f117Sdan ** onto the top of the stack. If argument bFree is true, then this 4120b290f117Sdan ** WITH clause will never be popped from the stack. In this case it 4121b290f117Sdan ** should be freed along with the Parse object. In other cases, when 4122b290f117Sdan ** bFree==0, the With object will be freed along with the SELECT 4123b290f117Sdan ** statement with which it is associated. 4124c49832c2Sdrh */ 4125b290f117Sdan void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){ 41266e772266Sdrh assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) ); 41274e9119d9Sdan if( pWith ){ 41282476a6f2Sdrh assert( pParse->pWith!=pWith ); 41294e9119d9Sdan pWith->pOuter = pParse->pWith; 41304e9119d9Sdan pParse->pWith = pWith; 41316e772266Sdrh if( bFree ) pParse->pWithToFree = pWith; 41324e9119d9Sdan } 41334e9119d9Sdan } 41344e9119d9Sdan 4135eede6a53Sdan /* 4136eede6a53Sdan ** This function checks if argument pFrom refers to a CTE declared by 4137eede6a53Sdan ** a WITH clause on the stack currently maintained by the parser. And, 4138eede6a53Sdan ** if currently processing a CTE expression, if it is a recursive 4139eede6a53Sdan ** reference to the current CTE. 4140eede6a53Sdan ** 4141eede6a53Sdan ** If pFrom falls into either of the two categories above, pFrom->pTab 4142eede6a53Sdan ** and other fields are populated accordingly. The caller should check 4143eede6a53Sdan ** (pFrom->pTab!=0) to determine whether or not a successful match 4144eede6a53Sdan ** was found. 4145eede6a53Sdan ** 4146eede6a53Sdan ** Whether or not a match is found, SQLITE_OK is returned if no error 4147eede6a53Sdan ** occurs. If an error does occur, an error message is stored in the 4148eede6a53Sdan ** parser and some error code other than SQLITE_OK returned. 4149eede6a53Sdan */ 41508ce7184bSdan static int withExpand( 41518ce7184bSdan Walker *pWalker, 4152eede6a53Sdan struct SrcList_item *pFrom 41538ce7184bSdan ){ 41548ce7184bSdan Parse *pParse = pWalker->pParse; 41558ce7184bSdan sqlite3 *db = pParse->db; 415698f45e53Sdan struct Cte *pCte; /* Matched CTE (or NULL if no match) */ 415798f45e53Sdan With *pWith; /* WITH clause that pCte belongs to */ 41588ce7184bSdan 41598ce7184bSdan assert( pFrom->pTab==0 ); 41608ce7184bSdan 416198f45e53Sdan pCte = searchWith(pParse->pWith, pFrom, &pWith); 4162eae73fbfSdan if( pCte ){ 416398f45e53Sdan Table *pTab; 41648ce7184bSdan ExprList *pEList; 41658ce7184bSdan Select *pSel; 416660e7068dSdan Select *pLeft; /* Left-most SELECT statement */ 4167f2655fe8Sdan int bMayRecursive; /* True if compound joined by UNION [ALL] */ 416898f45e53Sdan With *pSavedWith; /* Initial value of pParse->pWith */ 4169f2655fe8Sdan 41700576bc59Sdrh /* If pCte->zCteErr is non-NULL at this point, then this is an illegal 4171f2655fe8Sdan ** recursive reference to CTE pCte. Leave an error in pParse and return 41720576bc59Sdrh ** early. If pCte->zCteErr is NULL, then this is not a recursive reference. 4173f2655fe8Sdan ** In this case, proceed. */ 41740576bc59Sdrh if( pCte->zCteErr ){ 41750576bc59Sdrh sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName); 417698f45e53Sdan return SQLITE_ERROR; 4177f2655fe8Sdan } 417820292310Sdrh if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR; 41798ce7184bSdan 4180c25e2ebcSdrh assert( pFrom->pTab==0 ); 41818ce7184bSdan pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 41828ce7184bSdan if( pTab==0 ) return WRC_Abort; 418379df7782Sdrh pTab->nTabRef = 1; 41842d4dc5fcSdan pTab->zName = sqlite3DbStrDup(db, pCte->zName); 41858ce7184bSdan pTab->iPKey = -1; 4186cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 4187fccda8a1Sdrh pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid; 41888ce7184bSdan pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0); 4189fad3039cSmistachkin if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; 41908ce7184bSdan assert( pFrom->pSelect ); 41918ce7184bSdan 4192eae73fbfSdan /* Check if this is a recursive CTE. */ 41938ce7184bSdan pSel = pFrom->pSelect; 4194f2655fe8Sdan bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION ); 4195f2655fe8Sdan if( bMayRecursive ){ 4196eae73fbfSdan int i; 4197eae73fbfSdan SrcList *pSrc = pFrom->pSelect->pSrc; 4198eae73fbfSdan for(i=0; i<pSrc->nSrc; i++){ 4199eae73fbfSdan struct SrcList_item *pItem = &pSrc->a[i]; 4200eae73fbfSdan if( pItem->zDatabase==0 4201eae73fbfSdan && pItem->zName!=0 4202eae73fbfSdan && 0==sqlite3StrICmp(pItem->zName, pCte->zName) 4203eae73fbfSdan ){ 4204eae73fbfSdan pItem->pTab = pTab; 42058a48b9c0Sdrh pItem->fg.isRecursive = 1; 420679df7782Sdrh pTab->nTabRef++; 4207eae73fbfSdan pSel->selFlags |= SF_Recursive; 42088ce7184bSdan } 4209eae73fbfSdan } 4210eae73fbfSdan } 4211eae73fbfSdan 4212eae73fbfSdan /* Only one recursive reference is permitted. */ 421379df7782Sdrh if( pTab->nTabRef>2 ){ 4214eae73fbfSdan sqlite3ErrorMsg( 4215727a99f1Sdrh pParse, "multiple references to recursive table: %s", pCte->zName 4216eae73fbfSdan ); 421798f45e53Sdan return SQLITE_ERROR; 4218eae73fbfSdan } 421979df7782Sdrh assert( pTab->nTabRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 )); 4220eae73fbfSdan 42210576bc59Sdrh pCte->zCteErr = "circular reference: %s"; 422298f45e53Sdan pSavedWith = pParse->pWith; 422398f45e53Sdan pParse->pWith = pWith; 4224067cd837Sdan if( bMayRecursive ){ 4225067cd837Sdan Select *pPrior = pSel->pPrior; 4226067cd837Sdan assert( pPrior->pWith==0 ); 4227067cd837Sdan pPrior->pWith = pSel->pWith; 4228067cd837Sdan sqlite3WalkSelect(pWalker, pPrior); 4229067cd837Sdan pPrior->pWith = 0; 4230067cd837Sdan }else{ 4231067cd837Sdan sqlite3WalkSelect(pWalker, pSel); 4232067cd837Sdan } 42336e772266Sdrh pParse->pWith = pWith; 42348ce7184bSdan 42358ce7184bSdan for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior); 42368ce7184bSdan pEList = pLeft->pEList; 423760e7068dSdan if( pCte->pCols ){ 42388f9d0b2bSdrh if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){ 4239727a99f1Sdrh sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns", 424060e7068dSdan pCte->zName, pEList->nExpr, pCte->pCols->nExpr 424160e7068dSdan ); 424298f45e53Sdan pParse->pWith = pSavedWith; 424398f45e53Sdan return SQLITE_ERROR; 42448ce7184bSdan } 424560e7068dSdan pEList = pCte->pCols; 424660e7068dSdan } 42478ce7184bSdan 42488981b904Sdrh sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol); 4249f2655fe8Sdan if( bMayRecursive ){ 4250f2655fe8Sdan if( pSel->selFlags & SF_Recursive ){ 42510576bc59Sdrh pCte->zCteErr = "multiple recursive references: %s"; 4252f2655fe8Sdan }else{ 42530576bc59Sdrh pCte->zCteErr = "recursive reference in a subquery: %s"; 4254f2655fe8Sdan } 4255f2655fe8Sdan sqlite3WalkSelect(pWalker, pSel); 4256f2655fe8Sdan } 42570576bc59Sdrh pCte->zCteErr = 0; 425898f45e53Sdan pParse->pWith = pSavedWith; 42598ce7184bSdan } 42608ce7184bSdan 42618ce7184bSdan return SQLITE_OK; 42628ce7184bSdan } 4263eede6a53Sdan #endif 42644e9119d9Sdan 4265b290f117Sdan #ifndef SQLITE_OMIT_CTE 426671856944Sdan /* 426771856944Sdan ** If the SELECT passed as the second argument has an associated WITH 426871856944Sdan ** clause, pop it from the stack stored as part of the Parse object. 426971856944Sdan ** 427071856944Sdan ** This function is used as the xSelectCallback2() callback by 427171856944Sdan ** sqlite3SelectExpand() when walking a SELECT tree to resolve table 427271856944Sdan ** names and other FROM clause elements. 427371856944Sdan */ 4274b290f117Sdan static void selectPopWith(Walker *pWalker, Select *p){ 4275b290f117Sdan Parse *pParse = pWalker->pParse; 4276067cd837Sdan if( pParse->pWith && p->pPrior==0 ){ 4277d227a291Sdrh With *pWith = findRightmost(p)->pWith; 4278d227a291Sdrh if( pWith!=0 ){ 4279d227a291Sdrh assert( pParse->pWith==pWith ); 4280d227a291Sdrh pParse->pWith = pWith->pOuter; 4281b290f117Sdan } 4282b290f117Sdan } 4283067cd837Sdan } 4284b290f117Sdan #else 4285b290f117Sdan #define selectPopWith 0 4286b290f117Sdan #endif 4287b290f117Sdan 4288b1c685b0Sdanielk1977 /* 42897d10d5a6Sdrh ** This routine is a Walker callback for "expanding" a SELECT statement. 42907d10d5a6Sdrh ** "Expanding" means to do the following: 42917d10d5a6Sdrh ** 42927d10d5a6Sdrh ** (1) Make sure VDBE cursor numbers have been assigned to every 42937d10d5a6Sdrh ** element of the FROM clause. 42947d10d5a6Sdrh ** 42957d10d5a6Sdrh ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that 42967d10d5a6Sdrh ** defines FROM clause. When views appear in the FROM clause, 42977d10d5a6Sdrh ** fill pTabList->a[].pSelect with a copy of the SELECT statement 42987d10d5a6Sdrh ** that implements the view. A copy is made of the view's SELECT 42997d10d5a6Sdrh ** statement so that we can freely modify or delete that statement 430060ec914cSpeter.d.reid ** without worrying about messing up the persistent representation 43017d10d5a6Sdrh ** of the view. 43027d10d5a6Sdrh ** 430360ec914cSpeter.d.reid ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword 43047d10d5a6Sdrh ** on joins and the ON and USING clause of joins. 43057d10d5a6Sdrh ** 43067d10d5a6Sdrh ** (4) Scan the list of columns in the result set (pEList) looking 43077d10d5a6Sdrh ** for instances of the "*" operator or the TABLE.* operator. 43087d10d5a6Sdrh ** If found, expand each "*" to be every column in every table 43097d10d5a6Sdrh ** and TABLE.* to be every column in TABLE. 43107d10d5a6Sdrh ** 4311b3bce662Sdanielk1977 */ 43127d10d5a6Sdrh static int selectExpander(Walker *pWalker, Select *p){ 43137d10d5a6Sdrh Parse *pParse = pWalker->pParse; 43147d10d5a6Sdrh int i, j, k; 43157d10d5a6Sdrh SrcList *pTabList; 43167d10d5a6Sdrh ExprList *pEList; 43177d10d5a6Sdrh struct SrcList_item *pFrom; 43187d10d5a6Sdrh sqlite3 *db = pParse->db; 43193e3f1a5bSdrh Expr *pE, *pRight, *pExpr; 4320785097daSdrh u16 selFlags = p->selFlags; 43217d10d5a6Sdrh 4322785097daSdrh p->selFlags |= SF_Expanded; 43237d10d5a6Sdrh if( db->mallocFailed ){ 43247d10d5a6Sdrh return WRC_Abort; 43257d10d5a6Sdrh } 4326785097daSdrh if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ 43277d10d5a6Sdrh return WRC_Prune; 43287d10d5a6Sdrh } 43297d10d5a6Sdrh pTabList = p->pSrc; 43307d10d5a6Sdrh pEList = p->pEList; 4331067cd837Sdan if( p->pWith ){ 4332067cd837Sdan sqlite3WithPush(pParse, p->pWith, 0); 43333afd2b4dSdrh } 43347d10d5a6Sdrh 43357d10d5a6Sdrh /* Make sure cursor numbers have been assigned to all entries in 43367d10d5a6Sdrh ** the FROM clause of the SELECT statement. 43377d10d5a6Sdrh */ 43387d10d5a6Sdrh sqlite3SrcListAssignCursors(pParse, pTabList); 43397d10d5a6Sdrh 43407d10d5a6Sdrh /* Look up every table named in the FROM clause of the select. If 43417d10d5a6Sdrh ** an entry of the FROM clause is a subquery instead of a table or view, 43427d10d5a6Sdrh ** then create a transient table structure to describe the subquery. 43437d10d5a6Sdrh */ 43447d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 43457d10d5a6Sdrh Table *pTab; 4346e2b7d7a0Sdrh assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 ); 43478a48b9c0Sdrh if( pFrom->fg.isRecursive ) continue; 4348e2b7d7a0Sdrh assert( pFrom->pTab==0 ); 43494e9119d9Sdan #ifndef SQLITE_OMIT_CTE 4350eede6a53Sdan if( withExpand(pWalker, pFrom) ) return WRC_Abort; 4351eede6a53Sdan if( pFrom->pTab ) {} else 43524e9119d9Sdan #endif 43537d10d5a6Sdrh if( pFrom->zName==0 ){ 43547d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 43557d10d5a6Sdrh Select *pSel = pFrom->pSelect; 43567d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 43577d10d5a6Sdrh assert( pSel!=0 ); 43587d10d5a6Sdrh assert( pFrom->pTab==0 ); 43592b8c5a00Sdrh if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort; 43607d10d5a6Sdrh pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); 43617d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 436279df7782Sdrh pTab->nTabRef = 1; 4363186ad8ccSdrh pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab); 43647d10d5a6Sdrh while( pSel->pPrior ){ pSel = pSel->pPrior; } 43658981b904Sdrh sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol); 43667d10d5a6Sdrh pTab->iPKey = -1; 4367cfc9df76Sdan pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) ); 43687d10d5a6Sdrh pTab->tabFlags |= TF_Ephemeral; 43697d10d5a6Sdrh #endif 43707d10d5a6Sdrh }else{ 43717d10d5a6Sdrh /* An ordinary table or view name in the FROM clause */ 43727d10d5a6Sdrh assert( pFrom->pTab==0 ); 437341fb5cd1Sdan pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom); 43747d10d5a6Sdrh if( pTab==0 ) return WRC_Abort; 437579df7782Sdrh if( pTab->nTabRef>=0xffff ){ 4376d2a56238Sdrh sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535", 4377d2a56238Sdrh pTab->zName); 4378d2a56238Sdrh pFrom->pTab = 0; 4379d2a56238Sdrh return WRC_Abort; 4380d2a56238Sdrh } 438179df7782Sdrh pTab->nTabRef++; 438220292310Sdrh if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){ 438320292310Sdrh return WRC_Abort; 438420292310Sdrh } 43857d10d5a6Sdrh #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) 438620292310Sdrh if( IsVirtual(pTab) || pTab->pSelect ){ 4387bfad7be7Sdrh i16 nCol; 43887d10d5a6Sdrh if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; 438943152cf8Sdrh assert( pFrom->pSelect==0 ); 43906ab3a2ecSdanielk1977 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); 4391eb9b884cSdrh sqlite3SelectSetName(pFrom->pSelect, pTab->zName); 4392bfad7be7Sdrh nCol = pTab->nCol; 4393bfad7be7Sdrh pTab->nCol = -1; 43947d10d5a6Sdrh sqlite3WalkSelect(pWalker, pFrom->pSelect); 4395bfad7be7Sdrh pTab->nCol = nCol; 43967d10d5a6Sdrh } 43977d10d5a6Sdrh #endif 43987d10d5a6Sdrh } 439985574e31Sdanielk1977 440085574e31Sdanielk1977 /* Locate the index named by the INDEXED BY clause, if any. */ 4401b1c685b0Sdanielk1977 if( sqlite3IndexedByLookup(pParse, pFrom) ){ 440285574e31Sdanielk1977 return WRC_Abort; 440385574e31Sdanielk1977 } 44047d10d5a6Sdrh } 44057d10d5a6Sdrh 44067d10d5a6Sdrh /* Process NATURAL keywords, and ON and USING clauses of joins. 44077d10d5a6Sdrh */ 44087d10d5a6Sdrh if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){ 44097d10d5a6Sdrh return WRC_Abort; 44107d10d5a6Sdrh } 44117d10d5a6Sdrh 44127d10d5a6Sdrh /* For every "*" that occurs in the column list, insert the names of 44137d10d5a6Sdrh ** all columns in all tables. And for every TABLE.* insert the names 44147d10d5a6Sdrh ** of all columns in TABLE. The parser inserted a special expression 44151a1d3cd2Sdrh ** with the TK_ASTERISK operator for each "*" that it found in the column 44161a1d3cd2Sdrh ** list. The following code just has to locate the TK_ASTERISK 44171a1d3cd2Sdrh ** expressions and expand each one to the list of all columns in 44181a1d3cd2Sdrh ** all tables. 44197d10d5a6Sdrh ** 44207d10d5a6Sdrh ** The first loop just checks to see if there are any "*" operators 44217d10d5a6Sdrh ** that need expanding. 44227d10d5a6Sdrh */ 44237d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 44243e3f1a5bSdrh pE = pEList->a[k].pExpr; 44251a1d3cd2Sdrh if( pE->op==TK_ASTERISK ) break; 442643152cf8Sdrh assert( pE->op!=TK_DOT || pE->pRight!=0 ); 442743152cf8Sdrh assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) ); 44281a1d3cd2Sdrh if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break; 44297d10d5a6Sdrh } 44307d10d5a6Sdrh if( k<pEList->nExpr ){ 44317d10d5a6Sdrh /* 44327d10d5a6Sdrh ** If we get here it means the result set contains one or more "*" 44337d10d5a6Sdrh ** operators that need to be expanded. Loop through each expression 44347d10d5a6Sdrh ** in the result set and expand them one by one. 44357d10d5a6Sdrh */ 44367d10d5a6Sdrh struct ExprList_item *a = pEList->a; 44377d10d5a6Sdrh ExprList *pNew = 0; 44387d10d5a6Sdrh int flags = pParse->db->flags; 44397d10d5a6Sdrh int longNames = (flags & SQLITE_FullColNames)!=0 444038b384a0Sdrh && (flags & SQLITE_ShortColNames)==0; 444138b384a0Sdrh 44427d10d5a6Sdrh for(k=0; k<pEList->nExpr; k++){ 44433e3f1a5bSdrh pE = a[k].pExpr; 44443e3f1a5bSdrh pRight = pE->pRight; 44453e3f1a5bSdrh assert( pE->op!=TK_DOT || pRight!=0 ); 44461a1d3cd2Sdrh if( pE->op!=TK_ASTERISK 44471a1d3cd2Sdrh && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK) 44481a1d3cd2Sdrh ){ 44497d10d5a6Sdrh /* This particular expression does not need to be expanded. 44507d10d5a6Sdrh */ 4451b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr); 44527d10d5a6Sdrh if( pNew ){ 44537d10d5a6Sdrh pNew->a[pNew->nExpr-1].zName = a[k].zName; 4454b7916a78Sdrh pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; 4455b7916a78Sdrh a[k].zName = 0; 4456b7916a78Sdrh a[k].zSpan = 0; 44577d10d5a6Sdrh } 44587d10d5a6Sdrh a[k].pExpr = 0; 44597d10d5a6Sdrh }else{ 44607d10d5a6Sdrh /* This expression is a "*" or a "TABLE.*" and needs to be 44617d10d5a6Sdrh ** expanded. */ 44627d10d5a6Sdrh int tableSeen = 0; /* Set to 1 when TABLE matches */ 44633e3f1a5bSdrh char *zTName = 0; /* text of name of TABLE */ 446443152cf8Sdrh if( pE->op==TK_DOT ){ 446543152cf8Sdrh assert( pE->pLeft!=0 ); 446633e619fcSdrh assert( !ExprHasProperty(pE->pLeft, EP_IntValue) ); 446733e619fcSdrh zTName = pE->pLeft->u.zToken; 44687d10d5a6Sdrh } 44697d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 44707d10d5a6Sdrh Table *pTab = pFrom->pTab; 44713e3f1a5bSdrh Select *pSub = pFrom->pSelect; 44727d10d5a6Sdrh char *zTabName = pFrom->zAlias; 44733e3f1a5bSdrh const char *zSchemaName = 0; 4474c75e09c7Sdrh int iDb; 447543152cf8Sdrh if( zTabName==0 ){ 44767d10d5a6Sdrh zTabName = pTab->zName; 44777d10d5a6Sdrh } 44787d10d5a6Sdrh if( db->mallocFailed ) break; 44793e3f1a5bSdrh if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){ 44803e3f1a5bSdrh pSub = 0; 44817d10d5a6Sdrh if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ 44827d10d5a6Sdrh continue; 44837d10d5a6Sdrh } 44843e3f1a5bSdrh iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 448569c33826Sdrh zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*"; 44863e3f1a5bSdrh } 44877d10d5a6Sdrh for(j=0; j<pTab->nCol; j++){ 44887d10d5a6Sdrh char *zName = pTab->aCol[j].zName; 4489b7916a78Sdrh char *zColname; /* The computed column name */ 4490b7916a78Sdrh char *zToFree; /* Malloced string that needs to be freed */ 4491b7916a78Sdrh Token sColname; /* Computed column name as a token */ 44927d10d5a6Sdrh 4493c75e09c7Sdrh assert( zName ); 44943e3f1a5bSdrh if( zTName && pSub 44953e3f1a5bSdrh && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0 44963e3f1a5bSdrh ){ 44973e3f1a5bSdrh continue; 44983e3f1a5bSdrh } 44993e3f1a5bSdrh 450080090f92Sdrh /* If a column is marked as 'hidden', omit it from the expanded 450180090f92Sdrh ** result-set list unless the SELECT has the SF_IncludeHidden 450280090f92Sdrh ** bit set. 45037d10d5a6Sdrh */ 450480090f92Sdrh if( (p->selFlags & SF_IncludeHidden)==0 450580090f92Sdrh && IsHiddenColumn(&pTab->aCol[j]) 450680090f92Sdrh ){ 45077d10d5a6Sdrh continue; 45087d10d5a6Sdrh } 45093e3f1a5bSdrh tableSeen = 1; 45107d10d5a6Sdrh 4511da55c48aSdrh if( i>0 && zTName==0 ){ 45128a48b9c0Sdrh if( (pFrom->fg.jointype & JT_NATURAL)!=0 45132179b434Sdrh && tableAndColumnIndex(pTabList, i, zName, 0, 0) 45142179b434Sdrh ){ 45157d10d5a6Sdrh /* In a NATURAL join, omit the join columns from the 45162179b434Sdrh ** table to the right of the join */ 45177d10d5a6Sdrh continue; 45187d10d5a6Sdrh } 45192179b434Sdrh if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){ 45207d10d5a6Sdrh /* In a join with a USING clause, omit columns in the 45217d10d5a6Sdrh ** using clause from the table on the right. */ 45227d10d5a6Sdrh continue; 45237d10d5a6Sdrh } 45247d10d5a6Sdrh } 4525b7916a78Sdrh pRight = sqlite3Expr(db, TK_ID, zName); 4526b7916a78Sdrh zColname = zName; 4527b7916a78Sdrh zToFree = 0; 45287d10d5a6Sdrh if( longNames || pTabList->nSrc>1 ){ 4529b7916a78Sdrh Expr *pLeft; 4530b7916a78Sdrh pLeft = sqlite3Expr(db, TK_ID, zTabName); 4531abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight); 453238b384a0Sdrh if( zSchemaName ){ 4533c75e09c7Sdrh pLeft = sqlite3Expr(db, TK_ID, zSchemaName); 4534abfd35eaSdrh pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr); 4535c75e09c7Sdrh } 4536b7916a78Sdrh if( longNames ){ 4537b7916a78Sdrh zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName); 4538b7916a78Sdrh zToFree = zColname; 4539b7916a78Sdrh } 45407d10d5a6Sdrh }else{ 45417d10d5a6Sdrh pExpr = pRight; 45427d10d5a6Sdrh } 4543b7916a78Sdrh pNew = sqlite3ExprListAppend(pParse, pNew, pExpr); 454440aced5cSdrh sqlite3TokenInit(&sColname, zColname); 4545b7916a78Sdrh sqlite3ExprListSetName(pParse, pNew, &sColname, 0); 45468f25d18bSdrh if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){ 45473e3f1a5bSdrh struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; 45483e3f1a5bSdrh if( pSub ){ 45493e3f1a5bSdrh pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); 4550c75e09c7Sdrh testcase( pX->zSpan==0 ); 45513e3f1a5bSdrh }else{ 45523e3f1a5bSdrh pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", 45533e3f1a5bSdrh zSchemaName, zTabName, zColname); 4554c75e09c7Sdrh testcase( pX->zSpan==0 ); 45553e3f1a5bSdrh } 45563e3f1a5bSdrh pX->bSpanIsTab = 1; 45578f25d18bSdrh } 4558b7916a78Sdrh sqlite3DbFree(db, zToFree); 45597d10d5a6Sdrh } 45607d10d5a6Sdrh } 45617d10d5a6Sdrh if( !tableSeen ){ 45627d10d5a6Sdrh if( zTName ){ 45637d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no such table: %s", zTName); 45647d10d5a6Sdrh }else{ 45657d10d5a6Sdrh sqlite3ErrorMsg(pParse, "no tables specified"); 45667d10d5a6Sdrh } 45677d10d5a6Sdrh } 45687d10d5a6Sdrh } 45697d10d5a6Sdrh } 45707d10d5a6Sdrh sqlite3ExprListDelete(db, pEList); 45717d10d5a6Sdrh p->pEList = pNew; 45727d10d5a6Sdrh } 45737d10d5a6Sdrh #if SQLITE_MAX_COLUMN 45747d10d5a6Sdrh if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 45757d10d5a6Sdrh sqlite3ErrorMsg(pParse, "too many columns in result set"); 45768836cbbcSdan return WRC_Abort; 45777d10d5a6Sdrh } 45787d10d5a6Sdrh #endif 45797d10d5a6Sdrh return WRC_Continue; 45807d10d5a6Sdrh } 45817d10d5a6Sdrh 45827d10d5a6Sdrh /* 45837d10d5a6Sdrh ** No-op routine for the parse-tree walker. 45847d10d5a6Sdrh ** 45857d10d5a6Sdrh ** When this routine is the Walker.xExprCallback then expression trees 45867d10d5a6Sdrh ** are walked without any actions being taken at each node. Presumably, 45877d10d5a6Sdrh ** when this routine is used for Walker.xExprCallback then 45887d10d5a6Sdrh ** Walker.xSelectCallback is set to do something useful for every 45897d10d5a6Sdrh ** subquery in the parser tree. 45907d10d5a6Sdrh */ 45915b88bc4bSdrh int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){ 459262c14b34Sdanielk1977 UNUSED_PARAMETER2(NotUsed, NotUsed2); 45937d10d5a6Sdrh return WRC_Continue; 45947d10d5a6Sdrh } 45957d10d5a6Sdrh 45967d10d5a6Sdrh /* 45977d10d5a6Sdrh ** This routine "expands" a SELECT statement and all of its subqueries. 45987d10d5a6Sdrh ** For additional information on what it means to "expand" a SELECT 45997d10d5a6Sdrh ** statement, see the comment on the selectExpand worker callback above. 46007d10d5a6Sdrh ** 46017d10d5a6Sdrh ** Expanding a SELECT statement is the first step in processing a 46027d10d5a6Sdrh ** SELECT statement. The SELECT statement must be expanded before 46037d10d5a6Sdrh ** name resolution is performed. 46047d10d5a6Sdrh ** 46057d10d5a6Sdrh ** If anything goes wrong, an error message is written into pParse. 46067d10d5a6Sdrh ** The calling function can detect the problem by looking at pParse->nErr 46077d10d5a6Sdrh ** and/or pParse->db->mallocFailed. 46087d10d5a6Sdrh */ 46097d10d5a6Sdrh static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){ 46107d10d5a6Sdrh Walker w; 4611aa87f9a6Sdrh memset(&w, 0, sizeof(w)); 46125b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 46137d10d5a6Sdrh w.pParse = pParse; 4614d58d3278Sdrh if( pParse->hasCompound ){ 4615d58d3278Sdrh w.xSelectCallback = convertCompoundSelectToSubquery; 46167d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 4617d58d3278Sdrh } 4618c01b7306Sdrh w.xSelectCallback = selectExpander; 4619b290f117Sdan w.xSelectCallback2 = selectPopWith; 4620c01b7306Sdrh sqlite3WalkSelect(&w, pSelect); 46217d10d5a6Sdrh } 46227d10d5a6Sdrh 46237d10d5a6Sdrh 46247d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 46257d10d5a6Sdrh /* 46267d10d5a6Sdrh ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo() 46277d10d5a6Sdrh ** interface. 46287d10d5a6Sdrh ** 46297d10d5a6Sdrh ** For each FROM-clause subquery, add Column.zType and Column.zColl 46307d10d5a6Sdrh ** information to the Table structure that represents the result set 46317d10d5a6Sdrh ** of that subquery. 46327d10d5a6Sdrh ** 46337d10d5a6Sdrh ** The Table structure that represents the result set was constructed 46347d10d5a6Sdrh ** by selectExpander() but the type and collation information was omitted 46357d10d5a6Sdrh ** at that point because identifiers had not yet been resolved. This 46367d10d5a6Sdrh ** routine is called after identifier resolution. 46377d10d5a6Sdrh */ 4638b290f117Sdan static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){ 46397d10d5a6Sdrh Parse *pParse; 46407d10d5a6Sdrh int i; 46417d10d5a6Sdrh SrcList *pTabList; 46427d10d5a6Sdrh struct SrcList_item *pFrom; 46437d10d5a6Sdrh 46449d8b3072Sdrh assert( p->selFlags & SF_Resolved ); 4645e2b7d7a0Sdrh assert( (p->selFlags & SF_HasTypeInfo)==0 ); 46467d10d5a6Sdrh p->selFlags |= SF_HasTypeInfo; 46477d10d5a6Sdrh pParse = pWalker->pParse; 46487d10d5a6Sdrh pTabList = p->pSrc; 46497d10d5a6Sdrh for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){ 46507d10d5a6Sdrh Table *pTab = pFrom->pTab; 4651e2b7d7a0Sdrh assert( pTab!=0 ); 4652e2b7d7a0Sdrh if( (pTab->tabFlags & TF_Ephemeral)!=0 ){ 46537d10d5a6Sdrh /* A sub-query in the FROM clause of a SELECT */ 46547d10d5a6Sdrh Select *pSel = pFrom->pSelect; 46558ce7184bSdan if( pSel ){ 46567d10d5a6Sdrh while( pSel->pPrior ) pSel = pSel->pPrior; 4657ed06a131Sdrh sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel); 46587d10d5a6Sdrh } 46597d10d5a6Sdrh } 46605a29d9cbSdrh } 46618ce7184bSdan } 46627d10d5a6Sdrh #endif 46637d10d5a6Sdrh 46647d10d5a6Sdrh 46657d10d5a6Sdrh /* 46667d10d5a6Sdrh ** This routine adds datatype and collating sequence information to 46677d10d5a6Sdrh ** the Table structures of all FROM-clause subqueries in a 46687d10d5a6Sdrh ** SELECT statement. 46697d10d5a6Sdrh ** 46707d10d5a6Sdrh ** Use this routine after name resolution. 46717d10d5a6Sdrh */ 46727d10d5a6Sdrh static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){ 46737d10d5a6Sdrh #ifndef SQLITE_OMIT_SUBQUERY 46747d10d5a6Sdrh Walker w; 4675aa87f9a6Sdrh memset(&w, 0, sizeof(w)); 4676b290f117Sdan w.xSelectCallback2 = selectAddSubqueryTypeInfo; 46775b88bc4bSdrh w.xExprCallback = sqlite3ExprWalkNoop; 46787d10d5a6Sdrh w.pParse = pParse; 46797d10d5a6Sdrh sqlite3WalkSelect(&w, pSelect); 46807d10d5a6Sdrh #endif 46817d10d5a6Sdrh } 46827d10d5a6Sdrh 46837d10d5a6Sdrh 46847d10d5a6Sdrh /* 4685030796dfSdrh ** This routine sets up a SELECT statement for processing. The 46867d10d5a6Sdrh ** following is accomplished: 46877d10d5a6Sdrh ** 46887d10d5a6Sdrh ** * VDBE Cursor numbers are assigned to all FROM-clause terms. 46897d10d5a6Sdrh ** * Ephemeral Table objects are created for all FROM-clause subqueries. 46907d10d5a6Sdrh ** * ON and USING clauses are shifted into WHERE statements 46917d10d5a6Sdrh ** * Wildcards "*" and "TABLE.*" in result sets are expanded. 46927d10d5a6Sdrh ** * Identifiers in expression are matched to tables. 46937d10d5a6Sdrh ** 46947d10d5a6Sdrh ** This routine acts recursively on all subqueries within the SELECT. 46957d10d5a6Sdrh */ 46967d10d5a6Sdrh void sqlite3SelectPrep( 4697b3bce662Sdanielk1977 Parse *pParse, /* The parser context */ 4698b3bce662Sdanielk1977 Select *p, /* The SELECT statement being coded. */ 46997d10d5a6Sdrh NameContext *pOuterNC /* Name context for container */ 4700b3bce662Sdanielk1977 ){ 47017d10d5a6Sdrh sqlite3 *db; 470243152cf8Sdrh if( NEVER(p==0) ) return; 47037d10d5a6Sdrh db = pParse->db; 4704785097daSdrh if( db->mallocFailed ) return; 47057d10d5a6Sdrh if( p->selFlags & SF_HasTypeInfo ) return; 47067d10d5a6Sdrh sqlite3SelectExpand(pParse, p); 47077d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 47087d10d5a6Sdrh sqlite3ResolveSelectNames(pParse, p, pOuterNC); 47097d10d5a6Sdrh if( pParse->nErr || db->mallocFailed ) return; 47107d10d5a6Sdrh sqlite3SelectAddTypeInfo(pParse, p); 4711f6bbe022Sdrh } 4712b3bce662Sdanielk1977 4713b3bce662Sdanielk1977 /* 471413449892Sdrh ** Reset the aggregate accumulator. 471513449892Sdrh ** 471613449892Sdrh ** The aggregate accumulator is a set of memory cells that hold 471713449892Sdrh ** intermediate results while calculating an aggregate. This 4718030796dfSdrh ** routine generates code that stores NULLs in all of those memory 4719030796dfSdrh ** cells. 4720b3bce662Sdanielk1977 */ 472113449892Sdrh static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ 472213449892Sdrh Vdbe *v = pParse->pVdbe; 472313449892Sdrh int i; 4724c99130fdSdrh struct AggInfo_func *pFunc; 47257e61d18eSdrh int nReg = pAggInfo->nFunc + pAggInfo->nColumn; 47267e61d18eSdrh if( nReg==0 ) return; 47277e61d18eSdrh #ifdef SQLITE_DEBUG 47287e61d18eSdrh /* Verify that all AggInfo registers are within the range specified by 47297e61d18eSdrh ** AggInfo.mnReg..AggInfo.mxReg */ 47307e61d18eSdrh assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 ); 473113449892Sdrh for(i=0; i<pAggInfo->nColumn; i++){ 47327e61d18eSdrh assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg 47337e61d18eSdrh && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg ); 473413449892Sdrh } 47357e61d18eSdrh for(i=0; i<pAggInfo->nFunc; i++){ 47367e61d18eSdrh assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg 47377e61d18eSdrh && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg ); 47387e61d18eSdrh } 47397e61d18eSdrh #endif 47407e61d18eSdrh sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg); 4741c99130fdSdrh for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ 4742c99130fdSdrh if( pFunc->iDistinct>=0 ){ 4743c99130fdSdrh Expr *pE = pFunc->pExpr; 47446ab3a2ecSdanielk1977 assert( !ExprHasProperty(pE, EP_xIsSelect) ); 47456ab3a2ecSdanielk1977 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){ 47460daa002cSdrh sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one " 47470daa002cSdrh "argument"); 4748c99130fdSdrh pFunc->iDistinct = -1; 4749c99130fdSdrh }else{ 4750079a3072Sdrh KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0); 475166a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, 47522ec2fb22Sdrh (char*)pKeyInfo, P4_KEYINFO); 4753c99130fdSdrh } 4754c99130fdSdrh } 475513449892Sdrh } 4756b3bce662Sdanielk1977 } 4757b3bce662Sdanielk1977 4758b3bce662Sdanielk1977 /* 475913449892Sdrh ** Invoke the OP_AggFinalize opcode for every aggregate function 476013449892Sdrh ** in the AggInfo structure. 4761b3bce662Sdanielk1977 */ 476213449892Sdrh static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ 476313449892Sdrh Vdbe *v = pParse->pVdbe; 476413449892Sdrh int i; 476513449892Sdrh struct AggInfo_func *pF; 476613449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 47676ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 47686ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 47692700acaaSdrh sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0); 47702700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 4771b3bce662Sdanielk1977 } 477213449892Sdrh } 477313449892Sdrh 477413449892Sdrh /* 477513449892Sdrh ** Update the accumulator memory cells for an aggregate based on 477613449892Sdrh ** the current cursor position. 477713449892Sdrh */ 477813449892Sdrh static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ 477913449892Sdrh Vdbe *v = pParse->pVdbe; 478013449892Sdrh int i; 47817a95789cSdrh int regHit = 0; 47827a95789cSdrh int addrHitTest = 0; 478313449892Sdrh struct AggInfo_func *pF; 478413449892Sdrh struct AggInfo_col *pC; 478513449892Sdrh 478613449892Sdrh pAggInfo->directMode = 1; 478713449892Sdrh for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ 478813449892Sdrh int nArg; 4789c99130fdSdrh int addrNext = 0; 479098757157Sdrh int regAgg; 47916ab3a2ecSdanielk1977 ExprList *pList = pF->pExpr->x.pList; 47926ab3a2ecSdanielk1977 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); 479313449892Sdrh if( pList ){ 479413449892Sdrh nArg = pList->nExpr; 4795892d3179Sdrh regAgg = sqlite3GetTempRange(pParse, nArg); 47965579d59fSdrh sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP); 479713449892Sdrh }else{ 479813449892Sdrh nArg = 0; 479998757157Sdrh regAgg = 0; 480013449892Sdrh } 4801c99130fdSdrh if( pF->iDistinct>=0 ){ 4802c99130fdSdrh addrNext = sqlite3VdbeMakeLabel(v); 48037c052da5Sdrh testcase( nArg==0 ); /* Error condition */ 48047c052da5Sdrh testcase( nArg>1 ); /* Also an error */ 48052dcef11bSdrh codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); 4806c99130fdSdrh } 4807d36e1041Sdrh if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 480813449892Sdrh CollSeq *pColl = 0; 480913449892Sdrh struct ExprList_item *pItem; 481013449892Sdrh int j; 4811e82f5d04Sdrh assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */ 481243617e9aSdrh for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){ 481313449892Sdrh pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); 481413449892Sdrh } 481513449892Sdrh if( !pColl ){ 481613449892Sdrh pColl = pParse->db->pDfltColl; 481713449892Sdrh } 48187a95789cSdrh if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem; 48197a95789cSdrh sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ); 482013449892Sdrh } 48212700acaaSdrh sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem); 48222700acaaSdrh sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); 4823ea678832Sdrh sqlite3VdbeChangeP5(v, (u8)nArg); 4824da250ea5Sdrh sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); 4825f49f3523Sdrh sqlite3ReleaseTempRange(pParse, regAgg, nArg); 4826c99130fdSdrh if( addrNext ){ 4827c99130fdSdrh sqlite3VdbeResolveLabel(v, addrNext); 4828ceea3321Sdrh sqlite3ExprCacheClear(pParse); 4829c99130fdSdrh } 483013449892Sdrh } 483167a6a40cSdan 483267a6a40cSdan /* Before populating the accumulator registers, clear the column cache. 483367a6a40cSdan ** Otherwise, if any of the required column values are already present 483467a6a40cSdan ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value 483567a6a40cSdan ** to pC->iMem. But by the time the value is used, the original register 483667a6a40cSdan ** may have been used, invalidating the underlying buffer holding the 483767a6a40cSdan ** text or blob value. See ticket [883034dcb5]. 483867a6a40cSdan ** 483967a6a40cSdan ** Another solution would be to change the OP_SCopy used to copy cached 484067a6a40cSdan ** values to an OP_Copy. 484167a6a40cSdan */ 48427a95789cSdrh if( regHit ){ 4843688852abSdrh addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); 48447a95789cSdrh } 484567a6a40cSdan sqlite3ExprCacheClear(pParse); 484613449892Sdrh for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ 4847389a1adbSdrh sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); 484813449892Sdrh } 484913449892Sdrh pAggInfo->directMode = 0; 4850ceea3321Sdrh sqlite3ExprCacheClear(pParse); 48517a95789cSdrh if( addrHitTest ){ 48527a95789cSdrh sqlite3VdbeJumpHere(v, addrHitTest); 48537a95789cSdrh } 485413449892Sdrh } 485513449892Sdrh 4856b3bce662Sdanielk1977 /* 4857ef7075deSdan ** Add a single OP_Explain instruction to the VDBE to explain a simple 4858ef7075deSdan ** count(*) query ("SELECT count(*) FROM pTab"). 4859ef7075deSdan */ 4860ef7075deSdan #ifndef SQLITE_OMIT_EXPLAIN 4861ef7075deSdan static void explainSimpleCount( 4862ef7075deSdan Parse *pParse, /* Parse context */ 4863ef7075deSdan Table *pTab, /* Table being queried */ 4864ef7075deSdan Index *pIdx /* Index used to optimize scan, or NULL */ 4865ef7075deSdan ){ 4866ef7075deSdan if( pParse->explain==2 ){ 486748dd1d8eSdrh int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx))); 48688a4380d7Sdrh char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", 4869ef7075deSdan pTab->zName, 4870e96f2df3Sdan bCover ? " USING COVERING INDEX " : "", 4871e96f2df3Sdan bCover ? pIdx->zName : "" 4872ef7075deSdan ); 4873ef7075deSdan sqlite3VdbeAddOp4( 4874ef7075deSdan pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC 4875ef7075deSdan ); 4876ef7075deSdan } 4877ef7075deSdan } 4878ef7075deSdan #else 4879ef7075deSdan # define explainSimpleCount(a,b,c) 4880ef7075deSdan #endif 4881ef7075deSdan 4882ef7075deSdan /* 48837d10d5a6Sdrh ** Generate code for the SELECT statement given in the p argument. 48849bb61fe7Sdrh ** 4885340309fdSdrh ** The results are returned according to the SelectDest structure. 4886340309fdSdrh ** See comments in sqliteInt.h for further information. 4887e78e8284Sdrh ** 48889bb61fe7Sdrh ** This routine returns the number of errors. If any errors are 48899bb61fe7Sdrh ** encountered, then an appropriate error message is left in 48909bb61fe7Sdrh ** pParse->zErrMsg. 48919bb61fe7Sdrh ** 48929bb61fe7Sdrh ** This routine does NOT free the Select structure passed in. The 48939bb61fe7Sdrh ** calling function needs to do that. 48949bb61fe7Sdrh */ 48954adee20fSdanielk1977 int sqlite3Select( 4896cce7d176Sdrh Parse *pParse, /* The parser context */ 48979bb61fe7Sdrh Select *p, /* The SELECT statement being coded. */ 48987d10d5a6Sdrh SelectDest *pDest /* What to do with the query results */ 4899cce7d176Sdrh ){ 490013449892Sdrh int i, j; /* Loop counters */ 490113449892Sdrh WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ 490213449892Sdrh Vdbe *v; /* The virtual machine under construction */ 4903b3bce662Sdanielk1977 int isAgg; /* True for select lists like "count(*)" */ 4904c29cbb0bSmistachkin ExprList *pEList = 0; /* List of columns to extract. */ 4905ad3cab52Sdrh SrcList *pTabList; /* List of tables to select from */ 49069bb61fe7Sdrh Expr *pWhere; /* The WHERE clause. May be NULL */ 49072282792aSdrh ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */ 49082282792aSdrh Expr *pHaving; /* The HAVING clause. May be NULL */ 49091d83f052Sdrh int rc = 1; /* Value to return from this function */ 4910e8e4af76Sdrh DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */ 4911079a3072Sdrh SortCtx sSort; /* Info on how to code the ORDER BY clause */ 491213449892Sdrh AggInfo sAggInfo; /* Information used by aggregate queries */ 4913ec7429aeSdrh int iEnd; /* Address of the end of the query */ 491417435752Sdrh sqlite3 *db; /* The database connection */ 49159bb61fe7Sdrh 49162ce22453Sdan #ifndef SQLITE_OMIT_EXPLAIN 49172ce22453Sdan int iRestoreSelectId = pParse->iSelectId; 49182ce22453Sdan pParse->iSelectId = pParse->iNextSelectId++; 49192ce22453Sdan #endif 49202ce22453Sdan 492117435752Sdrh db = pParse->db; 492217435752Sdrh if( p==0 || db->mallocFailed || pParse->nErr ){ 49236f7adc8aSdrh return 1; 49246f7adc8aSdrh } 49254adee20fSdanielk1977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; 492613449892Sdrh memset(&sAggInfo, 0, sizeof(sAggInfo)); 4927eb9b884cSdrh #if SELECTTRACE_ENABLED 4928eb9b884cSdrh pParse->nSelectIndent++; 4929c90713d3Sdrh SELECTTRACE(1,pParse,p, ("begin processing:\n")); 4930c90713d3Sdrh if( sqlite3SelectTrace & 0x100 ){ 4931c90713d3Sdrh sqlite3TreeViewSelect(0, p, 0); 4932c90713d3Sdrh } 4933eb9b884cSdrh #endif 4934daffd0e5Sdrh 49358e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo ); 49368e1ee88cSdrh assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo ); 49379afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue ); 49389afccba2Sdan assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue ); 49396c8c8ce0Sdanielk1977 if( IgnorableOrderby(pDest) ){ 49409ed1dfa8Sdanielk1977 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 49419afccba2Sdan pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard || 49428e1ee88cSdrh pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo || 49438e1ee88cSdrh pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo); 4944ccfcbceaSdrh /* If ORDER BY makes no difference in the output then neither does 4945ccfcbceaSdrh ** DISTINCT so it can be removed too. */ 4946ccfcbceaSdrh sqlite3ExprListDelete(db, p->pOrderBy); 4947ccfcbceaSdrh p->pOrderBy = 0; 49487d10d5a6Sdrh p->selFlags &= ~SF_Distinct; 49499a99334dSdrh } 49507d10d5a6Sdrh sqlite3SelectPrep(pParse, p, 0); 4951079a3072Sdrh memset(&sSort, 0, sizeof(sSort)); 4952079a3072Sdrh sSort.pOrderBy = p->pOrderBy; 4953b27b7f5dSdrh pTabList = p->pSrc; 4954956f4319Sdanielk1977 if( pParse->nErr || db->mallocFailed ){ 49559a99334dSdrh goto select_end; 49569a99334dSdrh } 4957adc57f68Sdrh assert( p->pEList!=0 ); 49587d10d5a6Sdrh isAgg = (p->selFlags & SF_Aggregate)!=0; 495917645f5eSdrh #if SELECTTRACE_ENABLED 496017645f5eSdrh if( sqlite3SelectTrace & 0x100 ){ 496117645f5eSdrh SELECTTRACE(0x100,pParse,p, ("after name resolution:\n")); 496217645f5eSdrh sqlite3TreeViewSelect(0, p, 0); 496317645f5eSdrh } 496417645f5eSdrh #endif 4965cce7d176Sdrh 4966adc57f68Sdrh /* Try to flatten subqueries in the FROM clause up into the main query 4967d820cb1bSdrh */ 496851522cd3Sdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 4969f23329a2Sdanielk1977 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){ 497013449892Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 4971daf79acbSdanielk1977 Select *pSub = pItem->pSelect; 4972f23329a2Sdanielk1977 int isAggSub; 49732679f14fSdrh Table *pTab = pItem->pTab; 49744490c40bSdrh if( pSub==0 ) continue; 49752679f14fSdrh 49762679f14fSdrh /* Catch mismatch in the declared columns of a view and the number of 49772679f14fSdrh ** columns in the SELECT on the RHS */ 49782679f14fSdrh if( pTab->nCol!=pSub->pEList->nExpr ){ 49792679f14fSdrh sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d", 49802679f14fSdrh pTab->nCol, pTab->zName, pSub->pEList->nExpr); 49812679f14fSdrh goto select_end; 49822679f14fSdrh } 49832679f14fSdrh 49844490c40bSdrh isAggSub = (pSub->selFlags & SF_Aggregate)!=0; 49854490c40bSdrh if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ 49864490c40bSdrh /* This subquery can be absorbed into its parent. */ 49874490c40bSdrh if( isAggSub ){ 49884490c40bSdrh isAgg = 1; 49894490c40bSdrh p->selFlags |= SF_Aggregate; 49904490c40bSdrh } 49914490c40bSdrh i = -1; 49924490c40bSdrh } 49934490c40bSdrh pTabList = p->pSrc; 49944490c40bSdrh if( db->mallocFailed ) goto select_end; 49954490c40bSdrh if( !IgnorableOrderby(pDest) ){ 49964490c40bSdrh sSort.pOrderBy = p->pOrderBy; 49974490c40bSdrh } 49984490c40bSdrh } 49994490c40bSdrh #endif 50004490c40bSdrh 5001adc57f68Sdrh /* Get a pointer the VDBE under construction, allocating a new VDBE if one 5002adc57f68Sdrh ** does not already exist */ 5003adc57f68Sdrh v = sqlite3GetVdbe(pParse); 5004adc57f68Sdrh if( v==0 ) goto select_end; 50054490c40bSdrh 50064490c40bSdrh #ifndef SQLITE_OMIT_COMPOUND_SELECT 50074490c40bSdrh /* Handle compound SELECT statements using the separate multiSelect() 50084490c40bSdrh ** procedure. 50094490c40bSdrh */ 50104490c40bSdrh if( p->pPrior ){ 50114490c40bSdrh rc = multiSelect(pParse, p, pDest); 50124490c40bSdrh explainSetInteger(pParse->iSelectId, iRestoreSelectId); 50134490c40bSdrh #if SELECTTRACE_ENABLED 50144490c40bSdrh SELECTTRACE(1,pParse,p,("end compound-select processing\n")); 50154490c40bSdrh pParse->nSelectIndent--; 50164490c40bSdrh #endif 50174490c40bSdrh return rc; 50184490c40bSdrh } 50194490c40bSdrh #endif 50204490c40bSdrh 50216e17529eSdrh /* Generate code for all sub-queries in the FROM clause 50226e17529eSdrh */ 50236e17529eSdrh #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) 50244490c40bSdrh for(i=0; i<pTabList->nSrc; i++){ 5025ad3cab52Sdrh struct SrcList_item *pItem = &pTabList->a[i]; 50265cf590c1Sdrh SelectDest dest; 5027c31c2eb8Sdrh Select *pSub = pItem->pSelect; 50285b6a9ed4Sdrh if( pSub==0 ) continue; 502921172c4cSdrh 503021172c4cSdrh /* Sometimes the code for a subquery will be generated more than 503121172c4cSdrh ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, 503221172c4cSdrh ** for example. In that case, do not regenerate the code to manifest 503321172c4cSdrh ** a view or the co-routine to implement a view. The first instance 503421172c4cSdrh ** is sufficient, though the subroutine to manifest the view does need 503521172c4cSdrh ** to be invoked again. */ 50365b6a9ed4Sdrh if( pItem->addrFillSub ){ 50378a48b9c0Sdrh if( pItem->fg.viaCoroutine==0 ){ 5038*7555581fSdrh /* The subroutine that manifests the view might be a one-time routine, 5039*7555581fSdrh ** or it might need to be rerun on each iteration because it 5040*7555581fSdrh ** encodes a correlated subquery. */ 5041*7555581fSdrh testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once ); 50425b6a9ed4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); 504321172c4cSdrh } 50445b6a9ed4Sdrh continue; 50455b6a9ed4Sdrh } 5046daf79acbSdanielk1977 5047fc976065Sdanielk1977 /* Increment Parse.nHeight by the height of the largest expression 5048f7b5496eSdrh ** tree referred to by this, the parent select. The child select 5049fc976065Sdanielk1977 ** may contain expression trees of at most 5050fc976065Sdanielk1977 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit 5051fc976065Sdanielk1977 ** more conservative than necessary, but much easier than enforcing 5052fc976065Sdanielk1977 ** an exact limit. 5053fc976065Sdanielk1977 */ 5054fc976065Sdanielk1977 pParse->nHeight += sqlite3SelectExprHeight(p); 5055daf79acbSdanielk1977 5056adc57f68Sdrh /* Make copies of constant WHERE-clause terms in the outer query down 5057adc57f68Sdrh ** inside the subquery. This can help the subquery to run more efficiently. 5058adc57f68Sdrh */ 50598a48b9c0Sdrh if( (pItem->fg.jointype & JT_OUTER)==0 506044c5604cSdan && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor) 506169b72d5aSdrh ){ 506269b72d5aSdrh #if SELECTTRACE_ENABLED 506369b72d5aSdrh if( sqlite3SelectTrace & 0x100 ){ 5064bc8edba1Sdrh SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n")); 506569b72d5aSdrh sqlite3TreeViewSelect(0, p, 0); 5066daf79acbSdanielk1977 } 506769b72d5aSdrh #endif 506869b72d5aSdrh } 5069adc57f68Sdrh 5070adc57f68Sdrh /* Generate code to implement the subquery 50710ff47e9eSdrh ** 50720ff47e9eSdrh ** The subquery is implemented as a co-routine if all of these are true: 50730ff47e9eSdrh ** (1) The subquery is guaranteed to be the outer loop (so that it 50740ff47e9eSdrh ** does not need to be computed more than once) 50750ff47e9eSdrh ** (2) The ALL keyword after SELECT is omitted. (Applications are 50760ff47e9eSdrh ** allowed to say "SELECT ALL" instead of just "SELECT" to disable 50770ff47e9eSdrh ** the use of co-routines.) 50780ff47e9eSdrh ** (3) Co-routines are not disabled using sqlite3_test_control() 50790ff47e9eSdrh ** with SQLITE_TESTCTRL_OPTIMIZATIONS. 50800ff47e9eSdrh ** 50810ff47e9eSdrh ** TODO: Are there other reasons beside (1) to use a co-routine 50820ff47e9eSdrh ** implementation? 5083adc57f68Sdrh */ 50840ff47e9eSdrh if( i==0 50850ff47e9eSdrh && (pTabList->nSrc==1 50860ff47e9eSdrh || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */ 50870ff47e9eSdrh && (p->selFlags & SF_All)==0 /* (2) */ 50880ff47e9eSdrh && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */ 5089a5759677Sdrh ){ 509021172c4cSdrh /* Implement a co-routine that will return a single row of the result 509121172c4cSdrh ** set on each invocation. 509221172c4cSdrh */ 5093725de29aSdrh int addrTop = sqlite3VdbeCurrentAddr(v)+1; 509421172c4cSdrh pItem->regReturn = ++pParse->nMem; 5095725de29aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop); 5096725de29aSdrh VdbeComment((v, "%s", pItem->pTab->zName)); 509721172c4cSdrh pItem->addrFillSub = addrTop; 509821172c4cSdrh sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn); 509921172c4cSdrh explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 510021172c4cSdrh sqlite3Select(pParse, pSub, &dest); 5101c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 51028a48b9c0Sdrh pItem->fg.viaCoroutine = 1; 51035f612295Sdrh pItem->regResult = dest.iSdst; 51042fade2f7Sdrh sqlite3VdbeEndCoroutine(v, pItem->regReturn); 510521172c4cSdrh sqlite3VdbeJumpHere(v, addrTop-1); 510621172c4cSdrh sqlite3ClearTempRegCache(pParse); 5107daf79acbSdanielk1977 }else{ 51085b6a9ed4Sdrh /* Generate a subroutine that will fill an ephemeral table with 51095b6a9ed4Sdrh ** the content of this subquery. pItem->addrFillSub will point 51105b6a9ed4Sdrh ** to the address of the generated subroutine. pItem->regReturn 51115b6a9ed4Sdrh ** is a register allocated to hold the subroutine return address 51125b6a9ed4Sdrh */ 51137157e8eaSdrh int topAddr; 511448f2d3b1Sdrh int onceAddr = 0; 51157157e8eaSdrh int retAddr; 51165b6a9ed4Sdrh assert( pItem->addrFillSub==0 ); 51175b6a9ed4Sdrh pItem->regReturn = ++pParse->nMem; 51187157e8eaSdrh topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn); 51197157e8eaSdrh pItem->addrFillSub = topAddr+1; 51208a48b9c0Sdrh if( pItem->fg.isCorrelated==0 ){ 5121ed17167eSdrh /* If the subquery is not correlated and if we are not inside of 51225b6a9ed4Sdrh ** a trigger, then we only need to compute the value of the subquery 51235b6a9ed4Sdrh ** once. */ 5124511f9e8dSdrh onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 5125725de29aSdrh VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName)); 5126725de29aSdrh }else{ 5127725de29aSdrh VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName)); 51285b6a9ed4Sdrh } 51291013c932Sdrh sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); 5130ce7e189dSdan explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); 51317d10d5a6Sdrh sqlite3Select(pParse, pSub, &dest); 5132c3489bbfSdrh pItem->pTab->nRowLogEst = pSub->nSelectRow; 513348f2d3b1Sdrh if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr); 51347157e8eaSdrh retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn); 51357157e8eaSdrh VdbeComment((v, "end %s", pItem->pTab->zName)); 51367157e8eaSdrh sqlite3VdbeChangeP1(v, topAddr, retAddr); 5137cdc69557Sdrh sqlite3ClearTempRegCache(pParse); 5138daf79acbSdanielk1977 } 5139adc57f68Sdrh if( db->mallocFailed ) goto select_end; 5140fc976065Sdanielk1977 pParse->nHeight -= sqlite3SelectExprHeight(p); 5141acd4c695Sdrh } 5142daf79acbSdanielk1977 #endif 5143adc57f68Sdrh 514438b4149cSdrh /* Various elements of the SELECT copied into local variables for 514538b4149cSdrh ** convenience */ 5146adc57f68Sdrh pEList = p->pEList; 5147daf79acbSdanielk1977 pWhere = p->pWhere; 5148832508b7Sdrh pGroupBy = p->pGroupBy; 5149832508b7Sdrh pHaving = p->pHaving; 5150e8e4af76Sdrh sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0; 5151832508b7Sdrh 5152bc8edba1Sdrh #if SELECTTRACE_ENABLED 5153bc8edba1Sdrh if( sqlite3SelectTrace & 0x400 ){ 5154bc8edba1Sdrh SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); 5155bc8edba1Sdrh sqlite3TreeViewSelect(0, p, 0); 5156f23329a2Sdanielk1977 } 5157f23329a2Sdanielk1977 #endif 5158f23329a2Sdanielk1977 515950118cdfSdan /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 516050118cdfSdan ** if the select-list is the same as the ORDER BY list, then this query 516150118cdfSdan ** can be rewritten as a GROUP BY. In other words, this: 516250118cdfSdan ** 516350118cdfSdan ** SELECT DISTINCT xyz FROM ... ORDER BY xyz 516450118cdfSdan ** 516550118cdfSdan ** is transformed to: 516650118cdfSdan ** 5167dea7d70dSdrh ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz 516850118cdfSdan ** 516950118cdfSdan ** The second form is preferred as a single index (or temp-table) may be 517050118cdfSdan ** used for both the ORDER BY and DISTINCT processing. As originally 517150118cdfSdan ** written the query must use a temp-table for at least one of the ORDER 517250118cdfSdan ** BY and DISTINCT, and an index or separate temp-table for the other. 517350118cdfSdan */ 517450118cdfSdan if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 5175adc57f68Sdrh && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0 517650118cdfSdan ){ 517750118cdfSdan p->selFlags &= ~SF_Distinct; 5178adc57f68Sdrh pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); 5179e8e4af76Sdrh /* Notice that even thought SF_Distinct has been cleared from p->selFlags, 5180e8e4af76Sdrh ** the sDistinct.isTnct is still set. Hence, isTnct represents the 5181e8e4af76Sdrh ** original setting of the SF_Distinct flag, not the current setting */ 5182e8e4af76Sdrh assert( sDistinct.isTnct ); 51837512cb47Sdrh 51847512cb47Sdrh #if SELECTTRACE_ENABLED 51857512cb47Sdrh if( sqlite3SelectTrace & 0x400 ){ 51867512cb47Sdrh SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n")); 51877512cb47Sdrh sqlite3TreeViewSelect(0, p, 0); 51887512cb47Sdrh } 51897512cb47Sdrh #endif 519050118cdfSdan } 519150118cdfSdan 5192adc57f68Sdrh /* If there is an ORDER BY clause, then create an ephemeral index to 5193adc57f68Sdrh ** do the sorting. But this sorting ephemeral index might end up 5194adc57f68Sdrh ** being unused if the data can be extracted in pre-sorted order. 5195adc57f68Sdrh ** If that is the case, then the OP_OpenEphemeral instruction will be 5196adc57f68Sdrh ** changed to an OP_Noop once we figure out that the sorting index is 5197adc57f68Sdrh ** not needed. The sSort.addrSortIndex variable is used to facilitate 5198adc57f68Sdrh ** that change. 51997cedc8d4Sdanielk1977 */ 5200079a3072Sdrh if( sSort.pOrderBy ){ 52010342b1f5Sdrh KeyInfo *pKeyInfo; 52023f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr); 5203079a3072Sdrh sSort.iECursor = pParse->nTab++; 5204079a3072Sdrh sSort.addrSortIndex = 520566a5167bSdrh sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5206f45f2326Sdrh sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0, 5207f45f2326Sdrh (char*)pKeyInfo, P4_KEYINFO 5208f45f2326Sdrh ); 52099d2985c7Sdrh }else{ 5210079a3072Sdrh sSort.addrSortIndex = -1; 52117cedc8d4Sdanielk1977 } 52127cedc8d4Sdanielk1977 52132d0794e3Sdrh /* If the output is destined for a temporary table, open that table. 52142d0794e3Sdrh */ 52156c8c8ce0Sdanielk1977 if( pDest->eDest==SRT_EphemTab ){ 52162b596da8Sdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr); 52172d0794e3Sdrh } 52182d0794e3Sdrh 5219f42bacc2Sdrh /* Set the limiter. 5220f42bacc2Sdrh */ 5221f42bacc2Sdrh iEnd = sqlite3VdbeMakeLabel(v); 522269b9383eSdan if( (p->selFlags & SF_FixedLimit)==0 ){ 5223c3489bbfSdrh p->nSelectRow = 320; /* 4 billion rows */ 522469b9383eSdan } 5225f42bacc2Sdrh computeLimitRegisters(pParse, p, iEnd); 5226079a3072Sdrh if( p->iLimit==0 && sSort.addrSortIndex>=0 ){ 52270ff287fbSdrh sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen); 5228079a3072Sdrh sSort.sortFlags |= SORTFLAG_UseSorter; 5229c6aff30cSdrh } 5230f42bacc2Sdrh 5231adc57f68Sdrh /* Open an ephemeral index to use for the distinct set. 5232cce7d176Sdrh */ 52332ce22453Sdan if( p->selFlags & SF_Distinct ){ 5234e8e4af76Sdrh sDistinct.tabTnct = pParse->nTab++; 5235e8e4af76Sdrh sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 5236e8e4af76Sdrh sDistinct.tabTnct, 0, 0, 5237079a3072Sdrh (char*)keyInfoFromExprList(pParse, p->pEList,0,0), 52382ec2fb22Sdrh P4_KEYINFO); 5239d4187c71Sdrh sqlite3VdbeChangeP5(v, BTREE_UNORDERED); 5240e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED; 5241832508b7Sdrh }else{ 5242e8e4af76Sdrh sDistinct.eTnctType = WHERE_DISTINCT_NOOP; 5243efb7251dSdrh } 5244832508b7Sdrh 524513449892Sdrh if( !isAgg && pGroupBy==0 ){ 5246e8e4af76Sdrh /* No aggregate functions and no GROUP BY clause */ 52476457a353Sdrh u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0); 5248c3489bbfSdrh assert( WHERE_USE_LIMIT==SF_FixedLimit ); 5249c3489bbfSdrh wctrlFlags |= p->selFlags & SF_FixedLimit; 525038cc40c2Sdan 525138cc40c2Sdan /* Begin the database scan. */ 5252079a3072Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy, 5253c3489bbfSdrh p->pEList, wctrlFlags, p->nSelectRow); 52541d83f052Sdrh if( pWInfo==0 ) goto select_end; 52556f32848dSdrh if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){ 52566f32848dSdrh p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo); 52576f32848dSdrh } 52586457a353Sdrh if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){ 52596f32848dSdrh sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo); 52606f32848dSdrh } 5261079a3072Sdrh if( sSort.pOrderBy ){ 5262079a3072Sdrh sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo); 5263a536df4eSdrh sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo); 5264079a3072Sdrh if( sSort.nOBSat==sSort.pOrderBy->nExpr ){ 5265079a3072Sdrh sSort.pOrderBy = 0; 5266079a3072Sdrh } 5267079a3072Sdrh } 5268cce7d176Sdrh 5269b9bb7c18Sdrh /* If sorting index that was created by a prior OP_OpenEphemeral 5270b9bb7c18Sdrh ** instruction ended up not being needed, then change the OP_OpenEphemeral 52719d2985c7Sdrh ** into an OP_Noop. 52729d2985c7Sdrh */ 5273079a3072Sdrh if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){ 5274079a3072Sdrh sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 52759d2985c7Sdrh } 52769d2985c7Sdrh 527738cc40c2Sdan /* Use the standard inner loop. */ 5278079a3072Sdrh selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest, 52796f32848dSdrh sqlite3WhereContinueLabel(pWInfo), 52806f32848dSdrh sqlite3WhereBreakLabel(pWInfo)); 52812282792aSdrh 5282cce7d176Sdrh /* End the database scan loop. 5283cce7d176Sdrh */ 52844adee20fSdanielk1977 sqlite3WhereEnd(pWInfo); 528513449892Sdrh }else{ 5286e8e4af76Sdrh /* This case when there exist aggregate functions or a GROUP BY clause 5287e8e4af76Sdrh ** or both */ 528813449892Sdrh NameContext sNC; /* Name context for processing aggregate information */ 528913449892Sdrh int iAMem; /* First Mem address for storing current GROUP BY */ 529013449892Sdrh int iBMem; /* First Mem address for previous GROUP BY */ 529113449892Sdrh int iUseFlag; /* Mem address holding flag indicating that at least 529213449892Sdrh ** one row of the input to the aggregator has been 529313449892Sdrh ** processed */ 529413449892Sdrh int iAbortFlag; /* Mem address which causes query abort if positive */ 529513449892Sdrh int groupBySort; /* Rows come from source in GROUP BY order */ 5296d176611bSdrh int addrEnd; /* End of processing for this SELECT */ 52971c9d835dSdrh int sortPTab = 0; /* Pseudotable used to decode sorting results */ 52981c9d835dSdrh int sortOut = 0; /* Output register from the sorter */ 5299374cd78cSdan int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */ 5300d176611bSdrh 5301d176611bSdrh /* Remove any and all aliases between the result set and the 5302d176611bSdrh ** GROUP BY clause. 5303d176611bSdrh */ 5304d176611bSdrh if( pGroupBy ){ 5305dc5ea5c7Sdrh int k; /* Loop counter */ 5306d176611bSdrh struct ExprList_item *pItem; /* For looping over expression in a list */ 5307d176611bSdrh 5308dc5ea5c7Sdrh for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){ 5309c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5310d176611bSdrh } 5311dc5ea5c7Sdrh for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){ 5312c2acc4e4Sdrh pItem->u.x.iAlias = 0; 5313d176611bSdrh } 5314c3489bbfSdrh assert( 66==sqlite3LogEst(100) ); 5315c3489bbfSdrh if( p->nSelectRow>66 ) p->nSelectRow = 66; 531695aa47b1Sdrh }else{ 5317c3489bbfSdrh assert( 0==sqlite3LogEst(1) ); 5318c3489bbfSdrh p->nSelectRow = 0; 5319d176611bSdrh } 5320cce7d176Sdrh 5321374cd78cSdan /* If there is both a GROUP BY and an ORDER BY clause and they are 5322374cd78cSdan ** identical, then it may be possible to disable the ORDER BY clause 5323374cd78cSdan ** on the grounds that the GROUP BY will cause elements to come out 5324adc57f68Sdrh ** in the correct order. It also may not - the GROUP BY might use a 5325374cd78cSdan ** database index that causes rows to be grouped together as required 5326374cd78cSdan ** but not actually sorted. Either way, record the fact that the 5327374cd78cSdan ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp 5328374cd78cSdan ** variable. */ 5329374cd78cSdan if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ 5330374cd78cSdan orderByGrp = 1; 5331374cd78cSdan } 533213449892Sdrh 5333d176611bSdrh /* Create a label to jump to when we want to abort the query */ 533413449892Sdrh addrEnd = sqlite3VdbeMakeLabel(v); 533513449892Sdrh 533613449892Sdrh /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in 533713449892Sdrh ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the 533813449892Sdrh ** SELECT statement. 53392282792aSdrh */ 534013449892Sdrh memset(&sNC, 0, sizeof(sNC)); 534113449892Sdrh sNC.pParse = pParse; 534213449892Sdrh sNC.pSrcList = pTabList; 534313449892Sdrh sNC.pAggInfo = &sAggInfo; 53447e61d18eSdrh sAggInfo.mnReg = pParse->nMem+1; 5345dd23c6bfSdan sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; 53469d2985c7Sdrh sAggInfo.pGroupBy = pGroupBy; 5347d2b3e23bSdrh sqlite3ExprAnalyzeAggList(&sNC, pEList); 5348079a3072Sdrh sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); 5349d2b3e23bSdrh if( pHaving ){ 5350d2b3e23bSdrh sqlite3ExprAnalyzeAggregates(&sNC, pHaving); 535113449892Sdrh } 535213449892Sdrh sAggInfo.nAccumulator = sAggInfo.nColumn; 535313449892Sdrh for(i=0; i<sAggInfo.nFunc; i++){ 53546ab3a2ecSdanielk1977 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) ); 53553a8c4be7Sdrh sNC.ncFlags |= NC_InAggFunc; 53566ab3a2ecSdanielk1977 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList); 53573a8c4be7Sdrh sNC.ncFlags &= ~NC_InAggFunc; 535813449892Sdrh } 53597e61d18eSdrh sAggInfo.mxReg = pParse->nMem; 536017435752Sdrh if( db->mallocFailed ) goto select_end; 536113449892Sdrh 536213449892Sdrh /* Processing for aggregates with GROUP BY is very different and 53633c4809a2Sdanielk1977 ** much more complex than aggregates without a GROUP BY. 536413449892Sdrh */ 536513449892Sdrh if( pGroupBy ){ 536613449892Sdrh KeyInfo *pKeyInfo; /* Keying information for the group by clause */ 5367728e0f91Sdrh int addr1; /* A-vs-B comparision jump */ 5368d176611bSdrh int addrOutputRow; /* Start of subroutine that outputs a result row */ 5369d176611bSdrh int regOutputRow; /* Return address register for output subroutine */ 5370d176611bSdrh int addrSetAbort; /* Set the abort flag and return */ 5371d176611bSdrh int addrTopOfLoop; /* Top of the input loop */ 5372d176611bSdrh int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ 5373d176611bSdrh int addrReset; /* Subroutine for resetting the accumulator */ 5374d176611bSdrh int regReset; /* Return address register for reset subroutine */ 537513449892Sdrh 537613449892Sdrh /* If there is a GROUP BY clause we might need a sorting index to 537713449892Sdrh ** implement it. Allocate that sorting index now. If it turns out 53781c9d835dSdrh ** that we do not need it after all, the OP_SorterOpen instruction 537913449892Sdrh ** will be converted into a Noop. 538013449892Sdrh */ 538113449892Sdrh sAggInfo.sortingIdx = pParse->nTab++; 53823f39bcf5Sdrh pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); 53831c9d835dSdrh addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 5384cd3e8f7cSdanielk1977 sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 53852ec2fb22Sdrh 0, (char*)pKeyInfo, P4_KEYINFO); 538613449892Sdrh 538713449892Sdrh /* Initialize memory locations used by GROUP BY aggregate processing 538813449892Sdrh */ 53890a07c107Sdrh iUseFlag = ++pParse->nMem; 53900a07c107Sdrh iAbortFlag = ++pParse->nMem; 5391d176611bSdrh regOutputRow = ++pParse->nMem; 5392d176611bSdrh addrOutputRow = sqlite3VdbeMakeLabel(v); 5393d176611bSdrh regReset = ++pParse->nMem; 5394d176611bSdrh addrReset = sqlite3VdbeMakeLabel(v); 53950a07c107Sdrh iAMem = pParse->nMem + 1; 539613449892Sdrh pParse->nMem += pGroupBy->nExpr; 53970a07c107Sdrh iBMem = pParse->nMem + 1; 539813449892Sdrh pParse->nMem += pGroupBy->nExpr; 53994c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); 5400d4e70ebdSdrh VdbeComment((v, "clear abort flag")); 54014c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); 5402d4e70ebdSdrh VdbeComment((v, "indicate accumulator empty")); 5403b8475df8Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1); 5404e313382eSdrh 540513449892Sdrh /* Begin a loop that will extract all source rows in GROUP BY order. 540613449892Sdrh ** This might involve two separate loops with an OP_Sort in between, or 540713449892Sdrh ** it might be a single loop that uses an index to extract information 540813449892Sdrh ** in the right order to begin with. 540913449892Sdrh */ 54102eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 541193ec45d5Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 5412374cd78cSdan WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0 5413374cd78cSdan ); 54145360ad34Sdrh if( pWInfo==0 ) goto select_end; 5415ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){ 541613449892Sdrh /* The optimizer is able to deliver rows in group by order so 5417b9bb7c18Sdrh ** we do not have to sort. The OP_OpenEphemeral table will be 541813449892Sdrh ** cancelled later because we still need to use the pKeyInfo 541913449892Sdrh */ 542013449892Sdrh groupBySort = 0; 542113449892Sdrh }else{ 542213449892Sdrh /* Rows are coming out in undetermined order. We have to push 542313449892Sdrh ** each row into a sorting index, terminate the first loop, 542413449892Sdrh ** then loop over the sorting index in order to get the output 542513449892Sdrh ** in sorted order 542613449892Sdrh */ 5427892d3179Sdrh int regBase; 5428892d3179Sdrh int regRecord; 5429892d3179Sdrh int nCol; 5430892d3179Sdrh int nGroupBy; 5431892d3179Sdrh 54322ce22453Sdan explainTempTable(pParse, 5433e8e4af76Sdrh (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ? 5434e8e4af76Sdrh "DISTINCT" : "GROUP BY"); 54352ce22453Sdan 543613449892Sdrh groupBySort = 1; 5437892d3179Sdrh nGroupBy = pGroupBy->nExpr; 5438dd23c6bfSdan nCol = nGroupBy; 5439dd23c6bfSdan j = nGroupBy; 544013449892Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 5441892d3179Sdrh if( sAggInfo.aCol[i].iSorterColumn>=j ){ 5442892d3179Sdrh nCol++; 544313449892Sdrh j++; 544413449892Sdrh } 5445892d3179Sdrh } 5446892d3179Sdrh regBase = sqlite3GetTempRange(pParse, nCol); 5447ceea3321Sdrh sqlite3ExprCacheClear(pParse); 54485579d59fSdrh sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); 5449dd23c6bfSdan j = nGroupBy; 5450892d3179Sdrh for(i=0; i<sAggInfo.nColumn; i++){ 5451892d3179Sdrh struct AggInfo_col *pCol = &sAggInfo.aCol[i]; 5452892d3179Sdrh if( pCol->iSorterColumn>=j ){ 5453e55cbd72Sdrh int r1 = j + regBase; 5454ce78bc6eSdrh sqlite3ExprCodeGetColumnToReg(pParse, 5455ce78bc6eSdrh pCol->pTab, pCol->iColumn, pCol->iTable, r1); 54566a012f04Sdrh j++; 5457892d3179Sdrh } 5458892d3179Sdrh } 5459892d3179Sdrh regRecord = sqlite3GetTempReg(pParse); 54601db639ceSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); 54611c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); 5462892d3179Sdrh sqlite3ReleaseTempReg(pParse, regRecord); 5463892d3179Sdrh sqlite3ReleaseTempRange(pParse, regBase, nCol); 546413449892Sdrh sqlite3WhereEnd(pWInfo); 54655134d135Sdan sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; 54661c9d835dSdrh sortOut = sqlite3GetTempReg(pParse); 54671c9d835dSdrh sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); 54681c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); 5469688852abSdrh VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); 547013449892Sdrh sAggInfo.useSortingIdx = 1; 5471ceea3321Sdrh sqlite3ExprCacheClear(pParse); 5472374cd78cSdan 5473374cd78cSdan } 5474374cd78cSdan 5475374cd78cSdan /* If the index or temporary table used by the GROUP BY sort 5476374cd78cSdan ** will naturally deliver rows in the order required by the ORDER BY 5477374cd78cSdan ** clause, cancel the ephemeral table open coded earlier. 5478374cd78cSdan ** 5479374cd78cSdan ** This is an optimization - the correct answer should result regardless. 5480374cd78cSdan ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 5481374cd78cSdan ** disable this optimization for testing purposes. */ 5482374cd78cSdan if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 5483374cd78cSdan && (groupBySort || sqlite3WhereIsSorted(pWInfo)) 5484374cd78cSdan ){ 5485374cd78cSdan sSort.pOrderBy = 0; 5486374cd78cSdan sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex); 548713449892Sdrh } 548813449892Sdrh 548913449892Sdrh /* Evaluate the current GROUP BY terms and store in b0, b1, b2... 549013449892Sdrh ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) 549113449892Sdrh ** Then compare the current GROUP BY terms against the GROUP BY terms 549213449892Sdrh ** from the previous row currently stored in a0, a1, a2... 549313449892Sdrh */ 549413449892Sdrh addrTopOfLoop = sqlite3VdbeCurrentAddr(v); 5495ceea3321Sdrh sqlite3ExprCacheClear(pParse); 54961c9d835dSdrh if( groupBySort ){ 549738b4149cSdrh sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, 549838b4149cSdrh sortOut, sortPTab); 54991c9d835dSdrh } 550013449892Sdrh for(j=0; j<pGroupBy->nExpr; j++){ 550113449892Sdrh if( groupBySort ){ 55021c9d835dSdrh sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); 550313449892Sdrh }else{ 550413449892Sdrh sAggInfo.directMode = 1; 55052dcef11bSdrh sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); 550613449892Sdrh } 550713449892Sdrh } 550816ee60ffSdrh sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, 55092ec2fb22Sdrh (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO); 5510728e0f91Sdrh addr1 = sqlite3VdbeCurrentAddr(v); 5511728e0f91Sdrh sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v); 551213449892Sdrh 551313449892Sdrh /* Generate code that runs whenever the GROUP BY changes. 5514e00ee6ebSdrh ** Changes in the GROUP BY are detected by the previous code 551513449892Sdrh ** block. If there were no changes, this block is skipped. 551613449892Sdrh ** 551713449892Sdrh ** This code copies current group by terms in b0,b1,b2,... 551813449892Sdrh ** over to a0,a1,a2. It then calls the output subroutine 551913449892Sdrh ** and resets the aggregate accumulator registers in preparation 552013449892Sdrh ** for the next GROUP BY batch. 552113449892Sdrh */ 5522b21e7c70Sdrh sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); 55232eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5524d4e70ebdSdrh VdbeComment((v, "output one row")); 5525688852abSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v); 5526d4e70ebdSdrh VdbeComment((v, "check abort flag")); 55272eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); 5528d4e70ebdSdrh VdbeComment((v, "reset accumulator")); 552913449892Sdrh 553013449892Sdrh /* Update the aggregate accumulators based on the content of 553113449892Sdrh ** the current row 553213449892Sdrh */ 5533728e0f91Sdrh sqlite3VdbeJumpHere(v, addr1); 553413449892Sdrh updateAccumulator(pParse, &sAggInfo); 55354c583128Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); 5536d4e70ebdSdrh VdbeComment((v, "indicate data in accumulator")); 553713449892Sdrh 553813449892Sdrh /* End of the loop 553913449892Sdrh */ 554013449892Sdrh if( groupBySort ){ 55411c9d835dSdrh sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop); 5542688852abSdrh VdbeCoverage(v); 554313449892Sdrh }else{ 554413449892Sdrh sqlite3WhereEnd(pWInfo); 554548f2d3b1Sdrh sqlite3VdbeChangeToNoop(v, addrSortingIdx); 554613449892Sdrh } 554713449892Sdrh 554813449892Sdrh /* Output the final row of result 554913449892Sdrh */ 55502eb95377Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); 5551d4e70ebdSdrh VdbeComment((v, "output final row")); 555213449892Sdrh 5553d176611bSdrh /* Jump over the subroutines 5554d176611bSdrh */ 5555076e85f5Sdrh sqlite3VdbeGoto(v, addrEnd); 5556d176611bSdrh 5557d176611bSdrh /* Generate a subroutine that outputs a single row of the result 5558d176611bSdrh ** set. This subroutine first looks at the iUseFlag. If iUseFlag 5559d176611bSdrh ** is less than or equal to zero, the subroutine is a no-op. If 5560d176611bSdrh ** the processing calls for the query to abort, this subroutine 5561d176611bSdrh ** increments the iAbortFlag memory location before returning in 5562d176611bSdrh ** order to signal the caller to abort. 5563d176611bSdrh */ 5564d176611bSdrh addrSetAbort = sqlite3VdbeCurrentAddr(v); 5565d176611bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); 5566d176611bSdrh VdbeComment((v, "set abort flag")); 5567d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5568d176611bSdrh sqlite3VdbeResolveLabel(v, addrOutputRow); 5569d176611bSdrh addrOutputRow = sqlite3VdbeCurrentAddr(v); 5570d176611bSdrh sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); 557138b4149cSdrh VdbeCoverage(v); 5572d176611bSdrh VdbeComment((v, "Groupby result generator entry point")); 5573d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5574d176611bSdrh finalizeAggFunctions(pParse, &sAggInfo); 5575d176611bSdrh sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); 5576079a3072Sdrh selectInnerLoop(pParse, p, p->pEList, -1, &sSort, 5577e8e4af76Sdrh &sDistinct, pDest, 5578d176611bSdrh addrOutputRow+1, addrSetAbort); 5579d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); 5580d176611bSdrh VdbeComment((v, "end groupby result generator")); 5581d176611bSdrh 5582d176611bSdrh /* Generate a subroutine that will reset the group-by accumulator 5583d176611bSdrh */ 5584d176611bSdrh sqlite3VdbeResolveLabel(v, addrReset); 5585d176611bSdrh resetAccumulator(pParse, &sAggInfo); 5586d176611bSdrh sqlite3VdbeAddOp1(v, OP_Return, regReset); 5587d176611bSdrh 558843152cf8Sdrh } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ 558913449892Sdrh else { 5590dba0137eSdanielk1977 ExprList *pDel = 0; 5591a5533162Sdanielk1977 #ifndef SQLITE_OMIT_BTREECOUNT 5592a5533162Sdanielk1977 Table *pTab; 5593a5533162Sdanielk1977 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){ 5594a5533162Sdanielk1977 /* If isSimpleCount() returns a pointer to a Table structure, then 5595a5533162Sdanielk1977 ** the SQL statement is of the form: 5596a5533162Sdanielk1977 ** 5597a5533162Sdanielk1977 ** SELECT count(*) FROM <tbl> 5598a5533162Sdanielk1977 ** 5599a5533162Sdanielk1977 ** where the Table structure returned represents table <tbl>. 5600a5533162Sdanielk1977 ** 5601a5533162Sdanielk1977 ** This statement is so common that it is optimized specially. The 5602a5533162Sdanielk1977 ** OP_Count instruction is executed either on the intkey table that 5603a5533162Sdanielk1977 ** contains the data for table <tbl> or on one of its indexes. It 5604a5533162Sdanielk1977 ** is better to execute the op on an index, as indexes are almost 5605a5533162Sdanielk1977 ** always spread across less pages than their corresponding tables. 5606a5533162Sdanielk1977 */ 5607a5533162Sdanielk1977 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 5608a5533162Sdanielk1977 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */ 5609a5533162Sdanielk1977 Index *pIdx; /* Iterator variable */ 5610a5533162Sdanielk1977 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */ 5611a5533162Sdanielk1977 Index *pBest = 0; /* Best index found so far */ 5612a5533162Sdanielk1977 int iRoot = pTab->tnum; /* Root page of scanned b-tree */ 5613a9d1ccb9Sdanielk1977 5614a5533162Sdanielk1977 sqlite3CodeVerifySchema(pParse, iDb); 5615a5533162Sdanielk1977 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 5616a5533162Sdanielk1977 5617d9e3cad2Sdrh /* Search for the index that has the lowest scan cost. 5618a5533162Sdanielk1977 ** 56193e9548b3Sdrh ** (2011-04-15) Do not do a full scan of an unordered index. 56203e9548b3Sdrh ** 5621abcc1941Sdrh ** (2013-10-03) Do not count the entries in a partial index. 56225f33f375Sdrh ** 5623a5533162Sdanielk1977 ** In practice the KeyInfo structure will not be used. It is only 5624a5533162Sdanielk1977 ** passed to keep OP_OpenRead happy. 5625a5533162Sdanielk1977 */ 56265c7917e4Sdrh if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab); 5627a5533162Sdanielk1977 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 5628d9e3cad2Sdrh if( pIdx->bUnordered==0 5629e13e9f54Sdrh && pIdx->szIdxRow<pTab->szTabRow 5630d3037a41Sdrh && pIdx->pPartIdxWhere==0 5631e13e9f54Sdrh && (!pBest || pIdx->szIdxRow<pBest->szIdxRow) 5632d9e3cad2Sdrh ){ 5633a5533162Sdanielk1977 pBest = pIdx; 5634a5533162Sdanielk1977 } 5635a5533162Sdanielk1977 } 5636d9e3cad2Sdrh if( pBest ){ 5637a5533162Sdanielk1977 iRoot = pBest->tnum; 56382ec2fb22Sdrh pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest); 5639a5533162Sdanielk1977 } 5640a5533162Sdanielk1977 5641a5533162Sdanielk1977 /* Open a read-only cursor, execute the OP_Count, close the cursor. */ 5642261c02d9Sdrh sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1); 5643a5533162Sdanielk1977 if( pKeyInfo ){ 56442ec2fb22Sdrh sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); 5645a5533162Sdanielk1977 } 5646a5533162Sdanielk1977 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); 5647a5533162Sdanielk1977 sqlite3VdbeAddOp1(v, OP_Close, iCsr); 5648ef7075deSdan explainSimpleCount(pParse, pTab, pBest); 5649a5533162Sdanielk1977 }else 5650a5533162Sdanielk1977 #endif /* SQLITE_OMIT_BTREECOUNT */ 5651a5533162Sdanielk1977 { 5652738bdcfbSdanielk1977 /* Check if the query is of one of the following forms: 5653738bdcfbSdanielk1977 ** 5654738bdcfbSdanielk1977 ** SELECT min(x) FROM ... 5655738bdcfbSdanielk1977 ** SELECT max(x) FROM ... 5656738bdcfbSdanielk1977 ** 5657738bdcfbSdanielk1977 ** If it is, then ask the code in where.c to attempt to sort results 5658738bdcfbSdanielk1977 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 5659738bdcfbSdanielk1977 ** If where.c is able to produce results sorted in this order, then 5660738bdcfbSdanielk1977 ** add vdbe code to break out of the processing loop after the 5661738bdcfbSdanielk1977 ** first iteration (since the first iteration of the loop is 5662738bdcfbSdanielk1977 ** guaranteed to operate on the row with the minimum or maximum 5663738bdcfbSdanielk1977 ** value of x, the only row required). 5664738bdcfbSdanielk1977 ** 5665738bdcfbSdanielk1977 ** A special flag must be passed to sqlite3WhereBegin() to slightly 566648864df9Smistachkin ** modify behavior as follows: 5667738bdcfbSdanielk1977 ** 5668738bdcfbSdanielk1977 ** + If the query is a "SELECT min(x)", then the loop coded by 5669738bdcfbSdanielk1977 ** where.c should not iterate over any values with a NULL value 5670738bdcfbSdanielk1977 ** for x. 5671738bdcfbSdanielk1977 ** 5672738bdcfbSdanielk1977 ** + The optimizer code in where.c (the thing that decides which 5673738bdcfbSdanielk1977 ** index or indices to use) should place a different priority on 5674738bdcfbSdanielk1977 ** satisfying the 'ORDER BY' clause than it does in other cases. 5675738bdcfbSdanielk1977 ** Refer to code and comments in where.c for details. 5676738bdcfbSdanielk1977 */ 5677a5533162Sdanielk1977 ExprList *pMinMax = 0; 56784ac391fcSdan u8 flag = WHERE_ORDERBY_NORMAL; 56794ac391fcSdan 56804ac391fcSdan assert( p->pGroupBy==0 ); 56814ac391fcSdan assert( flag==0 ); 56824ac391fcSdan if( p->pHaving==0 ){ 56834ac391fcSdan flag = minMaxQuery(&sAggInfo, &pMinMax); 56844ac391fcSdan } 56854ac391fcSdan assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); 56864ac391fcSdan 5687a9d1ccb9Sdanielk1977 if( flag ){ 56884ac391fcSdan pMinMax = sqlite3ExprListDup(db, pMinMax, 0); 56896ab3a2ecSdanielk1977 pDel = pMinMax; 56904a642b60Sdrh assert( db->mallocFailed || pMinMax!=0 ); 56914a642b60Sdrh if( !db->mallocFailed ){ 5692ea678832Sdrh pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; 5693a9d1ccb9Sdanielk1977 pMinMax->a[0].pExpr->op = TK_COLUMN; 5694a9d1ccb9Sdanielk1977 } 56951013c932Sdrh } 5696a9d1ccb9Sdanielk1977 569713449892Sdrh /* This case runs if the aggregate has no GROUP BY clause. The 569813449892Sdrh ** processing is much simpler since there is only a single row 569913449892Sdrh ** of output. 570013449892Sdrh */ 570113449892Sdrh resetAccumulator(pParse, &sAggInfo); 570246ec5b63Sdrh pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0); 5703dba0137eSdanielk1977 if( pWInfo==0 ){ 5704633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 5705dba0137eSdanielk1977 goto select_end; 5706dba0137eSdanielk1977 } 570713449892Sdrh updateAccumulator(pParse, &sAggInfo); 570846c35f9bSdrh assert( pMinMax==0 || pMinMax->nExpr==1 ); 5709ddba0c22Sdrh if( sqlite3WhereIsOrdered(pWInfo)>0 ){ 5710076e85f5Sdrh sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); 5711a5533162Sdanielk1977 VdbeComment((v, "%s() by index", 5712a5533162Sdanielk1977 (flag==WHERE_ORDERBY_MIN?"min":"max"))); 5713a9d1ccb9Sdanielk1977 } 571413449892Sdrh sqlite3WhereEnd(pWInfo); 571513449892Sdrh finalizeAggFunctions(pParse, &sAggInfo); 57167a895a80Sdanielk1977 } 57177a895a80Sdanielk1977 5718079a3072Sdrh sSort.pOrderBy = 0; 571935573356Sdrh sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); 5720079a3072Sdrh selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, 5721a9671a22Sdrh pDest, addrEnd, addrEnd); 5722633e6d57Sdrh sqlite3ExprListDelete(db, pDel); 572313449892Sdrh } 572413449892Sdrh sqlite3VdbeResolveLabel(v, addrEnd); 572513449892Sdrh 572613449892Sdrh } /* endif aggregate query */ 57272282792aSdrh 5728e8e4af76Sdrh if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){ 57292ce22453Sdan explainTempTable(pParse, "DISTINCT"); 57302ce22453Sdan } 57312ce22453Sdan 5732cce7d176Sdrh /* If there is an ORDER BY clause, then we need to sort the results 5733cce7d176Sdrh ** and send them to the callback one by one. 5734cce7d176Sdrh */ 5735079a3072Sdrh if( sSort.pOrderBy ){ 573638b4149cSdrh explainTempTable(pParse, 573738b4149cSdrh sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY"); 5738079a3072Sdrh generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest); 5739cce7d176Sdrh } 57406a535340Sdrh 5741ec7429aeSdrh /* Jump here to skip this query 5742ec7429aeSdrh */ 5743ec7429aeSdrh sqlite3VdbeResolveLabel(v, iEnd); 5744ec7429aeSdrh 57455b1c07e7Sdan /* The SELECT has been coded. If there is an error in the Parse structure, 57465b1c07e7Sdan ** set the return code to 1. Otherwise 0. */ 57475b1c07e7Sdan rc = (pParse->nErr>0); 57481d83f052Sdrh 57491d83f052Sdrh /* Control jumps to here if an error is encountered above, or upon 57501d83f052Sdrh ** successful coding of the SELECT. 57511d83f052Sdrh */ 57521d83f052Sdrh select_end: 575317c0bc0cSdan explainSetInteger(pParse->iSelectId, iRestoreSelectId); 5754955de52cSdanielk1977 57557d10d5a6Sdrh /* Identify column names if results of the SELECT are to be output. 5756955de52cSdanielk1977 */ 57577d10d5a6Sdrh if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){ 5758955de52cSdanielk1977 generateColumnNames(pParse, pTabList, pEList); 5759955de52cSdanielk1977 } 5760955de52cSdanielk1977 5761633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aCol); 5762633e6d57Sdrh sqlite3DbFree(db, sAggInfo.aFunc); 5763eb9b884cSdrh #if SELECTTRACE_ENABLED 5764eb9b884cSdrh SELECTTRACE(1,pParse,p,("end processing\n")); 5765eb9b884cSdrh pParse->nSelectIndent--; 5766eb9b884cSdrh #endif 57671d83f052Sdrh return rc; 5768cce7d176Sdrh } 5769