16f82e85aSdrh /* 26f82e85aSdrh ** 2015-06-06 36f82e85aSdrh ** 46f82e85aSdrh ** The author disclaims copyright to this source code. In place of 56f82e85aSdrh ** a legal notice, here is a blessing: 66f82e85aSdrh ** 76f82e85aSdrh ** May you do good and not evil. 86f82e85aSdrh ** May you find forgiveness for yourself and forgive others. 96f82e85aSdrh ** May you share freely, never taking more than you give. 106f82e85aSdrh ** 116f82e85aSdrh ************************************************************************* 126f82e85aSdrh ** This module contains C code that generates VDBE code used to process 136f82e85aSdrh ** the WHERE clause of SQL statements. 146f82e85aSdrh ** 156f82e85aSdrh ** This file was split off from where.c on 2015-06-06 in order to reduce the 166f82e85aSdrh ** size of where.c and make it easier to edit. This file contains the routines 176f82e85aSdrh ** that actually generate the bulk of the WHERE loop code. The original where.c 186f82e85aSdrh ** file retains the code that does query planning and analysis. 196f82e85aSdrh */ 206f82e85aSdrh #include "sqliteInt.h" 216f82e85aSdrh #include "whereInt.h" 226f82e85aSdrh 236f82e85aSdrh #ifndef SQLITE_OMIT_EXPLAIN 241d9bc9b7Sdan 251d9bc9b7Sdan /* 261d9bc9b7Sdan ** Return the name of the i-th column of the pIdx index. 271d9bc9b7Sdan */ 281d9bc9b7Sdan static const char *explainIndexColumnName(Index *pIdx, int i){ 291d9bc9b7Sdan i = pIdx->aiColumn[i]; 301d9bc9b7Sdan if( i==XN_EXPR ) return "<expr>"; 311d9bc9b7Sdan if( i==XN_ROWID ) return "rowid"; 321d9bc9b7Sdan return pIdx->pTable->aCol[i].zName; 331d9bc9b7Sdan } 341d9bc9b7Sdan 356f82e85aSdrh /* 366f82e85aSdrh ** This routine is a helper for explainIndexRange() below 376f82e85aSdrh ** 386f82e85aSdrh ** pStr holds the text of an expression that we are building up one term 396f82e85aSdrh ** at a time. This routine adds a new term to the end of the expression. 406f82e85aSdrh ** Terms are separated by AND so add the "AND" text for second and subsequent 416f82e85aSdrh ** terms only. 426f82e85aSdrh */ 436f82e85aSdrh static void explainAppendTerm( 446f82e85aSdrh StrAccum *pStr, /* The text expression being built */ 451d9bc9b7Sdan Index *pIdx, /* Index to read column names from */ 461d9bc9b7Sdan int nTerm, /* Number of terms */ 471d9bc9b7Sdan int iTerm, /* Zero-based index of first term. */ 481d9bc9b7Sdan int bAnd, /* Non-zero to append " AND " */ 496f82e85aSdrh const char *zOp /* Name of the operator */ 506f82e85aSdrh ){ 511d9bc9b7Sdan int i; 521d9bc9b7Sdan 531d9bc9b7Sdan assert( nTerm>=1 ); 541d9bc9b7Sdan if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5); 551d9bc9b7Sdan 561d9bc9b7Sdan if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); 571d9bc9b7Sdan for(i=0; i<nTerm; i++){ 581d9bc9b7Sdan if( i ) sqlite3StrAccumAppend(pStr, ",", 1); 591d9bc9b7Sdan sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i)); 601d9bc9b7Sdan } 611d9bc9b7Sdan if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1); 621d9bc9b7Sdan 636f82e85aSdrh sqlite3StrAccumAppend(pStr, zOp, 1); 641d9bc9b7Sdan 651d9bc9b7Sdan if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); 661d9bc9b7Sdan for(i=0; i<nTerm; i++){ 671d9bc9b7Sdan if( i ) sqlite3StrAccumAppend(pStr, ",", 1); 686f82e85aSdrh sqlite3StrAccumAppend(pStr, "?", 1); 696f82e85aSdrh } 701d9bc9b7Sdan if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1); 71c7c4680fSdrh } 72c7c4680fSdrh 73c7c4680fSdrh /* 746f82e85aSdrh ** Argument pLevel describes a strategy for scanning table pTab. This 756f82e85aSdrh ** function appends text to pStr that describes the subset of table 766f82e85aSdrh ** rows scanned by the strategy in the form of an SQL expression. 776f82e85aSdrh ** 786f82e85aSdrh ** For example, if the query: 796f82e85aSdrh ** 806f82e85aSdrh ** SELECT * FROM t1 WHERE a=1 AND b>2; 816f82e85aSdrh ** 826f82e85aSdrh ** is run and there is an index on (a, b), then this function returns a 836f82e85aSdrh ** string similar to: 846f82e85aSdrh ** 856f82e85aSdrh ** "a=? AND b>?" 866f82e85aSdrh */ 878faee877Sdrh static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ 886f82e85aSdrh Index *pIndex = pLoop->u.btree.pIndex; 896f82e85aSdrh u16 nEq = pLoop->u.btree.nEq; 906f82e85aSdrh u16 nSkip = pLoop->nSkip; 916f82e85aSdrh int i, j; 926f82e85aSdrh 936f82e85aSdrh if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; 946f82e85aSdrh sqlite3StrAccumAppend(pStr, " (", 2); 956f82e85aSdrh for(i=0; i<nEq; i++){ 96c7c4680fSdrh const char *z = explainIndexColumnName(pIndex, i); 976f82e85aSdrh if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); 985f4a686fSdrh sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); 996f82e85aSdrh } 1006f82e85aSdrh 1016f82e85aSdrh j = i; 1026f82e85aSdrh if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ 1031d9bc9b7Sdan explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); 1041d9bc9b7Sdan i = 1; 1056f82e85aSdrh } 1066f82e85aSdrh if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ 1071d9bc9b7Sdan explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); 1086f82e85aSdrh } 1096f82e85aSdrh sqlite3StrAccumAppend(pStr, ")", 1); 1106f82e85aSdrh } 1116f82e85aSdrh 1126f82e85aSdrh /* 1136f82e85aSdrh ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN 1146f82e85aSdrh ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was 1156f82e85aSdrh ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 1166f82e85aSdrh ** is added to the output to describe the table scan strategy in pLevel. 1176f82e85aSdrh ** 1186f82e85aSdrh ** If an OP_Explain opcode is added to the VM, its address is returned. 1196f82e85aSdrh ** Otherwise, if no OP_Explain is coded, zero is returned. 1206f82e85aSdrh */ 1216f82e85aSdrh int sqlite3WhereExplainOneScan( 1226f82e85aSdrh Parse *pParse, /* Parse context */ 1236f82e85aSdrh SrcList *pTabList, /* Table list this loop refers to */ 1246f82e85aSdrh WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ 1256f82e85aSdrh int iLevel, /* Value for "level" column of output */ 1266f82e85aSdrh int iFrom, /* Value for "from" column of output */ 1276f82e85aSdrh u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ 1286f82e85aSdrh ){ 1296f82e85aSdrh int ret = 0; 1306f82e85aSdrh #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) 1316f82e85aSdrh if( pParse->explain==2 ) 1326f82e85aSdrh #endif 1336f82e85aSdrh { 1346f82e85aSdrh struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; 1356f82e85aSdrh Vdbe *v = pParse->pVdbe; /* VM being constructed */ 1366f82e85aSdrh sqlite3 *db = pParse->db; /* Database handle */ 1376f82e85aSdrh int iId = pParse->iSelectId; /* Select id (left-most output column) */ 1386f82e85aSdrh int isSearch; /* True for a SEARCH. False for SCAN. */ 1396f82e85aSdrh WhereLoop *pLoop; /* The controlling WhereLoop object */ 1406f82e85aSdrh u32 flags; /* Flags that describe this loop */ 1416f82e85aSdrh char *zMsg; /* Text to add to EQP output */ 1426f82e85aSdrh StrAccum str; /* EQP output string */ 1436f82e85aSdrh char zBuf[100]; /* Initial space for EQP output string */ 1446f82e85aSdrh 1456f82e85aSdrh pLoop = pLevel->pWLoop; 1466f82e85aSdrh flags = pLoop->wsFlags; 147ce943bc8Sdrh if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; 1486f82e85aSdrh 1496f82e85aSdrh isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 1506f82e85aSdrh || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) 1516f82e85aSdrh || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); 1526f82e85aSdrh 1536f82e85aSdrh sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); 1546f82e85aSdrh sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); 1556f82e85aSdrh if( pItem->pSelect ){ 1565f4a686fSdrh sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); 1576f82e85aSdrh }else{ 1585f4a686fSdrh sqlite3XPrintf(&str, " TABLE %s", pItem->zName); 1596f82e85aSdrh } 1606f82e85aSdrh 1616f82e85aSdrh if( pItem->zAlias ){ 1625f4a686fSdrh sqlite3XPrintf(&str, " AS %s", pItem->zAlias); 1636f82e85aSdrh } 1646f82e85aSdrh if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ 1656f82e85aSdrh const char *zFmt = 0; 1666f82e85aSdrh Index *pIdx; 1676f82e85aSdrh 1686f82e85aSdrh assert( pLoop->u.btree.pIndex!=0 ); 1696f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 1706f82e85aSdrh assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); 1716f82e85aSdrh if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ 1726f82e85aSdrh if( isSearch ){ 1736f82e85aSdrh zFmt = "PRIMARY KEY"; 1746f82e85aSdrh } 1756f82e85aSdrh }else if( flags & WHERE_PARTIALIDX ){ 1766f82e85aSdrh zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; 1776f82e85aSdrh }else if( flags & WHERE_AUTO_INDEX ){ 1786f82e85aSdrh zFmt = "AUTOMATIC COVERING INDEX"; 1796f82e85aSdrh }else if( flags & WHERE_IDX_ONLY ){ 1806f82e85aSdrh zFmt = "COVERING INDEX %s"; 1816f82e85aSdrh }else{ 1826f82e85aSdrh zFmt = "INDEX %s"; 1836f82e85aSdrh } 1846f82e85aSdrh if( zFmt ){ 1856f82e85aSdrh sqlite3StrAccumAppend(&str, " USING ", 7); 1865f4a686fSdrh sqlite3XPrintf(&str, zFmt, pIdx->zName); 1878faee877Sdrh explainIndexRange(&str, pLoop); 1886f82e85aSdrh } 1896f82e85aSdrh }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ 190d37bea5bSdrh const char *zRangeOp; 1916f82e85aSdrh if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ 192d37bea5bSdrh zRangeOp = "="; 1936f82e85aSdrh }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ 194d37bea5bSdrh zRangeOp = ">? AND rowid<"; 1956f82e85aSdrh }else if( flags&WHERE_BTM_LIMIT ){ 196d37bea5bSdrh zRangeOp = ">"; 1976f82e85aSdrh }else{ 1986f82e85aSdrh assert( flags&WHERE_TOP_LIMIT); 199d37bea5bSdrh zRangeOp = "<"; 2006f82e85aSdrh } 2015f4a686fSdrh sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); 2026f82e85aSdrh } 2036f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 2046f82e85aSdrh else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ 2055f4a686fSdrh sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s", 2066f82e85aSdrh pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); 2076f82e85aSdrh } 2086f82e85aSdrh #endif 2096f82e85aSdrh #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS 2106f82e85aSdrh if( pLoop->nOut>=10 ){ 2115f4a686fSdrh sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); 2126f82e85aSdrh }else{ 2136f82e85aSdrh sqlite3StrAccumAppend(&str, " (~1 row)", 9); 2146f82e85aSdrh } 2156f82e85aSdrh #endif 2166f82e85aSdrh zMsg = sqlite3StrAccumFinish(&str); 2176f82e85aSdrh ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC); 2186f82e85aSdrh } 2196f82e85aSdrh return ret; 2206f82e85aSdrh } 2216f82e85aSdrh #endif /* SQLITE_OMIT_EXPLAIN */ 2226f82e85aSdrh 2236f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 2246f82e85aSdrh /* 2256f82e85aSdrh ** Configure the VM passed as the first argument with an 2266f82e85aSdrh ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 2276f82e85aSdrh ** implement level pLvl. Argument pSrclist is a pointer to the FROM 2286f82e85aSdrh ** clause that the scan reads data from. 2296f82e85aSdrh ** 2306f82e85aSdrh ** If argument addrExplain is not 0, it must be the address of an 2316f82e85aSdrh ** OP_Explain instruction that describes the same loop. 2326f82e85aSdrh */ 2336f82e85aSdrh void sqlite3WhereAddScanStatus( 2346f82e85aSdrh Vdbe *v, /* Vdbe to add scanstatus entry to */ 2356f82e85aSdrh SrcList *pSrclist, /* FROM clause pLvl reads data from */ 2366f82e85aSdrh WhereLevel *pLvl, /* Level to add scanstatus() entry for */ 2376f82e85aSdrh int addrExplain /* Address of OP_Explain (or 0) */ 2386f82e85aSdrh ){ 2396f82e85aSdrh const char *zObj = 0; 2406f82e85aSdrh WhereLoop *pLoop = pLvl->pWLoop; 2416f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ 2426f82e85aSdrh zObj = pLoop->u.btree.pIndex->zName; 2436f82e85aSdrh }else{ 2446f82e85aSdrh zObj = pSrclist->a[pLvl->iFrom].zName; 2456f82e85aSdrh } 2466f82e85aSdrh sqlite3VdbeScanStatus( 2476f82e85aSdrh v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj 2486f82e85aSdrh ); 2496f82e85aSdrh } 2506f82e85aSdrh #endif 2516f82e85aSdrh 2526f82e85aSdrh 2536f82e85aSdrh /* 2546f82e85aSdrh ** Disable a term in the WHERE clause. Except, do not disable the term 2556f82e85aSdrh ** if it controls a LEFT OUTER JOIN and it did not originate in the ON 2566f82e85aSdrh ** or USING clause of that join. 2576f82e85aSdrh ** 2586f82e85aSdrh ** Consider the term t2.z='ok' in the following queries: 2596f82e85aSdrh ** 2606f82e85aSdrh ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' 2616f82e85aSdrh ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' 2626f82e85aSdrh ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' 2636f82e85aSdrh ** 2646f82e85aSdrh ** The t2.z='ok' is disabled in the in (2) because it originates 2656f82e85aSdrh ** in the ON clause. The term is disabled in (3) because it is not part 2666f82e85aSdrh ** of a LEFT OUTER JOIN. In (1), the term is not disabled. 2676f82e85aSdrh ** 2686f82e85aSdrh ** Disabling a term causes that term to not be tested in the inner loop 2696f82e85aSdrh ** of the join. Disabling is an optimization. When terms are satisfied 2706f82e85aSdrh ** by indices, we disable them to prevent redundant tests in the inner 2716f82e85aSdrh ** loop. We would get the correct results if nothing were ever disabled, 2726f82e85aSdrh ** but joins might run a little slower. The trick is to disable as much 2736f82e85aSdrh ** as we can without disabling too much. If we disabled in (1), we'd get 2746f82e85aSdrh ** the wrong answer. See ticket #813. 2756f82e85aSdrh ** 2766f82e85aSdrh ** If all the children of a term are disabled, then that term is also 2776f82e85aSdrh ** automatically disabled. In this way, terms get disabled if derived 2786f82e85aSdrh ** virtual terms are tested first. For example: 2796f82e85aSdrh ** 2806f82e85aSdrh ** x GLOB 'abc*' AND x>='abc' AND x<'acd' 2816f82e85aSdrh ** \___________/ \______/ \_____/ 2826f82e85aSdrh ** parent child1 child2 2836f82e85aSdrh ** 2846f82e85aSdrh ** Only the parent term was in the original WHERE clause. The child1 2856f82e85aSdrh ** and child2 terms were added by the LIKE optimization. If both of 2866f82e85aSdrh ** the virtual child terms are valid, then testing of the parent can be 2876f82e85aSdrh ** skipped. 2886f82e85aSdrh ** 2896f82e85aSdrh ** Usually the parent term is marked as TERM_CODED. But if the parent 2906f82e85aSdrh ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. 2916f82e85aSdrh ** The TERM_LIKECOND marking indicates that the term should be coded inside 2926f82e85aSdrh ** a conditional such that is only evaluated on the second pass of a 2936f82e85aSdrh ** LIKE-optimization loop, when scanning BLOBs instead of strings. 2946f82e85aSdrh */ 2956f82e85aSdrh static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ 2966f82e85aSdrh int nLoop = 0; 2979d9c41e2Sdrh assert( pTerm!=0 ); 2989d9c41e2Sdrh while( (pTerm->wtFlags & TERM_CODED)==0 2996f82e85aSdrh && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 3006f82e85aSdrh && (pLevel->notReady & pTerm->prereqAll)==0 3016f82e85aSdrh ){ 3026f82e85aSdrh if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ 3036f82e85aSdrh pTerm->wtFlags |= TERM_LIKECOND; 3046f82e85aSdrh }else{ 3056f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 3066f82e85aSdrh } 3076f82e85aSdrh if( pTerm->iParent<0 ) break; 3086f82e85aSdrh pTerm = &pTerm->pWC->a[pTerm->iParent]; 3099d9c41e2Sdrh assert( pTerm!=0 ); 3106f82e85aSdrh pTerm->nChild--; 3116f82e85aSdrh if( pTerm->nChild!=0 ) break; 3126f82e85aSdrh nLoop++; 3136f82e85aSdrh } 3146f82e85aSdrh } 3156f82e85aSdrh 3166f82e85aSdrh /* 3176f82e85aSdrh ** Code an OP_Affinity opcode to apply the column affinity string zAff 3186f82e85aSdrh ** to the n registers starting at base. 3196f82e85aSdrh ** 3206f82e85aSdrh ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the 3216f82e85aSdrh ** beginning and end of zAff are ignored. If all entries in zAff are 3226f82e85aSdrh ** SQLITE_AFF_BLOB, then no code gets generated. 3236f82e85aSdrh ** 3246f82e85aSdrh ** This routine makes its own copy of zAff so that the caller is free 3256f82e85aSdrh ** to modify zAff after this routine returns. 3266f82e85aSdrh */ 3276f82e85aSdrh static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ 3286f82e85aSdrh Vdbe *v = pParse->pVdbe; 3296f82e85aSdrh if( zAff==0 ){ 3306f82e85aSdrh assert( pParse->db->mallocFailed ); 3316f82e85aSdrh return; 3326f82e85aSdrh } 3336f82e85aSdrh assert( v!=0 ); 3346f82e85aSdrh 3356f82e85aSdrh /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning 3366f82e85aSdrh ** and end of the affinity string. 3376f82e85aSdrh */ 3386f82e85aSdrh while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){ 3396f82e85aSdrh n--; 3406f82e85aSdrh base++; 3416f82e85aSdrh zAff++; 3426f82e85aSdrh } 3436f82e85aSdrh while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){ 3446f82e85aSdrh n--; 3456f82e85aSdrh } 3466f82e85aSdrh 3476f82e85aSdrh /* Code the OP_Affinity opcode if there is anything left to do. */ 3486f82e85aSdrh if( n>0 ){ 3499b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); 3506f82e85aSdrh sqlite3ExprCacheAffinityChange(pParse, base, n); 3516f82e85aSdrh } 3526f82e85aSdrh } 3536f82e85aSdrh 354b7ca2177Sdan /* 355b7ca2177Sdan ** Expression pRight, which is the RHS of a comparison operation, is 356b7ca2177Sdan ** either a vector of n elements or, if n==1, a scalar expression. 357b7ca2177Sdan ** Before the comparison operation, affinity zAff is to be applied 358b7ca2177Sdan ** to the pRight values. This function modifies characters within the 359b7ca2177Sdan ** affinity string to SQLITE_AFF_BLOB if either: 360b7ca2177Sdan ** 361b7ca2177Sdan ** * the comparison will be performed with no affinity, or 362b7ca2177Sdan ** * the affinity change in zAff is guaranteed not to change the value. 363b7ca2177Sdan */ 364b7ca2177Sdan static void updateRangeAffinityStr( 365b7ca2177Sdan Expr *pRight, /* RHS of comparison */ 366b7ca2177Sdan int n, /* Number of vector elements in comparison */ 367b7ca2177Sdan char *zAff /* Affinity string to modify */ 368b7ca2177Sdan ){ 369b7ca2177Sdan int i; 370b7ca2177Sdan for(i=0; i<n; i++){ 371b7ca2177Sdan Expr *p = sqlite3VectorFieldSubexpr(pRight, i); 372b7ca2177Sdan if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB 373b7ca2177Sdan || sqlite3ExprNeedsNoAffinityChange(p, zAff[i]) 374b7ca2177Sdan ){ 375b7ca2177Sdan zAff[i] = SQLITE_AFF_BLOB; 376b7ca2177Sdan } 377b7ca2177Sdan } 378b7ca2177Sdan } 3796f82e85aSdrh 380*9b1ecb67Sdrh #ifdef SQLITE_DEBUG 381*9b1ecb67Sdrh /* Return true if the pSub ExprList is a subset of pMain. The terms 382*9b1ecb67Sdrh ** of pSub can be in a different order from pMain. The only requirement 383*9b1ecb67Sdrh ** is that every term in pSub must exist somewhere in pMain. 384*9b1ecb67Sdrh ** 385*9b1ecb67Sdrh ** Return false if pSub contains any term that is not found in pMain. 386*9b1ecb67Sdrh */ 387*9b1ecb67Sdrh static int exprListSubset(ExprList *pSub, ExprList *pMain){ 388*9b1ecb67Sdrh int i, j; 389*9b1ecb67Sdrh for(i=0; i<pSub->nExpr; i++){ 390*9b1ecb67Sdrh Expr *p = pSub->a[i].pExpr; 391*9b1ecb67Sdrh for(j=0; j<pMain->nExpr; j++){ 392*9b1ecb67Sdrh if( sqlite3ExprCompare(0, p, pMain->a[j].pExpr, 0)==0 ) break; 393*9b1ecb67Sdrh } 394*9b1ecb67Sdrh if( j>=pMain->nExpr ) return 0; 395*9b1ecb67Sdrh } 396*9b1ecb67Sdrh return 1; 397*9b1ecb67Sdrh } 398*9b1ecb67Sdrh #endif /* SQLITE_DEBUG */ 399*9b1ecb67Sdrh 400*9b1ecb67Sdrh 4016f82e85aSdrh /* 4026f82e85aSdrh ** Generate code for a single equality term of the WHERE clause. An equality 4036f82e85aSdrh ** term can be either X=expr or X IN (...). pTerm is the term to be 4046f82e85aSdrh ** coded. 4056f82e85aSdrh ** 406099a0f5fSdrh ** The current value for the constraint is left in a register, the index 407099a0f5fSdrh ** of which is returned. An attempt is made store the result in iTarget but 408099a0f5fSdrh ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the 409099a0f5fSdrh ** constraint is a TK_EQ or TK_IS, then the current value might be left in 410099a0f5fSdrh ** some other register and it is the caller's responsibility to compensate. 4116f82e85aSdrh ** 4124602b8e8Sdrh ** For a constraint of the form X=expr, the expression is evaluated in 4134602b8e8Sdrh ** straight-line code. For constraints of the form X IN (...) 4146f82e85aSdrh ** this routine sets up a loop that will iterate over all values of X. 4156f82e85aSdrh */ 4166f82e85aSdrh static int codeEqualityTerm( 4176f82e85aSdrh Parse *pParse, /* The parsing context */ 4186f82e85aSdrh WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ 4196f82e85aSdrh WhereLevel *pLevel, /* The level of the FROM clause we are working on */ 4206f82e85aSdrh int iEq, /* Index of the equality term within this level */ 4216f82e85aSdrh int bRev, /* True for reverse-order IN operations */ 4226f82e85aSdrh int iTarget /* Attempt to leave results in this register */ 4236f82e85aSdrh ){ 4246f82e85aSdrh Expr *pX = pTerm->pExpr; 4256f82e85aSdrh Vdbe *v = pParse->pVdbe; 4266f82e85aSdrh int iReg; /* Register holding results */ 4276f82e85aSdrh 4288da209b1Sdan assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); 4296f82e85aSdrh assert( iTarget>0 ); 4306f82e85aSdrh if( pX->op==TK_EQ || pX->op==TK_IS ){ 431fc7f27b9Sdrh iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); 4326f82e85aSdrh }else if( pX->op==TK_ISNULL ){ 4336f82e85aSdrh iReg = iTarget; 4346f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); 4356f82e85aSdrh #ifndef SQLITE_OMIT_SUBQUERY 4366f82e85aSdrh }else{ 437ac6b47d1Sdrh int eType = IN_INDEX_NOOP; 4386f82e85aSdrh int iTab; 4396f82e85aSdrh struct InLoop *pIn; 4406f82e85aSdrh WhereLoop *pLoop = pLevel->pWLoop; 4418da209b1Sdan int i; 4428da209b1Sdan int nEq = 0; 4438da209b1Sdan int *aiMap = 0; 4446f82e85aSdrh 4456f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 4466f82e85aSdrh && pLoop->u.btree.pIndex!=0 4476f82e85aSdrh && pLoop->u.btree.pIndex->aSortOrder[iEq] 4486f82e85aSdrh ){ 4496f82e85aSdrh testcase( iEq==0 ); 4506f82e85aSdrh testcase( bRev ); 4516f82e85aSdrh bRev = !bRev; 4526f82e85aSdrh } 4536f82e85aSdrh assert( pX->op==TK_IN ); 4546f82e85aSdrh iReg = iTarget; 4558da209b1Sdan 4568da209b1Sdan for(i=0; i<iEq; i++){ 4578da209b1Sdan if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ 4588da209b1Sdan disableTerm(pLevel, pTerm); 4598da209b1Sdan return iTarget; 4608da209b1Sdan } 4618da209b1Sdan } 4628da209b1Sdan for(i=iEq;i<pLoop->nLTerm; i++){ 4630c36fca0Sdrh if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++; 4648da209b1Sdan } 4658da209b1Sdan 4668da209b1Sdan if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ 467ba00e30aSdan eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); 4688da209b1Sdan }else{ 46926c8d0caSdan Select *pSelect = pX->x.pSelect; 4708da209b1Sdan sqlite3 *db = pParse->db; 47154cda4edSdrh u16 savedDbOptFlags = db->dbOptFlags; 47226c8d0caSdan ExprList *pOrigRhs = pSelect->pEList; 4738da209b1Sdan ExprList *pOrigLhs = pX->pLeft->x.pList; 4748da209b1Sdan ExprList *pRhs = 0; /* New Select.pEList for RHS */ 4758da209b1Sdan ExprList *pLhs = 0; /* New pX->pLeft vector */ 4768da209b1Sdan 4778da209b1Sdan for(i=iEq;i<pLoop->nLTerm; i++){ 4788da209b1Sdan if( pLoop->aLTerm[i]->pExpr==pX ){ 4798da209b1Sdan int iField = pLoop->aLTerm[i]->iField - 1; 4808da209b1Sdan Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); 4818da209b1Sdan Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); 4828da209b1Sdan 4838da209b1Sdan pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); 4848da209b1Sdan pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); 4858da209b1Sdan } 4868da209b1Sdan } 487*9b1ecb67Sdrh 488*9b1ecb67Sdrh /* pRhs should be a subset of pOrigRhs (though possibly in a different 489*9b1ecb67Sdrh ** order). And pLhs should be a subset of pOrigLhs. To put it 490*9b1ecb67Sdrh ** another way: Every term of pRhs should exist in pOrigRhs and 491*9b1ecb67Sdrh ** every term of pLhs should exist in pOrigLhs. */ 492*9b1ecb67Sdrh assert( db->mallocFailed || exprListSubset(pRhs, pOrigRhs) ); 493*9b1ecb67Sdrh assert( db->mallocFailed || exprListSubset(pLhs, pOrigLhs) ); 494*9b1ecb67Sdrh 495ac6b47d1Sdrh if( !db->mallocFailed ){ 49683c434e6Sdan Expr *pLeft = pX->pLeft; 49726c8d0caSdan 49826c8d0caSdan if( pSelect->pOrderBy ){ 49926c8d0caSdan /* If the SELECT statement has an ORDER BY clause, zero the 50026c8d0caSdan ** iOrderByCol variables. These are set to non-zero when an 50126c8d0caSdan ** ORDER BY term exactly matches one of the terms of the 50226c8d0caSdan ** result-set. Since the result-set of the SELECT statement may 50326c8d0caSdan ** have been modified or reordered, these variables are no longer 50426c8d0caSdan ** set correctly. Since setting them is just an optimization, 50526c8d0caSdan ** it's easiest just to zero them here. */ 50626c8d0caSdan ExprList *pOrderBy = pSelect->pOrderBy; 50726c8d0caSdan for(i=0; i<pOrderBy->nExpr; i++){ 50826c8d0caSdan pOrderBy->a[i].u.x.iOrderByCol = 0; 50926c8d0caSdan } 51026c8d0caSdan } 51126c8d0caSdan 51283c434e6Sdan /* Take care here not to generate a TK_VECTOR containing only a 51383c434e6Sdan ** single value. Since the parser never creates such a vector, some 51483c434e6Sdan ** of the subroutines do not handle this case. */ 51583c434e6Sdan if( pLhs->nExpr==1 ){ 51683c434e6Sdan pX->pLeft = pLhs->a[0].pExpr; 51783c434e6Sdan }else{ 51883c434e6Sdan pLeft->x.pList = pLhs; 519c7a77ae1Sdrh aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); 520c7a77ae1Sdrh testcase( aiMap==0 ); 52183c434e6Sdan } 52226c8d0caSdan pSelect->pEList = pRhs; 52354cda4edSdrh db->dbOptFlags |= SQLITE_QueryFlattener; 5248da209b1Sdan eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); 52554cda4edSdrh db->dbOptFlags = savedDbOptFlags; 526c7a77ae1Sdrh testcase( aiMap!=0 && aiMap[0]!=0 ); 52726c8d0caSdan pSelect->pEList = pOrigRhs; 52883c434e6Sdan pLeft->x.pList = pOrigLhs; 52983c434e6Sdan pX->pLeft = pLeft; 530ac6b47d1Sdrh } 5318da209b1Sdan sqlite3ExprListDelete(pParse->db, pLhs); 5328da209b1Sdan sqlite3ExprListDelete(pParse->db, pRhs); 5338da209b1Sdan } 5348da209b1Sdan 5356f82e85aSdrh if( eType==IN_INDEX_INDEX_DESC ){ 5366f82e85aSdrh testcase( bRev ); 5376f82e85aSdrh bRev = !bRev; 5386f82e85aSdrh } 5396f82e85aSdrh iTab = pX->iTable; 5406f82e85aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); 5416f82e85aSdrh VdbeCoverageIf(v, bRev); 5426f82e85aSdrh VdbeCoverageIf(v, !bRev); 5436f82e85aSdrh assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); 5448da209b1Sdan 5456f82e85aSdrh pLoop->wsFlags |= WHERE_IN_ABLE; 5466f82e85aSdrh if( pLevel->u.in.nIn==0 ){ 5476f82e85aSdrh pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 5486f82e85aSdrh } 5498da209b1Sdan 5508da209b1Sdan i = pLevel->u.in.nIn; 5518da209b1Sdan pLevel->u.in.nIn += nEq; 5526f82e85aSdrh pLevel->u.in.aInLoop = 5536f82e85aSdrh sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, 5546f82e85aSdrh sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); 5556f82e85aSdrh pIn = pLevel->u.in.aInLoop; 5566f82e85aSdrh if( pIn ){ 5578da209b1Sdan int iMap = 0; /* Index in aiMap[] */ 5588da209b1Sdan pIn += i; 5597887d7f2Sdan for(i=iEq;i<pLoop->nLTerm; i++){ 5608da209b1Sdan if( pLoop->aLTerm[i]->pExpr==pX ){ 561edc3537cSdan int iOut = iReg + i - iEq; 5626f82e85aSdrh if( eType==IN_INDEX_ROWID ){ 56372d5003eSdrh testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */ 564edc3537cSdan pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); 5656f82e85aSdrh }else{ 5668da209b1Sdan int iCol = aiMap ? aiMap[iMap++] : 0; 5678da209b1Sdan pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); 5686f82e85aSdrh } 56903181c8cSdrh sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); 5708da209b1Sdan if( i==iEq ){ 5718da209b1Sdan pIn->iCur = iTab; 5726f82e85aSdrh pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; 5738da209b1Sdan }else{ 5748da209b1Sdan pIn->eEndLoopOp = OP_Noop; 5758da209b1Sdan } 5767887d7f2Sdan pIn++; 5778da209b1Sdan } 5788da209b1Sdan } 5796f82e85aSdrh }else{ 5806f82e85aSdrh pLevel->u.in.nIn = 0; 5816f82e85aSdrh } 5828da209b1Sdan sqlite3DbFree(pParse->db, aiMap); 5836f82e85aSdrh #endif 5846f82e85aSdrh } 5856f82e85aSdrh disableTerm(pLevel, pTerm); 5866f82e85aSdrh return iReg; 5876f82e85aSdrh } 5886f82e85aSdrh 5896f82e85aSdrh /* 5906f82e85aSdrh ** Generate code that will evaluate all == and IN constraints for an 5916f82e85aSdrh ** index scan. 5926f82e85aSdrh ** 5936f82e85aSdrh ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). 5946f82e85aSdrh ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 5956f82e85aSdrh ** The index has as many as three equality constraints, but in this 5966f82e85aSdrh ** example, the third "c" value is an inequality. So only two 5976f82e85aSdrh ** constraints are coded. This routine will generate code to evaluate 5986f82e85aSdrh ** a==5 and b IN (1,2,3). The current values for a and b will be stored 5996f82e85aSdrh ** in consecutive registers and the index of the first register is returned. 6006f82e85aSdrh ** 6016f82e85aSdrh ** In the example above nEq==2. But this subroutine works for any value 6026f82e85aSdrh ** of nEq including 0. If nEq==0, this routine is nearly a no-op. 6036f82e85aSdrh ** The only thing it does is allocate the pLevel->iMem memory cell and 6046f82e85aSdrh ** compute the affinity string. 6056f82e85aSdrh ** 6066f82e85aSdrh ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints 6076f82e85aSdrh ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is 6086f82e85aSdrh ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that 6096f82e85aSdrh ** occurs after the nEq quality constraints. 6106f82e85aSdrh ** 6116f82e85aSdrh ** This routine allocates a range of nEq+nExtraReg memory cells and returns 6126f82e85aSdrh ** the index of the first memory cell in that range. The code that 6136f82e85aSdrh ** calls this routine will use that memory range to store keys for 6146f82e85aSdrh ** start and termination conditions of the loop. 6156f82e85aSdrh ** key value of the loop. If one or more IN operators appear, then 6166f82e85aSdrh ** this routine allocates an additional nEq memory cells for internal 6176f82e85aSdrh ** use. 6186f82e85aSdrh ** 6196f82e85aSdrh ** Before returning, *pzAff is set to point to a buffer containing a 6206f82e85aSdrh ** copy of the column affinity string of the index allocated using 6216f82e85aSdrh ** sqlite3DbMalloc(). Except, entries in the copy of the string associated 6226f82e85aSdrh ** with equality constraints that use BLOB or NONE affinity are set to 6236f82e85aSdrh ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: 6246f82e85aSdrh ** 6256f82e85aSdrh ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); 6266f82e85aSdrh ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; 6276f82e85aSdrh ** 6286f82e85aSdrh ** In the example above, the index on t1(a) has TEXT affinity. But since 6296f82e85aSdrh ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, 6306f82e85aSdrh ** no conversion should be attempted before using a t2.b value as part of 6316f82e85aSdrh ** a key to search the index. Hence the first byte in the returned affinity 6326f82e85aSdrh ** string in this example would be set to SQLITE_AFF_BLOB. 6336f82e85aSdrh */ 6346f82e85aSdrh static int codeAllEqualityTerms( 6356f82e85aSdrh Parse *pParse, /* Parsing context */ 6366f82e85aSdrh WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ 6376f82e85aSdrh int bRev, /* Reverse the order of IN operators */ 6386f82e85aSdrh int nExtraReg, /* Number of extra registers to allocate */ 6396f82e85aSdrh char **pzAff /* OUT: Set to point to affinity string */ 6406f82e85aSdrh ){ 6416f82e85aSdrh u16 nEq; /* The number of == or IN constraints to code */ 6426f82e85aSdrh u16 nSkip; /* Number of left-most columns to skip */ 6436f82e85aSdrh Vdbe *v = pParse->pVdbe; /* The vm under construction */ 6446f82e85aSdrh Index *pIdx; /* The index being used for this loop */ 6456f82e85aSdrh WhereTerm *pTerm; /* A single constraint term */ 6466f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object */ 6476f82e85aSdrh int j; /* Loop counter */ 6486f82e85aSdrh int regBase; /* Base register */ 6496f82e85aSdrh int nReg; /* Number of registers to allocate */ 6506f82e85aSdrh char *zAff; /* Affinity string to return */ 6516f82e85aSdrh 6526f82e85aSdrh /* This module is only called on query plans that use an index. */ 6536f82e85aSdrh pLoop = pLevel->pWLoop; 6546f82e85aSdrh assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); 6556f82e85aSdrh nEq = pLoop->u.btree.nEq; 6566f82e85aSdrh nSkip = pLoop->nSkip; 6576f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 6586f82e85aSdrh assert( pIdx!=0 ); 6596f82e85aSdrh 6606f82e85aSdrh /* Figure out how many memory cells we will need then allocate them. 6616f82e85aSdrh */ 6626f82e85aSdrh regBase = pParse->nMem + 1; 6636f82e85aSdrh nReg = pLoop->u.btree.nEq + nExtraReg; 6646f82e85aSdrh pParse->nMem += nReg; 6656f82e85aSdrh 666e9107698Sdrh zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); 6674df86af3Sdrh assert( zAff!=0 || pParse->db->mallocFailed ); 6686f82e85aSdrh 6696f82e85aSdrh if( nSkip ){ 6706f82e85aSdrh int iIdxCur = pLevel->iIdxCur; 6716f82e85aSdrh sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); 6726f82e85aSdrh VdbeCoverageIf(v, bRev==0); 6736f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 6746f82e85aSdrh VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); 6756f82e85aSdrh j = sqlite3VdbeAddOp0(v, OP_Goto); 6766f82e85aSdrh pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), 6776f82e85aSdrh iIdxCur, 0, regBase, nSkip); 6786f82e85aSdrh VdbeCoverageIf(v, bRev==0); 6796f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 6806f82e85aSdrh sqlite3VdbeJumpHere(v, j); 6816f82e85aSdrh for(j=0; j<nSkip; j++){ 6826f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); 6834b92f98cSdrh testcase( pIdx->aiColumn[j]==XN_EXPR ); 684e63e8a6cSdrh VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); 6856f82e85aSdrh } 6866f82e85aSdrh } 6876f82e85aSdrh 6886f82e85aSdrh /* Evaluate the equality constraints 6896f82e85aSdrh */ 6906f82e85aSdrh assert( zAff==0 || (int)strlen(zAff)>=nEq ); 6916f82e85aSdrh for(j=nSkip; j<nEq; j++){ 6926f82e85aSdrh int r1; 6936f82e85aSdrh pTerm = pLoop->aLTerm[j]; 6946f82e85aSdrh assert( pTerm!=0 ); 6956f82e85aSdrh /* The following testcase is true for indices with redundant columns. 6966f82e85aSdrh ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ 6976f82e85aSdrh testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); 6986f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 6996f82e85aSdrh r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); 7006f82e85aSdrh if( r1!=regBase+j ){ 7016f82e85aSdrh if( nReg==1 ){ 7026f82e85aSdrh sqlite3ReleaseTempReg(pParse, regBase); 7036f82e85aSdrh regBase = r1; 7046f82e85aSdrh }else{ 7056f82e85aSdrh sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); 7066f82e85aSdrh } 7076f82e85aSdrh } 70827189603Sdan if( pTerm->eOperator & WO_IN ){ 70927189603Sdan if( pTerm->pExpr->flags & EP_xIsSelect ){ 7101c12657fSdan /* No affinity ever needs to be (or should be) applied to a value 7111c12657fSdan ** from the RHS of an "? IN (SELECT ...)" expression. The 7121c12657fSdan ** sqlite3FindInIndex() routine has already ensured that the 7131c12657fSdan ** affinity of the comparison has been applied to the value. */ 714aaf8a064Sdrh if( zAff ) zAff[j] = SQLITE_AFF_BLOB; 71527189603Sdan } 716c097e122Sdrh }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ 7171c12657fSdan Expr *pRight = pTerm->pExpr->pRight; 7186f82e85aSdrh if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ 7196f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); 7206f82e85aSdrh VdbeCoverage(v); 7216f82e85aSdrh } 7221c12657fSdan if( zAff ){ 7236f82e85aSdrh if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ 7246f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB; 7256f82e85aSdrh } 7266f82e85aSdrh if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ 7276f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB; 7286f82e85aSdrh } 7296f82e85aSdrh } 7306f82e85aSdrh } 7316f82e85aSdrh } 7326f82e85aSdrh *pzAff = zAff; 7336f82e85aSdrh return regBase; 7346f82e85aSdrh } 7356f82e85aSdrh 73641d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 7376f82e85aSdrh /* 73844aebff2Sdrh ** If the most recently coded instruction is a constant range constraint 73944aebff2Sdrh ** (a string literal) that originated from the LIKE optimization, then 74044aebff2Sdrh ** set P3 and P5 on the OP_String opcode so that the string will be cast 74144aebff2Sdrh ** to a BLOB at appropriate times. 7426f82e85aSdrh ** 7436f82e85aSdrh ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range 7446f82e85aSdrh ** expression: "x>='ABC' AND x<'abd'". But this requires that the range 7456f82e85aSdrh ** scan loop run twice, once for strings and a second time for BLOBs. 7466f82e85aSdrh ** The OP_String opcodes on the second pass convert the upper and lower 747e234cfd1Smistachkin ** bound string constants to blobs. This routine makes the necessary changes 7486f82e85aSdrh ** to the OP_String opcodes for that to happen. 74941d2e66eSdrh ** 75041d2e66eSdrh ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then 75141d2e66eSdrh ** only the one pass through the string space is required, so this routine 75241d2e66eSdrh ** becomes a no-op. 7536f82e85aSdrh */ 7546f82e85aSdrh static void whereLikeOptimizationStringFixup( 7556f82e85aSdrh Vdbe *v, /* prepared statement under construction */ 7566f82e85aSdrh WhereLevel *pLevel, /* The loop that contains the LIKE operator */ 7576f82e85aSdrh WhereTerm *pTerm /* The upper or lower bound just coded */ 7586f82e85aSdrh ){ 7596f82e85aSdrh if( pTerm->wtFlags & TERM_LIKEOPT ){ 7606f82e85aSdrh VdbeOp *pOp; 7616f82e85aSdrh assert( pLevel->iLikeRepCntr>0 ); 7626f82e85aSdrh pOp = sqlite3VdbeGetOp(v, -1); 7636f82e85aSdrh assert( pOp!=0 ); 7646f82e85aSdrh assert( pOp->opcode==OP_String8 7656f82e85aSdrh || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); 76644aebff2Sdrh pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ 76744aebff2Sdrh pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ 7686f82e85aSdrh } 7696f82e85aSdrh } 77041d2e66eSdrh #else 77141d2e66eSdrh # define whereLikeOptimizationStringFixup(A,B,C) 77241d2e66eSdrh #endif 7736f82e85aSdrh 774bec2476aSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS 7752f2b0278Sdrh /* 7762f2b0278Sdrh ** Information is passed from codeCursorHint() down to individual nodes of 7772f2b0278Sdrh ** the expression tree (by sqlite3WalkExpr()) using an instance of this 7782f2b0278Sdrh ** structure. 7792f2b0278Sdrh */ 7802f2b0278Sdrh struct CCurHint { 7812f2b0278Sdrh int iTabCur; /* Cursor for the main table */ 7822f2b0278Sdrh int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ 7832f2b0278Sdrh Index *pIdx; /* The index used to access the table */ 7842f2b0278Sdrh }; 7852f2b0278Sdrh 7862f2b0278Sdrh /* 7872f2b0278Sdrh ** This function is called for every node of an expression that is a candidate 7882f2b0278Sdrh ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference 7892f2b0278Sdrh ** the table CCurHint.iTabCur, verify that the same column can be 7902f2b0278Sdrh ** accessed through the index. If it cannot, then set pWalker->eCode to 1. 7912f2b0278Sdrh */ 7922f2b0278Sdrh static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ 7932f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint; 7942f2b0278Sdrh assert( pHint->pIdx!=0 ); 7952f2b0278Sdrh if( pExpr->op==TK_COLUMN 7962f2b0278Sdrh && pExpr->iTable==pHint->iTabCur 7972f2b0278Sdrh && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0 7982f2b0278Sdrh ){ 7992f2b0278Sdrh pWalker->eCode = 1; 8002f2b0278Sdrh } 8012f2b0278Sdrh return WRC_Continue; 8022f2b0278Sdrh } 8032f2b0278Sdrh 804e6912fd8Sdan /* 805e6912fd8Sdan ** Test whether or not expression pExpr, which was part of a WHERE clause, 806e6912fd8Sdan ** should be included in the cursor-hint for a table that is on the rhs 807e6912fd8Sdan ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 808e6912fd8Sdan ** expression is not suitable. 809e6912fd8Sdan ** 810e6912fd8Sdan ** An expression is unsuitable if it might evaluate to non NULL even if 811e6912fd8Sdan ** a TK_COLUMN node that does affect the value of the expression is set 812e6912fd8Sdan ** to NULL. For example: 813e6912fd8Sdan ** 814e6912fd8Sdan ** col IS NULL 815e6912fd8Sdan ** col IS NOT NULL 816e6912fd8Sdan ** coalesce(col, 1) 817e6912fd8Sdan ** CASE WHEN col THEN 0 ELSE 1 END 818e6912fd8Sdan */ 819e6912fd8Sdan static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ 8202b693d63Sdan if( pExpr->op==TK_IS 821e6912fd8Sdan || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 822e6912fd8Sdan || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 823e6912fd8Sdan ){ 824e6912fd8Sdan pWalker->eCode = 1; 8252b693d63Sdan }else if( pExpr->op==TK_FUNCTION ){ 8262b693d63Sdan int d1; 8271d42ea71Sdrh char d2[4]; 8282b693d63Sdan if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ 8292b693d63Sdan pWalker->eCode = 1; 830e6912fd8Sdan } 8312b693d63Sdan } 8322b693d63Sdan 833e6912fd8Sdan return WRC_Continue; 834e6912fd8Sdan } 835e6912fd8Sdan 836bec2476aSdrh 837bec2476aSdrh /* 838bec2476aSdrh ** This function is called on every node of an expression tree used as an 839bec2476aSdrh ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN 8402f2b0278Sdrh ** that accesses any table other than the one identified by 8412f2b0278Sdrh ** CCurHint.iTabCur, then do the following: 842bec2476aSdrh ** 843bec2476aSdrh ** 1) allocate a register and code an OP_Column instruction to read 844bec2476aSdrh ** the specified column into the new register, and 845bec2476aSdrh ** 846bec2476aSdrh ** 2) transform the expression node to a TK_REGISTER node that reads 847bec2476aSdrh ** from the newly populated register. 8482f2b0278Sdrh ** 8492f2b0278Sdrh ** Also, if the node is a TK_COLUMN that does access the table idenified 8502f2b0278Sdrh ** by pCCurHint.iTabCur, and an index is being used (which we will 8512f2b0278Sdrh ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into 8522f2b0278Sdrh ** an access of the index rather than the original table. 853bec2476aSdrh */ 854bec2476aSdrh static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ 855bec2476aSdrh int rc = WRC_Continue; 8562f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint; 8572f2b0278Sdrh if( pExpr->op==TK_COLUMN ){ 8582f2b0278Sdrh if( pExpr->iTable!=pHint->iTabCur ){ 859bec2476aSdrh Vdbe *v = pWalker->pParse->pVdbe; 860bec2476aSdrh int reg = ++pWalker->pParse->nMem; /* Register for column value */ 861bec2476aSdrh sqlite3ExprCodeGetColumnOfTable( 862bec2476aSdrh v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg 863bec2476aSdrh ); 864bec2476aSdrh pExpr->op = TK_REGISTER; 865bec2476aSdrh pExpr->iTable = reg; 8662f2b0278Sdrh }else if( pHint->pIdx!=0 ){ 8672f2b0278Sdrh pExpr->iTable = pHint->iIdxCur; 8682f2b0278Sdrh pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn); 8692f2b0278Sdrh assert( pExpr->iColumn>=0 ); 8702f2b0278Sdrh } 871bec2476aSdrh }else if( pExpr->op==TK_AGG_FUNCTION ){ 872bec2476aSdrh /* An aggregate function in the WHERE clause of a query means this must 873bec2476aSdrh ** be a correlated sub-query, and expression pExpr is an aggregate from 874bec2476aSdrh ** the parent context. Do not walk the function arguments in this case. 875bec2476aSdrh ** 876bec2476aSdrh ** todo: It should be possible to replace this node with a TK_REGISTER 877bec2476aSdrh ** expression, as the result of the expression must be stored in a 878bec2476aSdrh ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ 879bec2476aSdrh rc = WRC_Prune; 880bec2476aSdrh } 881bec2476aSdrh return rc; 882bec2476aSdrh } 883bec2476aSdrh 884bec2476aSdrh /* 885bec2476aSdrh ** Insert an OP_CursorHint instruction if it is appropriate to do so. 886bec2476aSdrh */ 887bec2476aSdrh static void codeCursorHint( 888b324cf75Sdan struct SrcList_item *pTabItem, /* FROM clause item */ 889b413a546Sdrh WhereInfo *pWInfo, /* The where clause */ 890b413a546Sdrh WhereLevel *pLevel, /* Which loop to provide hints for */ 891b413a546Sdrh WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ 892bec2476aSdrh ){ 893bec2476aSdrh Parse *pParse = pWInfo->pParse; 894bec2476aSdrh sqlite3 *db = pParse->db; 895bec2476aSdrh Vdbe *v = pParse->pVdbe; 896bec2476aSdrh Expr *pExpr = 0; 8972f2b0278Sdrh WhereLoop *pLoop = pLevel->pWLoop; 898bec2476aSdrh int iCur; 899bec2476aSdrh WhereClause *pWC; 900bec2476aSdrh WhereTerm *pTerm; 901b413a546Sdrh int i, j; 9022f2b0278Sdrh struct CCurHint sHint; 9032f2b0278Sdrh Walker sWalker; 904bec2476aSdrh 905bec2476aSdrh if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; 9062f2b0278Sdrh iCur = pLevel->iTabCur; 9072f2b0278Sdrh assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); 9082f2b0278Sdrh sHint.iTabCur = iCur; 9092f2b0278Sdrh sHint.iIdxCur = pLevel->iIdxCur; 9102f2b0278Sdrh sHint.pIdx = pLoop->u.btree.pIndex; 9112f2b0278Sdrh memset(&sWalker, 0, sizeof(sWalker)); 9122f2b0278Sdrh sWalker.pParse = pParse; 9132f2b0278Sdrh sWalker.u.pCCurHint = &sHint; 914bec2476aSdrh pWC = &pWInfo->sWC; 915bec2476aSdrh for(i=0; i<pWC->nTerm; i++){ 916bec2476aSdrh pTerm = &pWC->a[i]; 917bec2476aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 918bec2476aSdrh if( pTerm->prereqAll & pLevel->notReady ) continue; 919b324cf75Sdan 920b324cf75Sdan /* Any terms specified as part of the ON(...) clause for any LEFT 921b324cf75Sdan ** JOIN for which the current table is not the rhs are omitted 922b324cf75Sdan ** from the cursor-hint. 923b324cf75Sdan ** 924e6912fd8Sdan ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 925e6912fd8Sdan ** that were specified as part of the WHERE clause must be excluded. 926e6912fd8Sdan ** This is to address the following: 927b324cf75Sdan ** 928b324cf75Sdan ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; 929b324cf75Sdan ** 930e6912fd8Sdan ** Say there is a single row in t2 that matches (t1.a=t2.b), but its 931e6912fd8Sdan ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 932e6912fd8Sdan ** pushed down to the cursor, this row is filtered out, causing 933e6912fd8Sdan ** SQLite to synthesize a row of NULL values. Which does match the 934e6912fd8Sdan ** WHERE clause, and so the query returns a row. Which is incorrect. 935e6912fd8Sdan ** 936e6912fd8Sdan ** For the same reason, WHERE terms such as: 937e6912fd8Sdan ** 938e6912fd8Sdan ** WHERE 1 = (t2.c IS NULL) 939e6912fd8Sdan ** 940e6912fd8Sdan ** are also excluded. See codeCursorHintIsOrFunction() for details. 941b324cf75Sdan */ 942b324cf75Sdan if( pTabItem->fg.jointype & JT_LEFT ){ 943e6912fd8Sdan Expr *pExpr = pTerm->pExpr; 944e6912fd8Sdan if( !ExprHasProperty(pExpr, EP_FromJoin) 945e6912fd8Sdan || pExpr->iRightJoinTable!=pTabItem->iCursor 946b324cf75Sdan ){ 947e6912fd8Sdan sWalker.eCode = 0; 948e6912fd8Sdan sWalker.xExprCallback = codeCursorHintIsOrFunction; 949e6912fd8Sdan sqlite3WalkExpr(&sWalker, pTerm->pExpr); 950e6912fd8Sdan if( sWalker.eCode ) continue; 951b324cf75Sdan } 952b324cf75Sdan }else{ 953bec2476aSdrh if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; 954b324cf75Sdan } 955b413a546Sdrh 956b413a546Sdrh /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize 957bcf40a7fSdrh ** the cursor. These terms are not needed as hints for a pure range 958bcf40a7fSdrh ** scan (that has no == terms) so omit them. */ 959bcf40a7fSdrh if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ 960bcf40a7fSdrh for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} 961bcf40a7fSdrh if( j<pLoop->nLTerm ) continue; 962b413a546Sdrh } 963b413a546Sdrh 964b413a546Sdrh /* No subqueries or non-deterministic functions allowed */ 965bec2476aSdrh if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; 966b413a546Sdrh 967b413a546Sdrh /* For an index scan, make sure referenced columns are actually in 968b413a546Sdrh ** the index. */ 9692f2b0278Sdrh if( sHint.pIdx!=0 ){ 9702f2b0278Sdrh sWalker.eCode = 0; 9712f2b0278Sdrh sWalker.xExprCallback = codeCursorHintCheckExpr; 9722f2b0278Sdrh sqlite3WalkExpr(&sWalker, pTerm->pExpr); 9732f2b0278Sdrh if( sWalker.eCode ) continue; 9742f2b0278Sdrh } 975b413a546Sdrh 976b413a546Sdrh /* If we survive all prior tests, that means this term is worth hinting */ 977bec2476aSdrh pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); 978bec2476aSdrh } 979bec2476aSdrh if( pExpr!=0 ){ 980bec2476aSdrh sWalker.xExprCallback = codeCursorHintFixExpr; 981bec2476aSdrh sqlite3WalkExpr(&sWalker, pExpr); 9822f2b0278Sdrh sqlite3VdbeAddOp4(v, OP_CursorHint, 9832f2b0278Sdrh (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, 9842f2b0278Sdrh (const char*)pExpr, P4_EXPR); 985bec2476aSdrh } 986bec2476aSdrh } 987bec2476aSdrh #else 988b324cf75Sdan # define codeCursorHint(A,B,C,D) /* No-op */ 989bec2476aSdrh #endif /* SQLITE_ENABLE_CURSOR_HINTS */ 9906f82e85aSdrh 9916f82e85aSdrh /* 992de892d96Sdan ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains 993de892d96Sdan ** a rowid value just read from cursor iIdxCur, open on index pIdx. This 994de892d96Sdan ** function generates code to do a deferred seek of cursor iCur to the 995de892d96Sdan ** rowid stored in register iRowid. 996de892d96Sdan ** 997de892d96Sdan ** Normally, this is just: 998de892d96Sdan ** 999170ad68aSdrh ** OP_DeferredSeek $iCur $iRowid 1000de892d96Sdan ** 1001de892d96Sdan ** However, if the scan currently being coded is a branch of an OR-loop and 1002170ad68aSdrh ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek 1003de892d96Sdan ** is set to iIdxCur and P4 is set to point to an array of integers 1004de892d96Sdan ** containing one entry for each column of the table cursor iCur is open 1005de892d96Sdan ** on. For each table column, if the column is the i'th column of the 1006de892d96Sdan ** index, then the corresponding array entry is set to (i+1). If the column 1007de892d96Sdan ** does not appear in the index at all, the array entry is set to 0. 1008de892d96Sdan */ 1009de892d96Sdan static void codeDeferredSeek( 1010de892d96Sdan WhereInfo *pWInfo, /* Where clause context */ 1011de892d96Sdan Index *pIdx, /* Index scan is using */ 1012de892d96Sdan int iCur, /* Cursor for IPK b-tree */ 1013de892d96Sdan int iIdxCur /* Index cursor */ 1014de892d96Sdan ){ 1015de892d96Sdan Parse *pParse = pWInfo->pParse; /* Parse context */ 1016de892d96Sdan Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ 1017de892d96Sdan 1018de892d96Sdan assert( iIdxCur>0 ); 1019de892d96Sdan assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); 1020de892d96Sdan 1021170ad68aSdrh sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur); 1022ce943bc8Sdrh if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) 1023cddb6ba0Sdan && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) 1024de892d96Sdan ){ 1025de892d96Sdan int i; 1026de892d96Sdan Table *pTab = pIdx->pTable; 1027b1702026Sdrh int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); 1028de892d96Sdan if( ai ){ 1029b1702026Sdrh ai[0] = pTab->nCol; 1030de892d96Sdan for(i=0; i<pIdx->nColumn-1; i++){ 1031de892d96Sdan assert( pIdx->aiColumn[i]<pTab->nCol ); 1032b1702026Sdrh if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1; 1033de892d96Sdan } 1034de892d96Sdan sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); 1035de892d96Sdan } 1036de892d96Sdan } 1037de892d96Sdan } 1038de892d96Sdan 1039553168c7Sdan /* 1040553168c7Sdan ** If the expression passed as the second argument is a vector, generate 1041553168c7Sdan ** code to write the first nReg elements of the vector into an array 1042553168c7Sdan ** of registers starting with iReg. 1043553168c7Sdan ** 1044553168c7Sdan ** If the expression is not a vector, then nReg must be passed 1. In 1045553168c7Sdan ** this case, generate code to evaluate the expression and leave the 1046553168c7Sdan ** result in register iReg. 1047553168c7Sdan */ 104871c57db0Sdan static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ 104971c57db0Sdan assert( nReg>0 ); 1050d03024d8Sdan if( p && sqlite3ExprIsVector(p) ){ 1051f9b2e05cSdan #ifndef SQLITE_OMIT_SUBQUERY 1052f9b2e05cSdan if( (p->flags & EP_xIsSelect) ){ 1053f9b2e05cSdan Vdbe *v = pParse->pVdbe; 1054f9b2e05cSdan int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0); 1055f9b2e05cSdan sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); 1056f9b2e05cSdan }else 1057f9b2e05cSdan #endif 1058f9b2e05cSdan { 105971c57db0Sdan int i; 106071c57db0Sdan ExprList *pList = p->x.pList; 106171c57db0Sdan assert( nReg<=pList->nExpr ); 106271c57db0Sdan for(i=0; i<nReg; i++){ 106371c57db0Sdan sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); 106471c57db0Sdan } 106571c57db0Sdan } 106671c57db0Sdan }else{ 106771c57db0Sdan assert( nReg==1 ); 106871c57db0Sdan sqlite3ExprCode(pParse, p, iReg); 106971c57db0Sdan } 107071c57db0Sdan } 107171c57db0Sdan 1072eac5fc04Sdrh /* An instance of the IdxExprTrans object carries information about a 1073eac5fc04Sdrh ** mapping from an expression on table columns into a column in an index 1074eac5fc04Sdrh ** down through the Walker. 1075eac5fc04Sdrh */ 1076aca19e19Sdrh typedef struct IdxExprTrans { 1077aca19e19Sdrh Expr *pIdxExpr; /* The index expression */ 1078aca19e19Sdrh int iTabCur; /* The cursor of the corresponding table */ 1079aca19e19Sdrh int iIdxCur; /* The cursor for the index */ 1080aca19e19Sdrh int iIdxCol; /* The column for the index */ 1081aca19e19Sdrh } IdxExprTrans; 1082aca19e19Sdrh 1083eac5fc04Sdrh /* The walker node callback used to transform matching expressions into 1084eac5fc04Sdrh ** a reference to an index column for an index on an expression. 1085eac5fc04Sdrh ** 1086eac5fc04Sdrh ** If pExpr matches, then transform it into a reference to the index column 1087eac5fc04Sdrh ** that contains the value of pExpr. 1088eac5fc04Sdrh */ 1089aca19e19Sdrh static int whereIndexExprTransNode(Walker *p, Expr *pExpr){ 1090aca19e19Sdrh IdxExprTrans *pX = p->u.pIdxTrans; 10915aa550cfSdan if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){ 1092aca19e19Sdrh pExpr->op = TK_COLUMN; 1093aca19e19Sdrh pExpr->iTable = pX->iIdxCur; 1094aca19e19Sdrh pExpr->iColumn = pX->iIdxCol; 1095aca19e19Sdrh pExpr->pTab = 0; 1096aca19e19Sdrh return WRC_Prune; 1097aca19e19Sdrh }else{ 1098aca19e19Sdrh return WRC_Continue; 1099aca19e19Sdrh } 1100aca19e19Sdrh } 1101aca19e19Sdrh 1102aca19e19Sdrh /* 1103f49759bfSdrh ** For an indexes on expression X, locate every instance of expression X 1104f49759bfSdrh ** in pExpr and change that subexpression into a reference to the appropriate 1105f49759bfSdrh ** column of the index. 1106aca19e19Sdrh */ 1107aca19e19Sdrh static void whereIndexExprTrans( 1108aca19e19Sdrh Index *pIdx, /* The Index */ 1109aca19e19Sdrh int iTabCur, /* Cursor of the table that is being indexed */ 1110aca19e19Sdrh int iIdxCur, /* Cursor of the index itself */ 1111aca19e19Sdrh WhereInfo *pWInfo /* Transform expressions in this WHERE clause */ 1112aca19e19Sdrh ){ 1113aca19e19Sdrh int iIdxCol; /* Column number of the index */ 1114aca19e19Sdrh ExprList *aColExpr; /* Expressions that are indexed */ 1115aca19e19Sdrh Walker w; 1116aca19e19Sdrh IdxExprTrans x; 1117aca19e19Sdrh aColExpr = pIdx->aColExpr; 1118aca19e19Sdrh if( aColExpr==0 ) return; /* Not an index on expressions */ 1119aca19e19Sdrh memset(&w, 0, sizeof(w)); 1120aca19e19Sdrh w.xExprCallback = whereIndexExprTransNode; 1121aca19e19Sdrh w.u.pIdxTrans = &x; 1122aca19e19Sdrh x.iTabCur = iTabCur; 1123aca19e19Sdrh x.iIdxCur = iIdxCur; 1124aca19e19Sdrh for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){ 1125aca19e19Sdrh if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue; 1126aca19e19Sdrh assert( aColExpr->a[iIdxCol].pExpr!=0 ); 1127aca19e19Sdrh x.iIdxCol = iIdxCol; 1128aca19e19Sdrh x.pIdxExpr = aColExpr->a[iIdxCol].pExpr; 1129aca19e19Sdrh sqlite3WalkExpr(&w, pWInfo->pWhere); 1130aca19e19Sdrh sqlite3WalkExprList(&w, pWInfo->pOrderBy); 1131aca19e19Sdrh sqlite3WalkExprList(&w, pWInfo->pResultSet); 1132aca19e19Sdrh } 1133aca19e19Sdrh } 1134aca19e19Sdrh 1135de892d96Sdan /* 11366f82e85aSdrh ** Generate code for the start of the iLevel-th loop in the WHERE clause 11376f82e85aSdrh ** implementation described by pWInfo. 11386f82e85aSdrh */ 11396f82e85aSdrh Bitmask sqlite3WhereCodeOneLoopStart( 11406f82e85aSdrh WhereInfo *pWInfo, /* Complete information about the WHERE clause */ 11416f82e85aSdrh int iLevel, /* Which level of pWInfo->a[] should be coded */ 11426f82e85aSdrh Bitmask notReady /* Which tables are currently available */ 11436f82e85aSdrh ){ 11446f82e85aSdrh int j, k; /* Loop counters */ 11456f82e85aSdrh int iCur; /* The VDBE cursor for the table */ 11466f82e85aSdrh int addrNxt; /* Where to jump to continue with the next IN case */ 11476f82e85aSdrh int omitTable; /* True if we use the index only */ 11486f82e85aSdrh int bRev; /* True if we need to scan in reverse order */ 11496f82e85aSdrh WhereLevel *pLevel; /* The where level to be coded */ 11506f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object being coded */ 11516f82e85aSdrh WhereClause *pWC; /* Decomposition of the entire WHERE clause */ 11526f82e85aSdrh WhereTerm *pTerm; /* A WHERE clause term */ 11536f82e85aSdrh Parse *pParse; /* Parsing context */ 11546f82e85aSdrh sqlite3 *db; /* Database connection */ 11556f82e85aSdrh Vdbe *v; /* The prepared stmt under constructions */ 11566f82e85aSdrh struct SrcList_item *pTabItem; /* FROM clause term being coded */ 11576f82e85aSdrh int addrBrk; /* Jump here to break out of the loop */ 11583a3b420aSdrh int addrHalt; /* addrBrk for the outermost loop */ 11596f82e85aSdrh int addrCont; /* Jump here to continue with next cycle */ 11606f82e85aSdrh int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ 11616f82e85aSdrh int iReleaseReg = 0; /* Temp register to free before returning */ 11626f654a40Sdan Index *pIdx = 0; /* Index used by loop (if any) */ 1163ebc63013Sdan int iLoop; /* Iteration of constraint generator loop */ 11646f82e85aSdrh 11656f82e85aSdrh pParse = pWInfo->pParse; 11666f82e85aSdrh v = pParse->pVdbe; 11676f82e85aSdrh pWC = &pWInfo->sWC; 11686f82e85aSdrh db = pParse->db; 11696f82e85aSdrh pLevel = &pWInfo->a[iLevel]; 11706f82e85aSdrh pLoop = pLevel->pWLoop; 11716f82e85aSdrh pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 11726f82e85aSdrh iCur = pTabItem->iCursor; 11736f82e85aSdrh pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); 11746f82e85aSdrh bRev = (pWInfo->revMask>>iLevel)&1; 11756f82e85aSdrh omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 1176ce943bc8Sdrh && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; 11776f82e85aSdrh VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); 11786f82e85aSdrh 11796f82e85aSdrh /* Create labels for the "break" and "continue" instructions 11806f82e85aSdrh ** for the current loop. Jump to addrBrk to break out of a loop. 11816f82e85aSdrh ** Jump to cont to go immediately to the next iteration of the 11826f82e85aSdrh ** loop. 11836f82e85aSdrh ** 11846f82e85aSdrh ** When there is an IN operator, we also have a "addrNxt" label that 11856f82e85aSdrh ** means to continue with the next IN value combination. When 11866f82e85aSdrh ** there are no IN operators in the constraints, the "addrNxt" label 11876f82e85aSdrh ** is the same as "addrBrk". 11886f82e85aSdrh */ 11896f82e85aSdrh addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 11906f82e85aSdrh addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); 11916f82e85aSdrh 11926f82e85aSdrh /* If this is the right table of a LEFT OUTER JOIN, allocate and 11936f82e85aSdrh ** initialize a memory cell that records if this table matches any 11946f82e85aSdrh ** row of the left table of the join. 11956f82e85aSdrh */ 11968a48b9c0Sdrh if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ 11976f82e85aSdrh pLevel->iLeftJoin = ++pParse->nMem; 11986f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); 11996f82e85aSdrh VdbeComment((v, "init LEFT JOIN no-match flag")); 12006f82e85aSdrh } 12016f82e85aSdrh 12023a3b420aSdrh /* Compute a safe address to jump to if we discover that the table for 12033a3b420aSdrh ** this loop is empty and can never contribute content. */ 12043a3b420aSdrh for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){} 12053a3b420aSdrh addrHalt = pWInfo->a[j].addrBrk; 12063a3b420aSdrh 12076f82e85aSdrh /* Special case of a FROM clause subquery implemented as a co-routine */ 12088a48b9c0Sdrh if( pTabItem->fg.viaCoroutine ){ 12096f82e85aSdrh int regYield = pTabItem->regReturn; 12106f82e85aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); 12116f82e85aSdrh pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); 12126f82e85aSdrh VdbeCoverage(v); 12136f82e85aSdrh VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); 12146f82e85aSdrh pLevel->op = OP_Goto; 12156f82e85aSdrh }else 12166f82e85aSdrh 12176f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 12186f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 12196f82e85aSdrh /* Case 1: The table is a virtual-table. Use the VFilter and VNext 12206f82e85aSdrh ** to access the data. 12216f82e85aSdrh */ 12226f82e85aSdrh int iReg; /* P3 Value for OP_VFilter */ 12236f82e85aSdrh int addrNotFound; 12246f82e85aSdrh int nConstraint = pLoop->nLTerm; 1225dbc49161Sdrh int iIn; /* Counter for IN constraints */ 12266f82e85aSdrh 12276f82e85aSdrh sqlite3ExprCachePush(pParse); 12286f82e85aSdrh iReg = sqlite3GetTempRange(pParse, nConstraint+2); 12296f82e85aSdrh addrNotFound = pLevel->addrBrk; 12306f82e85aSdrh for(j=0; j<nConstraint; j++){ 12316f82e85aSdrh int iTarget = iReg+j+2; 12326f82e85aSdrh pTerm = pLoop->aLTerm[j]; 1233599d5764Sdrh if( NEVER(pTerm==0) ) continue; 12346f82e85aSdrh if( pTerm->eOperator & WO_IN ){ 12356f82e85aSdrh codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); 12366f82e85aSdrh addrNotFound = pLevel->addrNxt; 12376f82e85aSdrh }else{ 12386256c1c2Sdan Expr *pRight = pTerm->pExpr->pRight; 12396256c1c2Sdan codeExprOrVector(pParse, pRight, iTarget, 1); 12406256c1c2Sdan } 12416f82e85aSdrh } 12426f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); 12436f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); 12446f82e85aSdrh sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, 12456f82e85aSdrh pLoop->u.vtab.idxStr, 1246861b1307Sdrh pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); 12476f82e85aSdrh VdbeCoverage(v); 12486f82e85aSdrh pLoop->u.vtab.needFree = 0; 12496f82e85aSdrh pLevel->p1 = iCur; 1250354474adSdan pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; 12516f82e85aSdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v); 1252dbc49161Sdrh iIn = pLevel->u.in.nIn; 1253dbc49161Sdrh for(j=nConstraint-1; j>=0; j--){ 1254dbc49161Sdrh pTerm = pLoop->aLTerm[j]; 1255dbc49161Sdrh if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ 1256dbc49161Sdrh disableTerm(pLevel, pTerm); 1257dbc49161Sdrh }else if( (pTerm->eOperator & WO_IN)!=0 ){ 1258dbc49161Sdrh Expr *pCompare; /* The comparison operator */ 1259dbc49161Sdrh Expr *pRight; /* RHS of the comparison */ 1260dbc49161Sdrh VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ 1261dbc49161Sdrh 1262dbc49161Sdrh /* Reload the constraint value into reg[iReg+j+2]. The same value 1263dbc49161Sdrh ** was loaded into the same register prior to the OP_VFilter, but 1264dbc49161Sdrh ** the xFilter implementation might have changed the datatype or 1265dbc49161Sdrh ** encoding of the value in the register, so it *must* be reloaded. */ 1266dbc49161Sdrh assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); 1267fb826b8cSdrh if( !db->mallocFailed ){ 1268dbc49161Sdrh assert( iIn>0 ); 1269dbc49161Sdrh pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop); 1270dbc49161Sdrh assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); 1271dbc49161Sdrh assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); 1272dbc49161Sdrh assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); 1273dbc49161Sdrh testcase( pOp->opcode==OP_Rowid ); 1274dbc49161Sdrh sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); 1275dbc49161Sdrh } 1276dbc49161Sdrh 1277dbc49161Sdrh /* Generate code that will continue to the next row if 1278dbc49161Sdrh ** the IN constraint is not satisfied */ 1279abfd35eaSdrh pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0); 1280dbc49161Sdrh assert( pCompare!=0 || db->mallocFailed ); 1281dbc49161Sdrh if( pCompare ){ 1282dbc49161Sdrh pCompare->pLeft = pTerm->pExpr->pLeft; 1283dbc49161Sdrh pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); 1284237b2b71Sdrh if( pRight ){ 1285237b2b71Sdrh pRight->iTable = iReg+j+2; 1286dbc49161Sdrh sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); 1287237b2b71Sdrh } 1288dbc49161Sdrh pCompare->pLeft = 0; 1289dbc49161Sdrh sqlite3ExprDelete(db, pCompare); 1290dbc49161Sdrh } 1291dbc49161Sdrh } 1292dbc49161Sdrh } 1293ba26faa3Sdrh /* These registers need to be preserved in case there is an IN operator 1294ba26faa3Sdrh ** loop. So we could deallocate the registers here (and potentially 1295ba26faa3Sdrh ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems 1296ba26faa3Sdrh ** simpler and safer to simply not reuse the registers. 1297ba26faa3Sdrh ** 1298ba26faa3Sdrh ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); 1299ba26faa3Sdrh */ 13006f82e85aSdrh sqlite3ExprCachePop(pParse); 13016f82e85aSdrh }else 13026f82e85aSdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */ 13036f82e85aSdrh 13046f82e85aSdrh if( (pLoop->wsFlags & WHERE_IPK)!=0 13056f82e85aSdrh && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 13066f82e85aSdrh ){ 13076f82e85aSdrh /* Case 2: We can directly reference a single row using an 13086f82e85aSdrh ** equality comparison against the ROWID field. Or 13096f82e85aSdrh ** we reference multiple rows using a "rowid IN (...)" 13106f82e85aSdrh ** construct. 13116f82e85aSdrh */ 13126f82e85aSdrh assert( pLoop->u.btree.nEq==1 ); 13136f82e85aSdrh pTerm = pLoop->aLTerm[0]; 13146f82e85aSdrh assert( pTerm!=0 ); 13156f82e85aSdrh assert( pTerm->pExpr!=0 ); 13166f82e85aSdrh assert( omitTable==0 ); 13176f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 13186f82e85aSdrh iReleaseReg = ++pParse->nMem; 13196f82e85aSdrh iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); 13206f82e85aSdrh if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); 13216f82e85aSdrh addrNxt = pLevel->addrNxt; 1322eeb9565aSdrh sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); 13236f82e85aSdrh VdbeCoverage(v); 13246f82e85aSdrh sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); 13256f82e85aSdrh sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 13266f82e85aSdrh VdbeComment((v, "pk")); 13276f82e85aSdrh pLevel->op = OP_Noop; 13286f82e85aSdrh }else if( (pLoop->wsFlags & WHERE_IPK)!=0 13296f82e85aSdrh && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 13306f82e85aSdrh ){ 13316f82e85aSdrh /* Case 3: We have an inequality comparison against the ROWID field. 13326f82e85aSdrh */ 13336f82e85aSdrh int testOp = OP_Noop; 13346f82e85aSdrh int start; 13356f82e85aSdrh int memEndValue = 0; 13366f82e85aSdrh WhereTerm *pStart, *pEnd; 13376f82e85aSdrh 13386f82e85aSdrh assert( omitTable==0 ); 13396f82e85aSdrh j = 0; 13406f82e85aSdrh pStart = pEnd = 0; 13416f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; 13426f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; 13436f82e85aSdrh assert( pStart!=0 || pEnd!=0 ); 13446f82e85aSdrh if( bRev ){ 13456f82e85aSdrh pTerm = pStart; 13466f82e85aSdrh pStart = pEnd; 13476f82e85aSdrh pEnd = pTerm; 13486f82e85aSdrh } 1349b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); 13506f82e85aSdrh if( pStart ){ 13516f82e85aSdrh Expr *pX; /* The expression that defines the start bound */ 13526f82e85aSdrh int r1, rTemp; /* Registers for holding the start boundary */ 135319ff12ddSdan int op; /* Cursor seek operation */ 13546f82e85aSdrh 13556f82e85aSdrh /* The following constant maps TK_xx codes into corresponding 13566f82e85aSdrh ** seek opcodes. It depends on a particular ordering of TK_xx 13576f82e85aSdrh */ 13586f82e85aSdrh const u8 aMoveOp[] = { 13596f82e85aSdrh /* TK_GT */ OP_SeekGT, 13606f82e85aSdrh /* TK_LE */ OP_SeekLE, 13616f82e85aSdrh /* TK_LT */ OP_SeekLT, 13626f82e85aSdrh /* TK_GE */ OP_SeekGE 13636f82e85aSdrh }; 13646f82e85aSdrh assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ 13656f82e85aSdrh assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ 13666f82e85aSdrh assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ 13676f82e85aSdrh 13686f82e85aSdrh assert( (pStart->wtFlags & TERM_VNULL)==0 ); 13696f82e85aSdrh testcase( pStart->wtFlags & TERM_VIRTUAL ); 13706f82e85aSdrh pX = pStart->pExpr; 13716f82e85aSdrh assert( pX!=0 ); 13726f82e85aSdrh testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ 1373625015e0Sdan if( sqlite3ExprIsVector(pX->pRight) ){ 137419ff12ddSdan r1 = rTemp = sqlite3GetTempReg(pParse); 137519ff12ddSdan codeExprOrVector(pParse, pX->pRight, r1, 1); 137619ff12ddSdan op = aMoveOp[(pX->op - TK_GT) | 0x0001]; 137719ff12ddSdan }else{ 13786f82e85aSdrh r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); 137919ff12ddSdan disableTerm(pLevel, pStart); 138019ff12ddSdan op = aMoveOp[(pX->op - TK_GT)]; 138119ff12ddSdan } 138219ff12ddSdan sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); 13836f82e85aSdrh VdbeComment((v, "pk")); 13846f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GT); 13856f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LE); 13866f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LT); 13876f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GE); 13886f82e85aSdrh sqlite3ExprCacheAffinityChange(pParse, r1, 1); 13896f82e85aSdrh sqlite3ReleaseTempReg(pParse, rTemp); 13906f82e85aSdrh }else{ 13913a3b420aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt); 13926f82e85aSdrh VdbeCoverageIf(v, bRev==0); 13936f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 13946f82e85aSdrh } 13956f82e85aSdrh if( pEnd ){ 13966f82e85aSdrh Expr *pX; 13976f82e85aSdrh pX = pEnd->pExpr; 13986f82e85aSdrh assert( pX!=0 ); 13996f82e85aSdrh assert( (pEnd->wtFlags & TERM_VNULL)==0 ); 14006f82e85aSdrh testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ 14016f82e85aSdrh testcase( pEnd->wtFlags & TERM_VIRTUAL ); 14026f82e85aSdrh memEndValue = ++pParse->nMem; 140319ff12ddSdan codeExprOrVector(pParse, pX->pRight, memEndValue, 1); 1404625015e0Sdan if( 0==sqlite3ExprIsVector(pX->pRight) 1405625015e0Sdan && (pX->op==TK_LT || pX->op==TK_GT) 1406625015e0Sdan ){ 14076f82e85aSdrh testOp = bRev ? OP_Le : OP_Ge; 14086f82e85aSdrh }else{ 14096f82e85aSdrh testOp = bRev ? OP_Lt : OP_Gt; 14106f82e85aSdrh } 1411553168c7Sdan if( 0==sqlite3ExprIsVector(pX->pRight) ){ 14126f82e85aSdrh disableTerm(pLevel, pEnd); 14136f82e85aSdrh } 1414553168c7Sdan } 14156f82e85aSdrh start = sqlite3VdbeCurrentAddr(v); 14166f82e85aSdrh pLevel->op = bRev ? OP_Prev : OP_Next; 14176f82e85aSdrh pLevel->p1 = iCur; 14186f82e85aSdrh pLevel->p2 = start; 14196f82e85aSdrh assert( pLevel->p5==0 ); 14206f82e85aSdrh if( testOp!=OP_Noop ){ 14216f82e85aSdrh iRowidReg = ++pParse->nMem; 14226f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); 14236f82e85aSdrh sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 14246f82e85aSdrh sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); 14256f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Le); 14266f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Lt); 14276f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Ge); 14286f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Gt); 14296f82e85aSdrh sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); 14306f82e85aSdrh } 14316f82e85aSdrh }else if( pLoop->wsFlags & WHERE_INDEXED ){ 14326f82e85aSdrh /* Case 4: A scan using an index. 14336f82e85aSdrh ** 14346f82e85aSdrh ** The WHERE clause may contain zero or more equality 14356f82e85aSdrh ** terms ("==" or "IN" operators) that refer to the N 14366f82e85aSdrh ** left-most columns of the index. It may also contain 14376f82e85aSdrh ** inequality constraints (>, <, >= or <=) on the indexed 14386f82e85aSdrh ** column that immediately follows the N equalities. Only 14396f82e85aSdrh ** the right-most column can be an inequality - the rest must 14406f82e85aSdrh ** use the "==" and "IN" operators. For example, if the 14416f82e85aSdrh ** index is on (x,y,z), then the following clauses are all 14426f82e85aSdrh ** optimized: 14436f82e85aSdrh ** 14446f82e85aSdrh ** x=5 14456f82e85aSdrh ** x=5 AND y=10 14466f82e85aSdrh ** x=5 AND y<10 14476f82e85aSdrh ** x=5 AND y>5 AND y<10 14486f82e85aSdrh ** x=5 AND y=5 AND z<=10 14496f82e85aSdrh ** 14506f82e85aSdrh ** The z<10 term of the following cannot be used, only 14516f82e85aSdrh ** the x=5 term: 14526f82e85aSdrh ** 14536f82e85aSdrh ** x=5 AND z<10 14546f82e85aSdrh ** 14556f82e85aSdrh ** N may be zero if there are inequality constraints. 14566f82e85aSdrh ** If there are no inequality constraints, then N is at 14576f82e85aSdrh ** least one. 14586f82e85aSdrh ** 14596f82e85aSdrh ** This case is also used when there are no WHERE clause 14606f82e85aSdrh ** constraints but an index is selected anyway, in order 14616f82e85aSdrh ** to force the output order to conform to an ORDER BY. 14626f82e85aSdrh */ 14636f82e85aSdrh static const u8 aStartOp[] = { 14646f82e85aSdrh 0, 14656f82e85aSdrh 0, 14666f82e85aSdrh OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ 14676f82e85aSdrh OP_Last, /* 3: (!start_constraints && startEq && bRev) */ 14686f82e85aSdrh OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ 14696f82e85aSdrh OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ 14706f82e85aSdrh OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ 14716f82e85aSdrh OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ 14726f82e85aSdrh }; 14736f82e85aSdrh static const u8 aEndOp[] = { 14746f82e85aSdrh OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ 14756f82e85aSdrh OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ 14766f82e85aSdrh OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ 14776f82e85aSdrh OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ 14786f82e85aSdrh }; 14796f82e85aSdrh u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ 148071c57db0Sdan u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ 148171c57db0Sdan u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ 14826f82e85aSdrh int regBase; /* Base register holding constraint values */ 14836f82e85aSdrh WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ 14846f82e85aSdrh WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ 14856f82e85aSdrh int startEq; /* True if range start uses ==, >= or <= */ 14866f82e85aSdrh int endEq; /* True if range end uses ==, >= or <= */ 14876f82e85aSdrh int start_constraints; /* Start of range is constrained */ 14886f82e85aSdrh int nConstraint; /* Number of constraint terms */ 14896f82e85aSdrh int iIdxCur; /* The VDBE cursor for the index */ 14906f82e85aSdrh int nExtraReg = 0; /* Number of extra registers needed */ 14916f82e85aSdrh int op; /* Instruction opcode */ 14926f82e85aSdrh char *zStartAff; /* Affinity for start of range constraint */ 1493b7ca2177Sdan char *zEndAff = 0; /* Affinity for end of range constraint */ 14946f82e85aSdrh u8 bSeekPastNull = 0; /* True to seek past initial nulls */ 14956f82e85aSdrh u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ 14966f82e85aSdrh 14976f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 14986f82e85aSdrh iIdxCur = pLevel->iIdxCur; 14996f82e85aSdrh assert( nEq>=pLoop->nSkip ); 15006f82e85aSdrh 15016f82e85aSdrh /* If this loop satisfies a sort order (pOrderBy) request that 15026f82e85aSdrh ** was passed to this function to implement a "SELECT min(x) ..." 15036f82e85aSdrh ** query, then the caller will only allow the loop to run for 15046f82e85aSdrh ** a single iteration. This means that the first row returned 15056f82e85aSdrh ** should not have a NULL value stored in 'x'. If column 'x' is 15066f82e85aSdrh ** the first one after the nEq equality constraints in the index, 15076f82e85aSdrh ** this requires some special handling. 15086f82e85aSdrh */ 15096f82e85aSdrh assert( pWInfo->pOrderBy==0 15106f82e85aSdrh || pWInfo->pOrderBy->nExpr==1 15116f82e85aSdrh || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); 15126f82e85aSdrh if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 15136f82e85aSdrh && pWInfo->nOBSat>0 15146f82e85aSdrh && (pIdx->nKeyCol>nEq) 15156f82e85aSdrh ){ 15166f82e85aSdrh assert( pLoop->nSkip==0 ); 15176f82e85aSdrh bSeekPastNull = 1; 15186f82e85aSdrh nExtraReg = 1; 15196f82e85aSdrh } 15206f82e85aSdrh 15216f82e85aSdrh /* Find any inequality constraint terms for the start and end 15226f82e85aSdrh ** of the range. 15236f82e85aSdrh */ 15246f82e85aSdrh j = nEq; 15256f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ 15266f82e85aSdrh pRangeStart = pLoop->aLTerm[j++]; 152771c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); 15286f82e85aSdrh /* Like optimization range constraints always occur in pairs */ 15296f82e85aSdrh assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 15306f82e85aSdrh (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); 15316f82e85aSdrh } 15326f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ 15336f82e85aSdrh pRangeEnd = pLoop->aLTerm[j++]; 153471c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); 153541d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 15366f82e85aSdrh if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ 15376f82e85aSdrh assert( pRangeStart!=0 ); /* LIKE opt constraints */ 15386f82e85aSdrh assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ 153944aebff2Sdrh pLevel->iLikeRepCntr = (u32)++pParse->nMem; 154044aebff2Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); 15416f82e85aSdrh VdbeComment((v, "LIKE loop counter")); 15426f82e85aSdrh pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); 154344aebff2Sdrh /* iLikeRepCntr actually stores 2x the counter register number. The 154444aebff2Sdrh ** bottom bit indicates whether the search order is ASC or DESC. */ 154544aebff2Sdrh testcase( bRev ); 154644aebff2Sdrh testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); 154744aebff2Sdrh assert( (bRev & ~1)==0 ); 154844aebff2Sdrh pLevel->iLikeRepCntr <<=1; 154944aebff2Sdrh pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); 15506f82e85aSdrh } 155141d2e66eSdrh #endif 155248590fcbSdrh if( pRangeStart==0 ){ 155348590fcbSdrh j = pIdx->aiColumn[nEq]; 155448590fcbSdrh if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ 15556f82e85aSdrh bSeekPastNull = 1; 15566f82e85aSdrh } 15576f82e85aSdrh } 155848590fcbSdrh } 15596f82e85aSdrh assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); 15606f82e85aSdrh 15616f82e85aSdrh /* If we are doing a reverse order scan on an ascending index, or 15626f82e85aSdrh ** a forward order scan on a descending index, interchange the 15636f82e85aSdrh ** start and end terms (pRangeStart and pRangeEnd). 15646f82e85aSdrh */ 15656f82e85aSdrh if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) 15666f82e85aSdrh || (bRev && pIdx->nKeyCol==nEq) 15676f82e85aSdrh ){ 15686f82e85aSdrh SWAP(WhereTerm *, pRangeEnd, pRangeStart); 15696f82e85aSdrh SWAP(u8, bSeekPastNull, bStopAtNull); 157071c57db0Sdan SWAP(u8, nBtm, nTop); 15716f82e85aSdrh } 15726f82e85aSdrh 1573bcf40a7fSdrh /* Generate code to evaluate all constraint terms using == or IN 1574bcf40a7fSdrh ** and store the values of those terms in an array of registers 1575bcf40a7fSdrh ** starting at regBase. 1576bcf40a7fSdrh */ 1577b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); 1578bcf40a7fSdrh regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); 1579bcf40a7fSdrh assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); 1580b7ca2177Sdan if( zStartAff && nTop ){ 1581b7ca2177Sdan zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); 1582b7ca2177Sdan } 1583bcf40a7fSdrh addrNxt = pLevel->addrNxt; 1584bcf40a7fSdrh 15856f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); 15866f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); 15876f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); 15886f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); 15896f82e85aSdrh startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); 15906f82e85aSdrh endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); 15916f82e85aSdrh start_constraints = pRangeStart || nEq>0; 15926f82e85aSdrh 15936f82e85aSdrh /* Seek the index cursor to the start of the range. */ 15946f82e85aSdrh nConstraint = nEq; 15956f82e85aSdrh if( pRangeStart ){ 15966f82e85aSdrh Expr *pRight = pRangeStart->pExpr->pRight; 159771c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); 15986f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); 15996f82e85aSdrh if( (pRangeStart->wtFlags & TERM_VNULL)==0 16006f82e85aSdrh && sqlite3ExprCanBeNull(pRight) 16016f82e85aSdrh ){ 16026f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 16036f82e85aSdrh VdbeCoverage(v); 16046f82e85aSdrh } 16056f82e85aSdrh if( zStartAff ){ 1606e3c6b61cSdrh updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); 16076f82e85aSdrh } 160871c57db0Sdan nConstraint += nBtm; 16096f82e85aSdrh testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); 1610625015e0Sdan if( sqlite3ExprIsVector(pRight)==0 ){ 161171c57db0Sdan disableTerm(pLevel, pRangeStart); 161271c57db0Sdan }else{ 161371c57db0Sdan startEq = 1; 161471c57db0Sdan } 1615426f4ab0Sdrh bSeekPastNull = 0; 16166f82e85aSdrh }else if( bSeekPastNull ){ 16176f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 16186f82e85aSdrh nConstraint++; 16196f82e85aSdrh startEq = 0; 16206f82e85aSdrh start_constraints = 1; 16216f82e85aSdrh } 16226f82e85aSdrh codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); 16230bf2ad6aSdrh if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ 16240bf2ad6aSdrh /* The skip-scan logic inside the call to codeAllEqualityConstraints() 16250bf2ad6aSdrh ** above has already left the cursor sitting on the correct row, 16260bf2ad6aSdrh ** so no further seeking is needed */ 16270bf2ad6aSdrh }else{ 16286f82e85aSdrh op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; 16296f82e85aSdrh assert( op!=0 ); 16306f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 16316f82e85aSdrh VdbeCoverage(v); 16326f82e85aSdrh VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 16336f82e85aSdrh VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 16346f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); 16356f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 16366f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 16376f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); 1638a6d2f8ebSdrh } 16396f82e85aSdrh 16406f82e85aSdrh /* Load the value for the inequality constraint at the end of the 16416f82e85aSdrh ** range (if any). 16426f82e85aSdrh */ 16436f82e85aSdrh nConstraint = nEq; 16446f82e85aSdrh if( pRangeEnd ){ 16456f82e85aSdrh Expr *pRight = pRangeEnd->pExpr->pRight; 16466f82e85aSdrh sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); 164771c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nTop); 16486f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); 16496f82e85aSdrh if( (pRangeEnd->wtFlags & TERM_VNULL)==0 16506f82e85aSdrh && sqlite3ExprCanBeNull(pRight) 16516f82e85aSdrh ){ 16526f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 16536f82e85aSdrh VdbeCoverage(v); 16546f82e85aSdrh } 16550c36fca0Sdrh if( zEndAff ){ 1656e3c6b61cSdrh updateRangeAffinityStr(pRight, nTop, zEndAff); 1657b7ca2177Sdan codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); 16580c36fca0Sdrh }else{ 16590c36fca0Sdrh assert( pParse->db->mallocFailed ); 16600c36fca0Sdrh } 166171c57db0Sdan nConstraint += nTop; 16626f82e85aSdrh testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); 166371c57db0Sdan 1664625015e0Sdan if( sqlite3ExprIsVector(pRight)==0 ){ 166571c57db0Sdan disableTerm(pLevel, pRangeEnd); 166671c57db0Sdan }else{ 166771c57db0Sdan endEq = 1; 166871c57db0Sdan } 16696f82e85aSdrh }else if( bStopAtNull ){ 16706f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 16716f82e85aSdrh endEq = 0; 16726f82e85aSdrh nConstraint++; 16736f82e85aSdrh } 16746f82e85aSdrh sqlite3DbFree(db, zStartAff); 1675b7ca2177Sdan sqlite3DbFree(db, zEndAff); 16766f82e85aSdrh 16776f82e85aSdrh /* Top of the loop body */ 16786f82e85aSdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v); 16796f82e85aSdrh 16806f82e85aSdrh /* Check if the index cursor is past the end of the range. */ 16816f82e85aSdrh if( nConstraint ){ 16826f82e85aSdrh op = aEndOp[bRev*2 + endEq]; 16836f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 16846f82e85aSdrh testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 16856f82e85aSdrh testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 16866f82e85aSdrh testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 16876f82e85aSdrh testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 16886f82e85aSdrh } 16896f82e85aSdrh 16906f82e85aSdrh /* Seek the table cursor, if required */ 16916f82e85aSdrh if( omitTable ){ 16926f82e85aSdrh /* pIdx is a covering index. No need to access the main table. */ 16936f82e85aSdrh }else if( HasRowid(pIdx->pTable) ){ 1694f64ece14Sdan if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || ( 1695f64ece14Sdan (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE) 1696f64ece14Sdan && (pWInfo->eOnePass==ONEPASS_SINGLE) 1697f64ece14Sdan )){ 16986f82e85aSdrh iRowidReg = ++pParse->nMem; 16996f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); 17006f82e85aSdrh sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 1701c6157e19Sdan sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); 170266336f37Sdrh VdbeCoverage(v); 1703c6157e19Sdan }else{ 1704784c1b93Sdrh codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); 1705c6157e19Sdan } 17066f82e85aSdrh }else if( iCur!=iIdxCur ){ 17076f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); 17086f82e85aSdrh iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); 17096f82e85aSdrh for(j=0; j<pPk->nKeyCol; j++){ 17106f82e85aSdrh k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); 17116f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); 17126f82e85aSdrh } 17136f82e85aSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, 17146f82e85aSdrh iRowidReg, pPk->nKeyCol); VdbeCoverage(v); 17156f82e85aSdrh } 17166f82e85aSdrh 1717eac5fc04Sdrh /* If pIdx is an index on one or more expressions, then look through 1718eac5fc04Sdrh ** all the expressions in pWInfo and try to transform matching expressions 1719eac5fc04Sdrh ** into reference to index columns. 1720eac5fc04Sdrh */ 1721aca19e19Sdrh whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo); 1722eac5fc04Sdrh 1723aca19e19Sdrh 172471c57db0Sdan /* Record the instruction used to terminate the loop. */ 17256f82e85aSdrh if( pLoop->wsFlags & WHERE_ONEROW ){ 17266f82e85aSdrh pLevel->op = OP_Noop; 17276f82e85aSdrh }else if( bRev ){ 17286f82e85aSdrh pLevel->op = OP_Prev; 17296f82e85aSdrh }else{ 17306f82e85aSdrh pLevel->op = OP_Next; 17316f82e85aSdrh } 17326f82e85aSdrh pLevel->p1 = iIdxCur; 17336f82e85aSdrh pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; 17346f82e85aSdrh if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ 17356f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 17366f82e85aSdrh }else{ 17376f82e85aSdrh assert( pLevel->p5==0 ); 17386f82e85aSdrh } 17396f654a40Sdan if( omitTable ) pIdx = 0; 17406f82e85aSdrh }else 17416f82e85aSdrh 17426f82e85aSdrh #ifndef SQLITE_OMIT_OR_OPTIMIZATION 17436f82e85aSdrh if( pLoop->wsFlags & WHERE_MULTI_OR ){ 17446f82e85aSdrh /* Case 5: Two or more separately indexed terms connected by OR 17456f82e85aSdrh ** 17466f82e85aSdrh ** Example: 17476f82e85aSdrh ** 17486f82e85aSdrh ** CREATE TABLE t1(a,b,c,d); 17496f82e85aSdrh ** CREATE INDEX i1 ON t1(a); 17506f82e85aSdrh ** CREATE INDEX i2 ON t1(b); 17516f82e85aSdrh ** CREATE INDEX i3 ON t1(c); 17526f82e85aSdrh ** 17536f82e85aSdrh ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) 17546f82e85aSdrh ** 17556f82e85aSdrh ** In the example, there are three indexed terms connected by OR. 17566f82e85aSdrh ** The top of the loop looks like this: 17576f82e85aSdrh ** 17586f82e85aSdrh ** Null 1 # Zero the rowset in reg 1 17596f82e85aSdrh ** 17606f82e85aSdrh ** Then, for each indexed term, the following. The arguments to 17616f82e85aSdrh ** RowSetTest are such that the rowid of the current row is inserted 17626f82e85aSdrh ** into the RowSet. If it is already present, control skips the 17636f82e85aSdrh ** Gosub opcode and jumps straight to the code generated by WhereEnd(). 17646f82e85aSdrh ** 17656f82e85aSdrh ** sqlite3WhereBegin(<term>) 17666f82e85aSdrh ** RowSetTest # Insert rowid into rowset 17676f82e85aSdrh ** Gosub 2 A 17686f82e85aSdrh ** sqlite3WhereEnd() 17696f82e85aSdrh ** 17706f82e85aSdrh ** Following the above, code to terminate the loop. Label A, the target 17716f82e85aSdrh ** of the Gosub above, jumps to the instruction right after the Goto. 17726f82e85aSdrh ** 17736f82e85aSdrh ** Null 1 # Zero the rowset in reg 1 17746f82e85aSdrh ** Goto B # The loop is finished. 17756f82e85aSdrh ** 17766f82e85aSdrh ** A: <loop body> # Return data, whatever. 17776f82e85aSdrh ** 17786f82e85aSdrh ** Return 2 # Jump back to the Gosub 17796f82e85aSdrh ** 17806f82e85aSdrh ** B: <after the loop> 17816f82e85aSdrh ** 17826f82e85aSdrh ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then 17836f82e85aSdrh ** use an ephemeral index instead of a RowSet to record the primary 17846f82e85aSdrh ** keys of the rows we have already seen. 17856f82e85aSdrh ** 17866f82e85aSdrh */ 17876f82e85aSdrh WhereClause *pOrWc; /* The OR-clause broken out into subterms */ 17886f82e85aSdrh SrcList *pOrTab; /* Shortened table list or OR-clause generation */ 17896f82e85aSdrh Index *pCov = 0; /* Potential covering index (or NULL) */ 17906f82e85aSdrh int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ 17916f82e85aSdrh 17926f82e85aSdrh int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ 17936f82e85aSdrh int regRowset = 0; /* Register for RowSet object */ 17946f82e85aSdrh int regRowid = 0; /* Register holding rowid */ 17956f82e85aSdrh int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ 17966f82e85aSdrh int iRetInit; /* Address of regReturn init */ 17976f82e85aSdrh int untestedTerms = 0; /* Some terms not completely tested */ 17986f82e85aSdrh int ii; /* Loop counter */ 17996f82e85aSdrh u16 wctrlFlags; /* Flags for sub-WHERE clause */ 18006f82e85aSdrh Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ 18016f82e85aSdrh Table *pTab = pTabItem->pTab; 18026f82e85aSdrh 18036f82e85aSdrh pTerm = pLoop->aLTerm[0]; 18046f82e85aSdrh assert( pTerm!=0 ); 18056f82e85aSdrh assert( pTerm->eOperator & WO_OR ); 18066f82e85aSdrh assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); 18076f82e85aSdrh pOrWc = &pTerm->u.pOrInfo->wc; 18086f82e85aSdrh pLevel->op = OP_Return; 18096f82e85aSdrh pLevel->p1 = regReturn; 18106f82e85aSdrh 18116f82e85aSdrh /* Set up a new SrcList in pOrTab containing the table being scanned 18126f82e85aSdrh ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. 18136f82e85aSdrh ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). 18146f82e85aSdrh */ 18156f82e85aSdrh if( pWInfo->nLevel>1 ){ 18166f82e85aSdrh int nNotReady; /* The number of notReady tables */ 18176f82e85aSdrh struct SrcList_item *origSrc; /* Original list of tables */ 18186f82e85aSdrh nNotReady = pWInfo->nLevel - iLevel - 1; 18196f82e85aSdrh pOrTab = sqlite3StackAllocRaw(db, 18206f82e85aSdrh sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); 18216f82e85aSdrh if( pOrTab==0 ) return notReady; 18226f82e85aSdrh pOrTab->nAlloc = (u8)(nNotReady + 1); 18236f82e85aSdrh pOrTab->nSrc = pOrTab->nAlloc; 18246f82e85aSdrh memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); 18256f82e85aSdrh origSrc = pWInfo->pTabList->a; 18266f82e85aSdrh for(k=1; k<=nNotReady; k++){ 18276f82e85aSdrh memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); 18286f82e85aSdrh } 18296f82e85aSdrh }else{ 18306f82e85aSdrh pOrTab = pWInfo->pTabList; 18316f82e85aSdrh } 18326f82e85aSdrh 18336f82e85aSdrh /* Initialize the rowset register to contain NULL. An SQL NULL is 18346f82e85aSdrh ** equivalent to an empty rowset. Or, create an ephemeral index 18356f82e85aSdrh ** capable of holding primary keys in the case of a WITHOUT ROWID. 18366f82e85aSdrh ** 18376f82e85aSdrh ** Also initialize regReturn to contain the address of the instruction 18386f82e85aSdrh ** immediately following the OP_Return at the bottom of the loop. This 18396f82e85aSdrh ** is required in a few obscure LEFT JOIN cases where control jumps 18406f82e85aSdrh ** over the top of the loop into the body of it. In this case the 18416f82e85aSdrh ** correct response for the end-of-loop code (the OP_Return) is to 18426f82e85aSdrh ** fall through to the next instruction, just as an OP_Next does if 18436f82e85aSdrh ** called on an uninitialized cursor. 18446f82e85aSdrh */ 18456f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 18466f82e85aSdrh if( HasRowid(pTab) ){ 18476f82e85aSdrh regRowset = ++pParse->nMem; 18486f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); 18496f82e85aSdrh }else{ 18506f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 18516f82e85aSdrh regRowset = pParse->nTab++; 18526f82e85aSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); 18536f82e85aSdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk); 18546f82e85aSdrh } 18556f82e85aSdrh regRowid = ++pParse->nMem; 18566f82e85aSdrh } 18576f82e85aSdrh iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); 18586f82e85aSdrh 18596f82e85aSdrh /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y 18606f82e85aSdrh ** Then for every term xN, evaluate as the subexpression: xN AND z 18616f82e85aSdrh ** That way, terms in y that are factored into the disjunction will 18626f82e85aSdrh ** be picked up by the recursive calls to sqlite3WhereBegin() below. 18636f82e85aSdrh ** 18646f82e85aSdrh ** Actually, each subexpression is converted to "xN AND w" where w is 18656f82e85aSdrh ** the "interesting" terms of z - terms that did not originate in the 18666f82e85aSdrh ** ON or USING clause of a LEFT JOIN, and terms that are usable as 18676f82e85aSdrh ** indices. 18686f82e85aSdrh ** 18696f82e85aSdrh ** This optimization also only applies if the (x1 OR x2 OR ...) term 18706f82e85aSdrh ** is not contained in the ON clause of a LEFT JOIN. 18716f82e85aSdrh ** See ticket http://www.sqlite.org/src/info/f2369304e4 18726f82e85aSdrh */ 18736f82e85aSdrh if( pWC->nTerm>1 ){ 18746f82e85aSdrh int iTerm; 18756f82e85aSdrh for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ 18766f82e85aSdrh Expr *pExpr = pWC->a[iTerm].pExpr; 18776f82e85aSdrh if( &pWC->a[iTerm] == pTerm ) continue; 18786f82e85aSdrh if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; 18793b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); 18803b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); 18813b83f0cdSdrh if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; 18826f82e85aSdrh if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; 18836f82e85aSdrh testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); 18846f82e85aSdrh pExpr = sqlite3ExprDup(db, pExpr, 0); 18856f82e85aSdrh pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); 18866f82e85aSdrh } 18876f82e85aSdrh if( pAndExpr ){ 1888abfd35eaSdrh pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr); 18896f82e85aSdrh } 18906f82e85aSdrh } 18916f82e85aSdrh 18926f82e85aSdrh /* Run a separate WHERE clause for each term of the OR clause. After 18936f82e85aSdrh ** eliminating duplicates from other WHERE clauses, the action for each 18946f82e85aSdrh ** sub-WHERE clause is to to invoke the main loop body as a subroutine. 18956f82e85aSdrh */ 1896ce943bc8Sdrh wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); 18976f82e85aSdrh for(ii=0; ii<pOrWc->nTerm; ii++){ 18986f82e85aSdrh WhereTerm *pOrTerm = &pOrWc->a[ii]; 18996f82e85aSdrh if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ 19006f82e85aSdrh WhereInfo *pSubWInfo; /* Info for single OR-term scan */ 19016f82e85aSdrh Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ 1902728e0f91Sdrh int jmp1 = 0; /* Address of jump operation */ 19036f82e85aSdrh if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ 19046f82e85aSdrh pAndExpr->pLeft = pOrExpr; 19056f82e85aSdrh pOrExpr = pAndExpr; 19066f82e85aSdrh } 19076f82e85aSdrh /* Loop through table entries that match term pOrTerm. */ 19086f82e85aSdrh WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); 19096f82e85aSdrh pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 19106f82e85aSdrh wctrlFlags, iCovCur); 19116f82e85aSdrh assert( pSubWInfo || pParse->nErr || db->mallocFailed ); 19126f82e85aSdrh if( pSubWInfo ){ 19136f82e85aSdrh WhereLoop *pSubLoop; 19146f82e85aSdrh int addrExplain = sqlite3WhereExplainOneScan( 19156f82e85aSdrh pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 19166f82e85aSdrh ); 19176f82e85aSdrh sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); 19186f82e85aSdrh 19196f82e85aSdrh /* This is the sub-WHERE clause body. First skip over 19206f82e85aSdrh ** duplicate rows from prior sub-WHERE clauses, and record the 19216f82e85aSdrh ** rowid (or PRIMARY KEY) for the current row so that the same 19226f82e85aSdrh ** row will be skipped in subsequent sub-WHERE clauses. 19236f82e85aSdrh */ 19246f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 19256f82e85aSdrh int r; 19266f82e85aSdrh int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); 19276f82e85aSdrh if( HasRowid(pTab) ){ 19286f82e85aSdrh r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); 1929728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, 1930728e0f91Sdrh r,iSet); 19316f82e85aSdrh VdbeCoverage(v); 19326f82e85aSdrh }else{ 19336f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 19346f82e85aSdrh int nPk = pPk->nKeyCol; 19356f82e85aSdrh int iPk; 19366f82e85aSdrh 19376f82e85aSdrh /* Read the PK into an array of temp registers. */ 19386f82e85aSdrh r = sqlite3GetTempRange(pParse, nPk); 19396f82e85aSdrh for(iPk=0; iPk<nPk; iPk++){ 19406f82e85aSdrh int iCol = pPk->aiColumn[iPk]; 1941ce78bc6eSdrh sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk); 19426f82e85aSdrh } 19436f82e85aSdrh 19446f82e85aSdrh /* Check if the temp table already contains this key. If so, 19456f82e85aSdrh ** the row has already been included in the result set and 19466f82e85aSdrh ** can be ignored (by jumping past the Gosub below). Otherwise, 19476f82e85aSdrh ** insert the key into the temp table and proceed with processing 19486f82e85aSdrh ** the row. 19496f82e85aSdrh ** 19506f82e85aSdrh ** Use some of the same optimizations as OP_RowSetTest: If iSet 19516f82e85aSdrh ** is zero, assume that the key cannot already be present in 19526f82e85aSdrh ** the temp table. And if iSet is -1, assume that there is no 19536f82e85aSdrh ** need to insert the key into the temp table, as it will never 19546f82e85aSdrh ** be tested for. */ 19556f82e85aSdrh if( iSet ){ 1956728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); 19576f82e85aSdrh VdbeCoverage(v); 19586f82e85aSdrh } 19596f82e85aSdrh if( iSet>=0 ){ 19606f82e85aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); 19619b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, 19629b4eaebcSdrh r, nPk); 19636f82e85aSdrh if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 19646f82e85aSdrh } 19656f82e85aSdrh 19666f82e85aSdrh /* Release the array of temp registers */ 19676f82e85aSdrh sqlite3ReleaseTempRange(pParse, r, nPk); 19686f82e85aSdrh } 19696f82e85aSdrh } 19706f82e85aSdrh 19716f82e85aSdrh /* Invoke the main loop body as a subroutine */ 19726f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); 19736f82e85aSdrh 19746f82e85aSdrh /* Jump here (skipping the main loop body subroutine) if the 19756f82e85aSdrh ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ 1976728e0f91Sdrh if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); 19776f82e85aSdrh 19786f82e85aSdrh /* The pSubWInfo->untestedTerms flag means that this OR term 19796f82e85aSdrh ** contained one or more AND term from a notReady table. The 19806f82e85aSdrh ** terms from the notReady table could not be tested and will 19816f82e85aSdrh ** need to be tested later. 19826f82e85aSdrh */ 19836f82e85aSdrh if( pSubWInfo->untestedTerms ) untestedTerms = 1; 19846f82e85aSdrh 19856f82e85aSdrh /* If all of the OR-connected terms are optimized using the same 19866f82e85aSdrh ** index, and the index is opened using the same cursor number 19876f82e85aSdrh ** by each call to sqlite3WhereBegin() made by this loop, it may 19886f82e85aSdrh ** be possible to use that index as a covering index. 19896f82e85aSdrh ** 19906f82e85aSdrh ** If the call to sqlite3WhereBegin() above resulted in a scan that 19916f82e85aSdrh ** uses an index, and this is either the first OR-connected term 19926f82e85aSdrh ** processed or the index is the same as that used by all previous 19936f82e85aSdrh ** terms, set pCov to the candidate covering index. Otherwise, set 19946f82e85aSdrh ** pCov to NULL to indicate that no candidate covering index will 19956f82e85aSdrh ** be available. 19966f82e85aSdrh */ 19976f82e85aSdrh pSubLoop = pSubWInfo->a[0].pWLoop; 19986f82e85aSdrh assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 19996f82e85aSdrh if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 20006f82e85aSdrh && (ii==0 || pSubLoop->u.btree.pIndex==pCov) 20016f82e85aSdrh && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) 20026f82e85aSdrh ){ 20036f82e85aSdrh assert( pSubWInfo->a[0].iIdxCur==iCovCur ); 20046f82e85aSdrh pCov = pSubLoop->u.btree.pIndex; 20056f82e85aSdrh }else{ 20066f82e85aSdrh pCov = 0; 20076f82e85aSdrh } 20086f82e85aSdrh 20096f82e85aSdrh /* Finish the loop through table entries that match term pOrTerm. */ 20106f82e85aSdrh sqlite3WhereEnd(pSubWInfo); 20116f82e85aSdrh } 20126f82e85aSdrh } 20136f82e85aSdrh } 20146f82e85aSdrh pLevel->u.pCovidx = pCov; 20156f82e85aSdrh if( pCov ) pLevel->iIdxCur = iCovCur; 20166f82e85aSdrh if( pAndExpr ){ 20176f82e85aSdrh pAndExpr->pLeft = 0; 20186f82e85aSdrh sqlite3ExprDelete(db, pAndExpr); 20196f82e85aSdrh } 20206f82e85aSdrh sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); 2021076e85f5Sdrh sqlite3VdbeGoto(v, pLevel->addrBrk); 20226f82e85aSdrh sqlite3VdbeResolveLabel(v, iLoopBody); 20236f82e85aSdrh 20246f82e85aSdrh if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); 20256f82e85aSdrh if( !untestedTerms ) disableTerm(pLevel, pTerm); 20266f82e85aSdrh }else 20276f82e85aSdrh #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 20286f82e85aSdrh 20296f82e85aSdrh { 20306f82e85aSdrh /* Case 6: There is no usable index. We must do a complete 20316f82e85aSdrh ** scan of the entire table. 20326f82e85aSdrh */ 20336f82e85aSdrh static const u8 aStep[] = { OP_Next, OP_Prev }; 20346f82e85aSdrh static const u8 aStart[] = { OP_Rewind, OP_Last }; 20356f82e85aSdrh assert( bRev==0 || bRev==1 ); 20368a48b9c0Sdrh if( pTabItem->fg.isRecursive ){ 20376f82e85aSdrh /* Tables marked isRecursive have only a single row that is stored in 20386f82e85aSdrh ** a pseudo-cursor. No need to Rewind or Next such cursors. */ 20396f82e85aSdrh pLevel->op = OP_Noop; 20406f82e85aSdrh }else{ 2041b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, 0); 20426f82e85aSdrh pLevel->op = aStep[bRev]; 20436f82e85aSdrh pLevel->p1 = iCur; 20443a3b420aSdrh pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt); 20456f82e85aSdrh VdbeCoverageIf(v, bRev==0); 20466f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 20476f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 20486f82e85aSdrh } 20496f82e85aSdrh } 20506f82e85aSdrh 20516f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 20526f82e85aSdrh pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); 20536f82e85aSdrh #endif 20546f82e85aSdrh 20556f82e85aSdrh /* Insert code to test every subexpression that can be completely 20566f82e85aSdrh ** computed using the current set of tables. 20576f654a40Sdan ** 2058ebc63013Sdan ** This loop may run between one and three times, depending on the 2059ebc63013Sdan ** constraints to be generated. The value of stack variable iLoop 2060ebc63013Sdan ** determines the constraints coded by each iteration, as follows: 2061ebc63013Sdan ** 2062ebc63013Sdan ** iLoop==1: Code only expressions that are entirely covered by pIdx. 2063ebc63013Sdan ** iLoop==2: Code remaining expressions that do not contain correlated 2064ebc63013Sdan ** sub-queries. 2065ebc63013Sdan ** iLoop==3: Code all remaining expressions. 2066ebc63013Sdan ** 2067ebc63013Sdan ** An effort is made to skip unnecessary iterations of the loop. 20686ab3eb5dSdrh */ 2069ebc63013Sdan iLoop = (pIdx ? 1 : 2); 20706ab3eb5dSdrh do{ 2071ebc63013Sdan int iNext = 0; /* Next value for iLoop */ 20726f82e85aSdrh for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 20736f82e85aSdrh Expr *pE; 20746f82e85aSdrh int skipLikeAddr = 0; 20756f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 20766f82e85aSdrh testcase( pTerm->wtFlags & TERM_CODED ); 20776f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 20786f82e85aSdrh if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 20796f82e85aSdrh testcase( pWInfo->untestedTerms==0 2080ce943bc8Sdrh && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); 20816f82e85aSdrh pWInfo->untestedTerms = 1; 20826f82e85aSdrh continue; 20836f82e85aSdrh } 20846f82e85aSdrh pE = pTerm->pExpr; 20856f82e85aSdrh assert( pE!=0 ); 20866ab3eb5dSdrh if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ 20876f654a40Sdan continue; 20886f654a40Sdan } 2089ebc63013Sdan 20908674ec5aSdan if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){ 2091ebc63013Sdan iNext = 2; 20926f82e85aSdrh continue; 20936f82e85aSdrh } 2094d3930b12Sdan if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){ 2095ebc63013Sdan if( iNext==0 ) iNext = 3; 2096ebc63013Sdan continue; 2097ebc63013Sdan } 2098ebc63013Sdan 20996f82e85aSdrh if( pTerm->wtFlags & TERM_LIKECOND ){ 210044aebff2Sdrh /* If the TERM_LIKECOND flag is set, that means that the range search 210144aebff2Sdrh ** is sufficient to guarantee that the LIKE operator is true, so we 210244aebff2Sdrh ** can skip the call to the like(A,B) function. But this only works 210344aebff2Sdrh ** for strings. So do not skip the call to the function on the pass 210444aebff2Sdrh ** that compares BLOBs. */ 210541d2e66eSdrh #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 210641d2e66eSdrh continue; 210741d2e66eSdrh #else 210844aebff2Sdrh u32 x = pLevel->iLikeRepCntr; 210944aebff2Sdrh assert( x>0 ); 211044aebff2Sdrh skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1)); 21116f82e85aSdrh VdbeCoverage(v); 211241d2e66eSdrh #endif 21136f82e85aSdrh } 211466a0bf31Sdrh #ifdef WHERETRACE_ENABLED /* 0xffff */ 211566a0bf31Sdrh if( sqlite3WhereTrace ){ 211666a0bf31Sdrh VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d", 211766a0bf31Sdrh pWC->nTerm-j, pTerm, iLoop)); 211866a0bf31Sdrh } 211966a0bf31Sdrh #endif 21206f82e85aSdrh sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); 21216f82e85aSdrh if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); 21226f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 21236f82e85aSdrh } 2124ebc63013Sdan iLoop = iNext; 2125ebc63013Sdan }while( iLoop>0 ); 21266f82e85aSdrh 21276f82e85aSdrh /* Insert code to test for implied constraints based on transitivity 21286f82e85aSdrh ** of the "==" operator. 21296f82e85aSdrh ** 21306f82e85aSdrh ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" 21316f82e85aSdrh ** and we are coding the t1 loop and the t2 loop has not yet coded, 21326f82e85aSdrh ** then we cannot use the "t1.a=t2.b" constraint, but we can code 21336f82e85aSdrh ** the implied "t1.a=123" constraint. 21346f82e85aSdrh */ 21356f82e85aSdrh for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 2136cb43a937Sdrh Expr *pE, sEAlt; 21376f82e85aSdrh WhereTerm *pAlt; 21386f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 21396f82e85aSdrh if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; 21406f82e85aSdrh if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; 21416f82e85aSdrh if( pTerm->leftCursor!=iCur ) continue; 21426f82e85aSdrh if( pLevel->iLeftJoin ) continue; 21436f82e85aSdrh pE = pTerm->pExpr; 21446f82e85aSdrh assert( !ExprHasProperty(pE, EP_FromJoin) ); 21456f82e85aSdrh assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); 21466f82e85aSdrh pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, 21476f82e85aSdrh WO_EQ|WO_IN|WO_IS, 0); 21486f82e85aSdrh if( pAlt==0 ) continue; 21496f82e85aSdrh if( pAlt->wtFlags & (TERM_CODED) ) continue; 21506f82e85aSdrh testcase( pAlt->eOperator & WO_EQ ); 21516f82e85aSdrh testcase( pAlt->eOperator & WO_IS ); 21526f82e85aSdrh testcase( pAlt->eOperator & WO_IN ); 21536f82e85aSdrh VdbeModuleComment((v, "begin transitive constraint")); 2154cb43a937Sdrh sEAlt = *pAlt->pExpr; 2155cb43a937Sdrh sEAlt.pLeft = pE->pLeft; 2156cb43a937Sdrh sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); 21576f82e85aSdrh } 21586f82e85aSdrh 21596f82e85aSdrh /* For a LEFT OUTER JOIN, generate code that will record the fact that 21606f82e85aSdrh ** at least one row of the right table has matched the left table. 21616f82e85aSdrh */ 21626f82e85aSdrh if( pLevel->iLeftJoin ){ 21636f82e85aSdrh pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); 21646f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); 21656f82e85aSdrh VdbeComment((v, "record LEFT JOIN hit")); 21666f82e85aSdrh sqlite3ExprCacheClear(pParse); 21676f82e85aSdrh for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ 21686f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 21696f82e85aSdrh testcase( pTerm->wtFlags & TERM_CODED ); 21706f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 21716f82e85aSdrh if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 21726f82e85aSdrh assert( pWInfo->untestedTerms ); 21736f82e85aSdrh continue; 21746f82e85aSdrh } 21756f82e85aSdrh assert( pTerm->pExpr ); 21766f82e85aSdrh sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 21776f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 21786f82e85aSdrh } 21796f82e85aSdrh } 21806f82e85aSdrh 21816f82e85aSdrh return pLevel->notReady; 21826f82e85aSdrh } 2183