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 246f82e85aSdrh /* 256f82e85aSdrh ** This routine is a helper for explainIndexRange() below 266f82e85aSdrh ** 276f82e85aSdrh ** pStr holds the text of an expression that we are building up one term 286f82e85aSdrh ** at a time. This routine adds a new term to the end of the expression. 296f82e85aSdrh ** Terms are separated by AND so add the "AND" text for second and subsequent 306f82e85aSdrh ** terms only. 316f82e85aSdrh */ 326f82e85aSdrh static void explainAppendTerm( 336f82e85aSdrh StrAccum *pStr, /* The text expression being built */ 346f82e85aSdrh int iTerm, /* Index of this term. First is zero */ 356f82e85aSdrh const char *zColumn, /* Name of the column */ 366f82e85aSdrh const char *zOp /* Name of the operator */ 376f82e85aSdrh ){ 386f82e85aSdrh if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5); 396f82e85aSdrh sqlite3StrAccumAppendAll(pStr, zColumn); 406f82e85aSdrh sqlite3StrAccumAppend(pStr, zOp, 1); 416f82e85aSdrh sqlite3StrAccumAppend(pStr, "?", 1); 426f82e85aSdrh } 436f82e85aSdrh 446f82e85aSdrh /* 45c7c4680fSdrh ** Return the name of the i-th column of the pIdx index. 46c7c4680fSdrh */ 47c7c4680fSdrh static const char *explainIndexColumnName(Index *pIdx, int i){ 48c7c4680fSdrh i = pIdx->aiColumn[i]; 494b92f98cSdrh if( i==XN_EXPR ) return "<expr>"; 504b92f98cSdrh if( i==XN_ROWID ) return "rowid"; 51c7c4680fSdrh return pIdx->pTable->aCol[i].zName; 52c7c4680fSdrh } 53c7c4680fSdrh 54c7c4680fSdrh /* 556f82e85aSdrh ** Argument pLevel describes a strategy for scanning table pTab. This 566f82e85aSdrh ** function appends text to pStr that describes the subset of table 576f82e85aSdrh ** rows scanned by the strategy in the form of an SQL expression. 586f82e85aSdrh ** 596f82e85aSdrh ** For example, if the query: 606f82e85aSdrh ** 616f82e85aSdrh ** SELECT * FROM t1 WHERE a=1 AND b>2; 626f82e85aSdrh ** 636f82e85aSdrh ** is run and there is an index on (a, b), then this function returns a 646f82e85aSdrh ** string similar to: 656f82e85aSdrh ** 666f82e85aSdrh ** "a=? AND b>?" 676f82e85aSdrh */ 688faee877Sdrh static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ 696f82e85aSdrh Index *pIndex = pLoop->u.btree.pIndex; 706f82e85aSdrh u16 nEq = pLoop->u.btree.nEq; 716f82e85aSdrh u16 nSkip = pLoop->nSkip; 726f82e85aSdrh int i, j; 736f82e85aSdrh 746f82e85aSdrh if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; 756f82e85aSdrh sqlite3StrAccumAppend(pStr, " (", 2); 766f82e85aSdrh for(i=0; i<nEq; i++){ 77c7c4680fSdrh const char *z = explainIndexColumnName(pIndex, i); 786f82e85aSdrh if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); 795f4a686fSdrh sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); 806f82e85aSdrh } 816f82e85aSdrh 826f82e85aSdrh j = i; 836f82e85aSdrh if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ 84c7c4680fSdrh const char *z = explainIndexColumnName(pIndex, i); 856f82e85aSdrh explainAppendTerm(pStr, i++, z, ">"); 866f82e85aSdrh } 876f82e85aSdrh if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ 88c7c4680fSdrh const char *z = explainIndexColumnName(pIndex, j); 896f82e85aSdrh explainAppendTerm(pStr, i, z, "<"); 906f82e85aSdrh } 916f82e85aSdrh sqlite3StrAccumAppend(pStr, ")", 1); 926f82e85aSdrh } 936f82e85aSdrh 946f82e85aSdrh /* 956f82e85aSdrh ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN 966f82e85aSdrh ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was 976f82e85aSdrh ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 986f82e85aSdrh ** is added to the output to describe the table scan strategy in pLevel. 996f82e85aSdrh ** 1006f82e85aSdrh ** If an OP_Explain opcode is added to the VM, its address is returned. 1016f82e85aSdrh ** Otherwise, if no OP_Explain is coded, zero is returned. 1026f82e85aSdrh */ 1036f82e85aSdrh int sqlite3WhereExplainOneScan( 1046f82e85aSdrh Parse *pParse, /* Parse context */ 1056f82e85aSdrh SrcList *pTabList, /* Table list this loop refers to */ 1066f82e85aSdrh WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ 1076f82e85aSdrh int iLevel, /* Value for "level" column of output */ 1086f82e85aSdrh int iFrom, /* Value for "from" column of output */ 1096f82e85aSdrh u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ 1106f82e85aSdrh ){ 1116f82e85aSdrh int ret = 0; 1126f82e85aSdrh #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) 1136f82e85aSdrh if( pParse->explain==2 ) 1146f82e85aSdrh #endif 1156f82e85aSdrh { 1166f82e85aSdrh struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; 1176f82e85aSdrh Vdbe *v = pParse->pVdbe; /* VM being constructed */ 1186f82e85aSdrh sqlite3 *db = pParse->db; /* Database handle */ 1196f82e85aSdrh int iId = pParse->iSelectId; /* Select id (left-most output column) */ 1206f82e85aSdrh int isSearch; /* True for a SEARCH. False for SCAN. */ 1216f82e85aSdrh WhereLoop *pLoop; /* The controlling WhereLoop object */ 1226f82e85aSdrh u32 flags; /* Flags that describe this loop */ 1236f82e85aSdrh char *zMsg; /* Text to add to EQP output */ 1246f82e85aSdrh StrAccum str; /* EQP output string */ 1256f82e85aSdrh char zBuf[100]; /* Initial space for EQP output string */ 1266f82e85aSdrh 1276f82e85aSdrh pLoop = pLevel->pWLoop; 1286f82e85aSdrh flags = pLoop->wsFlags; 129ce943bc8Sdrh if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; 1306f82e85aSdrh 1316f82e85aSdrh isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 1326f82e85aSdrh || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) 1336f82e85aSdrh || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); 1346f82e85aSdrh 1356f82e85aSdrh sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); 1366f82e85aSdrh sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); 1376f82e85aSdrh if( pItem->pSelect ){ 1385f4a686fSdrh sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); 1396f82e85aSdrh }else{ 1405f4a686fSdrh sqlite3XPrintf(&str, " TABLE %s", pItem->zName); 1416f82e85aSdrh } 1426f82e85aSdrh 1436f82e85aSdrh if( pItem->zAlias ){ 1445f4a686fSdrh sqlite3XPrintf(&str, " AS %s", pItem->zAlias); 1456f82e85aSdrh } 1466f82e85aSdrh if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ 1476f82e85aSdrh const char *zFmt = 0; 1486f82e85aSdrh Index *pIdx; 1496f82e85aSdrh 1506f82e85aSdrh assert( pLoop->u.btree.pIndex!=0 ); 1516f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 1526f82e85aSdrh assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); 1536f82e85aSdrh if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ 1546f82e85aSdrh if( isSearch ){ 1556f82e85aSdrh zFmt = "PRIMARY KEY"; 1566f82e85aSdrh } 1576f82e85aSdrh }else if( flags & WHERE_PARTIALIDX ){ 1586f82e85aSdrh zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; 1596f82e85aSdrh }else if( flags & WHERE_AUTO_INDEX ){ 1606f82e85aSdrh zFmt = "AUTOMATIC COVERING INDEX"; 1616f82e85aSdrh }else if( flags & WHERE_IDX_ONLY ){ 1626f82e85aSdrh zFmt = "COVERING INDEX %s"; 1636f82e85aSdrh }else{ 1646f82e85aSdrh zFmt = "INDEX %s"; 1656f82e85aSdrh } 1666f82e85aSdrh if( zFmt ){ 1676f82e85aSdrh sqlite3StrAccumAppend(&str, " USING ", 7); 1685f4a686fSdrh sqlite3XPrintf(&str, zFmt, pIdx->zName); 1698faee877Sdrh explainIndexRange(&str, pLoop); 1706f82e85aSdrh } 1716f82e85aSdrh }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ 172d37bea5bSdrh const char *zRangeOp; 1736f82e85aSdrh if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ 174d37bea5bSdrh zRangeOp = "="; 1756f82e85aSdrh }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ 176d37bea5bSdrh zRangeOp = ">? AND rowid<"; 1776f82e85aSdrh }else if( flags&WHERE_BTM_LIMIT ){ 178d37bea5bSdrh zRangeOp = ">"; 1796f82e85aSdrh }else{ 1806f82e85aSdrh assert( flags&WHERE_TOP_LIMIT); 181d37bea5bSdrh zRangeOp = "<"; 1826f82e85aSdrh } 1835f4a686fSdrh sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); 1846f82e85aSdrh } 1856f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 1866f82e85aSdrh else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ 1875f4a686fSdrh sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s", 1886f82e85aSdrh pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); 1896f82e85aSdrh } 1906f82e85aSdrh #endif 1916f82e85aSdrh #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS 1926f82e85aSdrh if( pLoop->nOut>=10 ){ 1935f4a686fSdrh sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); 1946f82e85aSdrh }else{ 1956f82e85aSdrh sqlite3StrAccumAppend(&str, " (~1 row)", 9); 1966f82e85aSdrh } 1976f82e85aSdrh #endif 1986f82e85aSdrh zMsg = sqlite3StrAccumFinish(&str); 1996f82e85aSdrh ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC); 2006f82e85aSdrh } 2016f82e85aSdrh return ret; 2026f82e85aSdrh } 2036f82e85aSdrh #endif /* SQLITE_OMIT_EXPLAIN */ 2046f82e85aSdrh 2056f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 2066f82e85aSdrh /* 2076f82e85aSdrh ** Configure the VM passed as the first argument with an 2086f82e85aSdrh ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 2096f82e85aSdrh ** implement level pLvl. Argument pSrclist is a pointer to the FROM 2106f82e85aSdrh ** clause that the scan reads data from. 2116f82e85aSdrh ** 2126f82e85aSdrh ** If argument addrExplain is not 0, it must be the address of an 2136f82e85aSdrh ** OP_Explain instruction that describes the same loop. 2146f82e85aSdrh */ 2156f82e85aSdrh void sqlite3WhereAddScanStatus( 2166f82e85aSdrh Vdbe *v, /* Vdbe to add scanstatus entry to */ 2176f82e85aSdrh SrcList *pSrclist, /* FROM clause pLvl reads data from */ 2186f82e85aSdrh WhereLevel *pLvl, /* Level to add scanstatus() entry for */ 2196f82e85aSdrh int addrExplain /* Address of OP_Explain (or 0) */ 2206f82e85aSdrh ){ 2216f82e85aSdrh const char *zObj = 0; 2226f82e85aSdrh WhereLoop *pLoop = pLvl->pWLoop; 2236f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ 2246f82e85aSdrh zObj = pLoop->u.btree.pIndex->zName; 2256f82e85aSdrh }else{ 2266f82e85aSdrh zObj = pSrclist->a[pLvl->iFrom].zName; 2276f82e85aSdrh } 2286f82e85aSdrh sqlite3VdbeScanStatus( 2296f82e85aSdrh v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj 2306f82e85aSdrh ); 2316f82e85aSdrh } 2326f82e85aSdrh #endif 2336f82e85aSdrh 2346f82e85aSdrh 2356f82e85aSdrh /* 2366f82e85aSdrh ** Disable a term in the WHERE clause. Except, do not disable the term 2376f82e85aSdrh ** if it controls a LEFT OUTER JOIN and it did not originate in the ON 2386f82e85aSdrh ** or USING clause of that join. 2396f82e85aSdrh ** 2406f82e85aSdrh ** Consider the term t2.z='ok' in the following queries: 2416f82e85aSdrh ** 2426f82e85aSdrh ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' 2436f82e85aSdrh ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' 2446f82e85aSdrh ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' 2456f82e85aSdrh ** 2466f82e85aSdrh ** The t2.z='ok' is disabled in the in (2) because it originates 2476f82e85aSdrh ** in the ON clause. The term is disabled in (3) because it is not part 2486f82e85aSdrh ** of a LEFT OUTER JOIN. In (1), the term is not disabled. 2496f82e85aSdrh ** 2506f82e85aSdrh ** Disabling a term causes that term to not be tested in the inner loop 2516f82e85aSdrh ** of the join. Disabling is an optimization. When terms are satisfied 2526f82e85aSdrh ** by indices, we disable them to prevent redundant tests in the inner 2536f82e85aSdrh ** loop. We would get the correct results if nothing were ever disabled, 2546f82e85aSdrh ** but joins might run a little slower. The trick is to disable as much 2556f82e85aSdrh ** as we can without disabling too much. If we disabled in (1), we'd get 2566f82e85aSdrh ** the wrong answer. See ticket #813. 2576f82e85aSdrh ** 2586f82e85aSdrh ** If all the children of a term are disabled, then that term is also 2596f82e85aSdrh ** automatically disabled. In this way, terms get disabled if derived 2606f82e85aSdrh ** virtual terms are tested first. For example: 2616f82e85aSdrh ** 2626f82e85aSdrh ** x GLOB 'abc*' AND x>='abc' AND x<'acd' 2636f82e85aSdrh ** \___________/ \______/ \_____/ 2646f82e85aSdrh ** parent child1 child2 2656f82e85aSdrh ** 2666f82e85aSdrh ** Only the parent term was in the original WHERE clause. The child1 2676f82e85aSdrh ** and child2 terms were added by the LIKE optimization. If both of 2686f82e85aSdrh ** the virtual child terms are valid, then testing of the parent can be 2696f82e85aSdrh ** skipped. 2706f82e85aSdrh ** 2716f82e85aSdrh ** Usually the parent term is marked as TERM_CODED. But if the parent 2726f82e85aSdrh ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. 2736f82e85aSdrh ** The TERM_LIKECOND marking indicates that the term should be coded inside 2746f82e85aSdrh ** a conditional such that is only evaluated on the second pass of a 2756f82e85aSdrh ** LIKE-optimization loop, when scanning BLOBs instead of strings. 2766f82e85aSdrh */ 2776f82e85aSdrh static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ 2786f82e85aSdrh int nLoop = 0; 2796f82e85aSdrh while( pTerm 2806f82e85aSdrh && (pTerm->wtFlags & TERM_CODED)==0 2816f82e85aSdrh && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 2826f82e85aSdrh && (pLevel->notReady & pTerm->prereqAll)==0 2836f82e85aSdrh ){ 2846f82e85aSdrh if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ 2856f82e85aSdrh pTerm->wtFlags |= TERM_LIKECOND; 2866f82e85aSdrh }else{ 2876f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 2886f82e85aSdrh } 2896f82e85aSdrh if( pTerm->iParent<0 ) break; 2906f82e85aSdrh pTerm = &pTerm->pWC->a[pTerm->iParent]; 2916f82e85aSdrh pTerm->nChild--; 2926f82e85aSdrh if( pTerm->nChild!=0 ) break; 2936f82e85aSdrh nLoop++; 2946f82e85aSdrh } 2956f82e85aSdrh } 2966f82e85aSdrh 2976f82e85aSdrh /* 2986f82e85aSdrh ** Code an OP_Affinity opcode to apply the column affinity string zAff 2996f82e85aSdrh ** to the n registers starting at base. 3006f82e85aSdrh ** 3016f82e85aSdrh ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the 3026f82e85aSdrh ** beginning and end of zAff are ignored. If all entries in zAff are 3036f82e85aSdrh ** SQLITE_AFF_BLOB, then no code gets generated. 3046f82e85aSdrh ** 3056f82e85aSdrh ** This routine makes its own copy of zAff so that the caller is free 3066f82e85aSdrh ** to modify zAff after this routine returns. 3076f82e85aSdrh */ 3086f82e85aSdrh static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ 3096f82e85aSdrh Vdbe *v = pParse->pVdbe; 3106f82e85aSdrh if( zAff==0 ){ 3116f82e85aSdrh assert( pParse->db->mallocFailed ); 3126f82e85aSdrh return; 3136f82e85aSdrh } 3146f82e85aSdrh assert( v!=0 ); 3156f82e85aSdrh 3166f82e85aSdrh /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning 3176f82e85aSdrh ** and end of the affinity string. 3186f82e85aSdrh */ 3196f82e85aSdrh while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){ 3206f82e85aSdrh n--; 3216f82e85aSdrh base++; 3226f82e85aSdrh zAff++; 3236f82e85aSdrh } 3246f82e85aSdrh while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){ 3256f82e85aSdrh n--; 3266f82e85aSdrh } 3276f82e85aSdrh 3286f82e85aSdrh /* Code the OP_Affinity opcode if there is anything left to do. */ 3296f82e85aSdrh if( n>0 ){ 3309b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); 3316f82e85aSdrh sqlite3ExprCacheAffinityChange(pParse, base, n); 3326f82e85aSdrh } 3336f82e85aSdrh } 3346f82e85aSdrh 3356f82e85aSdrh 3366f82e85aSdrh /* 3376f82e85aSdrh ** Generate code for a single equality term of the WHERE clause. An equality 3386f82e85aSdrh ** term can be either X=expr or X IN (...). pTerm is the term to be 3396f82e85aSdrh ** coded. 3406f82e85aSdrh ** 3416f82e85aSdrh ** The current value for the constraint is left in register iReg. 3426f82e85aSdrh ** 3436f82e85aSdrh ** For a constraint of the form X=expr, the expression is evaluated and its 3446f82e85aSdrh ** result is left on the stack. For constraints of the form X IN (...) 3456f82e85aSdrh ** this routine sets up a loop that will iterate over all values of X. 3466f82e85aSdrh */ 3476f82e85aSdrh static int codeEqualityTerm( 3486f82e85aSdrh Parse *pParse, /* The parsing context */ 3496f82e85aSdrh WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ 3506f82e85aSdrh WhereLevel *pLevel, /* The level of the FROM clause we are working on */ 3516f82e85aSdrh int iEq, /* Index of the equality term within this level */ 3526f82e85aSdrh int bRev, /* True for reverse-order IN operations */ 3536f82e85aSdrh int iTarget /* Attempt to leave results in this register */ 3546f82e85aSdrh ){ 3556f82e85aSdrh Expr *pX = pTerm->pExpr; 3566f82e85aSdrh Vdbe *v = pParse->pVdbe; 3576f82e85aSdrh int iReg; /* Register holding results */ 3586f82e85aSdrh 3598da209b1Sdan assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); 3606f82e85aSdrh assert( iTarget>0 ); 3616f82e85aSdrh if( pX->op==TK_EQ || pX->op==TK_IS ){ 362145b4ea5Sdan Expr *pRight = pX->pRight; 363145b4ea5Sdan if( pRight->op==TK_SELECT_COLUMN ){ 364145b4ea5Sdan /* This case occurs for expressions like "(a, b) == (SELECT ...)". */ 365145b4ea5Sdan WhereLoop *pLoop = pLevel->pWLoop; 366145b4ea5Sdan int i; 367145b4ea5Sdan Expr *pSub = pRight->pLeft; 368145b4ea5Sdan assert( pSub->op==TK_SELECT ); 369145b4ea5Sdan for(i=pLoop->nSkip; i<iEq; i++){ 370145b4ea5Sdan Expr *pExpr = pLoop->aLTerm[i]->pExpr->pRight; 371145b4ea5Sdan if( pExpr && pExpr->op==TK_SELECT_COLUMN && pExpr->pLeft==pSub ) break; 372145b4ea5Sdan } 373145b4ea5Sdan 374145b4ea5Sdan if( i==iEq ){ 375145b4ea5Sdan iReg = sqlite3CodeSubselect(pParse, pSub, 0, 0); 376145b4ea5Sdan for(/*no-op*/; i<pLoop->nLTerm; i++){ 377145b4ea5Sdan Expr *pExpr = pLoop->aLTerm[i]->pExpr->pRight; 378145b4ea5Sdan if( pExpr && pExpr->op==TK_SELECT_COLUMN && pExpr->pLeft==pSub ){ 379145b4ea5Sdan sqlite3VdbeAddOp2(v, OP_Copy, iReg+pExpr->iColumn, iTarget-iEq+i); 380145b4ea5Sdan } 381145b4ea5Sdan } 382145b4ea5Sdan } 383145b4ea5Sdan iReg = iTarget; 384145b4ea5Sdan }else{ 385145b4ea5Sdan iReg = sqlite3ExprCodeTarget(pParse, pRight, iTarget); 386145b4ea5Sdan } 3876f82e85aSdrh }else if( pX->op==TK_ISNULL ){ 3886f82e85aSdrh iReg = iTarget; 3896f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); 3906f82e85aSdrh #ifndef SQLITE_OMIT_SUBQUERY 3916f82e85aSdrh }else{ 3926f82e85aSdrh int eType; 3936f82e85aSdrh int iTab; 3946f82e85aSdrh struct InLoop *pIn; 3956f82e85aSdrh WhereLoop *pLoop = pLevel->pWLoop; 3968da209b1Sdan int i; 3978da209b1Sdan int nEq = 0; 3988da209b1Sdan int *aiMap = 0; 3996f82e85aSdrh 4006f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 4016f82e85aSdrh && pLoop->u.btree.pIndex!=0 4026f82e85aSdrh && pLoop->u.btree.pIndex->aSortOrder[iEq] 4036f82e85aSdrh ){ 4046f82e85aSdrh testcase( iEq==0 ); 4056f82e85aSdrh testcase( bRev ); 4066f82e85aSdrh bRev = !bRev; 4076f82e85aSdrh } 4086f82e85aSdrh assert( pX->op==TK_IN ); 4096f82e85aSdrh iReg = iTarget; 4108da209b1Sdan 4118da209b1Sdan for(i=0; i<iEq; i++){ 4128da209b1Sdan if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ 4138da209b1Sdan disableTerm(pLevel, pTerm); 4148da209b1Sdan return iTarget; 4158da209b1Sdan } 4168da209b1Sdan } 4178da209b1Sdan for(i=iEq;i<pLoop->nLTerm; i++){ 4188da209b1Sdan if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ) nEq++; 4198da209b1Sdan } 4208da209b1Sdan 4218da209b1Sdan if( nEq>1 ){ 4228da209b1Sdan aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); 4238da209b1Sdan if( !aiMap ) return 0; 4248da209b1Sdan } 4258da209b1Sdan 4268da209b1Sdan if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ 427ba00e30aSdan eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); 4288da209b1Sdan }else{ 4298da209b1Sdan sqlite3 *db = pParse->db; 4308da209b1Sdan ExprList *pOrigRhs = pX->x.pSelect->pEList; 4318da209b1Sdan ExprList *pOrigLhs = pX->pLeft->x.pList; 4328da209b1Sdan ExprList *pRhs = 0; /* New Select.pEList for RHS */ 4338da209b1Sdan ExprList *pLhs = 0; /* New pX->pLeft vector */ 4348da209b1Sdan 4358da209b1Sdan for(i=iEq;i<pLoop->nLTerm; i++){ 4368da209b1Sdan if( pLoop->aLTerm[i]->pExpr==pX ){ 4378da209b1Sdan int iField = pLoop->aLTerm[i]->iField - 1; 4388da209b1Sdan Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); 4398da209b1Sdan Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); 4408da209b1Sdan 4418da209b1Sdan pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); 4428da209b1Sdan pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); 4438da209b1Sdan } 4448da209b1Sdan } 4458da209b1Sdan 4468da209b1Sdan pX->x.pSelect->pEList = pRhs; 4478da209b1Sdan pX->pLeft->x.pList = pLhs; 4488da209b1Sdan 4498da209b1Sdan eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); 4508da209b1Sdan pX->x.pSelect->pEList = pOrigRhs; 4518da209b1Sdan pX->pLeft->x.pList = pOrigLhs; 4528da209b1Sdan sqlite3ExprListDelete(pParse->db, pLhs); 4538da209b1Sdan sqlite3ExprListDelete(pParse->db, pRhs); 4548da209b1Sdan } 4558da209b1Sdan 4566f82e85aSdrh if( eType==IN_INDEX_INDEX_DESC ){ 4576f82e85aSdrh testcase( bRev ); 4586f82e85aSdrh bRev = !bRev; 4596f82e85aSdrh } 4606f82e85aSdrh iTab = pX->iTable; 4616f82e85aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); 4626f82e85aSdrh VdbeCoverageIf(v, bRev); 4636f82e85aSdrh VdbeCoverageIf(v, !bRev); 4646f82e85aSdrh assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); 4658da209b1Sdan 4666f82e85aSdrh pLoop->wsFlags |= WHERE_IN_ABLE; 4676f82e85aSdrh if( pLevel->u.in.nIn==0 ){ 4686f82e85aSdrh pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 4696f82e85aSdrh } 4708da209b1Sdan 4718da209b1Sdan i = pLevel->u.in.nIn; 4728da209b1Sdan pLevel->u.in.nIn += nEq; 4736f82e85aSdrh pLevel->u.in.aInLoop = 4746f82e85aSdrh sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, 4756f82e85aSdrh sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); 4766f82e85aSdrh pIn = pLevel->u.in.aInLoop; 4776f82e85aSdrh if( pIn ){ 4788da209b1Sdan int iMap = 0; /* Index in aiMap[] */ 4798da209b1Sdan pIn += i; 4808da209b1Sdan for(i=iEq;i<pLoop->nLTerm; i++, pIn++){ 4818da209b1Sdan if( pLoop->aLTerm[i]->pExpr==pX ){ 4826f82e85aSdrh if( eType==IN_INDEX_ROWID ){ 4838da209b1Sdan assert( nEq==1 && i==iEq ); 4846f82e85aSdrh pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); 4856f82e85aSdrh }else{ 4868da209b1Sdan int iCol = aiMap ? aiMap[iMap++] : 0; 4878da209b1Sdan int iOut = iReg + i - iEq; 4888da209b1Sdan pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); 4896f82e85aSdrh } 4908da209b1Sdan if( i==iEq ){ 4918da209b1Sdan pIn->iCur = iTab; 4926f82e85aSdrh pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; 4938da209b1Sdan }else{ 4948da209b1Sdan pIn->eEndLoopOp = OP_Noop; 4958da209b1Sdan } 4968da209b1Sdan } 4976f82e85aSdrh sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v); 4988da209b1Sdan } 4996f82e85aSdrh }else{ 5006f82e85aSdrh pLevel->u.in.nIn = 0; 5016f82e85aSdrh } 5028da209b1Sdan sqlite3DbFree(pParse->db, aiMap); 5036f82e85aSdrh #endif 5046f82e85aSdrh } 5056f82e85aSdrh disableTerm(pLevel, pTerm); 5066f82e85aSdrh return iReg; 5076f82e85aSdrh } 5086f82e85aSdrh 5096f82e85aSdrh /* 5106f82e85aSdrh ** Generate code that will evaluate all == and IN constraints for an 5116f82e85aSdrh ** index scan. 5126f82e85aSdrh ** 5136f82e85aSdrh ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). 5146f82e85aSdrh ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 5156f82e85aSdrh ** The index has as many as three equality constraints, but in this 5166f82e85aSdrh ** example, the third "c" value is an inequality. So only two 5176f82e85aSdrh ** constraints are coded. This routine will generate code to evaluate 5186f82e85aSdrh ** a==5 and b IN (1,2,3). The current values for a and b will be stored 5196f82e85aSdrh ** in consecutive registers and the index of the first register is returned. 5206f82e85aSdrh ** 5216f82e85aSdrh ** In the example above nEq==2. But this subroutine works for any value 5226f82e85aSdrh ** of nEq including 0. If nEq==0, this routine is nearly a no-op. 5236f82e85aSdrh ** The only thing it does is allocate the pLevel->iMem memory cell and 5246f82e85aSdrh ** compute the affinity string. 5256f82e85aSdrh ** 5266f82e85aSdrh ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints 5276f82e85aSdrh ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is 5286f82e85aSdrh ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that 5296f82e85aSdrh ** occurs after the nEq quality constraints. 5306f82e85aSdrh ** 5316f82e85aSdrh ** This routine allocates a range of nEq+nExtraReg memory cells and returns 5326f82e85aSdrh ** the index of the first memory cell in that range. The code that 5336f82e85aSdrh ** calls this routine will use that memory range to store keys for 5346f82e85aSdrh ** start and termination conditions of the loop. 5356f82e85aSdrh ** key value of the loop. If one or more IN operators appear, then 5366f82e85aSdrh ** this routine allocates an additional nEq memory cells for internal 5376f82e85aSdrh ** use. 5386f82e85aSdrh ** 5396f82e85aSdrh ** Before returning, *pzAff is set to point to a buffer containing a 5406f82e85aSdrh ** copy of the column affinity string of the index allocated using 5416f82e85aSdrh ** sqlite3DbMalloc(). Except, entries in the copy of the string associated 5426f82e85aSdrh ** with equality constraints that use BLOB or NONE affinity are set to 5436f82e85aSdrh ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: 5446f82e85aSdrh ** 5456f82e85aSdrh ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); 5466f82e85aSdrh ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; 5476f82e85aSdrh ** 5486f82e85aSdrh ** In the example above, the index on t1(a) has TEXT affinity. But since 5496f82e85aSdrh ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, 5506f82e85aSdrh ** no conversion should be attempted before using a t2.b value as part of 5516f82e85aSdrh ** a key to search the index. Hence the first byte in the returned affinity 5526f82e85aSdrh ** string in this example would be set to SQLITE_AFF_BLOB. 5536f82e85aSdrh */ 5546f82e85aSdrh static int codeAllEqualityTerms( 5556f82e85aSdrh Parse *pParse, /* Parsing context */ 5566f82e85aSdrh WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ 5576f82e85aSdrh int bRev, /* Reverse the order of IN operators */ 5586f82e85aSdrh int nExtraReg, /* Number of extra registers to allocate */ 5596f82e85aSdrh char **pzAff /* OUT: Set to point to affinity string */ 5606f82e85aSdrh ){ 5616f82e85aSdrh u16 nEq; /* The number of == or IN constraints to code */ 5626f82e85aSdrh u16 nSkip; /* Number of left-most columns to skip */ 5636f82e85aSdrh Vdbe *v = pParse->pVdbe; /* The vm under construction */ 5646f82e85aSdrh Index *pIdx; /* The index being used for this loop */ 5656f82e85aSdrh WhereTerm *pTerm; /* A single constraint term */ 5666f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object */ 5676f82e85aSdrh int j; /* Loop counter */ 5686f82e85aSdrh int regBase; /* Base register */ 5696f82e85aSdrh int nReg; /* Number of registers to allocate */ 5706f82e85aSdrh char *zAff; /* Affinity string to return */ 5716f82e85aSdrh 5726f82e85aSdrh /* This module is only called on query plans that use an index. */ 5736f82e85aSdrh pLoop = pLevel->pWLoop; 5746f82e85aSdrh assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); 5756f82e85aSdrh nEq = pLoop->u.btree.nEq; 5766f82e85aSdrh nSkip = pLoop->nSkip; 5776f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 5786f82e85aSdrh assert( pIdx!=0 ); 5796f82e85aSdrh 5806f82e85aSdrh /* Figure out how many memory cells we will need then allocate them. 5816f82e85aSdrh */ 5826f82e85aSdrh regBase = pParse->nMem + 1; 5836f82e85aSdrh nReg = pLoop->u.btree.nEq + nExtraReg; 5846f82e85aSdrh pParse->nMem += nReg; 5856f82e85aSdrh 586e9107698Sdrh zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); 5874df86af3Sdrh assert( zAff!=0 || pParse->db->mallocFailed ); 5886f82e85aSdrh 5896f82e85aSdrh if( nSkip ){ 5906f82e85aSdrh int iIdxCur = pLevel->iIdxCur; 5916f82e85aSdrh sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); 5926f82e85aSdrh VdbeCoverageIf(v, bRev==0); 5936f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 5946f82e85aSdrh VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); 5956f82e85aSdrh j = sqlite3VdbeAddOp0(v, OP_Goto); 5966f82e85aSdrh pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), 5976f82e85aSdrh iIdxCur, 0, regBase, nSkip); 5986f82e85aSdrh VdbeCoverageIf(v, bRev==0); 5996f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 6006f82e85aSdrh sqlite3VdbeJumpHere(v, j); 6016f82e85aSdrh for(j=0; j<nSkip; j++){ 6026f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); 6034b92f98cSdrh testcase( pIdx->aiColumn[j]==XN_EXPR ); 604e63e8a6cSdrh VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); 6056f82e85aSdrh } 6066f82e85aSdrh } 6076f82e85aSdrh 6086f82e85aSdrh /* Evaluate the equality constraints 6096f82e85aSdrh */ 6106f82e85aSdrh assert( zAff==0 || (int)strlen(zAff)>=nEq ); 6116f82e85aSdrh for(j=nSkip; j<nEq; j++){ 6126f82e85aSdrh int r1; 6136f82e85aSdrh pTerm = pLoop->aLTerm[j]; 6146f82e85aSdrh assert( pTerm!=0 ); 6156f82e85aSdrh /* The following testcase is true for indices with redundant columns. 6166f82e85aSdrh ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ 6176f82e85aSdrh testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); 6186f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 6196f82e85aSdrh r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); 6206f82e85aSdrh if( r1!=regBase+j ){ 6216f82e85aSdrh if( nReg==1 ){ 6226f82e85aSdrh sqlite3ReleaseTempReg(pParse, regBase); 6236f82e85aSdrh regBase = r1; 6246f82e85aSdrh }else{ 6256f82e85aSdrh sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); 6266f82e85aSdrh } 6276f82e85aSdrh } 6286f82e85aSdrh testcase( pTerm->eOperator & WO_ISNULL ); 6296f82e85aSdrh testcase( pTerm->eOperator & WO_IN ); 6306f82e85aSdrh if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ 6316f82e85aSdrh Expr *pRight = pTerm->pExpr->pRight; 6326f82e85aSdrh if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ 6336f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); 6346f82e85aSdrh VdbeCoverage(v); 6356f82e85aSdrh } 6366f82e85aSdrh if( zAff ){ 6376f82e85aSdrh if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ 6386f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB; 6396f82e85aSdrh } 6406f82e85aSdrh if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ 6416f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB; 6426f82e85aSdrh } 6436f82e85aSdrh } 6446f82e85aSdrh } 6456f82e85aSdrh } 6466f82e85aSdrh *pzAff = zAff; 6476f82e85aSdrh return regBase; 6486f82e85aSdrh } 6496f82e85aSdrh 65041d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 6516f82e85aSdrh /* 65244aebff2Sdrh ** If the most recently coded instruction is a constant range constraint 65344aebff2Sdrh ** (a string literal) that originated from the LIKE optimization, then 65444aebff2Sdrh ** set P3 and P5 on the OP_String opcode so that the string will be cast 65544aebff2Sdrh ** to a BLOB at appropriate times. 6566f82e85aSdrh ** 6576f82e85aSdrh ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range 6586f82e85aSdrh ** expression: "x>='ABC' AND x<'abd'". But this requires that the range 6596f82e85aSdrh ** scan loop run twice, once for strings and a second time for BLOBs. 6606f82e85aSdrh ** The OP_String opcodes on the second pass convert the upper and lower 661e234cfd1Smistachkin ** bound string constants to blobs. This routine makes the necessary changes 6626f82e85aSdrh ** to the OP_String opcodes for that to happen. 66341d2e66eSdrh ** 66441d2e66eSdrh ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then 66541d2e66eSdrh ** only the one pass through the string space is required, so this routine 66641d2e66eSdrh ** becomes a no-op. 6676f82e85aSdrh */ 6686f82e85aSdrh static void whereLikeOptimizationStringFixup( 6696f82e85aSdrh Vdbe *v, /* prepared statement under construction */ 6706f82e85aSdrh WhereLevel *pLevel, /* The loop that contains the LIKE operator */ 6716f82e85aSdrh WhereTerm *pTerm /* The upper or lower bound just coded */ 6726f82e85aSdrh ){ 6736f82e85aSdrh if( pTerm->wtFlags & TERM_LIKEOPT ){ 6746f82e85aSdrh VdbeOp *pOp; 6756f82e85aSdrh assert( pLevel->iLikeRepCntr>0 ); 6766f82e85aSdrh pOp = sqlite3VdbeGetOp(v, -1); 6776f82e85aSdrh assert( pOp!=0 ); 6786f82e85aSdrh assert( pOp->opcode==OP_String8 6796f82e85aSdrh || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); 68044aebff2Sdrh pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ 68144aebff2Sdrh pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ 6826f82e85aSdrh } 6836f82e85aSdrh } 68441d2e66eSdrh #else 68541d2e66eSdrh # define whereLikeOptimizationStringFixup(A,B,C) 68641d2e66eSdrh #endif 6876f82e85aSdrh 688bec2476aSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS 6892f2b0278Sdrh /* 6902f2b0278Sdrh ** Information is passed from codeCursorHint() down to individual nodes of 6912f2b0278Sdrh ** the expression tree (by sqlite3WalkExpr()) using an instance of this 6922f2b0278Sdrh ** structure. 6932f2b0278Sdrh */ 6942f2b0278Sdrh struct CCurHint { 6952f2b0278Sdrh int iTabCur; /* Cursor for the main table */ 6962f2b0278Sdrh int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ 6972f2b0278Sdrh Index *pIdx; /* The index used to access the table */ 6982f2b0278Sdrh }; 6992f2b0278Sdrh 7002f2b0278Sdrh /* 7012f2b0278Sdrh ** This function is called for every node of an expression that is a candidate 7022f2b0278Sdrh ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference 7032f2b0278Sdrh ** the table CCurHint.iTabCur, verify that the same column can be 7042f2b0278Sdrh ** accessed through the index. If it cannot, then set pWalker->eCode to 1. 7052f2b0278Sdrh */ 7062f2b0278Sdrh static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ 7072f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint; 7082f2b0278Sdrh assert( pHint->pIdx!=0 ); 7092f2b0278Sdrh if( pExpr->op==TK_COLUMN 7102f2b0278Sdrh && pExpr->iTable==pHint->iTabCur 7112f2b0278Sdrh && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0 7122f2b0278Sdrh ){ 7132f2b0278Sdrh pWalker->eCode = 1; 7142f2b0278Sdrh } 7152f2b0278Sdrh return WRC_Continue; 7162f2b0278Sdrh } 7172f2b0278Sdrh 718e6912fd8Sdan /* 719e6912fd8Sdan ** Test whether or not expression pExpr, which was part of a WHERE clause, 720e6912fd8Sdan ** should be included in the cursor-hint for a table that is on the rhs 721e6912fd8Sdan ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 722e6912fd8Sdan ** expression is not suitable. 723e6912fd8Sdan ** 724e6912fd8Sdan ** An expression is unsuitable if it might evaluate to non NULL even if 725e6912fd8Sdan ** a TK_COLUMN node that does affect the value of the expression is set 726e6912fd8Sdan ** to NULL. For example: 727e6912fd8Sdan ** 728e6912fd8Sdan ** col IS NULL 729e6912fd8Sdan ** col IS NOT NULL 730e6912fd8Sdan ** coalesce(col, 1) 731e6912fd8Sdan ** CASE WHEN col THEN 0 ELSE 1 END 732e6912fd8Sdan */ 733e6912fd8Sdan static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ 7342b693d63Sdan if( pExpr->op==TK_IS 735e6912fd8Sdan || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 736e6912fd8Sdan || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 737e6912fd8Sdan ){ 738e6912fd8Sdan pWalker->eCode = 1; 7392b693d63Sdan }else if( pExpr->op==TK_FUNCTION ){ 7402b693d63Sdan int d1; 7412b693d63Sdan char d2[3]; 7422b693d63Sdan if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ 7432b693d63Sdan pWalker->eCode = 1; 744e6912fd8Sdan } 7452b693d63Sdan } 7462b693d63Sdan 747e6912fd8Sdan return WRC_Continue; 748e6912fd8Sdan } 749e6912fd8Sdan 750bec2476aSdrh 751bec2476aSdrh /* 752bec2476aSdrh ** This function is called on every node of an expression tree used as an 753bec2476aSdrh ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN 7542f2b0278Sdrh ** that accesses any table other than the one identified by 7552f2b0278Sdrh ** CCurHint.iTabCur, then do the following: 756bec2476aSdrh ** 757bec2476aSdrh ** 1) allocate a register and code an OP_Column instruction to read 758bec2476aSdrh ** the specified column into the new register, and 759bec2476aSdrh ** 760bec2476aSdrh ** 2) transform the expression node to a TK_REGISTER node that reads 761bec2476aSdrh ** from the newly populated register. 7622f2b0278Sdrh ** 7632f2b0278Sdrh ** Also, if the node is a TK_COLUMN that does access the table idenified 7642f2b0278Sdrh ** by pCCurHint.iTabCur, and an index is being used (which we will 7652f2b0278Sdrh ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into 7662f2b0278Sdrh ** an access of the index rather than the original table. 767bec2476aSdrh */ 768bec2476aSdrh static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ 769bec2476aSdrh int rc = WRC_Continue; 7702f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint; 7712f2b0278Sdrh if( pExpr->op==TK_COLUMN ){ 7722f2b0278Sdrh if( pExpr->iTable!=pHint->iTabCur ){ 773bec2476aSdrh Vdbe *v = pWalker->pParse->pVdbe; 774bec2476aSdrh int reg = ++pWalker->pParse->nMem; /* Register for column value */ 775bec2476aSdrh sqlite3ExprCodeGetColumnOfTable( 776bec2476aSdrh v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg 777bec2476aSdrh ); 778bec2476aSdrh pExpr->op = TK_REGISTER; 779bec2476aSdrh pExpr->iTable = reg; 7802f2b0278Sdrh }else if( pHint->pIdx!=0 ){ 7812f2b0278Sdrh pExpr->iTable = pHint->iIdxCur; 7822f2b0278Sdrh pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn); 7832f2b0278Sdrh assert( pExpr->iColumn>=0 ); 7842f2b0278Sdrh } 785bec2476aSdrh }else if( pExpr->op==TK_AGG_FUNCTION ){ 786bec2476aSdrh /* An aggregate function in the WHERE clause of a query means this must 787bec2476aSdrh ** be a correlated sub-query, and expression pExpr is an aggregate from 788bec2476aSdrh ** the parent context. Do not walk the function arguments in this case. 789bec2476aSdrh ** 790bec2476aSdrh ** todo: It should be possible to replace this node with a TK_REGISTER 791bec2476aSdrh ** expression, as the result of the expression must be stored in a 792bec2476aSdrh ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ 793bec2476aSdrh rc = WRC_Prune; 794bec2476aSdrh } 795bec2476aSdrh return rc; 796bec2476aSdrh } 797bec2476aSdrh 798bec2476aSdrh /* 799bec2476aSdrh ** Insert an OP_CursorHint instruction if it is appropriate to do so. 800bec2476aSdrh */ 801bec2476aSdrh static void codeCursorHint( 802b324cf75Sdan struct SrcList_item *pTabItem, /* FROM clause item */ 803b413a546Sdrh WhereInfo *pWInfo, /* The where clause */ 804b413a546Sdrh WhereLevel *pLevel, /* Which loop to provide hints for */ 805b413a546Sdrh WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ 806bec2476aSdrh ){ 807bec2476aSdrh Parse *pParse = pWInfo->pParse; 808bec2476aSdrh sqlite3 *db = pParse->db; 809bec2476aSdrh Vdbe *v = pParse->pVdbe; 810bec2476aSdrh Expr *pExpr = 0; 8112f2b0278Sdrh WhereLoop *pLoop = pLevel->pWLoop; 812bec2476aSdrh int iCur; 813bec2476aSdrh WhereClause *pWC; 814bec2476aSdrh WhereTerm *pTerm; 815b413a546Sdrh int i, j; 8162f2b0278Sdrh struct CCurHint sHint; 8172f2b0278Sdrh Walker sWalker; 818bec2476aSdrh 819bec2476aSdrh if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; 8202f2b0278Sdrh iCur = pLevel->iTabCur; 8212f2b0278Sdrh assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); 8222f2b0278Sdrh sHint.iTabCur = iCur; 8232f2b0278Sdrh sHint.iIdxCur = pLevel->iIdxCur; 8242f2b0278Sdrh sHint.pIdx = pLoop->u.btree.pIndex; 8252f2b0278Sdrh memset(&sWalker, 0, sizeof(sWalker)); 8262f2b0278Sdrh sWalker.pParse = pParse; 8272f2b0278Sdrh sWalker.u.pCCurHint = &sHint; 828bec2476aSdrh pWC = &pWInfo->sWC; 829bec2476aSdrh for(i=0; i<pWC->nTerm; i++){ 830bec2476aSdrh pTerm = &pWC->a[i]; 831bec2476aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 832bec2476aSdrh if( pTerm->prereqAll & pLevel->notReady ) continue; 833b324cf75Sdan 834b324cf75Sdan /* Any terms specified as part of the ON(...) clause for any LEFT 835b324cf75Sdan ** JOIN for which the current table is not the rhs are omitted 836b324cf75Sdan ** from the cursor-hint. 837b324cf75Sdan ** 838e6912fd8Sdan ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 839e6912fd8Sdan ** that were specified as part of the WHERE clause must be excluded. 840e6912fd8Sdan ** This is to address the following: 841b324cf75Sdan ** 842b324cf75Sdan ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; 843b324cf75Sdan ** 844e6912fd8Sdan ** Say there is a single row in t2 that matches (t1.a=t2.b), but its 845e6912fd8Sdan ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 846e6912fd8Sdan ** pushed down to the cursor, this row is filtered out, causing 847e6912fd8Sdan ** SQLite to synthesize a row of NULL values. Which does match the 848e6912fd8Sdan ** WHERE clause, and so the query returns a row. Which is incorrect. 849e6912fd8Sdan ** 850e6912fd8Sdan ** For the same reason, WHERE terms such as: 851e6912fd8Sdan ** 852e6912fd8Sdan ** WHERE 1 = (t2.c IS NULL) 853e6912fd8Sdan ** 854e6912fd8Sdan ** are also excluded. See codeCursorHintIsOrFunction() for details. 855b324cf75Sdan */ 856b324cf75Sdan if( pTabItem->fg.jointype & JT_LEFT ){ 857e6912fd8Sdan Expr *pExpr = pTerm->pExpr; 858e6912fd8Sdan if( !ExprHasProperty(pExpr, EP_FromJoin) 859e6912fd8Sdan || pExpr->iRightJoinTable!=pTabItem->iCursor 860b324cf75Sdan ){ 861e6912fd8Sdan sWalker.eCode = 0; 862e6912fd8Sdan sWalker.xExprCallback = codeCursorHintIsOrFunction; 863e6912fd8Sdan sqlite3WalkExpr(&sWalker, pTerm->pExpr); 864e6912fd8Sdan if( sWalker.eCode ) continue; 865b324cf75Sdan } 866b324cf75Sdan }else{ 867bec2476aSdrh if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; 868b324cf75Sdan } 869b413a546Sdrh 870b413a546Sdrh /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize 871bcf40a7fSdrh ** the cursor. These terms are not needed as hints for a pure range 872bcf40a7fSdrh ** scan (that has no == terms) so omit them. */ 873bcf40a7fSdrh if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ 874bcf40a7fSdrh for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} 875bcf40a7fSdrh if( j<pLoop->nLTerm ) continue; 876b413a546Sdrh } 877b413a546Sdrh 878b413a546Sdrh /* No subqueries or non-deterministic functions allowed */ 879bec2476aSdrh if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; 880b413a546Sdrh 881b413a546Sdrh /* For an index scan, make sure referenced columns are actually in 882b413a546Sdrh ** the index. */ 8832f2b0278Sdrh if( sHint.pIdx!=0 ){ 8842f2b0278Sdrh sWalker.eCode = 0; 8852f2b0278Sdrh sWalker.xExprCallback = codeCursorHintCheckExpr; 8862f2b0278Sdrh sqlite3WalkExpr(&sWalker, pTerm->pExpr); 8872f2b0278Sdrh if( sWalker.eCode ) continue; 8882f2b0278Sdrh } 889b413a546Sdrh 890b413a546Sdrh /* If we survive all prior tests, that means this term is worth hinting */ 891bec2476aSdrh pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); 892bec2476aSdrh } 893bec2476aSdrh if( pExpr!=0 ){ 894bec2476aSdrh sWalker.xExprCallback = codeCursorHintFixExpr; 895bec2476aSdrh sqlite3WalkExpr(&sWalker, pExpr); 8962f2b0278Sdrh sqlite3VdbeAddOp4(v, OP_CursorHint, 8972f2b0278Sdrh (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, 8982f2b0278Sdrh (const char*)pExpr, P4_EXPR); 899bec2476aSdrh } 900bec2476aSdrh } 901bec2476aSdrh #else 902b324cf75Sdan # define codeCursorHint(A,B,C,D) /* No-op */ 903bec2476aSdrh #endif /* SQLITE_ENABLE_CURSOR_HINTS */ 9046f82e85aSdrh 9056f82e85aSdrh /* 906de892d96Sdan ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains 907de892d96Sdan ** a rowid value just read from cursor iIdxCur, open on index pIdx. This 908de892d96Sdan ** function generates code to do a deferred seek of cursor iCur to the 909de892d96Sdan ** rowid stored in register iRowid. 910de892d96Sdan ** 911de892d96Sdan ** Normally, this is just: 912de892d96Sdan ** 913de892d96Sdan ** OP_Seek $iCur $iRowid 914de892d96Sdan ** 915de892d96Sdan ** However, if the scan currently being coded is a branch of an OR-loop and 916de892d96Sdan ** the statement currently being coded is a SELECT, then P3 of the OP_Seek 917de892d96Sdan ** is set to iIdxCur and P4 is set to point to an array of integers 918de892d96Sdan ** containing one entry for each column of the table cursor iCur is open 919de892d96Sdan ** on. For each table column, if the column is the i'th column of the 920de892d96Sdan ** index, then the corresponding array entry is set to (i+1). If the column 921de892d96Sdan ** does not appear in the index at all, the array entry is set to 0. 922de892d96Sdan */ 923de892d96Sdan static void codeDeferredSeek( 924de892d96Sdan WhereInfo *pWInfo, /* Where clause context */ 925de892d96Sdan Index *pIdx, /* Index scan is using */ 926de892d96Sdan int iCur, /* Cursor for IPK b-tree */ 927de892d96Sdan int iIdxCur /* Index cursor */ 928de892d96Sdan ){ 929de892d96Sdan Parse *pParse = pWInfo->pParse; /* Parse context */ 930de892d96Sdan Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ 931de892d96Sdan 932de892d96Sdan assert( iIdxCur>0 ); 933de892d96Sdan assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); 934de892d96Sdan 935784c1b93Sdrh sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur); 936ce943bc8Sdrh if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) 937cddb6ba0Sdan && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) 938de892d96Sdan ){ 939de892d96Sdan int i; 940de892d96Sdan Table *pTab = pIdx->pTable; 941b1702026Sdrh int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); 942de892d96Sdan if( ai ){ 943b1702026Sdrh ai[0] = pTab->nCol; 944de892d96Sdan for(i=0; i<pIdx->nColumn-1; i++){ 945de892d96Sdan assert( pIdx->aiColumn[i]<pTab->nCol ); 946b1702026Sdrh if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1; 947de892d96Sdan } 948de892d96Sdan sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); 949de892d96Sdan } 950de892d96Sdan } 951de892d96Sdan } 952de892d96Sdan 95371c57db0Sdan static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ 95471c57db0Sdan assert( nReg>0 ); 95571c57db0Sdan if( p->flags & EP_Vector ){ 95671c57db0Sdan int i; 95771c57db0Sdan if( (p->flags & EP_xIsSelect)==0 ){ 95871c57db0Sdan ExprList *pList = p->x.pList; 95971c57db0Sdan assert( nReg<=pList->nExpr ); 96071c57db0Sdan for(i=0; i<nReg; i++){ 96171c57db0Sdan sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); 96271c57db0Sdan } 96371c57db0Sdan }else{ 96471c57db0Sdan Vdbe *v = pParse->pVdbe; 96571c57db0Sdan int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0); 96671c57db0Sdan sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); 96771c57db0Sdan } 96871c57db0Sdan }else{ 96971c57db0Sdan assert( nReg==1 ); 97071c57db0Sdan sqlite3ExprCode(pParse, p, iReg); 97171c57db0Sdan } 97271c57db0Sdan } 97371c57db0Sdan 974de892d96Sdan /* 9756f82e85aSdrh ** Generate code for the start of the iLevel-th loop in the WHERE clause 9766f82e85aSdrh ** implementation described by pWInfo. 9776f82e85aSdrh */ 9786f82e85aSdrh Bitmask sqlite3WhereCodeOneLoopStart( 9796f82e85aSdrh WhereInfo *pWInfo, /* Complete information about the WHERE clause */ 9806f82e85aSdrh int iLevel, /* Which level of pWInfo->a[] should be coded */ 9816f82e85aSdrh Bitmask notReady /* Which tables are currently available */ 9826f82e85aSdrh ){ 9836f82e85aSdrh int j, k; /* Loop counters */ 9846f82e85aSdrh int iCur; /* The VDBE cursor for the table */ 9856f82e85aSdrh int addrNxt; /* Where to jump to continue with the next IN case */ 9866f82e85aSdrh int omitTable; /* True if we use the index only */ 9876f82e85aSdrh int bRev; /* True if we need to scan in reverse order */ 9886f82e85aSdrh WhereLevel *pLevel; /* The where level to be coded */ 9896f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object being coded */ 9906f82e85aSdrh WhereClause *pWC; /* Decomposition of the entire WHERE clause */ 9916f82e85aSdrh WhereTerm *pTerm; /* A WHERE clause term */ 9926f82e85aSdrh Parse *pParse; /* Parsing context */ 9936f82e85aSdrh sqlite3 *db; /* Database connection */ 9946f82e85aSdrh Vdbe *v; /* The prepared stmt under constructions */ 9956f82e85aSdrh struct SrcList_item *pTabItem; /* FROM clause term being coded */ 9966f82e85aSdrh int addrBrk; /* Jump here to break out of the loop */ 9976f82e85aSdrh int addrCont; /* Jump here to continue with next cycle */ 9986f82e85aSdrh int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ 9996f82e85aSdrh int iReleaseReg = 0; /* Temp register to free before returning */ 10006f82e85aSdrh 10016f82e85aSdrh pParse = pWInfo->pParse; 10026f82e85aSdrh v = pParse->pVdbe; 10036f82e85aSdrh pWC = &pWInfo->sWC; 10046f82e85aSdrh db = pParse->db; 10056f82e85aSdrh pLevel = &pWInfo->a[iLevel]; 10066f82e85aSdrh pLoop = pLevel->pWLoop; 10076f82e85aSdrh pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 10086f82e85aSdrh iCur = pTabItem->iCursor; 10096f82e85aSdrh pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); 10106f82e85aSdrh bRev = (pWInfo->revMask>>iLevel)&1; 10116f82e85aSdrh omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 1012ce943bc8Sdrh && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; 10136f82e85aSdrh VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); 10146f82e85aSdrh 10156f82e85aSdrh /* Create labels for the "break" and "continue" instructions 10166f82e85aSdrh ** for the current loop. Jump to addrBrk to break out of a loop. 10176f82e85aSdrh ** Jump to cont to go immediately to the next iteration of the 10186f82e85aSdrh ** loop. 10196f82e85aSdrh ** 10206f82e85aSdrh ** When there is an IN operator, we also have a "addrNxt" label that 10216f82e85aSdrh ** means to continue with the next IN value combination. When 10226f82e85aSdrh ** there are no IN operators in the constraints, the "addrNxt" label 10236f82e85aSdrh ** is the same as "addrBrk". 10246f82e85aSdrh */ 10256f82e85aSdrh addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 10266f82e85aSdrh addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); 10276f82e85aSdrh 10286f82e85aSdrh /* If this is the right table of a LEFT OUTER JOIN, allocate and 10296f82e85aSdrh ** initialize a memory cell that records if this table matches any 10306f82e85aSdrh ** row of the left table of the join. 10316f82e85aSdrh */ 10328a48b9c0Sdrh if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ 10336f82e85aSdrh pLevel->iLeftJoin = ++pParse->nMem; 10346f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); 10356f82e85aSdrh VdbeComment((v, "init LEFT JOIN no-match flag")); 10366f82e85aSdrh } 10376f82e85aSdrh 10386f82e85aSdrh /* Special case of a FROM clause subquery implemented as a co-routine */ 10398a48b9c0Sdrh if( pTabItem->fg.viaCoroutine ){ 10406f82e85aSdrh int regYield = pTabItem->regReturn; 10416f82e85aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); 10426f82e85aSdrh pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); 10436f82e85aSdrh VdbeCoverage(v); 10446f82e85aSdrh VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); 10456f82e85aSdrh pLevel->op = OP_Goto; 10466f82e85aSdrh }else 10476f82e85aSdrh 10486f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 10496f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 10506f82e85aSdrh /* Case 1: The table is a virtual-table. Use the VFilter and VNext 10516f82e85aSdrh ** to access the data. 10526f82e85aSdrh */ 10536f82e85aSdrh int iReg; /* P3 Value for OP_VFilter */ 10546f82e85aSdrh int addrNotFound; 10556f82e85aSdrh int nConstraint = pLoop->nLTerm; 1056dbc49161Sdrh int iIn; /* Counter for IN constraints */ 10576f82e85aSdrh 10586f82e85aSdrh sqlite3ExprCachePush(pParse); 10596f82e85aSdrh iReg = sqlite3GetTempRange(pParse, nConstraint+2); 10606f82e85aSdrh addrNotFound = pLevel->addrBrk; 10616f82e85aSdrh for(j=0; j<nConstraint; j++){ 10626f82e85aSdrh int iTarget = iReg+j+2; 10636f82e85aSdrh pTerm = pLoop->aLTerm[j]; 1064599d5764Sdrh if( NEVER(pTerm==0) ) continue; 10656f82e85aSdrh if( pTerm->eOperator & WO_IN ){ 10666f82e85aSdrh codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); 10676f82e85aSdrh addrNotFound = pLevel->addrNxt; 10686f82e85aSdrh }else{ 10696f82e85aSdrh sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget); 10706f82e85aSdrh } 10716f82e85aSdrh } 10726f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); 10736f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); 10746f82e85aSdrh sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, 10756f82e85aSdrh pLoop->u.vtab.idxStr, 10766f82e85aSdrh pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); 10776f82e85aSdrh VdbeCoverage(v); 10786f82e85aSdrh pLoop->u.vtab.needFree = 0; 10796f82e85aSdrh pLevel->p1 = iCur; 1080354474adSdan pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; 10816f82e85aSdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v); 1082dbc49161Sdrh iIn = pLevel->u.in.nIn; 1083dbc49161Sdrh for(j=nConstraint-1; j>=0; j--){ 1084dbc49161Sdrh pTerm = pLoop->aLTerm[j]; 1085dbc49161Sdrh if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ 1086dbc49161Sdrh disableTerm(pLevel, pTerm); 1087dbc49161Sdrh }else if( (pTerm->eOperator & WO_IN)!=0 ){ 1088dbc49161Sdrh Expr *pCompare; /* The comparison operator */ 1089dbc49161Sdrh Expr *pRight; /* RHS of the comparison */ 1090dbc49161Sdrh VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ 1091dbc49161Sdrh 1092dbc49161Sdrh /* Reload the constraint value into reg[iReg+j+2]. The same value 1093dbc49161Sdrh ** was loaded into the same register prior to the OP_VFilter, but 1094dbc49161Sdrh ** the xFilter implementation might have changed the datatype or 1095dbc49161Sdrh ** encoding of the value in the register, so it *must* be reloaded. */ 1096dbc49161Sdrh assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); 1097fb826b8cSdrh if( !db->mallocFailed ){ 1098dbc49161Sdrh assert( iIn>0 ); 1099dbc49161Sdrh pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop); 1100dbc49161Sdrh assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); 1101dbc49161Sdrh assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); 1102dbc49161Sdrh assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); 1103dbc49161Sdrh testcase( pOp->opcode==OP_Rowid ); 1104dbc49161Sdrh sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); 1105dbc49161Sdrh } 1106dbc49161Sdrh 1107dbc49161Sdrh /* Generate code that will continue to the next row if 1108dbc49161Sdrh ** the IN constraint is not satisfied */ 1109dbc49161Sdrh pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0); 1110dbc49161Sdrh assert( pCompare!=0 || db->mallocFailed ); 1111dbc49161Sdrh if( pCompare ){ 1112dbc49161Sdrh pCompare->pLeft = pTerm->pExpr->pLeft; 1113dbc49161Sdrh pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); 1114237b2b71Sdrh if( pRight ){ 1115237b2b71Sdrh pRight->iTable = iReg+j+2; 1116dbc49161Sdrh sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0); 1117237b2b71Sdrh } 1118dbc49161Sdrh pCompare->pLeft = 0; 1119dbc49161Sdrh sqlite3ExprDelete(db, pCompare); 1120dbc49161Sdrh } 1121dbc49161Sdrh } 1122dbc49161Sdrh } 1123ba26faa3Sdrh /* These registers need to be preserved in case there is an IN operator 1124ba26faa3Sdrh ** loop. So we could deallocate the registers here (and potentially 1125ba26faa3Sdrh ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems 1126ba26faa3Sdrh ** simpler and safer to simply not reuse the registers. 1127ba26faa3Sdrh ** 1128ba26faa3Sdrh ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); 1129ba26faa3Sdrh */ 11306f82e85aSdrh sqlite3ExprCachePop(pParse); 11316f82e85aSdrh }else 11326f82e85aSdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */ 11336f82e85aSdrh 11346f82e85aSdrh if( (pLoop->wsFlags & WHERE_IPK)!=0 11356f82e85aSdrh && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 11366f82e85aSdrh ){ 11376f82e85aSdrh /* Case 2: We can directly reference a single row using an 11386f82e85aSdrh ** equality comparison against the ROWID field. Or 11396f82e85aSdrh ** we reference multiple rows using a "rowid IN (...)" 11406f82e85aSdrh ** construct. 11416f82e85aSdrh */ 11426f82e85aSdrh assert( pLoop->u.btree.nEq==1 ); 11436f82e85aSdrh pTerm = pLoop->aLTerm[0]; 11446f82e85aSdrh assert( pTerm!=0 ); 11456f82e85aSdrh assert( pTerm->pExpr!=0 ); 11466f82e85aSdrh assert( omitTable==0 ); 11476f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 11486f82e85aSdrh iReleaseReg = ++pParse->nMem; 11496f82e85aSdrh iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); 11506f82e85aSdrh if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); 11516f82e85aSdrh addrNxt = pLevel->addrNxt; 1152eeb9565aSdrh sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); 11536f82e85aSdrh VdbeCoverage(v); 11546f82e85aSdrh sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); 11556f82e85aSdrh sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 11566f82e85aSdrh VdbeComment((v, "pk")); 11576f82e85aSdrh pLevel->op = OP_Noop; 11586f82e85aSdrh }else if( (pLoop->wsFlags & WHERE_IPK)!=0 11596f82e85aSdrh && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 11606f82e85aSdrh ){ 11616f82e85aSdrh /* Case 3: We have an inequality comparison against the ROWID field. 11626f82e85aSdrh */ 11636f82e85aSdrh int testOp = OP_Noop; 11646f82e85aSdrh int start; 11656f82e85aSdrh int memEndValue = 0; 11666f82e85aSdrh WhereTerm *pStart, *pEnd; 11676f82e85aSdrh 11686f82e85aSdrh assert( omitTable==0 ); 11696f82e85aSdrh j = 0; 11706f82e85aSdrh pStart = pEnd = 0; 11716f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; 11726f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; 11736f82e85aSdrh assert( pStart!=0 || pEnd!=0 ); 11746f82e85aSdrh if( bRev ){ 11756f82e85aSdrh pTerm = pStart; 11766f82e85aSdrh pStart = pEnd; 11776f82e85aSdrh pEnd = pTerm; 11786f82e85aSdrh } 1179b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); 11806f82e85aSdrh if( pStart ){ 11816f82e85aSdrh Expr *pX; /* The expression that defines the start bound */ 11826f82e85aSdrh int r1, rTemp; /* Registers for holding the start boundary */ 1183*19ff12ddSdan int op; /* Cursor seek operation */ 11846f82e85aSdrh 11856f82e85aSdrh /* The following constant maps TK_xx codes into corresponding 11866f82e85aSdrh ** seek opcodes. It depends on a particular ordering of TK_xx 11876f82e85aSdrh */ 11886f82e85aSdrh const u8 aMoveOp[] = { 11896f82e85aSdrh /* TK_GT */ OP_SeekGT, 11906f82e85aSdrh /* TK_LE */ OP_SeekLE, 11916f82e85aSdrh /* TK_LT */ OP_SeekLT, 11926f82e85aSdrh /* TK_GE */ OP_SeekGE 11936f82e85aSdrh }; 11946f82e85aSdrh assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ 11956f82e85aSdrh assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ 11966f82e85aSdrh assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ 11976f82e85aSdrh 11986f82e85aSdrh assert( (pStart->wtFlags & TERM_VNULL)==0 ); 11996f82e85aSdrh testcase( pStart->wtFlags & TERM_VIRTUAL ); 12006f82e85aSdrh pX = pStart->pExpr; 12016f82e85aSdrh assert( pX!=0 ); 12026f82e85aSdrh testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ 1203*19ff12ddSdan if( pX->pRight->flags & EP_Vector ){ 1204*19ff12ddSdan r1 = rTemp = sqlite3GetTempReg(pParse); 1205*19ff12ddSdan codeExprOrVector(pParse, pX->pRight, r1, 1); 1206*19ff12ddSdan op = aMoveOp[(pX->op - TK_GT) | 0x0001]; 1207*19ff12ddSdan }else{ 12086f82e85aSdrh r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); 1209*19ff12ddSdan disableTerm(pLevel, pStart); 1210*19ff12ddSdan op = aMoveOp[(pX->op - TK_GT)]; 1211*19ff12ddSdan } 1212*19ff12ddSdan sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); 12136f82e85aSdrh VdbeComment((v, "pk")); 12146f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GT); 12156f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LE); 12166f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LT); 12176f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GE); 12186f82e85aSdrh sqlite3ExprCacheAffinityChange(pParse, r1, 1); 12196f82e85aSdrh sqlite3ReleaseTempReg(pParse, rTemp); 12206f82e85aSdrh }else{ 12216f82e85aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); 12226f82e85aSdrh VdbeCoverageIf(v, bRev==0); 12236f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 12246f82e85aSdrh } 12256f82e85aSdrh if( pEnd ){ 12266f82e85aSdrh Expr *pX; 12276f82e85aSdrh pX = pEnd->pExpr; 12286f82e85aSdrh assert( pX!=0 ); 12296f82e85aSdrh assert( (pEnd->wtFlags & TERM_VNULL)==0 ); 12306f82e85aSdrh testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ 12316f82e85aSdrh testcase( pEnd->wtFlags & TERM_VIRTUAL ); 12326f82e85aSdrh memEndValue = ++pParse->nMem; 1233*19ff12ddSdan codeExprOrVector(pParse, pX->pRight, memEndValue, 1); 1234*19ff12ddSdan if( !(pX->pRight->flags&EP_Vector) && (pX->op==TK_LT || pX->op==TK_GT) ){ 12356f82e85aSdrh testOp = bRev ? OP_Le : OP_Ge; 12366f82e85aSdrh }else{ 12376f82e85aSdrh testOp = bRev ? OP_Lt : OP_Gt; 12386f82e85aSdrh } 12396f82e85aSdrh disableTerm(pLevel, pEnd); 12406f82e85aSdrh } 12416f82e85aSdrh start = sqlite3VdbeCurrentAddr(v); 12426f82e85aSdrh pLevel->op = bRev ? OP_Prev : OP_Next; 12436f82e85aSdrh pLevel->p1 = iCur; 12446f82e85aSdrh pLevel->p2 = start; 12456f82e85aSdrh assert( pLevel->p5==0 ); 12466f82e85aSdrh if( testOp!=OP_Noop ){ 12476f82e85aSdrh iRowidReg = ++pParse->nMem; 12486f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); 12496f82e85aSdrh sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 12506f82e85aSdrh sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); 12516f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Le); 12526f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Lt); 12536f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Ge); 12546f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Gt); 12556f82e85aSdrh sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); 12566f82e85aSdrh } 12576f82e85aSdrh }else if( pLoop->wsFlags & WHERE_INDEXED ){ 12586f82e85aSdrh /* Case 4: A scan using an index. 12596f82e85aSdrh ** 12606f82e85aSdrh ** The WHERE clause may contain zero or more equality 12616f82e85aSdrh ** terms ("==" or "IN" operators) that refer to the N 12626f82e85aSdrh ** left-most columns of the index. It may also contain 12636f82e85aSdrh ** inequality constraints (>, <, >= or <=) on the indexed 12646f82e85aSdrh ** column that immediately follows the N equalities. Only 12656f82e85aSdrh ** the right-most column can be an inequality - the rest must 12666f82e85aSdrh ** use the "==" and "IN" operators. For example, if the 12676f82e85aSdrh ** index is on (x,y,z), then the following clauses are all 12686f82e85aSdrh ** optimized: 12696f82e85aSdrh ** 12706f82e85aSdrh ** x=5 12716f82e85aSdrh ** x=5 AND y=10 12726f82e85aSdrh ** x=5 AND y<10 12736f82e85aSdrh ** x=5 AND y>5 AND y<10 12746f82e85aSdrh ** x=5 AND y=5 AND z<=10 12756f82e85aSdrh ** 12766f82e85aSdrh ** The z<10 term of the following cannot be used, only 12776f82e85aSdrh ** the x=5 term: 12786f82e85aSdrh ** 12796f82e85aSdrh ** x=5 AND z<10 12806f82e85aSdrh ** 12816f82e85aSdrh ** N may be zero if there are inequality constraints. 12826f82e85aSdrh ** If there are no inequality constraints, then N is at 12836f82e85aSdrh ** least one. 12846f82e85aSdrh ** 12856f82e85aSdrh ** This case is also used when there are no WHERE clause 12866f82e85aSdrh ** constraints but an index is selected anyway, in order 12876f82e85aSdrh ** to force the output order to conform to an ORDER BY. 12886f82e85aSdrh */ 12896f82e85aSdrh static const u8 aStartOp[] = { 12906f82e85aSdrh 0, 12916f82e85aSdrh 0, 12926f82e85aSdrh OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ 12936f82e85aSdrh OP_Last, /* 3: (!start_constraints && startEq && bRev) */ 12946f82e85aSdrh OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ 12956f82e85aSdrh OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ 12966f82e85aSdrh OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ 12976f82e85aSdrh OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ 12986f82e85aSdrh }; 12996f82e85aSdrh static const u8 aEndOp[] = { 13006f82e85aSdrh OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ 13016f82e85aSdrh OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ 13026f82e85aSdrh OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ 13036f82e85aSdrh OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ 13046f82e85aSdrh }; 13056f82e85aSdrh u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ 130671c57db0Sdan u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ 130771c57db0Sdan u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ 13086f82e85aSdrh int regBase; /* Base register holding constraint values */ 13096f82e85aSdrh WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ 13106f82e85aSdrh WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ 13116f82e85aSdrh int startEq; /* True if range start uses ==, >= or <= */ 13126f82e85aSdrh int endEq; /* True if range end uses ==, >= or <= */ 13136f82e85aSdrh int start_constraints; /* Start of range is constrained */ 13146f82e85aSdrh int nConstraint; /* Number of constraint terms */ 13156f82e85aSdrh Index *pIdx; /* The index we will be using */ 13166f82e85aSdrh int iIdxCur; /* The VDBE cursor for the index */ 13176f82e85aSdrh int nExtraReg = 0; /* Number of extra registers needed */ 13186f82e85aSdrh int op; /* Instruction opcode */ 13196f82e85aSdrh char *zStartAff; /* Affinity for start of range constraint */ 13206f82e85aSdrh char cEndAff = 0; /* Affinity for end of range constraint */ 13216f82e85aSdrh u8 bSeekPastNull = 0; /* True to seek past initial nulls */ 13226f82e85aSdrh u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ 13236f82e85aSdrh 13246f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 13256f82e85aSdrh iIdxCur = pLevel->iIdxCur; 13266f82e85aSdrh assert( nEq>=pLoop->nSkip ); 13276f82e85aSdrh 13286f82e85aSdrh /* If this loop satisfies a sort order (pOrderBy) request that 13296f82e85aSdrh ** was passed to this function to implement a "SELECT min(x) ..." 13306f82e85aSdrh ** query, then the caller will only allow the loop to run for 13316f82e85aSdrh ** a single iteration. This means that the first row returned 13326f82e85aSdrh ** should not have a NULL value stored in 'x'. If column 'x' is 13336f82e85aSdrh ** the first one after the nEq equality constraints in the index, 13346f82e85aSdrh ** this requires some special handling. 13356f82e85aSdrh */ 13366f82e85aSdrh assert( pWInfo->pOrderBy==0 13376f82e85aSdrh || pWInfo->pOrderBy->nExpr==1 13386f82e85aSdrh || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); 13396f82e85aSdrh if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 13406f82e85aSdrh && pWInfo->nOBSat>0 13416f82e85aSdrh && (pIdx->nKeyCol>nEq) 13426f82e85aSdrh ){ 13436f82e85aSdrh assert( pLoop->nSkip==0 ); 13446f82e85aSdrh bSeekPastNull = 1; 13456f82e85aSdrh nExtraReg = 1; 13466f82e85aSdrh } 13476f82e85aSdrh 13486f82e85aSdrh /* Find any inequality constraint terms for the start and end 13496f82e85aSdrh ** of the range. 13506f82e85aSdrh */ 13516f82e85aSdrh j = nEq; 13526f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ 13536f82e85aSdrh pRangeStart = pLoop->aLTerm[j++]; 135471c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); 13556f82e85aSdrh /* Like optimization range constraints always occur in pairs */ 13566f82e85aSdrh assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 13576f82e85aSdrh (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); 13586f82e85aSdrh } 13596f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ 13606f82e85aSdrh pRangeEnd = pLoop->aLTerm[j++]; 136171c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); 136241d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 13636f82e85aSdrh if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ 13646f82e85aSdrh assert( pRangeStart!=0 ); /* LIKE opt constraints */ 13656f82e85aSdrh assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ 136644aebff2Sdrh pLevel->iLikeRepCntr = (u32)++pParse->nMem; 136744aebff2Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); 13686f82e85aSdrh VdbeComment((v, "LIKE loop counter")); 13696f82e85aSdrh pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); 137044aebff2Sdrh /* iLikeRepCntr actually stores 2x the counter register number. The 137144aebff2Sdrh ** bottom bit indicates whether the search order is ASC or DESC. */ 137244aebff2Sdrh testcase( bRev ); 137344aebff2Sdrh testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); 137444aebff2Sdrh assert( (bRev & ~1)==0 ); 137544aebff2Sdrh pLevel->iLikeRepCntr <<=1; 137644aebff2Sdrh pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); 13776f82e85aSdrh } 137841d2e66eSdrh #endif 13796f82e85aSdrh if( pRangeStart==0 13806f82e85aSdrh && (j = pIdx->aiColumn[nEq])>=0 13816f82e85aSdrh && pIdx->pTable->aCol[j].notNull==0 13826f82e85aSdrh ){ 13836f82e85aSdrh bSeekPastNull = 1; 13846f82e85aSdrh } 13856f82e85aSdrh } 13866f82e85aSdrh assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); 13876f82e85aSdrh 13886f82e85aSdrh /* If we are doing a reverse order scan on an ascending index, or 13896f82e85aSdrh ** a forward order scan on a descending index, interchange the 13906f82e85aSdrh ** start and end terms (pRangeStart and pRangeEnd). 13916f82e85aSdrh */ 13926f82e85aSdrh if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) 13936f82e85aSdrh || (bRev && pIdx->nKeyCol==nEq) 13946f82e85aSdrh ){ 13956f82e85aSdrh SWAP(WhereTerm *, pRangeEnd, pRangeStart); 13966f82e85aSdrh SWAP(u8, bSeekPastNull, bStopAtNull); 139771c57db0Sdan SWAP(u8, nBtm, nTop); 13986f82e85aSdrh } 13996f82e85aSdrh 1400bcf40a7fSdrh /* Generate code to evaluate all constraint terms using == or IN 1401bcf40a7fSdrh ** and store the values of those terms in an array of registers 1402bcf40a7fSdrh ** starting at regBase. 1403bcf40a7fSdrh */ 1404b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); 1405bcf40a7fSdrh regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); 1406bcf40a7fSdrh assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); 1407bcf40a7fSdrh if( zStartAff ) cEndAff = zStartAff[nEq]; 1408bcf40a7fSdrh addrNxt = pLevel->addrNxt; 1409bcf40a7fSdrh 14106f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); 14116f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); 14126f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); 14136f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); 14146f82e85aSdrh startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); 14156f82e85aSdrh endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); 14166f82e85aSdrh start_constraints = pRangeStart || nEq>0; 14176f82e85aSdrh 14186f82e85aSdrh /* Seek the index cursor to the start of the range. */ 14196f82e85aSdrh nConstraint = nEq; 14206f82e85aSdrh if( pRangeStart ){ 14216f82e85aSdrh Expr *pRight = pRangeStart->pExpr->pRight; 142271c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); 14236f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); 14246f82e85aSdrh if( (pRangeStart->wtFlags & TERM_VNULL)==0 14256f82e85aSdrh && sqlite3ExprCanBeNull(pRight) 14266f82e85aSdrh ){ 14276f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 14286f82e85aSdrh VdbeCoverage(v); 14296f82e85aSdrh } 14306f82e85aSdrh if( zStartAff ){ 14316f82e85aSdrh if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){ 14326f82e85aSdrh /* Since the comparison is to be performed with no conversions 14336f82e85aSdrh ** applied to the operands, set the affinity to apply to pRight to 14346f82e85aSdrh ** SQLITE_AFF_BLOB. */ 14356f82e85aSdrh zStartAff[nEq] = SQLITE_AFF_BLOB; 14366f82e85aSdrh } 14376f82e85aSdrh if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ 14386f82e85aSdrh zStartAff[nEq] = SQLITE_AFF_BLOB; 14396f82e85aSdrh } 14406f82e85aSdrh } 144171c57db0Sdan nConstraint += nBtm; 14426f82e85aSdrh testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); 144371c57db0Sdan if( (pRight->flags & EP_Vector)==0 ){ 144471c57db0Sdan disableTerm(pLevel, pRangeStart); 144571c57db0Sdan }else{ 144671c57db0Sdan startEq = 1; 144771c57db0Sdan } 1448426f4ab0Sdrh bSeekPastNull = 0; 14496f82e85aSdrh }else if( bSeekPastNull ){ 14506f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 14516f82e85aSdrh nConstraint++; 14526f82e85aSdrh startEq = 0; 14536f82e85aSdrh start_constraints = 1; 14546f82e85aSdrh } 14556f82e85aSdrh codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); 14560bf2ad6aSdrh if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ 14570bf2ad6aSdrh /* The skip-scan logic inside the call to codeAllEqualityConstraints() 14580bf2ad6aSdrh ** above has already left the cursor sitting on the correct row, 14590bf2ad6aSdrh ** so no further seeking is needed */ 14600bf2ad6aSdrh }else{ 14616f82e85aSdrh op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; 14626f82e85aSdrh assert( op!=0 ); 14636f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 14646f82e85aSdrh VdbeCoverage(v); 14656f82e85aSdrh VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 14666f82e85aSdrh VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 14676f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); 14686f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 14696f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 14706f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); 1471a6d2f8ebSdrh } 14726f82e85aSdrh 14736f82e85aSdrh /* Load the value for the inequality constraint at the end of the 14746f82e85aSdrh ** range (if any). 14756f82e85aSdrh */ 14766f82e85aSdrh nConstraint = nEq; 14776f82e85aSdrh if( pRangeEnd ){ 14786f82e85aSdrh Expr *pRight = pRangeEnd->pExpr->pRight; 14796f82e85aSdrh sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); 148071c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nTop); 14816f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); 14826f82e85aSdrh if( (pRangeEnd->wtFlags & TERM_VNULL)==0 14836f82e85aSdrh && sqlite3ExprCanBeNull(pRight) 14846f82e85aSdrh ){ 14856f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 14866f82e85aSdrh VdbeCoverage(v); 14876f82e85aSdrh } 14886f82e85aSdrh if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB 14896f82e85aSdrh && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff) 14906f82e85aSdrh ){ 14916f82e85aSdrh codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff); 14926f82e85aSdrh } 149371c57db0Sdan nConstraint += nTop; 14946f82e85aSdrh testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); 149571c57db0Sdan 149671c57db0Sdan if( (pRight->flags & EP_Vector)==0 ){ 149771c57db0Sdan disableTerm(pLevel, pRangeEnd); 149871c57db0Sdan }else{ 149971c57db0Sdan endEq = 1; 150071c57db0Sdan } 15016f82e85aSdrh }else if( bStopAtNull ){ 15026f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 15036f82e85aSdrh endEq = 0; 15046f82e85aSdrh nConstraint++; 15056f82e85aSdrh } 15066f82e85aSdrh sqlite3DbFree(db, zStartAff); 15076f82e85aSdrh 15086f82e85aSdrh /* Top of the loop body */ 15096f82e85aSdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v); 15106f82e85aSdrh 15116f82e85aSdrh /* Check if the index cursor is past the end of the range. */ 15126f82e85aSdrh if( nConstraint ){ 15136f82e85aSdrh op = aEndOp[bRev*2 + endEq]; 15146f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 15156f82e85aSdrh testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 15166f82e85aSdrh testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 15176f82e85aSdrh testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 15186f82e85aSdrh testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 15196f82e85aSdrh } 15206f82e85aSdrh 15216f82e85aSdrh /* Seek the table cursor, if required */ 15226f82e85aSdrh if( omitTable ){ 15236f82e85aSdrh /* pIdx is a covering index. No need to access the main table. */ 15246f82e85aSdrh }else if( HasRowid(pIdx->pTable) ){ 1525f09c4823Sdrh if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){ 15266f82e85aSdrh iRowidReg = ++pParse->nMem; 15276f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); 15286f82e85aSdrh sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 1529c6157e19Sdan sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg); 153066336f37Sdrh VdbeCoverage(v); 1531c6157e19Sdan }else{ 1532784c1b93Sdrh codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); 1533c6157e19Sdan } 15346f82e85aSdrh }else if( iCur!=iIdxCur ){ 15356f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); 15366f82e85aSdrh iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); 15376f82e85aSdrh for(j=0; j<pPk->nKeyCol; j++){ 15386f82e85aSdrh k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); 15396f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); 15406f82e85aSdrh } 15416f82e85aSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, 15426f82e85aSdrh iRowidReg, pPk->nKeyCol); VdbeCoverage(v); 15436f82e85aSdrh } 15446f82e85aSdrh 154571c57db0Sdan /* Record the instruction used to terminate the loop. */ 15466f82e85aSdrh if( pLoop->wsFlags & WHERE_ONEROW ){ 15476f82e85aSdrh pLevel->op = OP_Noop; 15486f82e85aSdrh }else if( bRev ){ 15496f82e85aSdrh pLevel->op = OP_Prev; 15506f82e85aSdrh }else{ 15516f82e85aSdrh pLevel->op = OP_Next; 15526f82e85aSdrh } 15536f82e85aSdrh pLevel->p1 = iIdxCur; 15546f82e85aSdrh pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; 15556f82e85aSdrh if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ 15566f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 15576f82e85aSdrh }else{ 15586f82e85aSdrh assert( pLevel->p5==0 ); 15596f82e85aSdrh } 15606f82e85aSdrh }else 15616f82e85aSdrh 15626f82e85aSdrh #ifndef SQLITE_OMIT_OR_OPTIMIZATION 15636f82e85aSdrh if( pLoop->wsFlags & WHERE_MULTI_OR ){ 15646f82e85aSdrh /* Case 5: Two or more separately indexed terms connected by OR 15656f82e85aSdrh ** 15666f82e85aSdrh ** Example: 15676f82e85aSdrh ** 15686f82e85aSdrh ** CREATE TABLE t1(a,b,c,d); 15696f82e85aSdrh ** CREATE INDEX i1 ON t1(a); 15706f82e85aSdrh ** CREATE INDEX i2 ON t1(b); 15716f82e85aSdrh ** CREATE INDEX i3 ON t1(c); 15726f82e85aSdrh ** 15736f82e85aSdrh ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) 15746f82e85aSdrh ** 15756f82e85aSdrh ** In the example, there are three indexed terms connected by OR. 15766f82e85aSdrh ** The top of the loop looks like this: 15776f82e85aSdrh ** 15786f82e85aSdrh ** Null 1 # Zero the rowset in reg 1 15796f82e85aSdrh ** 15806f82e85aSdrh ** Then, for each indexed term, the following. The arguments to 15816f82e85aSdrh ** RowSetTest are such that the rowid of the current row is inserted 15826f82e85aSdrh ** into the RowSet. If it is already present, control skips the 15836f82e85aSdrh ** Gosub opcode and jumps straight to the code generated by WhereEnd(). 15846f82e85aSdrh ** 15856f82e85aSdrh ** sqlite3WhereBegin(<term>) 15866f82e85aSdrh ** RowSetTest # Insert rowid into rowset 15876f82e85aSdrh ** Gosub 2 A 15886f82e85aSdrh ** sqlite3WhereEnd() 15896f82e85aSdrh ** 15906f82e85aSdrh ** Following the above, code to terminate the loop. Label A, the target 15916f82e85aSdrh ** of the Gosub above, jumps to the instruction right after the Goto. 15926f82e85aSdrh ** 15936f82e85aSdrh ** Null 1 # Zero the rowset in reg 1 15946f82e85aSdrh ** Goto B # The loop is finished. 15956f82e85aSdrh ** 15966f82e85aSdrh ** A: <loop body> # Return data, whatever. 15976f82e85aSdrh ** 15986f82e85aSdrh ** Return 2 # Jump back to the Gosub 15996f82e85aSdrh ** 16006f82e85aSdrh ** B: <after the loop> 16016f82e85aSdrh ** 16026f82e85aSdrh ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then 16036f82e85aSdrh ** use an ephemeral index instead of a RowSet to record the primary 16046f82e85aSdrh ** keys of the rows we have already seen. 16056f82e85aSdrh ** 16066f82e85aSdrh */ 16076f82e85aSdrh WhereClause *pOrWc; /* The OR-clause broken out into subterms */ 16086f82e85aSdrh SrcList *pOrTab; /* Shortened table list or OR-clause generation */ 16096f82e85aSdrh Index *pCov = 0; /* Potential covering index (or NULL) */ 16106f82e85aSdrh int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ 16116f82e85aSdrh 16126f82e85aSdrh int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ 16136f82e85aSdrh int regRowset = 0; /* Register for RowSet object */ 16146f82e85aSdrh int regRowid = 0; /* Register holding rowid */ 16156f82e85aSdrh int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ 16166f82e85aSdrh int iRetInit; /* Address of regReturn init */ 16176f82e85aSdrh int untestedTerms = 0; /* Some terms not completely tested */ 16186f82e85aSdrh int ii; /* Loop counter */ 16196f82e85aSdrh u16 wctrlFlags; /* Flags for sub-WHERE clause */ 16206f82e85aSdrh Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ 16216f82e85aSdrh Table *pTab = pTabItem->pTab; 16226f82e85aSdrh 16236f82e85aSdrh pTerm = pLoop->aLTerm[0]; 16246f82e85aSdrh assert( pTerm!=0 ); 16256f82e85aSdrh assert( pTerm->eOperator & WO_OR ); 16266f82e85aSdrh assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); 16276f82e85aSdrh pOrWc = &pTerm->u.pOrInfo->wc; 16286f82e85aSdrh pLevel->op = OP_Return; 16296f82e85aSdrh pLevel->p1 = regReturn; 16306f82e85aSdrh 16316f82e85aSdrh /* Set up a new SrcList in pOrTab containing the table being scanned 16326f82e85aSdrh ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. 16336f82e85aSdrh ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). 16346f82e85aSdrh */ 16356f82e85aSdrh if( pWInfo->nLevel>1 ){ 16366f82e85aSdrh int nNotReady; /* The number of notReady tables */ 16376f82e85aSdrh struct SrcList_item *origSrc; /* Original list of tables */ 16386f82e85aSdrh nNotReady = pWInfo->nLevel - iLevel - 1; 16396f82e85aSdrh pOrTab = sqlite3StackAllocRaw(db, 16406f82e85aSdrh sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); 16416f82e85aSdrh if( pOrTab==0 ) return notReady; 16426f82e85aSdrh pOrTab->nAlloc = (u8)(nNotReady + 1); 16436f82e85aSdrh pOrTab->nSrc = pOrTab->nAlloc; 16446f82e85aSdrh memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); 16456f82e85aSdrh origSrc = pWInfo->pTabList->a; 16466f82e85aSdrh for(k=1; k<=nNotReady; k++){ 16476f82e85aSdrh memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); 16486f82e85aSdrh } 16496f82e85aSdrh }else{ 16506f82e85aSdrh pOrTab = pWInfo->pTabList; 16516f82e85aSdrh } 16526f82e85aSdrh 16536f82e85aSdrh /* Initialize the rowset register to contain NULL. An SQL NULL is 16546f82e85aSdrh ** equivalent to an empty rowset. Or, create an ephemeral index 16556f82e85aSdrh ** capable of holding primary keys in the case of a WITHOUT ROWID. 16566f82e85aSdrh ** 16576f82e85aSdrh ** Also initialize regReturn to contain the address of the instruction 16586f82e85aSdrh ** immediately following the OP_Return at the bottom of the loop. This 16596f82e85aSdrh ** is required in a few obscure LEFT JOIN cases where control jumps 16606f82e85aSdrh ** over the top of the loop into the body of it. In this case the 16616f82e85aSdrh ** correct response for the end-of-loop code (the OP_Return) is to 16626f82e85aSdrh ** fall through to the next instruction, just as an OP_Next does if 16636f82e85aSdrh ** called on an uninitialized cursor. 16646f82e85aSdrh */ 16656f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 16666f82e85aSdrh if( HasRowid(pTab) ){ 16676f82e85aSdrh regRowset = ++pParse->nMem; 16686f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); 16696f82e85aSdrh }else{ 16706f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 16716f82e85aSdrh regRowset = pParse->nTab++; 16726f82e85aSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); 16736f82e85aSdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk); 16746f82e85aSdrh } 16756f82e85aSdrh regRowid = ++pParse->nMem; 16766f82e85aSdrh } 16776f82e85aSdrh iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); 16786f82e85aSdrh 16796f82e85aSdrh /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y 16806f82e85aSdrh ** Then for every term xN, evaluate as the subexpression: xN AND z 16816f82e85aSdrh ** That way, terms in y that are factored into the disjunction will 16826f82e85aSdrh ** be picked up by the recursive calls to sqlite3WhereBegin() below. 16836f82e85aSdrh ** 16846f82e85aSdrh ** Actually, each subexpression is converted to "xN AND w" where w is 16856f82e85aSdrh ** the "interesting" terms of z - terms that did not originate in the 16866f82e85aSdrh ** ON or USING clause of a LEFT JOIN, and terms that are usable as 16876f82e85aSdrh ** indices. 16886f82e85aSdrh ** 16896f82e85aSdrh ** This optimization also only applies if the (x1 OR x2 OR ...) term 16906f82e85aSdrh ** is not contained in the ON clause of a LEFT JOIN. 16916f82e85aSdrh ** See ticket http://www.sqlite.org/src/info/f2369304e4 16926f82e85aSdrh */ 16936f82e85aSdrh if( pWC->nTerm>1 ){ 16946f82e85aSdrh int iTerm; 16956f82e85aSdrh for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ 16966f82e85aSdrh Expr *pExpr = pWC->a[iTerm].pExpr; 16976f82e85aSdrh if( &pWC->a[iTerm] == pTerm ) continue; 16986f82e85aSdrh if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; 16993b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); 17003b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); 17013b83f0cdSdrh if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; 17026f82e85aSdrh if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; 17036f82e85aSdrh testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); 17046f82e85aSdrh pExpr = sqlite3ExprDup(db, pExpr, 0); 17056f82e85aSdrh pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); 17066f82e85aSdrh } 17076f82e85aSdrh if( pAndExpr ){ 17081167d327Sdrh pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0); 17096f82e85aSdrh } 17106f82e85aSdrh } 17116f82e85aSdrh 17126f82e85aSdrh /* Run a separate WHERE clause for each term of the OR clause. After 17136f82e85aSdrh ** eliminating duplicates from other WHERE clauses, the action for each 17146f82e85aSdrh ** sub-WHERE clause is to to invoke the main loop body as a subroutine. 17156f82e85aSdrh */ 1716ce943bc8Sdrh wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE); 17176f82e85aSdrh for(ii=0; ii<pOrWc->nTerm; ii++){ 17186f82e85aSdrh WhereTerm *pOrTerm = &pOrWc->a[ii]; 17196f82e85aSdrh if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ 17206f82e85aSdrh WhereInfo *pSubWInfo; /* Info for single OR-term scan */ 17216f82e85aSdrh Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ 1722728e0f91Sdrh int jmp1 = 0; /* Address of jump operation */ 17236f82e85aSdrh if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ 17246f82e85aSdrh pAndExpr->pLeft = pOrExpr; 17256f82e85aSdrh pOrExpr = pAndExpr; 17266f82e85aSdrh } 17276f82e85aSdrh /* Loop through table entries that match term pOrTerm. */ 17286f82e85aSdrh WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); 17296f82e85aSdrh pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 17306f82e85aSdrh wctrlFlags, iCovCur); 17316f82e85aSdrh assert( pSubWInfo || pParse->nErr || db->mallocFailed ); 17326f82e85aSdrh if( pSubWInfo ){ 17336f82e85aSdrh WhereLoop *pSubLoop; 17346f82e85aSdrh int addrExplain = sqlite3WhereExplainOneScan( 17356f82e85aSdrh pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 17366f82e85aSdrh ); 17376f82e85aSdrh sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); 17386f82e85aSdrh 17396f82e85aSdrh /* This is the sub-WHERE clause body. First skip over 17406f82e85aSdrh ** duplicate rows from prior sub-WHERE clauses, and record the 17416f82e85aSdrh ** rowid (or PRIMARY KEY) for the current row so that the same 17426f82e85aSdrh ** row will be skipped in subsequent sub-WHERE clauses. 17436f82e85aSdrh */ 17446f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 17456f82e85aSdrh int r; 17466f82e85aSdrh int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); 17476f82e85aSdrh if( HasRowid(pTab) ){ 17486f82e85aSdrh r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); 1749728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, 1750728e0f91Sdrh r,iSet); 17516f82e85aSdrh VdbeCoverage(v); 17526f82e85aSdrh }else{ 17536f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 17546f82e85aSdrh int nPk = pPk->nKeyCol; 17556f82e85aSdrh int iPk; 17566f82e85aSdrh 17576f82e85aSdrh /* Read the PK into an array of temp registers. */ 17586f82e85aSdrh r = sqlite3GetTempRange(pParse, nPk); 17596f82e85aSdrh for(iPk=0; iPk<nPk; iPk++){ 17606f82e85aSdrh int iCol = pPk->aiColumn[iPk]; 1761ce78bc6eSdrh sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk); 17626f82e85aSdrh } 17636f82e85aSdrh 17646f82e85aSdrh /* Check if the temp table already contains this key. If so, 17656f82e85aSdrh ** the row has already been included in the result set and 17666f82e85aSdrh ** can be ignored (by jumping past the Gosub below). Otherwise, 17676f82e85aSdrh ** insert the key into the temp table and proceed with processing 17686f82e85aSdrh ** the row. 17696f82e85aSdrh ** 17706f82e85aSdrh ** Use some of the same optimizations as OP_RowSetTest: If iSet 17716f82e85aSdrh ** is zero, assume that the key cannot already be present in 17726f82e85aSdrh ** the temp table. And if iSet is -1, assume that there is no 17736f82e85aSdrh ** need to insert the key into the temp table, as it will never 17746f82e85aSdrh ** be tested for. */ 17756f82e85aSdrh if( iSet ){ 1776728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); 17776f82e85aSdrh VdbeCoverage(v); 17786f82e85aSdrh } 17796f82e85aSdrh if( iSet>=0 ){ 17806f82e85aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); 17816f82e85aSdrh sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0); 17826f82e85aSdrh if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 17836f82e85aSdrh } 17846f82e85aSdrh 17856f82e85aSdrh /* Release the array of temp registers */ 17866f82e85aSdrh sqlite3ReleaseTempRange(pParse, r, nPk); 17876f82e85aSdrh } 17886f82e85aSdrh } 17896f82e85aSdrh 17906f82e85aSdrh /* Invoke the main loop body as a subroutine */ 17916f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); 17926f82e85aSdrh 17936f82e85aSdrh /* Jump here (skipping the main loop body subroutine) if the 17946f82e85aSdrh ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ 1795728e0f91Sdrh if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); 17966f82e85aSdrh 17976f82e85aSdrh /* The pSubWInfo->untestedTerms flag means that this OR term 17986f82e85aSdrh ** contained one or more AND term from a notReady table. The 17996f82e85aSdrh ** terms from the notReady table could not be tested and will 18006f82e85aSdrh ** need to be tested later. 18016f82e85aSdrh */ 18026f82e85aSdrh if( pSubWInfo->untestedTerms ) untestedTerms = 1; 18036f82e85aSdrh 18046f82e85aSdrh /* If all of the OR-connected terms are optimized using the same 18056f82e85aSdrh ** index, and the index is opened using the same cursor number 18066f82e85aSdrh ** by each call to sqlite3WhereBegin() made by this loop, it may 18076f82e85aSdrh ** be possible to use that index as a covering index. 18086f82e85aSdrh ** 18096f82e85aSdrh ** If the call to sqlite3WhereBegin() above resulted in a scan that 18106f82e85aSdrh ** uses an index, and this is either the first OR-connected term 18116f82e85aSdrh ** processed or the index is the same as that used by all previous 18126f82e85aSdrh ** terms, set pCov to the candidate covering index. Otherwise, set 18136f82e85aSdrh ** pCov to NULL to indicate that no candidate covering index will 18146f82e85aSdrh ** be available. 18156f82e85aSdrh */ 18166f82e85aSdrh pSubLoop = pSubWInfo->a[0].pWLoop; 18176f82e85aSdrh assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 18186f82e85aSdrh if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 18196f82e85aSdrh && (ii==0 || pSubLoop->u.btree.pIndex==pCov) 18206f82e85aSdrh && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) 18216f82e85aSdrh ){ 18226f82e85aSdrh assert( pSubWInfo->a[0].iIdxCur==iCovCur ); 18236f82e85aSdrh pCov = pSubLoop->u.btree.pIndex; 18246f82e85aSdrh }else{ 18256f82e85aSdrh pCov = 0; 18266f82e85aSdrh } 18276f82e85aSdrh 18286f82e85aSdrh /* Finish the loop through table entries that match term pOrTerm. */ 18296f82e85aSdrh sqlite3WhereEnd(pSubWInfo); 18306f82e85aSdrh } 18316f82e85aSdrh } 18326f82e85aSdrh } 18336f82e85aSdrh pLevel->u.pCovidx = pCov; 18346f82e85aSdrh if( pCov ) pLevel->iIdxCur = iCovCur; 18356f82e85aSdrh if( pAndExpr ){ 18366f82e85aSdrh pAndExpr->pLeft = 0; 18376f82e85aSdrh sqlite3ExprDelete(db, pAndExpr); 18386f82e85aSdrh } 18396f82e85aSdrh sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); 1840076e85f5Sdrh sqlite3VdbeGoto(v, pLevel->addrBrk); 18416f82e85aSdrh sqlite3VdbeResolveLabel(v, iLoopBody); 18426f82e85aSdrh 18436f82e85aSdrh if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); 18446f82e85aSdrh if( !untestedTerms ) disableTerm(pLevel, pTerm); 18456f82e85aSdrh }else 18466f82e85aSdrh #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 18476f82e85aSdrh 18486f82e85aSdrh { 18496f82e85aSdrh /* Case 6: There is no usable index. We must do a complete 18506f82e85aSdrh ** scan of the entire table. 18516f82e85aSdrh */ 18526f82e85aSdrh static const u8 aStep[] = { OP_Next, OP_Prev }; 18536f82e85aSdrh static const u8 aStart[] = { OP_Rewind, OP_Last }; 18546f82e85aSdrh assert( bRev==0 || bRev==1 ); 18558a48b9c0Sdrh if( pTabItem->fg.isRecursive ){ 18566f82e85aSdrh /* Tables marked isRecursive have only a single row that is stored in 18576f82e85aSdrh ** a pseudo-cursor. No need to Rewind or Next such cursors. */ 18586f82e85aSdrh pLevel->op = OP_Noop; 18596f82e85aSdrh }else{ 1860b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, 0); 18616f82e85aSdrh pLevel->op = aStep[bRev]; 18626f82e85aSdrh pLevel->p1 = iCur; 18636f82e85aSdrh pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); 18646f82e85aSdrh VdbeCoverageIf(v, bRev==0); 18656f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 18666f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 18676f82e85aSdrh } 18686f82e85aSdrh } 18696f82e85aSdrh 18706f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 18716f82e85aSdrh pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); 18726f82e85aSdrh #endif 18736f82e85aSdrh 18746f82e85aSdrh /* Insert code to test every subexpression that can be completely 18756f82e85aSdrh ** computed using the current set of tables. 18766f82e85aSdrh */ 18776f82e85aSdrh for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 18786f82e85aSdrh Expr *pE; 18796f82e85aSdrh int skipLikeAddr = 0; 18806f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 18816f82e85aSdrh testcase( pTerm->wtFlags & TERM_CODED ); 18826f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 18836f82e85aSdrh if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 18846f82e85aSdrh testcase( pWInfo->untestedTerms==0 1885ce943bc8Sdrh && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); 18866f82e85aSdrh pWInfo->untestedTerms = 1; 18876f82e85aSdrh continue; 18886f82e85aSdrh } 18896f82e85aSdrh pE = pTerm->pExpr; 18906f82e85aSdrh assert( pE!=0 ); 18916f82e85aSdrh if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ 18926f82e85aSdrh continue; 18936f82e85aSdrh } 18946f82e85aSdrh if( pTerm->wtFlags & TERM_LIKECOND ){ 189544aebff2Sdrh /* If the TERM_LIKECOND flag is set, that means that the range search 189644aebff2Sdrh ** is sufficient to guarantee that the LIKE operator is true, so we 189744aebff2Sdrh ** can skip the call to the like(A,B) function. But this only works 189844aebff2Sdrh ** for strings. So do not skip the call to the function on the pass 189944aebff2Sdrh ** that compares BLOBs. */ 190041d2e66eSdrh #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 190141d2e66eSdrh continue; 190241d2e66eSdrh #else 190344aebff2Sdrh u32 x = pLevel->iLikeRepCntr; 190444aebff2Sdrh assert( x>0 ); 190544aebff2Sdrh skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1)); 19066f82e85aSdrh VdbeCoverage(v); 190741d2e66eSdrh #endif 19086f82e85aSdrh } 19096f82e85aSdrh sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); 19106f82e85aSdrh if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); 19116f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 19126f82e85aSdrh } 19136f82e85aSdrh 19146f82e85aSdrh /* Insert code to test for implied constraints based on transitivity 19156f82e85aSdrh ** of the "==" operator. 19166f82e85aSdrh ** 19176f82e85aSdrh ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" 19186f82e85aSdrh ** and we are coding the t1 loop and the t2 loop has not yet coded, 19196f82e85aSdrh ** then we cannot use the "t1.a=t2.b" constraint, but we can code 19206f82e85aSdrh ** the implied "t1.a=123" constraint. 19216f82e85aSdrh */ 19226f82e85aSdrh for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 19236f82e85aSdrh Expr *pE, *pEAlt; 19246f82e85aSdrh WhereTerm *pAlt; 19256f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 19266f82e85aSdrh if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; 19276f82e85aSdrh if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; 19286f82e85aSdrh if( pTerm->leftCursor!=iCur ) continue; 19296f82e85aSdrh if( pLevel->iLeftJoin ) continue; 19306f82e85aSdrh pE = pTerm->pExpr; 19316f82e85aSdrh assert( !ExprHasProperty(pE, EP_FromJoin) ); 19326f82e85aSdrh assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); 19336f82e85aSdrh pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, 19346f82e85aSdrh WO_EQ|WO_IN|WO_IS, 0); 19356f82e85aSdrh if( pAlt==0 ) continue; 19366f82e85aSdrh if( pAlt->wtFlags & (TERM_CODED) ) continue; 19376f82e85aSdrh testcase( pAlt->eOperator & WO_EQ ); 19386f82e85aSdrh testcase( pAlt->eOperator & WO_IS ); 19396f82e85aSdrh testcase( pAlt->eOperator & WO_IN ); 19406f82e85aSdrh VdbeModuleComment((v, "begin transitive constraint")); 19416f82e85aSdrh pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt)); 19426f82e85aSdrh if( pEAlt ){ 19436f82e85aSdrh *pEAlt = *pAlt->pExpr; 19446f82e85aSdrh pEAlt->pLeft = pE->pLeft; 19456f82e85aSdrh sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL); 19466f82e85aSdrh sqlite3StackFree(db, pEAlt); 19476f82e85aSdrh } 19486f82e85aSdrh } 19496f82e85aSdrh 19506f82e85aSdrh /* For a LEFT OUTER JOIN, generate code that will record the fact that 19516f82e85aSdrh ** at least one row of the right table has matched the left table. 19526f82e85aSdrh */ 19536f82e85aSdrh if( pLevel->iLeftJoin ){ 19546f82e85aSdrh pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); 19556f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); 19566f82e85aSdrh VdbeComment((v, "record LEFT JOIN hit")); 19576f82e85aSdrh sqlite3ExprCacheClear(pParse); 19586f82e85aSdrh for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ 19596f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 19606f82e85aSdrh testcase( pTerm->wtFlags & TERM_CODED ); 19616f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 19626f82e85aSdrh if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 19636f82e85aSdrh assert( pWInfo->untestedTerms ); 19646f82e85aSdrh continue; 19656f82e85aSdrh } 19666f82e85aSdrh assert( pTerm->pExpr ); 19676f82e85aSdrh sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 19686f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 19696f82e85aSdrh } 19706f82e85aSdrh } 19716f82e85aSdrh 19726f82e85aSdrh return pLevel->notReady; 19736f82e85aSdrh } 1974