16f82e85aSdrh /* 26f82e85aSdrh ** 2015-06-06 36f82e85aSdrh ** 46f82e85aSdrh ** The author disclaims copyright to this source code. In place of 56f82e85aSdrh ** a legal notice, here is a blessing: 66f82e85aSdrh ** 76f82e85aSdrh ** May you do good and not evil. 86f82e85aSdrh ** May you find forgiveness for yourself and forgive others. 96f82e85aSdrh ** May you share freely, never taking more than you give. 106f82e85aSdrh ** 116f82e85aSdrh ************************************************************************* 126f82e85aSdrh ** This module contains C code that generates VDBE code used to process 136f82e85aSdrh ** the WHERE clause of SQL statements. 146f82e85aSdrh ** 156f82e85aSdrh ** This file was split off from where.c on 2015-06-06 in order to reduce the 166f82e85aSdrh ** size of where.c and make it easier to edit. This file contains the routines 176f82e85aSdrh ** that actually generate the bulk of the WHERE loop code. The original where.c 186f82e85aSdrh ** file retains the code that does query planning and analysis. 196f82e85aSdrh */ 206f82e85aSdrh #include "sqliteInt.h" 216f82e85aSdrh #include "whereInt.h" 226f82e85aSdrh 236f82e85aSdrh #ifndef SQLITE_OMIT_EXPLAIN 241d9bc9b7Sdan 251d9bc9b7Sdan /* 261d9bc9b7Sdan ** Return the name of the i-th column of the pIdx index. 271d9bc9b7Sdan */ 281d9bc9b7Sdan static const char *explainIndexColumnName(Index *pIdx, int i){ 291d9bc9b7Sdan i = pIdx->aiColumn[i]; 301d9bc9b7Sdan if( i==XN_EXPR ) return "<expr>"; 311d9bc9b7Sdan if( i==XN_ROWID ) return "rowid"; 321d9bc9b7Sdan return pIdx->pTable->aCol[i].zName; 331d9bc9b7Sdan } 341d9bc9b7Sdan 356f82e85aSdrh /* 366f82e85aSdrh ** This routine is a helper for explainIndexRange() below 376f82e85aSdrh ** 386f82e85aSdrh ** pStr holds the text of an expression that we are building up one term 396f82e85aSdrh ** at a time. This routine adds a new term to the end of the expression. 406f82e85aSdrh ** Terms are separated by AND so add the "AND" text for second and subsequent 416f82e85aSdrh ** terms only. 426f82e85aSdrh */ 436f82e85aSdrh static void explainAppendTerm( 446f82e85aSdrh StrAccum *pStr, /* The text expression being built */ 451d9bc9b7Sdan Index *pIdx, /* Index to read column names from */ 461d9bc9b7Sdan int nTerm, /* Number of terms */ 471d9bc9b7Sdan int iTerm, /* Zero-based index of first term. */ 481d9bc9b7Sdan int bAnd, /* Non-zero to append " AND " */ 496f82e85aSdrh const char *zOp /* Name of the operator */ 506f82e85aSdrh ){ 511d9bc9b7Sdan int i; 521d9bc9b7Sdan 531d9bc9b7Sdan assert( nTerm>=1 ); 540cdbe1aeSdrh if( bAnd ) sqlite3_str_append(pStr, " AND ", 5); 551d9bc9b7Sdan 560cdbe1aeSdrh if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); 571d9bc9b7Sdan for(i=0; i<nTerm; i++){ 580cdbe1aeSdrh if( i ) sqlite3_str_append(pStr, ",", 1); 590cdbe1aeSdrh sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i)); 601d9bc9b7Sdan } 610cdbe1aeSdrh if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1); 621d9bc9b7Sdan 630cdbe1aeSdrh sqlite3_str_append(pStr, zOp, 1); 641d9bc9b7Sdan 650cdbe1aeSdrh if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); 661d9bc9b7Sdan for(i=0; i<nTerm; i++){ 670cdbe1aeSdrh if( i ) sqlite3_str_append(pStr, ",", 1); 680cdbe1aeSdrh sqlite3_str_append(pStr, "?", 1); 696f82e85aSdrh } 700cdbe1aeSdrh if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1); 71c7c4680fSdrh } 72c7c4680fSdrh 73c7c4680fSdrh /* 746f82e85aSdrh ** Argument pLevel describes a strategy for scanning table pTab. This 756f82e85aSdrh ** function appends text to pStr that describes the subset of table 766f82e85aSdrh ** rows scanned by the strategy in the form of an SQL expression. 776f82e85aSdrh ** 786f82e85aSdrh ** For example, if the query: 796f82e85aSdrh ** 806f82e85aSdrh ** SELECT * FROM t1 WHERE a=1 AND b>2; 816f82e85aSdrh ** 826f82e85aSdrh ** is run and there is an index on (a, b), then this function returns a 836f82e85aSdrh ** string similar to: 846f82e85aSdrh ** 856f82e85aSdrh ** "a=? AND b>?" 866f82e85aSdrh */ 878faee877Sdrh static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ 886f82e85aSdrh Index *pIndex = pLoop->u.btree.pIndex; 896f82e85aSdrh u16 nEq = pLoop->u.btree.nEq; 906f82e85aSdrh u16 nSkip = pLoop->nSkip; 916f82e85aSdrh int i, j; 926f82e85aSdrh 936f82e85aSdrh if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; 940cdbe1aeSdrh sqlite3_str_append(pStr, " (", 2); 956f82e85aSdrh for(i=0; i<nEq; i++){ 96c7c4680fSdrh const char *z = explainIndexColumnName(pIndex, i); 970cdbe1aeSdrh if( i ) sqlite3_str_append(pStr, " AND ", 5); 980cdbe1aeSdrh sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); 996f82e85aSdrh } 1006f82e85aSdrh 1016f82e85aSdrh j = i; 1026f82e85aSdrh if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ 1031d9bc9b7Sdan explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); 1041d9bc9b7Sdan i = 1; 1056f82e85aSdrh } 1066f82e85aSdrh if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ 1071d9bc9b7Sdan explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); 1086f82e85aSdrh } 1090cdbe1aeSdrh sqlite3_str_append(pStr, ")", 1); 1106f82e85aSdrh } 1116f82e85aSdrh 1126f82e85aSdrh /* 1136f82e85aSdrh ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN 1146f82e85aSdrh ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was 1156f82e85aSdrh ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 1166f82e85aSdrh ** is added to the output to describe the table scan strategy in pLevel. 1176f82e85aSdrh ** 1186f82e85aSdrh ** If an OP_Explain opcode is added to the VM, its address is returned. 1196f82e85aSdrh ** Otherwise, if no OP_Explain is coded, zero is returned. 1206f82e85aSdrh */ 1216f82e85aSdrh int sqlite3WhereExplainOneScan( 1226f82e85aSdrh Parse *pParse, /* Parse context */ 1236f82e85aSdrh SrcList *pTabList, /* Table list this loop refers to */ 1246f82e85aSdrh WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ 1256f82e85aSdrh u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ 1266f82e85aSdrh ){ 1276f82e85aSdrh int ret = 0; 1286f82e85aSdrh #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) 129ef7231b8Sdrh if( sqlite3ParseToplevel(pParse)->explain==2 ) 1306f82e85aSdrh #endif 1316f82e85aSdrh { 1327601294aSdrh SrcItem *pItem = &pTabList->a[pLevel->iFrom]; 1336f82e85aSdrh Vdbe *v = pParse->pVdbe; /* VM being constructed */ 1346f82e85aSdrh sqlite3 *db = pParse->db; /* Database handle */ 1356f82e85aSdrh int isSearch; /* True for a SEARCH. False for SCAN. */ 1366f82e85aSdrh WhereLoop *pLoop; /* The controlling WhereLoop object */ 1376f82e85aSdrh u32 flags; /* Flags that describe this loop */ 1386f82e85aSdrh char *zMsg; /* Text to add to EQP output */ 1396f82e85aSdrh StrAccum str; /* EQP output string */ 1406f82e85aSdrh char zBuf[100]; /* Initial space for EQP output string */ 1416f82e85aSdrh 1426f82e85aSdrh pLoop = pLevel->pWLoop; 1436f82e85aSdrh flags = pLoop->wsFlags; 144ce943bc8Sdrh if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; 1456f82e85aSdrh 1466f82e85aSdrh isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 1476f82e85aSdrh || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) 1486f82e85aSdrh || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); 1496f82e85aSdrh 1506f82e85aSdrh sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); 151a979993bSdrh str.printfFlags = SQLITE_PRINTF_INTERNAL; 1522f2091b1Sdrh sqlite3_str_appendf(&str, "%s %S", isSearch ? "SEARCH" : "SCAN", pItem); 1536f82e85aSdrh if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ 1546f82e85aSdrh const char *zFmt = 0; 1556f82e85aSdrh Index *pIdx; 1566f82e85aSdrh 1576f82e85aSdrh assert( pLoop->u.btree.pIndex!=0 ); 1586f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 1596f82e85aSdrh assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); 1606f82e85aSdrh if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ 1616f82e85aSdrh if( isSearch ){ 1626f82e85aSdrh zFmt = "PRIMARY KEY"; 1636f82e85aSdrh } 1646f82e85aSdrh }else if( flags & WHERE_PARTIALIDX ){ 1656f82e85aSdrh zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; 1666f82e85aSdrh }else if( flags & WHERE_AUTO_INDEX ){ 1676f82e85aSdrh zFmt = "AUTOMATIC COVERING INDEX"; 1686f82e85aSdrh }else if( flags & WHERE_IDX_ONLY ){ 1696f82e85aSdrh zFmt = "COVERING INDEX %s"; 1706f82e85aSdrh }else{ 1716f82e85aSdrh zFmt = "INDEX %s"; 1726f82e85aSdrh } 1736f82e85aSdrh if( zFmt ){ 1740cdbe1aeSdrh sqlite3_str_append(&str, " USING ", 7); 1750cdbe1aeSdrh sqlite3_str_appendf(&str, zFmt, pIdx->zName); 1768faee877Sdrh explainIndexRange(&str, pLoop); 1776f82e85aSdrh } 1786f82e85aSdrh }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ 179d37bea5bSdrh const char *zRangeOp; 1806f82e85aSdrh if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ 181d37bea5bSdrh zRangeOp = "="; 1826f82e85aSdrh }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ 183d37bea5bSdrh zRangeOp = ">? AND rowid<"; 1846f82e85aSdrh }else if( flags&WHERE_BTM_LIMIT ){ 185d37bea5bSdrh zRangeOp = ">"; 1866f82e85aSdrh }else{ 1876f82e85aSdrh assert( flags&WHERE_TOP_LIMIT); 188d37bea5bSdrh zRangeOp = "<"; 1896f82e85aSdrh } 1900cdbe1aeSdrh sqlite3_str_appendf(&str, 1910cdbe1aeSdrh " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); 1926f82e85aSdrh } 1936f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 1946f82e85aSdrh else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ 1950cdbe1aeSdrh sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s", 1966f82e85aSdrh pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); 1976f82e85aSdrh } 1986f82e85aSdrh #endif 1996f82e85aSdrh #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS 2006f82e85aSdrh if( pLoop->nOut>=10 ){ 2010cdbe1aeSdrh sqlite3_str_appendf(&str, " (~%llu rows)", 2020cdbe1aeSdrh sqlite3LogEstToInt(pLoop->nOut)); 2036f82e85aSdrh }else{ 2040cdbe1aeSdrh sqlite3_str_append(&str, " (~1 row)", 9); 2056f82e85aSdrh } 2066f82e85aSdrh #endif 2076f82e85aSdrh zMsg = sqlite3StrAccumFinish(&str); 208bd462bccSdrh sqlite3ExplainBreakpoint("",zMsg); 209e2ca99c9Sdrh ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v), 210e2ca99c9Sdrh pParse->addrExplain, 0, zMsg,P4_DYNAMIC); 2116f82e85aSdrh } 2126f82e85aSdrh return ret; 2136f82e85aSdrh } 2146f82e85aSdrh #endif /* SQLITE_OMIT_EXPLAIN */ 2156f82e85aSdrh 2166f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 2176f82e85aSdrh /* 2186f82e85aSdrh ** Configure the VM passed as the first argument with an 2196f82e85aSdrh ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 2206f82e85aSdrh ** implement level pLvl. Argument pSrclist is a pointer to the FROM 2216f82e85aSdrh ** clause that the scan reads data from. 2226f82e85aSdrh ** 2236f82e85aSdrh ** If argument addrExplain is not 0, it must be the address of an 2246f82e85aSdrh ** OP_Explain instruction that describes the same loop. 2256f82e85aSdrh */ 2266f82e85aSdrh void sqlite3WhereAddScanStatus( 2276f82e85aSdrh Vdbe *v, /* Vdbe to add scanstatus entry to */ 2286f82e85aSdrh SrcList *pSrclist, /* FROM clause pLvl reads data from */ 2296f82e85aSdrh WhereLevel *pLvl, /* Level to add scanstatus() entry for */ 2306f82e85aSdrh int addrExplain /* Address of OP_Explain (or 0) */ 2316f82e85aSdrh ){ 2326f82e85aSdrh const char *zObj = 0; 2336f82e85aSdrh WhereLoop *pLoop = pLvl->pWLoop; 2346f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ 2356f82e85aSdrh zObj = pLoop->u.btree.pIndex->zName; 2366f82e85aSdrh }else{ 2376f82e85aSdrh zObj = pSrclist->a[pLvl->iFrom].zName; 2386f82e85aSdrh } 2396f82e85aSdrh sqlite3VdbeScanStatus( 2406f82e85aSdrh v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj 2416f82e85aSdrh ); 2426f82e85aSdrh } 2436f82e85aSdrh #endif 2446f82e85aSdrh 2456f82e85aSdrh 2466f82e85aSdrh /* 2476f82e85aSdrh ** Disable a term in the WHERE clause. Except, do not disable the term 2486f82e85aSdrh ** if it controls a LEFT OUTER JOIN and it did not originate in the ON 2496f82e85aSdrh ** or USING clause of that join. 2506f82e85aSdrh ** 2516f82e85aSdrh ** Consider the term t2.z='ok' in the following queries: 2526f82e85aSdrh ** 2536f82e85aSdrh ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' 2546f82e85aSdrh ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' 2556f82e85aSdrh ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' 2566f82e85aSdrh ** 2576f82e85aSdrh ** The t2.z='ok' is disabled in the in (2) because it originates 2586f82e85aSdrh ** in the ON clause. The term is disabled in (3) because it is not part 2596f82e85aSdrh ** of a LEFT OUTER JOIN. In (1), the term is not disabled. 2606f82e85aSdrh ** 2616f82e85aSdrh ** Disabling a term causes that term to not be tested in the inner loop 2626f82e85aSdrh ** of the join. Disabling is an optimization. When terms are satisfied 2636f82e85aSdrh ** by indices, we disable them to prevent redundant tests in the inner 2646f82e85aSdrh ** loop. We would get the correct results if nothing were ever disabled, 2656f82e85aSdrh ** but joins might run a little slower. The trick is to disable as much 2666f82e85aSdrh ** as we can without disabling too much. If we disabled in (1), we'd get 2676f82e85aSdrh ** the wrong answer. See ticket #813. 2686f82e85aSdrh ** 2696f82e85aSdrh ** If all the children of a term are disabled, then that term is also 2706f82e85aSdrh ** automatically disabled. In this way, terms get disabled if derived 2716f82e85aSdrh ** virtual terms are tested first. For example: 2726f82e85aSdrh ** 2736f82e85aSdrh ** x GLOB 'abc*' AND x>='abc' AND x<'acd' 2746f82e85aSdrh ** \___________/ \______/ \_____/ 2756f82e85aSdrh ** parent child1 child2 2766f82e85aSdrh ** 2776f82e85aSdrh ** Only the parent term was in the original WHERE clause. The child1 2786f82e85aSdrh ** and child2 terms were added by the LIKE optimization. If both of 2796f82e85aSdrh ** the virtual child terms are valid, then testing of the parent can be 2806f82e85aSdrh ** skipped. 2816f82e85aSdrh ** 2826f82e85aSdrh ** Usually the parent term is marked as TERM_CODED. But if the parent 2836f82e85aSdrh ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. 2846f82e85aSdrh ** The TERM_LIKECOND marking indicates that the term should be coded inside 2856f82e85aSdrh ** a conditional such that is only evaluated on the second pass of a 2866f82e85aSdrh ** LIKE-optimization loop, when scanning BLOBs instead of strings. 2876f82e85aSdrh */ 2886f82e85aSdrh static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ 2896f82e85aSdrh int nLoop = 0; 2909d9c41e2Sdrh assert( pTerm!=0 ); 2919d9c41e2Sdrh while( (pTerm->wtFlags & TERM_CODED)==0 2926f82e85aSdrh && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 2936f82e85aSdrh && (pLevel->notReady & pTerm->prereqAll)==0 2946f82e85aSdrh ){ 2956f82e85aSdrh if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ 2966f82e85aSdrh pTerm->wtFlags |= TERM_LIKECOND; 2976f82e85aSdrh }else{ 2986f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 2996f82e85aSdrh } 3006f82e85aSdrh if( pTerm->iParent<0 ) break; 3016f82e85aSdrh pTerm = &pTerm->pWC->a[pTerm->iParent]; 3029d9c41e2Sdrh assert( pTerm!=0 ); 3036f82e85aSdrh pTerm->nChild--; 3046f82e85aSdrh if( pTerm->nChild!=0 ) break; 3056f82e85aSdrh nLoop++; 3066f82e85aSdrh } 3076f82e85aSdrh } 3086f82e85aSdrh 3096f82e85aSdrh /* 3106f82e85aSdrh ** Code an OP_Affinity opcode to apply the column affinity string zAff 3116f82e85aSdrh ** to the n registers starting at base. 3126f82e85aSdrh ** 31396fb16eeSdrh ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which 31496fb16eeSdrh ** are no-ops) at the beginning and end of zAff are ignored. If all entries 31596fb16eeSdrh ** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated. 3166f82e85aSdrh ** 3176f82e85aSdrh ** This routine makes its own copy of zAff so that the caller is free 3186f82e85aSdrh ** to modify zAff after this routine returns. 3196f82e85aSdrh */ 3206f82e85aSdrh static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ 3216f82e85aSdrh Vdbe *v = pParse->pVdbe; 3226f82e85aSdrh if( zAff==0 ){ 3236f82e85aSdrh assert( pParse->db->mallocFailed ); 3246f82e85aSdrh return; 3256f82e85aSdrh } 3266f82e85aSdrh assert( v!=0 ); 3276f82e85aSdrh 32896fb16eeSdrh /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE 32996fb16eeSdrh ** entries at the beginning and end of the affinity string. 3306f82e85aSdrh */ 33196fb16eeSdrh assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB ); 33296fb16eeSdrh while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){ 3336f82e85aSdrh n--; 3346f82e85aSdrh base++; 3356f82e85aSdrh zAff++; 3366f82e85aSdrh } 33796fb16eeSdrh while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){ 3386f82e85aSdrh n--; 3396f82e85aSdrh } 3406f82e85aSdrh 3416f82e85aSdrh /* Code the OP_Affinity opcode if there is anything left to do. */ 3426f82e85aSdrh if( n>0 ){ 3439b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); 3446f82e85aSdrh } 3456f82e85aSdrh } 3466f82e85aSdrh 347b7ca2177Sdan /* 348b7ca2177Sdan ** Expression pRight, which is the RHS of a comparison operation, is 349b7ca2177Sdan ** either a vector of n elements or, if n==1, a scalar expression. 350b7ca2177Sdan ** Before the comparison operation, affinity zAff is to be applied 351b7ca2177Sdan ** to the pRight values. This function modifies characters within the 352b7ca2177Sdan ** affinity string to SQLITE_AFF_BLOB if either: 353b7ca2177Sdan ** 354b7ca2177Sdan ** * the comparison will be performed with no affinity, or 355b7ca2177Sdan ** * the affinity change in zAff is guaranteed not to change the value. 356b7ca2177Sdan */ 357b7ca2177Sdan static void updateRangeAffinityStr( 358b7ca2177Sdan Expr *pRight, /* RHS of comparison */ 359b7ca2177Sdan int n, /* Number of vector elements in comparison */ 360b7ca2177Sdan char *zAff /* Affinity string to modify */ 361b7ca2177Sdan ){ 362b7ca2177Sdan int i; 363b7ca2177Sdan for(i=0; i<n; i++){ 364b7ca2177Sdan Expr *p = sqlite3VectorFieldSubexpr(pRight, i); 365b7ca2177Sdan if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB 366b7ca2177Sdan || sqlite3ExprNeedsNoAffinityChange(p, zAff[i]) 367b7ca2177Sdan ){ 368b7ca2177Sdan zAff[i] = SQLITE_AFF_BLOB; 369b7ca2177Sdan } 370b7ca2177Sdan } 371b7ca2177Sdan } 3726f82e85aSdrh 3732410243eSdrh 3742410243eSdrh /* 3752410243eSdrh ** pX is an expression of the form: (vector) IN (SELECT ...) 3762410243eSdrh ** In other words, it is a vector IN operator with a SELECT clause on the 3772410243eSdrh ** LHS. But not all terms in the vector are indexable and the terms might 3782410243eSdrh ** not be in the correct order for indexing. 3799b1ecb67Sdrh ** 3802410243eSdrh ** This routine makes a copy of the input pX expression and then adjusts 3812410243eSdrh ** the vector on the LHS with corresponding changes to the SELECT so that 3822410243eSdrh ** the vector contains only index terms and those terms are in the correct 3832410243eSdrh ** order. The modified IN expression is returned. The caller is responsible 3842410243eSdrh ** for deleting the returned expression. 3852410243eSdrh ** 3862410243eSdrh ** Example: 3872410243eSdrh ** 3882410243eSdrh ** CREATE TABLE t1(a,b,c,d,e,f); 3892410243eSdrh ** CREATE INDEX t1x1 ON t1(e,c); 3902410243eSdrh ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2) 3912410243eSdrh ** \_______________________________________/ 3922410243eSdrh ** The pX expression 3932410243eSdrh ** 3942410243eSdrh ** Since only columns e and c can be used with the index, in that order, 3952410243eSdrh ** the modified IN expression that is returned will be: 3962410243eSdrh ** 3972410243eSdrh ** (e,c) IN (SELECT z,x FROM t2) 3982410243eSdrh ** 3992410243eSdrh ** The reduced pX is different from the original (obviously) and thus is 4002410243eSdrh ** only used for indexing, to improve performance. The original unaltered 4012410243eSdrh ** IN expression must also be run on each output row for correctness. 4029b1ecb67Sdrh */ 4032410243eSdrh static Expr *removeUnindexableInClauseTerms( 4042410243eSdrh Parse *pParse, /* The parsing context */ 4052410243eSdrh int iEq, /* Look at loop terms starting here */ 4062410243eSdrh WhereLoop *pLoop, /* The current loop */ 4072410243eSdrh Expr *pX /* The IN expression to be reduced */ 4082410243eSdrh ){ 4092410243eSdrh sqlite3 *db = pParse->db; 41069843342Sdan Expr *pNew; 41169843342Sdan pNew = sqlite3ExprDup(db, pX, 0); 4122410243eSdrh if( db->mallocFailed==0 ){ 4132410243eSdrh ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */ 4142410243eSdrh ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */ 4152410243eSdrh ExprList *pRhs = 0; /* New RHS after modifications */ 4162410243eSdrh ExprList *pLhs = 0; /* New LHS after mods */ 4172410243eSdrh int i; /* Loop counter */ 4182410243eSdrh Select *pSelect; /* Pointer to the SELECT on the RHS */ 4192410243eSdrh 4202410243eSdrh for(i=iEq; i<pLoop->nLTerm; i++){ 4212410243eSdrh if( pLoop->aLTerm[i]->pExpr==pX ){ 42275fa2663Sdrh int iField = pLoop->aLTerm[i]->u.x.iField - 1; 423c6e519f3Sdrh if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */ 4242410243eSdrh pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr); 4252410243eSdrh pOrigRhs->a[iField].pExpr = 0; 4262410243eSdrh assert( pOrigLhs->a[iField].pExpr!=0 ); 4272410243eSdrh pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr); 4282410243eSdrh pOrigLhs->a[iField].pExpr = 0; 4299b1ecb67Sdrh } 4309b1ecb67Sdrh } 4312410243eSdrh sqlite3ExprListDelete(db, pOrigRhs); 4322410243eSdrh sqlite3ExprListDelete(db, pOrigLhs); 4332410243eSdrh pNew->pLeft->x.pList = pLhs; 4342410243eSdrh pNew->x.pSelect->pEList = pRhs; 4352410243eSdrh if( pLhs && pLhs->nExpr==1 ){ 4362410243eSdrh /* Take care here not to generate a TK_VECTOR containing only a 4372410243eSdrh ** single value. Since the parser never creates such a vector, some 4382410243eSdrh ** of the subroutines do not handle this case. */ 4392410243eSdrh Expr *p = pLhs->a[0].pExpr; 4402410243eSdrh pLhs->a[0].pExpr = 0; 4412410243eSdrh sqlite3ExprDelete(db, pNew->pLeft); 4422410243eSdrh pNew->pLeft = p; 4439b1ecb67Sdrh } 4442410243eSdrh pSelect = pNew->x.pSelect; 4452410243eSdrh if( pSelect->pOrderBy ){ 4462410243eSdrh /* If the SELECT statement has an ORDER BY clause, zero the 4472410243eSdrh ** iOrderByCol variables. These are set to non-zero when an 4482410243eSdrh ** ORDER BY term exactly matches one of the terms of the 4492410243eSdrh ** result-set. Since the result-set of the SELECT statement may 4502410243eSdrh ** have been modified or reordered, these variables are no longer 4512410243eSdrh ** set correctly. Since setting them is just an optimization, 4522410243eSdrh ** it's easiest just to zero them here. */ 4532410243eSdrh ExprList *pOrderBy = pSelect->pOrderBy; 4542410243eSdrh for(i=0; i<pOrderBy->nExpr; i++){ 4552410243eSdrh pOrderBy->a[i].u.x.iOrderByCol = 0; 4562410243eSdrh } 4572410243eSdrh } 4582410243eSdrh 4592410243eSdrh #if 0 4602410243eSdrh printf("For indexing, change the IN expr:\n"); 4612410243eSdrh sqlite3TreeViewExpr(0, pX, 0); 4622410243eSdrh printf("Into:\n"); 4632410243eSdrh sqlite3TreeViewExpr(0, pNew, 0); 4642410243eSdrh #endif 4652410243eSdrh } 4662410243eSdrh return pNew; 4672410243eSdrh } 4689b1ecb67Sdrh 4699b1ecb67Sdrh 4706f82e85aSdrh /* 4716f82e85aSdrh ** Generate code for a single equality term of the WHERE clause. An equality 4726f82e85aSdrh ** term can be either X=expr or X IN (...). pTerm is the term to be 4736f82e85aSdrh ** coded. 4746f82e85aSdrh ** 475099a0f5fSdrh ** The current value for the constraint is left in a register, the index 476099a0f5fSdrh ** of which is returned. An attempt is made store the result in iTarget but 477099a0f5fSdrh ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the 478099a0f5fSdrh ** constraint is a TK_EQ or TK_IS, then the current value might be left in 479099a0f5fSdrh ** some other register and it is the caller's responsibility to compensate. 4806f82e85aSdrh ** 4814602b8e8Sdrh ** For a constraint of the form X=expr, the expression is evaluated in 4824602b8e8Sdrh ** straight-line code. For constraints of the form X IN (...) 4836f82e85aSdrh ** this routine sets up a loop that will iterate over all values of X. 4846f82e85aSdrh */ 4856f82e85aSdrh static int codeEqualityTerm( 4866f82e85aSdrh Parse *pParse, /* The parsing context */ 4876f82e85aSdrh WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ 4886f82e85aSdrh WhereLevel *pLevel, /* The level of the FROM clause we are working on */ 4896f82e85aSdrh int iEq, /* Index of the equality term within this level */ 4906f82e85aSdrh int bRev, /* True for reverse-order IN operations */ 4916f82e85aSdrh int iTarget /* Attempt to leave results in this register */ 4926f82e85aSdrh ){ 4936f82e85aSdrh Expr *pX = pTerm->pExpr; 4946f82e85aSdrh Vdbe *v = pParse->pVdbe; 4956f82e85aSdrh int iReg; /* Register holding results */ 4966f82e85aSdrh 4978da209b1Sdan assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); 4986f82e85aSdrh assert( iTarget>0 ); 4996f82e85aSdrh if( pX->op==TK_EQ || pX->op==TK_IS ){ 500fc7f27b9Sdrh iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); 5016f82e85aSdrh }else if( pX->op==TK_ISNULL ){ 5026f82e85aSdrh iReg = iTarget; 5036f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); 5046f82e85aSdrh #ifndef SQLITE_OMIT_SUBQUERY 5056f82e85aSdrh }else{ 506ac6b47d1Sdrh int eType = IN_INDEX_NOOP; 5076f82e85aSdrh int iTab; 5086f82e85aSdrh struct InLoop *pIn; 5096f82e85aSdrh WhereLoop *pLoop = pLevel->pWLoop; 5108da209b1Sdan int i; 5118da209b1Sdan int nEq = 0; 5128da209b1Sdan int *aiMap = 0; 5136f82e85aSdrh 5146f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 5156f82e85aSdrh && pLoop->u.btree.pIndex!=0 5166f82e85aSdrh && pLoop->u.btree.pIndex->aSortOrder[iEq] 5176f82e85aSdrh ){ 5186f82e85aSdrh testcase( iEq==0 ); 5196f82e85aSdrh testcase( bRev ); 5206f82e85aSdrh bRev = !bRev; 5216f82e85aSdrh } 5226f82e85aSdrh assert( pX->op==TK_IN ); 5236f82e85aSdrh iReg = iTarget; 5248da209b1Sdan 5258da209b1Sdan for(i=0; i<iEq; i++){ 5268da209b1Sdan if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ 5278da209b1Sdan disableTerm(pLevel, pTerm); 5288da209b1Sdan return iTarget; 5298da209b1Sdan } 5308da209b1Sdan } 5318da209b1Sdan for(i=iEq;i<pLoop->nLTerm; i++){ 5322410243eSdrh assert( pLoop->aLTerm[i]!=0 ); 5332410243eSdrh if( pLoop->aLTerm[i]->pExpr==pX ) nEq++; 5348da209b1Sdan } 5358da209b1Sdan 5362c04131cSdrh iTab = 0; 5378da209b1Sdan if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ 5382c04131cSdrh eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab); 5398da209b1Sdan }else{ 5408da209b1Sdan sqlite3 *db = pParse->db; 5412410243eSdrh pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX); 5429b1ecb67Sdrh 543ac6b47d1Sdrh if( !db->mallocFailed ){ 544c7a77ae1Sdrh aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq); 5452c04131cSdrh eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab); 5462c04131cSdrh pTerm->pExpr->iTable = iTab; 547ac6b47d1Sdrh } 5482410243eSdrh sqlite3ExprDelete(db, pX); 5492410243eSdrh pX = pTerm->pExpr; 5508da209b1Sdan } 5518da209b1Sdan 5526f82e85aSdrh if( eType==IN_INDEX_INDEX_DESC ){ 5536f82e85aSdrh testcase( bRev ); 5546f82e85aSdrh bRev = !bRev; 5556f82e85aSdrh } 5566f82e85aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); 5576f82e85aSdrh VdbeCoverageIf(v, bRev); 5586f82e85aSdrh VdbeCoverageIf(v, !bRev); 5596f82e85aSdrh assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); 5608da209b1Sdan 5616f82e85aSdrh pLoop->wsFlags |= WHERE_IN_ABLE; 5626f82e85aSdrh if( pLevel->u.in.nIn==0 ){ 563ec4ccdbcSdrh pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); 5646f82e85aSdrh } 56546f0f4e5Sdrh if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){ 566fa17e134Sdrh pLoop->wsFlags |= WHERE_IN_EARLYOUT; 567fa17e134Sdrh } 5688da209b1Sdan 5698da209b1Sdan i = pLevel->u.in.nIn; 5708da209b1Sdan pLevel->u.in.nIn += nEq; 5716f82e85aSdrh pLevel->u.in.aInLoop = 5726f82e85aSdrh sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, 5736f82e85aSdrh sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); 5746f82e85aSdrh pIn = pLevel->u.in.aInLoop; 5756f82e85aSdrh if( pIn ){ 5768da209b1Sdan int iMap = 0; /* Index in aiMap[] */ 5778da209b1Sdan pIn += i; 5787887d7f2Sdan for(i=iEq;i<pLoop->nLTerm; i++){ 5798da209b1Sdan if( pLoop->aLTerm[i]->pExpr==pX ){ 580edc3537cSdan int iOut = iReg + i - iEq; 5816f82e85aSdrh if( eType==IN_INDEX_ROWID ){ 582edc3537cSdan pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); 5836f82e85aSdrh }else{ 5848da209b1Sdan int iCol = aiMap ? aiMap[iMap++] : 0; 5858da209b1Sdan pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); 5866f82e85aSdrh } 58703181c8cSdrh sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); 5888da209b1Sdan if( i==iEq ){ 5898da209b1Sdan pIn->iCur = iTab; 590f1949b66Sdrh pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next; 59174ebaadcSdan if( iEq>0 ){ 592a0368d93Sdrh pIn->iBase = iReg - i; 593a0368d93Sdrh pIn->nPrefix = i; 5948da209b1Sdan }else{ 59586d0ea75Sdrh pIn->nPrefix = 0; 59686d0ea75Sdrh } 59786d0ea75Sdrh }else{ 5988da209b1Sdan pIn->eEndLoopOp = OP_Noop; 5998da209b1Sdan } 6007887d7f2Sdan pIn++; 6018da209b1Sdan } 6028da209b1Sdan } 60367306cb3Sdrh testcase( iEq>0 60467306cb3Sdrh && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 60567306cb3Sdrh && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ); 60667306cb3Sdrh if( iEq>0 60767306cb3Sdrh && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0 60867306cb3Sdrh ){ 609fa17e134Sdrh sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq); 610fa17e134Sdrh } 6116f82e85aSdrh }else{ 6126f82e85aSdrh pLevel->u.in.nIn = 0; 6136f82e85aSdrh } 6148da209b1Sdan sqlite3DbFree(pParse->db, aiMap); 6156f82e85aSdrh #endif 6166f82e85aSdrh } 6176f82e85aSdrh disableTerm(pLevel, pTerm); 6186f82e85aSdrh return iReg; 6196f82e85aSdrh } 6206f82e85aSdrh 6216f82e85aSdrh /* 6226f82e85aSdrh ** Generate code that will evaluate all == and IN constraints for an 6236f82e85aSdrh ** index scan. 6246f82e85aSdrh ** 6256f82e85aSdrh ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). 6266f82e85aSdrh ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 6276f82e85aSdrh ** The index has as many as three equality constraints, but in this 6286f82e85aSdrh ** example, the third "c" value is an inequality. So only two 6296f82e85aSdrh ** constraints are coded. This routine will generate code to evaluate 6306f82e85aSdrh ** a==5 and b IN (1,2,3). The current values for a and b will be stored 6316f82e85aSdrh ** in consecutive registers and the index of the first register is returned. 6326f82e85aSdrh ** 6336f82e85aSdrh ** In the example above nEq==2. But this subroutine works for any value 6346f82e85aSdrh ** of nEq including 0. If nEq==0, this routine is nearly a no-op. 6356f82e85aSdrh ** The only thing it does is allocate the pLevel->iMem memory cell and 6366f82e85aSdrh ** compute the affinity string. 6376f82e85aSdrh ** 6386f82e85aSdrh ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints 6396f82e85aSdrh ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is 6406f82e85aSdrh ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that 6416f82e85aSdrh ** occurs after the nEq quality constraints. 6426f82e85aSdrh ** 6436f82e85aSdrh ** This routine allocates a range of nEq+nExtraReg memory cells and returns 6446f82e85aSdrh ** the index of the first memory cell in that range. The code that 6456f82e85aSdrh ** calls this routine will use that memory range to store keys for 6466f82e85aSdrh ** start and termination conditions of the loop. 6476f82e85aSdrh ** key value of the loop. If one or more IN operators appear, then 6486f82e85aSdrh ** this routine allocates an additional nEq memory cells for internal 6496f82e85aSdrh ** use. 6506f82e85aSdrh ** 6516f82e85aSdrh ** Before returning, *pzAff is set to point to a buffer containing a 6526f82e85aSdrh ** copy of the column affinity string of the index allocated using 6536f82e85aSdrh ** sqlite3DbMalloc(). Except, entries in the copy of the string associated 6546f82e85aSdrh ** with equality constraints that use BLOB or NONE affinity are set to 6556f82e85aSdrh ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: 6566f82e85aSdrh ** 6576f82e85aSdrh ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); 6586f82e85aSdrh ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; 6596f82e85aSdrh ** 6606f82e85aSdrh ** In the example above, the index on t1(a) has TEXT affinity. But since 6616f82e85aSdrh ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, 6626f82e85aSdrh ** no conversion should be attempted before using a t2.b value as part of 6636f82e85aSdrh ** a key to search the index. Hence the first byte in the returned affinity 6646f82e85aSdrh ** string in this example would be set to SQLITE_AFF_BLOB. 6656f82e85aSdrh */ 6666f82e85aSdrh static int codeAllEqualityTerms( 6676f82e85aSdrh Parse *pParse, /* Parsing context */ 6686f82e85aSdrh WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ 6696f82e85aSdrh int bRev, /* Reverse the order of IN operators */ 6706f82e85aSdrh int nExtraReg, /* Number of extra registers to allocate */ 6716f82e85aSdrh char **pzAff /* OUT: Set to point to affinity string */ 6726f82e85aSdrh ){ 6736f82e85aSdrh u16 nEq; /* The number of == or IN constraints to code */ 6746f82e85aSdrh u16 nSkip; /* Number of left-most columns to skip */ 6756f82e85aSdrh Vdbe *v = pParse->pVdbe; /* The vm under construction */ 6766f82e85aSdrh Index *pIdx; /* The index being used for this loop */ 6776f82e85aSdrh WhereTerm *pTerm; /* A single constraint term */ 6786f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object */ 6796f82e85aSdrh int j; /* Loop counter */ 6806f82e85aSdrh int regBase; /* Base register */ 6816f82e85aSdrh int nReg; /* Number of registers to allocate */ 6826f82e85aSdrh char *zAff; /* Affinity string to return */ 6836f82e85aSdrh 6846f82e85aSdrh /* This module is only called on query plans that use an index. */ 6856f82e85aSdrh pLoop = pLevel->pWLoop; 6866f82e85aSdrh assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); 6876f82e85aSdrh nEq = pLoop->u.btree.nEq; 6886f82e85aSdrh nSkip = pLoop->nSkip; 6896f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 6906f82e85aSdrh assert( pIdx!=0 ); 6916f82e85aSdrh 6926f82e85aSdrh /* Figure out how many memory cells we will need then allocate them. 6936f82e85aSdrh */ 6946f82e85aSdrh regBase = pParse->nMem + 1; 6956f82e85aSdrh nReg = pLoop->u.btree.nEq + nExtraReg; 6966f82e85aSdrh pParse->nMem += nReg; 6976f82e85aSdrh 698e9107698Sdrh zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); 6994df86af3Sdrh assert( zAff!=0 || pParse->db->mallocFailed ); 7006f82e85aSdrh 7016f82e85aSdrh if( nSkip ){ 7026f82e85aSdrh int iIdxCur = pLevel->iIdxCur; 703*31536304Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1); 7046f82e85aSdrh sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); 7056f82e85aSdrh VdbeCoverageIf(v, bRev==0); 7066f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 7076f82e85aSdrh VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); 7086f82e85aSdrh j = sqlite3VdbeAddOp0(v, OP_Goto); 7096f82e85aSdrh pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), 7106f82e85aSdrh iIdxCur, 0, regBase, nSkip); 7116f82e85aSdrh VdbeCoverageIf(v, bRev==0); 7126f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 7136f82e85aSdrh sqlite3VdbeJumpHere(v, j); 7146f82e85aSdrh for(j=0; j<nSkip; j++){ 7156f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); 7164b92f98cSdrh testcase( pIdx->aiColumn[j]==XN_EXPR ); 717e63e8a6cSdrh VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); 7186f82e85aSdrh } 7196f82e85aSdrh } 7206f82e85aSdrh 7216f82e85aSdrh /* Evaluate the equality constraints 7226f82e85aSdrh */ 7236f82e85aSdrh assert( zAff==0 || (int)strlen(zAff)>=nEq ); 7246f82e85aSdrh for(j=nSkip; j<nEq; j++){ 7256f82e85aSdrh int r1; 7266f82e85aSdrh pTerm = pLoop->aLTerm[j]; 7276f82e85aSdrh assert( pTerm!=0 ); 7286f82e85aSdrh /* The following testcase is true for indices with redundant columns. 7296f82e85aSdrh ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ 7306f82e85aSdrh testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); 7316f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 7326f82e85aSdrh r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); 7336f82e85aSdrh if( r1!=regBase+j ){ 7346f82e85aSdrh if( nReg==1 ){ 7356f82e85aSdrh sqlite3ReleaseTempReg(pParse, regBase); 7366f82e85aSdrh regBase = r1; 7376f82e85aSdrh }else{ 7386f82e85aSdrh sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); 7396f82e85aSdrh } 7406f82e85aSdrh } 74127189603Sdan if( pTerm->eOperator & WO_IN ){ 74227189603Sdan if( pTerm->pExpr->flags & EP_xIsSelect ){ 7431c12657fSdan /* No affinity ever needs to be (or should be) applied to a value 7441c12657fSdan ** from the RHS of an "? IN (SELECT ...)" expression. The 7451c12657fSdan ** sqlite3FindInIndex() routine has already ensured that the 7461c12657fSdan ** affinity of the comparison has been applied to the value. */ 747aaf8a064Sdrh if( zAff ) zAff[j] = SQLITE_AFF_BLOB; 74827189603Sdan } 749c097e122Sdrh }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ 7501c12657fSdan Expr *pRight = pTerm->pExpr->pRight; 7516f82e85aSdrh if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ 7526f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); 7536f82e85aSdrh VdbeCoverage(v); 7546f82e85aSdrh } 75534c11e2fSdrh if( pParse->db->mallocFailed==0 ){ 7566f82e85aSdrh if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ 7576f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB; 7586f82e85aSdrh } 7596f82e85aSdrh if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ 7606f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB; 7616f82e85aSdrh } 7626f82e85aSdrh } 7636f82e85aSdrh } 7646f82e85aSdrh } 7656f82e85aSdrh *pzAff = zAff; 7666f82e85aSdrh return regBase; 7676f82e85aSdrh } 7686f82e85aSdrh 76941d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 7706f82e85aSdrh /* 77144aebff2Sdrh ** If the most recently coded instruction is a constant range constraint 77244aebff2Sdrh ** (a string literal) that originated from the LIKE optimization, then 77344aebff2Sdrh ** set P3 and P5 on the OP_String opcode so that the string will be cast 77444aebff2Sdrh ** to a BLOB at appropriate times. 7756f82e85aSdrh ** 7766f82e85aSdrh ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range 7776f82e85aSdrh ** expression: "x>='ABC' AND x<'abd'". But this requires that the range 7786f82e85aSdrh ** scan loop run twice, once for strings and a second time for BLOBs. 7796f82e85aSdrh ** The OP_String opcodes on the second pass convert the upper and lower 780e234cfd1Smistachkin ** bound string constants to blobs. This routine makes the necessary changes 7816f82e85aSdrh ** to the OP_String opcodes for that to happen. 78241d2e66eSdrh ** 78341d2e66eSdrh ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then 78441d2e66eSdrh ** only the one pass through the string space is required, so this routine 78541d2e66eSdrh ** becomes a no-op. 7866f82e85aSdrh */ 7876f82e85aSdrh static void whereLikeOptimizationStringFixup( 7886f82e85aSdrh Vdbe *v, /* prepared statement under construction */ 7896f82e85aSdrh WhereLevel *pLevel, /* The loop that contains the LIKE operator */ 7906f82e85aSdrh WhereTerm *pTerm /* The upper or lower bound just coded */ 7916f82e85aSdrh ){ 7926f82e85aSdrh if( pTerm->wtFlags & TERM_LIKEOPT ){ 7936f82e85aSdrh VdbeOp *pOp; 7946f82e85aSdrh assert( pLevel->iLikeRepCntr>0 ); 7956f82e85aSdrh pOp = sqlite3VdbeGetOp(v, -1); 7966f82e85aSdrh assert( pOp!=0 ); 7976f82e85aSdrh assert( pOp->opcode==OP_String8 7986f82e85aSdrh || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); 79944aebff2Sdrh pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ 80044aebff2Sdrh pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ 8016f82e85aSdrh } 8026f82e85aSdrh } 80341d2e66eSdrh #else 80441d2e66eSdrh # define whereLikeOptimizationStringFixup(A,B,C) 80541d2e66eSdrh #endif 8066f82e85aSdrh 807bec2476aSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS 8082f2b0278Sdrh /* 8092f2b0278Sdrh ** Information is passed from codeCursorHint() down to individual nodes of 8102f2b0278Sdrh ** the expression tree (by sqlite3WalkExpr()) using an instance of this 8112f2b0278Sdrh ** structure. 8122f2b0278Sdrh */ 8132f2b0278Sdrh struct CCurHint { 8142f2b0278Sdrh int iTabCur; /* Cursor for the main table */ 8152f2b0278Sdrh int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ 8162f2b0278Sdrh Index *pIdx; /* The index used to access the table */ 8172f2b0278Sdrh }; 8182f2b0278Sdrh 8192f2b0278Sdrh /* 8202f2b0278Sdrh ** This function is called for every node of an expression that is a candidate 8212f2b0278Sdrh ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference 8222f2b0278Sdrh ** the table CCurHint.iTabCur, verify that the same column can be 8232f2b0278Sdrh ** accessed through the index. If it cannot, then set pWalker->eCode to 1. 8242f2b0278Sdrh */ 8252f2b0278Sdrh static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ 8262f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint; 8272f2b0278Sdrh assert( pHint->pIdx!=0 ); 8282f2b0278Sdrh if( pExpr->op==TK_COLUMN 8292f2b0278Sdrh && pExpr->iTable==pHint->iTabCur 830b9bcf7caSdrh && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0 8312f2b0278Sdrh ){ 8322f2b0278Sdrh pWalker->eCode = 1; 8332f2b0278Sdrh } 8342f2b0278Sdrh return WRC_Continue; 8352f2b0278Sdrh } 8362f2b0278Sdrh 837e6912fd8Sdan /* 838e6912fd8Sdan ** Test whether or not expression pExpr, which was part of a WHERE clause, 839e6912fd8Sdan ** should be included in the cursor-hint for a table that is on the rhs 840e6912fd8Sdan ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 841e6912fd8Sdan ** expression is not suitable. 842e6912fd8Sdan ** 843e6912fd8Sdan ** An expression is unsuitable if it might evaluate to non NULL even if 844e6912fd8Sdan ** a TK_COLUMN node that does affect the value of the expression is set 845e6912fd8Sdan ** to NULL. For example: 846e6912fd8Sdan ** 847e6912fd8Sdan ** col IS NULL 848e6912fd8Sdan ** col IS NOT NULL 849e6912fd8Sdan ** coalesce(col, 1) 850e6912fd8Sdan ** CASE WHEN col THEN 0 ELSE 1 END 851e6912fd8Sdan */ 852e6912fd8Sdan static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ 8532b693d63Sdan if( pExpr->op==TK_IS 854e6912fd8Sdan || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 855e6912fd8Sdan || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 856e6912fd8Sdan ){ 857e6912fd8Sdan pWalker->eCode = 1; 8582b693d63Sdan }else if( pExpr->op==TK_FUNCTION ){ 8592b693d63Sdan int d1; 8601d42ea71Sdrh char d2[4]; 8612b693d63Sdan if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ 8622b693d63Sdan pWalker->eCode = 1; 863e6912fd8Sdan } 8642b693d63Sdan } 8652b693d63Sdan 866e6912fd8Sdan return WRC_Continue; 867e6912fd8Sdan } 868e6912fd8Sdan 869bec2476aSdrh 870bec2476aSdrh /* 871bec2476aSdrh ** This function is called on every node of an expression tree used as an 872bec2476aSdrh ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN 8732f2b0278Sdrh ** that accesses any table other than the one identified by 8742f2b0278Sdrh ** CCurHint.iTabCur, then do the following: 875bec2476aSdrh ** 876bec2476aSdrh ** 1) allocate a register and code an OP_Column instruction to read 877bec2476aSdrh ** the specified column into the new register, and 878bec2476aSdrh ** 879bec2476aSdrh ** 2) transform the expression node to a TK_REGISTER node that reads 880bec2476aSdrh ** from the newly populated register. 8812f2b0278Sdrh ** 8822f2b0278Sdrh ** Also, if the node is a TK_COLUMN that does access the table idenified 8832f2b0278Sdrh ** by pCCurHint.iTabCur, and an index is being used (which we will 8842f2b0278Sdrh ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into 8852f2b0278Sdrh ** an access of the index rather than the original table. 886bec2476aSdrh */ 887bec2476aSdrh static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ 888bec2476aSdrh int rc = WRC_Continue; 8892f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint; 890be312ae9Sdan if( pExpr->op==TK_COLUMN ){ 8912f2b0278Sdrh if( pExpr->iTable!=pHint->iTabCur ){ 892bec2476aSdrh int reg = ++pWalker->pParse->nMem; /* Register for column value */ 893e3e79213Sdan sqlite3ExprCode(pWalker->pParse, pExpr, reg); 894bec2476aSdrh pExpr->op = TK_REGISTER; 895bec2476aSdrh pExpr->iTable = reg; 8962f2b0278Sdrh }else if( pHint->pIdx!=0 ){ 8972f2b0278Sdrh pExpr->iTable = pHint->iIdxCur; 898b9bcf7caSdrh pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn); 8992f2b0278Sdrh assert( pExpr->iColumn>=0 ); 9002f2b0278Sdrh } 901bec2476aSdrh }else if( pExpr->op==TK_AGG_FUNCTION ){ 902bec2476aSdrh /* An aggregate function in the WHERE clause of a query means this must 903bec2476aSdrh ** be a correlated sub-query, and expression pExpr is an aggregate from 904bec2476aSdrh ** the parent context. Do not walk the function arguments in this case. 905bec2476aSdrh ** 906bec2476aSdrh ** todo: It should be possible to replace this node with a TK_REGISTER 907bec2476aSdrh ** expression, as the result of the expression must be stored in a 908bec2476aSdrh ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ 909bec2476aSdrh rc = WRC_Prune; 910bec2476aSdrh } 911bec2476aSdrh return rc; 912bec2476aSdrh } 913bec2476aSdrh 914bec2476aSdrh /* 915bec2476aSdrh ** Insert an OP_CursorHint instruction if it is appropriate to do so. 916bec2476aSdrh */ 917bec2476aSdrh static void codeCursorHint( 9187601294aSdrh SrcItem *pTabItem, /* FROM clause item */ 919b413a546Sdrh WhereInfo *pWInfo, /* The where clause */ 920b413a546Sdrh WhereLevel *pLevel, /* Which loop to provide hints for */ 921b413a546Sdrh WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ 922bec2476aSdrh ){ 923bec2476aSdrh Parse *pParse = pWInfo->pParse; 924bec2476aSdrh sqlite3 *db = pParse->db; 925bec2476aSdrh Vdbe *v = pParse->pVdbe; 926bec2476aSdrh Expr *pExpr = 0; 9272f2b0278Sdrh WhereLoop *pLoop = pLevel->pWLoop; 928bec2476aSdrh int iCur; 929bec2476aSdrh WhereClause *pWC; 930bec2476aSdrh WhereTerm *pTerm; 931b413a546Sdrh int i, j; 9322f2b0278Sdrh struct CCurHint sHint; 9332f2b0278Sdrh Walker sWalker; 934bec2476aSdrh 935bec2476aSdrh if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; 9362f2b0278Sdrh iCur = pLevel->iTabCur; 9372f2b0278Sdrh assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); 9382f2b0278Sdrh sHint.iTabCur = iCur; 9392f2b0278Sdrh sHint.iIdxCur = pLevel->iIdxCur; 9402f2b0278Sdrh sHint.pIdx = pLoop->u.btree.pIndex; 9412f2b0278Sdrh memset(&sWalker, 0, sizeof(sWalker)); 9422f2b0278Sdrh sWalker.pParse = pParse; 9432f2b0278Sdrh sWalker.u.pCCurHint = &sHint; 944bec2476aSdrh pWC = &pWInfo->sWC; 945bec2476aSdrh for(i=0; i<pWC->nTerm; i++){ 946bec2476aSdrh pTerm = &pWC->a[i]; 947bec2476aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 948bec2476aSdrh if( pTerm->prereqAll & pLevel->notReady ) continue; 949b324cf75Sdan 950b324cf75Sdan /* Any terms specified as part of the ON(...) clause for any LEFT 951b324cf75Sdan ** JOIN for which the current table is not the rhs are omitted 952b324cf75Sdan ** from the cursor-hint. 953b324cf75Sdan ** 954e6912fd8Sdan ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 955e6912fd8Sdan ** that were specified as part of the WHERE clause must be excluded. 956e6912fd8Sdan ** This is to address the following: 957b324cf75Sdan ** 958b324cf75Sdan ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; 959b324cf75Sdan ** 960e6912fd8Sdan ** Say there is a single row in t2 that matches (t1.a=t2.b), but its 961e6912fd8Sdan ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 962e6912fd8Sdan ** pushed down to the cursor, this row is filtered out, causing 963e6912fd8Sdan ** SQLite to synthesize a row of NULL values. Which does match the 964e6912fd8Sdan ** WHERE clause, and so the query returns a row. Which is incorrect. 965e6912fd8Sdan ** 966e6912fd8Sdan ** For the same reason, WHERE terms such as: 967e6912fd8Sdan ** 968e6912fd8Sdan ** WHERE 1 = (t2.c IS NULL) 969e6912fd8Sdan ** 970e6912fd8Sdan ** are also excluded. See codeCursorHintIsOrFunction() for details. 971b324cf75Sdan */ 972b324cf75Sdan if( pTabItem->fg.jointype & JT_LEFT ){ 973e6912fd8Sdan Expr *pExpr = pTerm->pExpr; 974e6912fd8Sdan if( !ExprHasProperty(pExpr, EP_FromJoin) 975e6912fd8Sdan || pExpr->iRightJoinTable!=pTabItem->iCursor 976b324cf75Sdan ){ 977e6912fd8Sdan sWalker.eCode = 0; 978e6912fd8Sdan sWalker.xExprCallback = codeCursorHintIsOrFunction; 979e6912fd8Sdan sqlite3WalkExpr(&sWalker, pTerm->pExpr); 980e6912fd8Sdan if( sWalker.eCode ) continue; 981b324cf75Sdan } 982b324cf75Sdan }else{ 983bec2476aSdrh if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; 984b324cf75Sdan } 985b413a546Sdrh 986b413a546Sdrh /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize 987bcf40a7fSdrh ** the cursor. These terms are not needed as hints for a pure range 988bcf40a7fSdrh ** scan (that has no == terms) so omit them. */ 989bcf40a7fSdrh if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ 990bcf40a7fSdrh for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} 991bcf40a7fSdrh if( j<pLoop->nLTerm ) continue; 992b413a546Sdrh } 993b413a546Sdrh 994b413a546Sdrh /* No subqueries or non-deterministic functions allowed */ 995bec2476aSdrh if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; 996b413a546Sdrh 997b413a546Sdrh /* For an index scan, make sure referenced columns are actually in 998b413a546Sdrh ** the index. */ 9992f2b0278Sdrh if( sHint.pIdx!=0 ){ 10002f2b0278Sdrh sWalker.eCode = 0; 10012f2b0278Sdrh sWalker.xExprCallback = codeCursorHintCheckExpr; 10022f2b0278Sdrh sqlite3WalkExpr(&sWalker, pTerm->pExpr); 10032f2b0278Sdrh if( sWalker.eCode ) continue; 10042f2b0278Sdrh } 1005b413a546Sdrh 1006b413a546Sdrh /* If we survive all prior tests, that means this term is worth hinting */ 1007d5c851c1Sdrh pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); 1008bec2476aSdrh } 1009bec2476aSdrh if( pExpr!=0 ){ 1010bec2476aSdrh sWalker.xExprCallback = codeCursorHintFixExpr; 1011bec2476aSdrh sqlite3WalkExpr(&sWalker, pExpr); 10122f2b0278Sdrh sqlite3VdbeAddOp4(v, OP_CursorHint, 10132f2b0278Sdrh (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, 10142f2b0278Sdrh (const char*)pExpr, P4_EXPR); 1015bec2476aSdrh } 1016bec2476aSdrh } 1017bec2476aSdrh #else 1018b324cf75Sdan # define codeCursorHint(A,B,C,D) /* No-op */ 1019bec2476aSdrh #endif /* SQLITE_ENABLE_CURSOR_HINTS */ 10206f82e85aSdrh 10216f82e85aSdrh /* 1022de892d96Sdan ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains 1023de892d96Sdan ** a rowid value just read from cursor iIdxCur, open on index pIdx. This 1024de892d96Sdan ** function generates code to do a deferred seek of cursor iCur to the 1025de892d96Sdan ** rowid stored in register iRowid. 1026de892d96Sdan ** 1027de892d96Sdan ** Normally, this is just: 1028de892d96Sdan ** 1029170ad68aSdrh ** OP_DeferredSeek $iCur $iRowid 1030de892d96Sdan ** 1031de892d96Sdan ** However, if the scan currently being coded is a branch of an OR-loop and 1032170ad68aSdrh ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek 1033de892d96Sdan ** is set to iIdxCur and P4 is set to point to an array of integers 1034de892d96Sdan ** containing one entry for each column of the table cursor iCur is open 1035de892d96Sdan ** on. For each table column, if the column is the i'th column of the 1036de892d96Sdan ** index, then the corresponding array entry is set to (i+1). If the column 1037de892d96Sdan ** does not appear in the index at all, the array entry is set to 0. 1038de892d96Sdan */ 1039de892d96Sdan static void codeDeferredSeek( 1040de892d96Sdan WhereInfo *pWInfo, /* Where clause context */ 1041de892d96Sdan Index *pIdx, /* Index scan is using */ 1042de892d96Sdan int iCur, /* Cursor for IPK b-tree */ 1043de892d96Sdan int iIdxCur /* Index cursor */ 1044de892d96Sdan ){ 1045de892d96Sdan Parse *pParse = pWInfo->pParse; /* Parse context */ 1046de892d96Sdan Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ 1047de892d96Sdan 1048de892d96Sdan assert( iIdxCur>0 ); 1049de892d96Sdan assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); 1050de892d96Sdan 1051be3da241Sdrh pWInfo->bDeferredSeek = 1; 1052170ad68aSdrh sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur); 1053ce943bc8Sdrh if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) 1054cddb6ba0Sdan && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) 1055de892d96Sdan ){ 1056de892d96Sdan int i; 1057de892d96Sdan Table *pTab = pIdx->pTable; 1058abc38158Sdrh u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1)); 1059de892d96Sdan if( ai ){ 1060b1702026Sdrh ai[0] = pTab->nCol; 1061de892d96Sdan for(i=0; i<pIdx->nColumn-1; i++){ 10624fb24c82Sdrh int x1, x2; 1063de892d96Sdan assert( pIdx->aiColumn[i]<pTab->nCol ); 10644fb24c82Sdrh x1 = pIdx->aiColumn[i]; 10654fb24c82Sdrh x2 = sqlite3TableColumnToStorage(pTab, x1); 10664fb24c82Sdrh testcase( x1!=x2 ); 1067bde3a4f6Smistachkin if( x1>=0 ) ai[x2+1] = i+1; 1068de892d96Sdan } 1069de892d96Sdan sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); 1070de892d96Sdan } 1071de892d96Sdan } 1072de892d96Sdan } 1073de892d96Sdan 1074553168c7Sdan /* 1075553168c7Sdan ** If the expression passed as the second argument is a vector, generate 1076553168c7Sdan ** code to write the first nReg elements of the vector into an array 1077553168c7Sdan ** of registers starting with iReg. 1078553168c7Sdan ** 1079553168c7Sdan ** If the expression is not a vector, then nReg must be passed 1. In 1080553168c7Sdan ** this case, generate code to evaluate the expression and leave the 1081553168c7Sdan ** result in register iReg. 1082553168c7Sdan */ 108371c57db0Sdan static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ 108471c57db0Sdan assert( nReg>0 ); 1085d03024d8Sdan if( p && sqlite3ExprIsVector(p) ){ 1086f9b2e05cSdan #ifndef SQLITE_OMIT_SUBQUERY 1087f9b2e05cSdan if( (p->flags & EP_xIsSelect) ){ 1088f9b2e05cSdan Vdbe *v = pParse->pVdbe; 108985bcdce2Sdrh int iSelect; 109085bcdce2Sdrh assert( p->op==TK_SELECT ); 109185bcdce2Sdrh iSelect = sqlite3CodeSubselect(pParse, p); 1092f9b2e05cSdan sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); 1093f9b2e05cSdan }else 1094f9b2e05cSdan #endif 1095f9b2e05cSdan { 109671c57db0Sdan int i; 109771c57db0Sdan ExprList *pList = p->x.pList; 109871c57db0Sdan assert( nReg<=pList->nExpr ); 109971c57db0Sdan for(i=0; i<nReg; i++){ 110071c57db0Sdan sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); 110171c57db0Sdan } 110271c57db0Sdan } 110371c57db0Sdan }else{ 110471c57db0Sdan assert( nReg==1 ); 110571c57db0Sdan sqlite3ExprCode(pParse, p, iReg); 110671c57db0Sdan } 110771c57db0Sdan } 110871c57db0Sdan 1109eac5fc04Sdrh /* An instance of the IdxExprTrans object carries information about a 1110eac5fc04Sdrh ** mapping from an expression on table columns into a column in an index 1111eac5fc04Sdrh ** down through the Walker. 1112eac5fc04Sdrh */ 1113aca19e19Sdrh typedef struct IdxExprTrans { 1114aca19e19Sdrh Expr *pIdxExpr; /* The index expression */ 1115aca19e19Sdrh int iTabCur; /* The cursor of the corresponding table */ 1116aca19e19Sdrh int iIdxCur; /* The cursor for the index */ 1117aca19e19Sdrh int iIdxCol; /* The column for the index */ 1118c7476735Sdrh int iTabCol; /* The column for the table */ 111936e678bcSdrh WhereInfo *pWInfo; /* Complete WHERE clause information */ 112036e678bcSdrh sqlite3 *db; /* Database connection (for malloc()) */ 1121aca19e19Sdrh } IdxExprTrans; 1122aca19e19Sdrh 112336e678bcSdrh /* 112436e678bcSdrh ** Preserve pExpr on the WhereETrans list of the WhereInfo. 112536e678bcSdrh */ 112636e678bcSdrh static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){ 112736e678bcSdrh WhereExprMod *pNew; 112836e678bcSdrh pNew = sqlite3DbMallocRaw(pTrans->db, sizeof(*pNew)); 112936e678bcSdrh if( pNew==0 ) return; 113036e678bcSdrh pNew->pNext = pTrans->pWInfo->pExprMods; 113136e678bcSdrh pTrans->pWInfo->pExprMods = pNew; 113236e678bcSdrh pNew->pExpr = pExpr; 113336e678bcSdrh memcpy(&pNew->orig, pExpr, sizeof(*pExpr)); 113436e678bcSdrh } 113536e678bcSdrh 1136eac5fc04Sdrh /* The walker node callback used to transform matching expressions into 1137eac5fc04Sdrh ** a reference to an index column for an index on an expression. 1138eac5fc04Sdrh ** 1139eac5fc04Sdrh ** If pExpr matches, then transform it into a reference to the index column 1140eac5fc04Sdrh ** that contains the value of pExpr. 1141eac5fc04Sdrh */ 1142aca19e19Sdrh static int whereIndexExprTransNode(Walker *p, Expr *pExpr){ 1143aca19e19Sdrh IdxExprTrans *pX = p->u.pIdxTrans; 11445aa550cfSdan if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){ 114536e678bcSdrh preserveExpr(pX, pExpr); 1146b6ce71bdSdan pExpr->affExpr = sqlite3ExprAffinity(pExpr); 1147aca19e19Sdrh pExpr->op = TK_COLUMN; 1148aca19e19Sdrh pExpr->iTable = pX->iIdxCur; 1149aca19e19Sdrh pExpr->iColumn = pX->iIdxCol; 1150eda079cdSdrh pExpr->y.pTab = 0; 11516c1c85caSdrh testcase( ExprHasProperty(pExpr, EP_Skip) ); 11526c1c85caSdrh testcase( ExprHasProperty(pExpr, EP_Unlikely) ); 11536c1c85caSdrh ExprClearProperty(pExpr, EP_Skip|EP_Unlikely); 1154aca19e19Sdrh return WRC_Prune; 1155aca19e19Sdrh }else{ 1156aca19e19Sdrh return WRC_Continue; 1157aca19e19Sdrh } 1158aca19e19Sdrh } 1159aca19e19Sdrh 1160c7476735Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1161c7476735Sdrh /* A walker node callback that translates a column reference to a table 1162c7476735Sdrh ** into a corresponding column reference of an index. 1163c7476735Sdrh */ 1164c7476735Sdrh static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){ 1165c7476735Sdrh if( pExpr->op==TK_COLUMN ){ 1166c7476735Sdrh IdxExprTrans *pX = p->u.pIdxTrans; 1167c7476735Sdrh if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){ 116857f7ece7Sdrh assert( pExpr->y.pTab!=0 ); 116936e678bcSdrh preserveExpr(pX, pExpr); 117057f7ece7Sdrh pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn); 1171c7476735Sdrh pExpr->iTable = pX->iIdxCur; 1172c7476735Sdrh pExpr->iColumn = pX->iIdxCol; 11734485ac1aSdrh pExpr->y.pTab = 0; 1174c7476735Sdrh } 1175c7476735Sdrh } 1176c7476735Sdrh return WRC_Continue; 1177c7476735Sdrh } 1178c7476735Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 1179c7476735Sdrh 1180aca19e19Sdrh /* 1181f49759bfSdrh ** For an indexes on expression X, locate every instance of expression X 1182f49759bfSdrh ** in pExpr and change that subexpression into a reference to the appropriate 1183f49759bfSdrh ** column of the index. 1184c7476735Sdrh ** 1185c7476735Sdrh ** 2019-10-24: Updated to also translate references to a VIRTUAL column in 1186c7476735Sdrh ** the table into references to the corresponding (stored) column of the 1187c7476735Sdrh ** index. 1188aca19e19Sdrh */ 1189aca19e19Sdrh static void whereIndexExprTrans( 1190aca19e19Sdrh Index *pIdx, /* The Index */ 1191aca19e19Sdrh int iTabCur, /* Cursor of the table that is being indexed */ 1192aca19e19Sdrh int iIdxCur, /* Cursor of the index itself */ 1193aca19e19Sdrh WhereInfo *pWInfo /* Transform expressions in this WHERE clause */ 1194aca19e19Sdrh ){ 1195aca19e19Sdrh int iIdxCol; /* Column number of the index */ 1196aca19e19Sdrh ExprList *aColExpr; /* Expressions that are indexed */ 1197c7476735Sdrh Table *pTab; 1198aca19e19Sdrh Walker w; 1199aca19e19Sdrh IdxExprTrans x; 1200aca19e19Sdrh aColExpr = pIdx->aColExpr; 1201c7476735Sdrh if( aColExpr==0 && !pIdx->bHasVCol ){ 1202c7476735Sdrh /* The index does not reference any expressions or virtual columns 1203c7476735Sdrh ** so no translations are needed. */ 1204c7476735Sdrh return; 1205c7476735Sdrh } 1206c7476735Sdrh pTab = pIdx->pTable; 1207aca19e19Sdrh memset(&w, 0, sizeof(w)); 1208aca19e19Sdrh w.u.pIdxTrans = &x; 1209aca19e19Sdrh x.iTabCur = iTabCur; 1210aca19e19Sdrh x.iIdxCur = iIdxCur; 121136e678bcSdrh x.pWInfo = pWInfo; 121236e678bcSdrh x.db = pWInfo->pParse->db; 1213c7476735Sdrh for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){ 1214c7476735Sdrh i16 iRef = pIdx->aiColumn[iIdxCol]; 1215c7476735Sdrh if( iRef==XN_EXPR ){ 1216aca19e19Sdrh assert( aColExpr->a[iIdxCol].pExpr!=0 ); 1217aca19e19Sdrh x.pIdxExpr = aColExpr->a[iIdxCol].pExpr; 1218e86f3402Sdrh if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue; 1219c7476735Sdrh w.xExprCallback = whereIndexExprTransNode; 1220c7476735Sdrh #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1221ed0c3485Sdrh }else if( iRef>=0 1222ed0c3485Sdrh && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0 1223ed0c3485Sdrh && (pTab->aCol[iRef].zColl==0 1224ed0c3485Sdrh || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0) 1225ed0c3485Sdrh ){ 1226ed0c3485Sdrh /* Check to see if there are direct references to generated columns 1227ed0c3485Sdrh ** that are contained in the index. Pulling the generated column 1228ed0c3485Sdrh ** out of the index is an optimization only - the main table is always 1229ed0c3485Sdrh ** available if the index cannot be used. To avoid unnecessary 1230ed0c3485Sdrh ** complication, omit this optimization if the collating sequence for 1231ed0c3485Sdrh ** the column is non-standard */ 1232c7476735Sdrh x.iTabCol = iRef; 1233c7476735Sdrh w.xExprCallback = whereIndexExprTransColumn; 1234c7476735Sdrh #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 1235c7476735Sdrh }else{ 1236c7476735Sdrh continue; 1237c7476735Sdrh } 1238c7476735Sdrh x.iIdxCol = iIdxCol; 1239aca19e19Sdrh sqlite3WalkExpr(&w, pWInfo->pWhere); 1240aca19e19Sdrh sqlite3WalkExprList(&w, pWInfo->pOrderBy); 1241aca19e19Sdrh sqlite3WalkExprList(&w, pWInfo->pResultSet); 1242aca19e19Sdrh } 1243aca19e19Sdrh } 1244aca19e19Sdrh 1245de892d96Sdan /* 1246610f11deSdrh ** The pTruth expression is always true because it is the WHERE clause 1247b531aa8fSdrh ** a partial index that is driving a query loop. Look through all of the 1248b531aa8fSdrh ** WHERE clause terms on the query, and if any of those terms must be 1249b531aa8fSdrh ** true because pTruth is true, then mark those WHERE clause terms as 1250b531aa8fSdrh ** coded. 1251b531aa8fSdrh */ 1252b531aa8fSdrh static void whereApplyPartialIndexConstraints( 1253b531aa8fSdrh Expr *pTruth, 1254b531aa8fSdrh int iTabCur, 1255b531aa8fSdrh WhereClause *pWC 1256b531aa8fSdrh ){ 1257b531aa8fSdrh int i; 1258b531aa8fSdrh WhereTerm *pTerm; 1259b531aa8fSdrh while( pTruth->op==TK_AND ){ 1260b531aa8fSdrh whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC); 1261b531aa8fSdrh pTruth = pTruth->pRight; 1262b531aa8fSdrh } 1263b531aa8fSdrh for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 1264b531aa8fSdrh Expr *pExpr; 1265b531aa8fSdrh if( pTerm->wtFlags & TERM_CODED ) continue; 1266b531aa8fSdrh pExpr = pTerm->pExpr; 1267b531aa8fSdrh if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){ 1268b531aa8fSdrh pTerm->wtFlags |= TERM_CODED; 1269b531aa8fSdrh } 1270b531aa8fSdrh } 1271b531aa8fSdrh } 1272b531aa8fSdrh 1273b531aa8fSdrh /* 12746f82e85aSdrh ** Generate code for the start of the iLevel-th loop in the WHERE clause 12756f82e85aSdrh ** implementation described by pWInfo. 12766f82e85aSdrh */ 12776f82e85aSdrh Bitmask sqlite3WhereCodeOneLoopStart( 127847df8a2cSdrh Parse *pParse, /* Parsing context */ 127947df8a2cSdrh Vdbe *v, /* Prepared statement under construction */ 12806f82e85aSdrh WhereInfo *pWInfo, /* Complete information about the WHERE clause */ 12816f82e85aSdrh int iLevel, /* Which level of pWInfo->a[] should be coded */ 128247df8a2cSdrh WhereLevel *pLevel, /* The current level pointer */ 12836f82e85aSdrh Bitmask notReady /* Which tables are currently available */ 12846f82e85aSdrh ){ 12856f82e85aSdrh int j, k; /* Loop counters */ 12866f82e85aSdrh int iCur; /* The VDBE cursor for the table */ 12876f82e85aSdrh int addrNxt; /* Where to jump to continue with the next IN case */ 12886f82e85aSdrh int bRev; /* True if we need to scan in reverse order */ 12896f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object being coded */ 12906f82e85aSdrh WhereClause *pWC; /* Decomposition of the entire WHERE clause */ 12916f82e85aSdrh WhereTerm *pTerm; /* A WHERE clause term */ 12926f82e85aSdrh sqlite3 *db; /* Database connection */ 12937601294aSdrh SrcItem *pTabItem; /* FROM clause term being coded */ 12946f82e85aSdrh int addrBrk; /* Jump here to break out of the loop */ 12953a3b420aSdrh int addrHalt; /* addrBrk for the outermost loop */ 12966f82e85aSdrh int addrCont; /* Jump here to continue with next cycle */ 12976f82e85aSdrh int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ 12986f82e85aSdrh int iReleaseReg = 0; /* Temp register to free before returning */ 12996f654a40Sdan Index *pIdx = 0; /* Index used by loop (if any) */ 1300ebc63013Sdan int iLoop; /* Iteration of constraint generator loop */ 13016f82e85aSdrh 13026f82e85aSdrh pWC = &pWInfo->sWC; 13036f82e85aSdrh db = pParse->db; 13046f82e85aSdrh pLoop = pLevel->pWLoop; 13056f82e85aSdrh pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 13066f82e85aSdrh iCur = pTabItem->iCursor; 13076f82e85aSdrh pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); 13086f82e85aSdrh bRev = (pWInfo->revMask>>iLevel)&1; 13096f82e85aSdrh VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); 1310118efd16Sdrh #if WHERETRACE_ENABLED /* 0x20800 */ 1311118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){ 1312a4b2df5cSdrh sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n", 1313a4b2df5cSdrh iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom); 1314118efd16Sdrh sqlite3WhereLoopPrint(pLoop, pWC); 1315118efd16Sdrh } 1316118efd16Sdrh if( sqlite3WhereTrace & 0x20000 ){ 1317f1bb31e2Sdrh if( iLevel==0 ){ 1318f1bb31e2Sdrh sqlite3DebugPrintf("WHERE clause being coded:\n"); 1319f1bb31e2Sdrh sqlite3TreeViewExpr(0, pWInfo->pWhere, 0); 1320f1bb31e2Sdrh } 1321f1bb31e2Sdrh sqlite3DebugPrintf("All WHERE-clause terms before coding:\n"); 1322118efd16Sdrh sqlite3WhereClausePrint(pWC); 1323118efd16Sdrh } 1324118efd16Sdrh #endif 13256f82e85aSdrh 13266f82e85aSdrh /* Create labels for the "break" and "continue" instructions 13276f82e85aSdrh ** for the current loop. Jump to addrBrk to break out of a loop. 13286f82e85aSdrh ** Jump to cont to go immediately to the next iteration of the 13296f82e85aSdrh ** loop. 13306f82e85aSdrh ** 13316f82e85aSdrh ** When there is an IN operator, we also have a "addrNxt" label that 13326f82e85aSdrh ** means to continue with the next IN value combination. When 13336f82e85aSdrh ** there are no IN operators in the constraints, the "addrNxt" label 13346f82e85aSdrh ** is the same as "addrBrk". 13356f82e85aSdrh */ 1336ec4ccdbcSdrh addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); 1337ec4ccdbcSdrh addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse); 13386f82e85aSdrh 13396f82e85aSdrh /* If this is the right table of a LEFT OUTER JOIN, allocate and 13406f82e85aSdrh ** initialize a memory cell that records if this table matches any 13416f82e85aSdrh ** row of the left table of the join. 13426f82e85aSdrh */ 1343820fcd2cSdan assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) 1344820fcd2cSdan || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0 1345820fcd2cSdan ); 13468a48b9c0Sdrh if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ 13476f82e85aSdrh pLevel->iLeftJoin = ++pParse->nMem; 13486f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); 13496f82e85aSdrh VdbeComment((v, "init LEFT JOIN no-match flag")); 13506f82e85aSdrh } 13516f82e85aSdrh 13523a3b420aSdrh /* Compute a safe address to jump to if we discover that the table for 13533a3b420aSdrh ** this loop is empty and can never contribute content. */ 13543a3b420aSdrh for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){} 13553a3b420aSdrh addrHalt = pWInfo->a[j].addrBrk; 13563a3b420aSdrh 13576f82e85aSdrh /* Special case of a FROM clause subquery implemented as a co-routine */ 13588a48b9c0Sdrh if( pTabItem->fg.viaCoroutine ){ 13596f82e85aSdrh int regYield = pTabItem->regReturn; 13606f82e85aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); 13616f82e85aSdrh pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); 13626f82e85aSdrh VdbeCoverage(v); 1363fef37760Sdrh VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); 13646f82e85aSdrh pLevel->op = OP_Goto; 13656f82e85aSdrh }else 13666f82e85aSdrh 13676f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE 13686f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 13696f82e85aSdrh /* Case 1: The table is a virtual-table. Use the VFilter and VNext 13706f82e85aSdrh ** to access the data. 13716f82e85aSdrh */ 13726f82e85aSdrh int iReg; /* P3 Value for OP_VFilter */ 13736f82e85aSdrh int addrNotFound; 13746f82e85aSdrh int nConstraint = pLoop->nLTerm; 1375dbc49161Sdrh int iIn; /* Counter for IN constraints */ 13766f82e85aSdrh 13776f82e85aSdrh iReg = sqlite3GetTempRange(pParse, nConstraint+2); 13786f82e85aSdrh addrNotFound = pLevel->addrBrk; 13796f82e85aSdrh for(j=0; j<nConstraint; j++){ 13806f82e85aSdrh int iTarget = iReg+j+2; 13816f82e85aSdrh pTerm = pLoop->aLTerm[j]; 1382599d5764Sdrh if( NEVER(pTerm==0) ) continue; 13836f82e85aSdrh if( pTerm->eOperator & WO_IN ){ 13846f82e85aSdrh codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); 13856f82e85aSdrh addrNotFound = pLevel->addrNxt; 13866f82e85aSdrh }else{ 13876256c1c2Sdan Expr *pRight = pTerm->pExpr->pRight; 13886256c1c2Sdan codeExprOrVector(pParse, pRight, iTarget, 1); 13896256c1c2Sdan } 13906f82e85aSdrh } 13916f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); 13926f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); 13936f82e85aSdrh sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, 13946f82e85aSdrh pLoop->u.vtab.idxStr, 1395861b1307Sdrh pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); 13966f82e85aSdrh VdbeCoverage(v); 13976f82e85aSdrh pLoop->u.vtab.needFree = 0; 1398bc2e9514Sdrh /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed 1399bc2e9514Sdrh ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */ 1400bc2e9514Sdrh if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0; 14016f82e85aSdrh pLevel->p1 = iCur; 1402354474adSdan pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; 14036f82e85aSdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v); 1404dbc49161Sdrh iIn = pLevel->u.in.nIn; 1405dbc49161Sdrh for(j=nConstraint-1; j>=0; j--){ 1406dbc49161Sdrh pTerm = pLoop->aLTerm[j]; 140768748ec5Sdrh if( (pTerm->eOperator & WO_IN)!=0 ) iIn--; 1408dbc49161Sdrh if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ 1409dbc49161Sdrh disableTerm(pLevel, pTerm); 14104ec3e820Sdrh }else if( (pTerm->eOperator & WO_IN)!=0 14114ec3e820Sdrh && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1 14122d82269cSdan ){ 1413dbc49161Sdrh Expr *pCompare; /* The comparison operator */ 1414dbc49161Sdrh Expr *pRight; /* RHS of the comparison */ 1415dbc49161Sdrh VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ 1416dbc49161Sdrh 1417dbc49161Sdrh /* Reload the constraint value into reg[iReg+j+2]. The same value 1418dbc49161Sdrh ** was loaded into the same register prior to the OP_VFilter, but 1419dbc49161Sdrh ** the xFilter implementation might have changed the datatype or 1420dbc49161Sdrh ** encoding of the value in the register, so it *must* be reloaded. */ 1421dbc49161Sdrh assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); 1422fb826b8cSdrh if( !db->mallocFailed ){ 142368748ec5Sdrh assert( iIn>=0 && iIn<pLevel->u.in.nIn ); 142468748ec5Sdrh pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop); 1425dbc49161Sdrh assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); 1426dbc49161Sdrh assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); 1427dbc49161Sdrh assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); 1428dbc49161Sdrh testcase( pOp->opcode==OP_Rowid ); 1429dbc49161Sdrh sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); 1430dbc49161Sdrh } 1431dbc49161Sdrh 1432dbc49161Sdrh /* Generate code that will continue to the next row if 1433dbc49161Sdrh ** the IN constraint is not satisfied */ 1434abfd35eaSdrh pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0); 1435dbc49161Sdrh assert( pCompare!=0 || db->mallocFailed ); 1436dbc49161Sdrh if( pCompare ){ 1437dbc49161Sdrh pCompare->pLeft = pTerm->pExpr->pLeft; 1438dbc49161Sdrh pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); 1439237b2b71Sdrh if( pRight ){ 1440237b2b71Sdrh pRight->iTable = iReg+j+2; 1441d03f77aeSdan sqlite3ExprIfFalse( 1442d03f77aeSdan pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL 1443d03f77aeSdan ); 1444237b2b71Sdrh } 1445dbc49161Sdrh pCompare->pLeft = 0; 1446dbc49161Sdrh sqlite3ExprDelete(db, pCompare); 1447dbc49161Sdrh } 1448dbc49161Sdrh } 1449dbc49161Sdrh } 145068748ec5Sdrh assert( iIn==0 || db->mallocFailed ); 1451ba26faa3Sdrh /* These registers need to be preserved in case there is an IN operator 1452ba26faa3Sdrh ** loop. So we could deallocate the registers here (and potentially 1453ba26faa3Sdrh ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems 1454ba26faa3Sdrh ** simpler and safer to simply not reuse the registers. 1455ba26faa3Sdrh ** 1456ba26faa3Sdrh ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); 1457ba26faa3Sdrh */ 14586f82e85aSdrh }else 14596f82e85aSdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */ 14606f82e85aSdrh 14616f82e85aSdrh if( (pLoop->wsFlags & WHERE_IPK)!=0 14626f82e85aSdrh && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 14636f82e85aSdrh ){ 14646f82e85aSdrh /* Case 2: We can directly reference a single row using an 14656f82e85aSdrh ** equality comparison against the ROWID field. Or 14666f82e85aSdrh ** we reference multiple rows using a "rowid IN (...)" 14676f82e85aSdrh ** construct. 14686f82e85aSdrh */ 14696f82e85aSdrh assert( pLoop->u.btree.nEq==1 ); 14706f82e85aSdrh pTerm = pLoop->aLTerm[0]; 14716f82e85aSdrh assert( pTerm!=0 ); 14726f82e85aSdrh assert( pTerm->pExpr!=0 ); 14736f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 14746f82e85aSdrh iReleaseReg = ++pParse->nMem; 14756f82e85aSdrh iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); 14766f82e85aSdrh if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); 14776f82e85aSdrh addrNxt = pLevel->addrNxt; 1478eeb9565aSdrh sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); 14796f82e85aSdrh VdbeCoverage(v); 14806f82e85aSdrh pLevel->op = OP_Noop; 1481bc0a55cfSdrh if( (pTerm->prereqAll & pLevel->notReady)==0 ){ 1482042666e4Sdrh pTerm->wtFlags |= TERM_CODED; 1483bc0a55cfSdrh } 14846f82e85aSdrh }else if( (pLoop->wsFlags & WHERE_IPK)!=0 14856f82e85aSdrh && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 14866f82e85aSdrh ){ 14876f82e85aSdrh /* Case 3: We have an inequality comparison against the ROWID field. 14886f82e85aSdrh */ 14896f82e85aSdrh int testOp = OP_Noop; 14906f82e85aSdrh int start; 14916f82e85aSdrh int memEndValue = 0; 14926f82e85aSdrh WhereTerm *pStart, *pEnd; 14936f82e85aSdrh 14946f82e85aSdrh j = 0; 14956f82e85aSdrh pStart = pEnd = 0; 14966f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; 14976f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; 14986f82e85aSdrh assert( pStart!=0 || pEnd!=0 ); 14996f82e85aSdrh if( bRev ){ 15006f82e85aSdrh pTerm = pStart; 15016f82e85aSdrh pStart = pEnd; 15026f82e85aSdrh pEnd = pTerm; 15036f82e85aSdrh } 1504b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); 15056f82e85aSdrh if( pStart ){ 15066f82e85aSdrh Expr *pX; /* The expression that defines the start bound */ 15076f82e85aSdrh int r1, rTemp; /* Registers for holding the start boundary */ 150819ff12ddSdan int op; /* Cursor seek operation */ 15096f82e85aSdrh 15106f82e85aSdrh /* The following constant maps TK_xx codes into corresponding 15116f82e85aSdrh ** seek opcodes. It depends on a particular ordering of TK_xx 15126f82e85aSdrh */ 15136f82e85aSdrh const u8 aMoveOp[] = { 15146f82e85aSdrh /* TK_GT */ OP_SeekGT, 15156f82e85aSdrh /* TK_LE */ OP_SeekLE, 15166f82e85aSdrh /* TK_LT */ OP_SeekLT, 15176f82e85aSdrh /* TK_GE */ OP_SeekGE 15186f82e85aSdrh }; 15196f82e85aSdrh assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ 15206f82e85aSdrh assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ 15216f82e85aSdrh assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ 15226f82e85aSdrh 15236f82e85aSdrh assert( (pStart->wtFlags & TERM_VNULL)==0 ); 15246f82e85aSdrh testcase( pStart->wtFlags & TERM_VIRTUAL ); 15256f82e85aSdrh pX = pStart->pExpr; 15266f82e85aSdrh assert( pX!=0 ); 15276f82e85aSdrh testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ 1528625015e0Sdan if( sqlite3ExprIsVector(pX->pRight) ){ 152919ff12ddSdan r1 = rTemp = sqlite3GetTempReg(pParse); 153019ff12ddSdan codeExprOrVector(pParse, pX->pRight, r1, 1); 15314d1c6845Sdrh testcase( pX->op==TK_GT ); 15324d1c6845Sdrh testcase( pX->op==TK_GE ); 15334d1c6845Sdrh testcase( pX->op==TK_LT ); 15344d1c6845Sdrh testcase( pX->op==TK_LE ); 15354d1c6845Sdrh op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1]; 15364d1c6845Sdrh assert( pX->op!=TK_GT || op==OP_SeekGE ); 15374d1c6845Sdrh assert( pX->op!=TK_GE || op==OP_SeekGE ); 15384d1c6845Sdrh assert( pX->op!=TK_LT || op==OP_SeekLE ); 15394d1c6845Sdrh assert( pX->op!=TK_LE || op==OP_SeekLE ); 154019ff12ddSdan }else{ 15416f82e85aSdrh r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); 154219ff12ddSdan disableTerm(pLevel, pStart); 154319ff12ddSdan op = aMoveOp[(pX->op - TK_GT)]; 154419ff12ddSdan } 154519ff12ddSdan sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); 15466f82e85aSdrh VdbeComment((v, "pk")); 15476f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GT); 15486f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LE); 15496f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LT); 15506f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GE); 15516f82e85aSdrh sqlite3ReleaseTempReg(pParse, rTemp); 15526f82e85aSdrh }else{ 15533a3b420aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt); 15546f82e85aSdrh VdbeCoverageIf(v, bRev==0); 15556f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 15566f82e85aSdrh } 15576f82e85aSdrh if( pEnd ){ 15586f82e85aSdrh Expr *pX; 15596f82e85aSdrh pX = pEnd->pExpr; 15606f82e85aSdrh assert( pX!=0 ); 15616f82e85aSdrh assert( (pEnd->wtFlags & TERM_VNULL)==0 ); 15626f82e85aSdrh testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ 15636f82e85aSdrh testcase( pEnd->wtFlags & TERM_VIRTUAL ); 15646f82e85aSdrh memEndValue = ++pParse->nMem; 156519ff12ddSdan codeExprOrVector(pParse, pX->pRight, memEndValue, 1); 1566625015e0Sdan if( 0==sqlite3ExprIsVector(pX->pRight) 1567625015e0Sdan && (pX->op==TK_LT || pX->op==TK_GT) 1568625015e0Sdan ){ 15696f82e85aSdrh testOp = bRev ? OP_Le : OP_Ge; 15706f82e85aSdrh }else{ 15716f82e85aSdrh testOp = bRev ? OP_Lt : OP_Gt; 15726f82e85aSdrh } 1573553168c7Sdan if( 0==sqlite3ExprIsVector(pX->pRight) ){ 15746f82e85aSdrh disableTerm(pLevel, pEnd); 15756f82e85aSdrh } 1576553168c7Sdan } 15776f82e85aSdrh start = sqlite3VdbeCurrentAddr(v); 15786f82e85aSdrh pLevel->op = bRev ? OP_Prev : OP_Next; 15796f82e85aSdrh pLevel->p1 = iCur; 15806f82e85aSdrh pLevel->p2 = start; 15816f82e85aSdrh assert( pLevel->p5==0 ); 15826f82e85aSdrh if( testOp!=OP_Noop ){ 15836f82e85aSdrh iRowidReg = ++pParse->nMem; 15846f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); 15856f82e85aSdrh sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); 15866f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Le); 15876f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Lt); 15886f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Ge); 15896f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Gt); 15906f82e85aSdrh sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); 15916f82e85aSdrh } 15926f82e85aSdrh }else if( pLoop->wsFlags & WHERE_INDEXED ){ 15936f82e85aSdrh /* Case 4: A scan using an index. 15946f82e85aSdrh ** 15956f82e85aSdrh ** The WHERE clause may contain zero or more equality 15966f82e85aSdrh ** terms ("==" or "IN" operators) that refer to the N 15976f82e85aSdrh ** left-most columns of the index. It may also contain 15986f82e85aSdrh ** inequality constraints (>, <, >= or <=) on the indexed 15996f82e85aSdrh ** column that immediately follows the N equalities. Only 16006f82e85aSdrh ** the right-most column can be an inequality - the rest must 16016f82e85aSdrh ** use the "==" and "IN" operators. For example, if the 16026f82e85aSdrh ** index is on (x,y,z), then the following clauses are all 16036f82e85aSdrh ** optimized: 16046f82e85aSdrh ** 16056f82e85aSdrh ** x=5 16066f82e85aSdrh ** x=5 AND y=10 16076f82e85aSdrh ** x=5 AND y<10 16086f82e85aSdrh ** x=5 AND y>5 AND y<10 16096f82e85aSdrh ** x=5 AND y=5 AND z<=10 16106f82e85aSdrh ** 16116f82e85aSdrh ** The z<10 term of the following cannot be used, only 16126f82e85aSdrh ** the x=5 term: 16136f82e85aSdrh ** 16146f82e85aSdrh ** x=5 AND z<10 16156f82e85aSdrh ** 16166f82e85aSdrh ** N may be zero if there are inequality constraints. 16176f82e85aSdrh ** If there are no inequality constraints, then N is at 16186f82e85aSdrh ** least one. 16196f82e85aSdrh ** 16206f82e85aSdrh ** This case is also used when there are no WHERE clause 16216f82e85aSdrh ** constraints but an index is selected anyway, in order 16226f82e85aSdrh ** to force the output order to conform to an ORDER BY. 16236f82e85aSdrh */ 16246f82e85aSdrh static const u8 aStartOp[] = { 16256f82e85aSdrh 0, 16266f82e85aSdrh 0, 16276f82e85aSdrh OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ 16286f82e85aSdrh OP_Last, /* 3: (!start_constraints && startEq && bRev) */ 16296f82e85aSdrh OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ 16306f82e85aSdrh OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ 16316f82e85aSdrh OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ 16326f82e85aSdrh OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ 16336f82e85aSdrh }; 16346f82e85aSdrh static const u8 aEndOp[] = { 16356f82e85aSdrh OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ 16366f82e85aSdrh OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ 16376f82e85aSdrh OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ 16386f82e85aSdrh OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ 16396f82e85aSdrh }; 16406f82e85aSdrh u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ 164171c57db0Sdan u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ 164271c57db0Sdan u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ 16436f82e85aSdrh int regBase; /* Base register holding constraint values */ 16446f82e85aSdrh WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ 16456f82e85aSdrh WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ 16466f82e85aSdrh int startEq; /* True if range start uses ==, >= or <= */ 16476f82e85aSdrh int endEq; /* True if range end uses ==, >= or <= */ 16486f82e85aSdrh int start_constraints; /* Start of range is constrained */ 16496f82e85aSdrh int nConstraint; /* Number of constraint terms */ 16506f82e85aSdrh int iIdxCur; /* The VDBE cursor for the index */ 16516f82e85aSdrh int nExtraReg = 0; /* Number of extra registers needed */ 16526f82e85aSdrh int op; /* Instruction opcode */ 16536f82e85aSdrh char *zStartAff; /* Affinity for start of range constraint */ 1654b7ca2177Sdan char *zEndAff = 0; /* Affinity for end of range constraint */ 16556f82e85aSdrh u8 bSeekPastNull = 0; /* True to seek past initial nulls */ 16566f82e85aSdrh u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ 165747df8a2cSdrh int omitTable; /* True if we use the index only */ 165874e1b861Sdrh int regBignull = 0; /* big-null flag register */ 165904e70ce0Sdrh int addrSeekScan = 0; /* Opcode of the OP_SeekScan, if any */ 16606f82e85aSdrh 16616f82e85aSdrh pIdx = pLoop->u.btree.pIndex; 16626f82e85aSdrh iIdxCur = pLevel->iIdxCur; 16636f82e85aSdrh assert( nEq>=pLoop->nSkip ); 16646f82e85aSdrh 16656f82e85aSdrh /* Find any inequality constraint terms for the start and end 16666f82e85aSdrh ** of the range. 16676f82e85aSdrh */ 16686f82e85aSdrh j = nEq; 16696f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ 16706f82e85aSdrh pRangeStart = pLoop->aLTerm[j++]; 167171c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); 16726f82e85aSdrh /* Like optimization range constraints always occur in pairs */ 16736f82e85aSdrh assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 16746f82e85aSdrh (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); 16756f82e85aSdrh } 16766f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ 16776f82e85aSdrh pRangeEnd = pLoop->aLTerm[j++]; 167871c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); 167941d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 16806f82e85aSdrh if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ 16816f82e85aSdrh assert( pRangeStart!=0 ); /* LIKE opt constraints */ 16826f82e85aSdrh assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ 168344aebff2Sdrh pLevel->iLikeRepCntr = (u32)++pParse->nMem; 168444aebff2Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); 16856f82e85aSdrh VdbeComment((v, "LIKE loop counter")); 16866f82e85aSdrh pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); 168744aebff2Sdrh /* iLikeRepCntr actually stores 2x the counter register number. The 168844aebff2Sdrh ** bottom bit indicates whether the search order is ASC or DESC. */ 168944aebff2Sdrh testcase( bRev ); 169044aebff2Sdrh testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); 169144aebff2Sdrh assert( (bRev & ~1)==0 ); 169244aebff2Sdrh pLevel->iLikeRepCntr <<=1; 169344aebff2Sdrh pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); 16946f82e85aSdrh } 169541d2e66eSdrh #endif 169648590fcbSdrh if( pRangeStart==0 ){ 169748590fcbSdrh j = pIdx->aiColumn[nEq]; 169848590fcbSdrh if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ 16996f82e85aSdrh bSeekPastNull = 1; 17006f82e85aSdrh } 17016f82e85aSdrh } 170248590fcbSdrh } 17036f82e85aSdrh assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); 17046f82e85aSdrh 170515750a26Sdan /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses 170615750a26Sdan ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS 170715750a26Sdan ** FIRST). In both cases separate ordered scans are made of those 170815750a26Sdan ** index entries for which the column is null and for those for which 170915750a26Sdan ** it is not. For an ASC sort, the non-NULL entries are scanned first. 171015750a26Sdan ** For DESC, NULL entries are scanned first. 171115750a26Sdan */ 171215750a26Sdan if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0 171315750a26Sdan && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0 171415750a26Sdan ){ 171515750a26Sdan assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 ); 171615750a26Sdan assert( pRangeEnd==0 && pRangeStart==0 ); 17174adb1d00Sdan testcase( pLoop->nSkip>0 ); 171815750a26Sdan nExtraReg = 1; 171915750a26Sdan bSeekPastNull = 1; 172015750a26Sdan pLevel->regBignull = regBignull = ++pParse->nMem; 17217f05d52cSdrh if( pLevel->iLeftJoin ){ 17227f05d52cSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull); 17237f05d52cSdrh } 1724cc491f4bSdan pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse); 172515750a26Sdan } 172615750a26Sdan 17276f82e85aSdrh /* If we are doing a reverse order scan on an ascending index, or 17286f82e85aSdrh ** a forward order scan on a descending index, interchange the 17296f82e85aSdrh ** start and end terms (pRangeStart and pRangeEnd). 17306f82e85aSdrh */ 17316f82e85aSdrh if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) 17326f82e85aSdrh || (bRev && pIdx->nKeyCol==nEq) 17336f82e85aSdrh ){ 17346f82e85aSdrh SWAP(WhereTerm *, pRangeEnd, pRangeStart); 17356f82e85aSdrh SWAP(u8, bSeekPastNull, bStopAtNull); 173671c57db0Sdan SWAP(u8, nBtm, nTop); 17376f82e85aSdrh } 17386f82e85aSdrh 1739df1b52e7Sdan if( iLevel>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 ){ 1740df1b52e7Sdan /* In case OP_SeekScan is used, ensure that the index cursor does not 1741df1b52e7Sdan ** point to a valid row for the first iteration of this loop. */ 1742df1b52e7Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur); 1743df1b52e7Sdan } 1744df1b52e7Sdan 1745bcf40a7fSdrh /* Generate code to evaluate all constraint terms using == or IN 1746bcf40a7fSdrh ** and store the values of those terms in an array of registers 1747bcf40a7fSdrh ** starting at regBase. 1748bcf40a7fSdrh */ 1749b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); 1750bcf40a7fSdrh regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); 1751bcf40a7fSdrh assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); 1752b7ca2177Sdan if( zStartAff && nTop ){ 1753b7ca2177Sdan zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); 1754b7ca2177Sdan } 1755cc491f4bSdan addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt); 1756bcf40a7fSdrh 17576f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); 17586f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); 17596f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); 17606f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); 17616f82e85aSdrh startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); 17626f82e85aSdrh endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); 17636f82e85aSdrh start_constraints = pRangeStart || nEq>0; 17646f82e85aSdrh 17656f82e85aSdrh /* Seek the index cursor to the start of the range. */ 17666f82e85aSdrh nConstraint = nEq; 17676f82e85aSdrh if( pRangeStart ){ 17686f82e85aSdrh Expr *pRight = pRangeStart->pExpr->pRight; 176971c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); 17706f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); 1771395a60daSdrh if( (pRangeStart->wtFlags & TERM_VNULL)==0 17726f82e85aSdrh && sqlite3ExprCanBeNull(pRight) 17736f82e85aSdrh ){ 17746f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 17756f82e85aSdrh VdbeCoverage(v); 17766f82e85aSdrh } 17776f82e85aSdrh if( zStartAff ){ 1778e3c6b61cSdrh updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); 17796f82e85aSdrh } 178071c57db0Sdan nConstraint += nBtm; 17816f82e85aSdrh testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); 1782625015e0Sdan if( sqlite3ExprIsVector(pRight)==0 ){ 178371c57db0Sdan disableTerm(pLevel, pRangeStart); 178471c57db0Sdan }else{ 178571c57db0Sdan startEq = 1; 178671c57db0Sdan } 1787426f4ab0Sdrh bSeekPastNull = 0; 17886f82e85aSdrh }else if( bSeekPastNull ){ 17896f82e85aSdrh startEq = 0; 17900086e078Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 17916f82e85aSdrh start_constraints = 1; 17920086e078Sdrh nConstraint++; 179315750a26Sdan }else if( regBignull ){ 179415750a26Sdan sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 179515750a26Sdan start_constraints = 1; 179615750a26Sdan nConstraint++; 17976f82e85aSdrh } 17986f82e85aSdrh codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); 17990bf2ad6aSdrh if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ 18000bf2ad6aSdrh /* The skip-scan logic inside the call to codeAllEqualityConstraints() 18010bf2ad6aSdrh ** above has already left the cursor sitting on the correct row, 18020bf2ad6aSdrh ** so no further seeking is needed */ 18030bf2ad6aSdrh }else{ 180415750a26Sdan if( regBignull ){ 1805ec3dda5bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull); 1806a31d3554Sdrh VdbeComment((v, "NULL-scan pass ctr")); 180715750a26Sdan } 180815750a26Sdan 18096f82e85aSdrh op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; 18106f82e85aSdrh assert( op!=0 ); 18117d14ffe4Sdrh if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){ 181268cf0aceSdrh assert( regBignull==0 ); 18134f65b3bbSdrh /* TUNING: The OP_SeekScan opcode seeks to reduce the number 18144f65b3bbSdrh ** of expensive seek operations by replacing a single seek with 18154f65b3bbSdrh ** 1 or more step operations. The question is, how many steps 18164f65b3bbSdrh ** should we try before giving up and going with a seek. The cost 18174f65b3bbSdrh ** of a seek is proportional to the logarithm of the of the number 18184f65b3bbSdrh ** of entries in the tree, so basing the number of steps to try 18194f65b3bbSdrh ** on the estimated number of rows in the btree seems like a good 18204f65b3bbSdrh ** guess. */ 182104e70ce0Sdrh addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan, 182204e70ce0Sdrh (pIdx->aiRowLogEst[0]+9)/10); 18234f65b3bbSdrh VdbeCoverage(v); 182468cf0aceSdrh } 18256f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 18266f82e85aSdrh VdbeCoverage(v); 18276f82e85aSdrh VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 18286f82e85aSdrh VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 18296f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); 18306f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 18316f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 18326f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); 1833ddd7421cSdan 18340086e078Sdrh assert( bSeekPastNull==0 || bStopAtNull==0 ); 183515750a26Sdan if( regBignull ){ 18360086e078Sdrh assert( bSeekPastNull==1 || bStopAtNull==1 ); 18375f6a4ea2Sdrh assert( bSeekPastNull==!bStopAtNull ); 18380086e078Sdrh assert( bStopAtNull==startEq ); 1839ddd7421cSdan sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); 18400086e078Sdrh op = aStartOp[(nConstraint>1)*4 + 2 + bRev]; 18410086e078Sdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, 18420086e078Sdrh nConstraint-startEq); 1843505ae9deSdrh VdbeCoverage(v); 1844505ae9deSdrh VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 1845505ae9deSdrh VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 1846505ae9deSdrh VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 1847505ae9deSdrh VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 18480086e078Sdrh assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE); 1849ddd7421cSdan } 1850a6d2f8ebSdrh } 18516f82e85aSdrh 18526f82e85aSdrh /* Load the value for the inequality constraint at the end of the 18536f82e85aSdrh ** range (if any). 18546f82e85aSdrh */ 18556f82e85aSdrh nConstraint = nEq; 18566f82e85aSdrh if( pRangeEnd ){ 18576f82e85aSdrh Expr *pRight = pRangeEnd->pExpr->pRight; 185871c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nTop); 18596f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); 1860395a60daSdrh if( (pRangeEnd->wtFlags & TERM_VNULL)==0 18616f82e85aSdrh && sqlite3ExprCanBeNull(pRight) 18626f82e85aSdrh ){ 18636f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 18646f82e85aSdrh VdbeCoverage(v); 18656f82e85aSdrh } 18660c36fca0Sdrh if( zEndAff ){ 1867e3c6b61cSdrh updateRangeAffinityStr(pRight, nTop, zEndAff); 1868b7ca2177Sdan codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); 18690c36fca0Sdrh }else{ 18700c36fca0Sdrh assert( pParse->db->mallocFailed ); 18710c36fca0Sdrh } 187271c57db0Sdan nConstraint += nTop; 18736f82e85aSdrh testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); 187471c57db0Sdan 1875625015e0Sdan if( sqlite3ExprIsVector(pRight)==0 ){ 187671c57db0Sdan disableTerm(pLevel, pRangeEnd); 187771c57db0Sdan }else{ 187871c57db0Sdan endEq = 1; 187971c57db0Sdan } 18806f82e85aSdrh }else if( bStopAtNull ){ 188115750a26Sdan if( regBignull==0 ){ 18826f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 18836f82e85aSdrh endEq = 0; 188415750a26Sdan } 18856f82e85aSdrh nConstraint++; 18866f82e85aSdrh } 18876f82e85aSdrh sqlite3DbFree(db, zStartAff); 1888b7ca2177Sdan sqlite3DbFree(db, zEndAff); 18896f82e85aSdrh 18906f82e85aSdrh /* Top of the loop body */ 18916f82e85aSdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v); 18926f82e85aSdrh 18936f82e85aSdrh /* Check if the index cursor is past the end of the range. */ 18946f82e85aSdrh if( nConstraint ){ 189515750a26Sdan if( regBignull ){ 18965f6a4ea2Sdrh /* Except, skip the end-of-range check while doing the NULL-scan */ 1897ec3dda5bSdrh sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3); 1898a31d3554Sdrh VdbeComment((v, "If NULL-scan 2nd pass")); 1899505ae9deSdrh VdbeCoverage(v); 190015750a26Sdan } 19016f82e85aSdrh op = aEndOp[bRev*2 + endEq]; 19026f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 19036f82e85aSdrh testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 19046f82e85aSdrh testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 19056f82e85aSdrh testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 19066f82e85aSdrh testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 190704e70ce0Sdrh if( addrSeekScan ) sqlite3VdbeJumpHere(v, addrSeekScan); 19086f82e85aSdrh } 190915750a26Sdan if( regBignull ){ 19105f6a4ea2Sdrh /* During a NULL-scan, check to see if we have reached the end of 19115f6a4ea2Sdrh ** the NULLs */ 19125f6a4ea2Sdrh assert( bSeekPastNull==!bStopAtNull ); 19135f6a4ea2Sdrh assert( bSeekPastNull+bStopAtNull==1 ); 19145f6a4ea2Sdrh assert( nConstraint+bSeekPastNull>0 ); 1915ec3dda5bSdrh sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2); 1916a31d3554Sdrh VdbeComment((v, "If NULL-scan 1st pass")); 1917505ae9deSdrh VdbeCoverage(v); 19185f6a4ea2Sdrh op = aEndOp[bRev*2 + bSeekPastNull]; 19195f6a4ea2Sdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, 19205f6a4ea2Sdrh nConstraint+bSeekPastNull); 1921505ae9deSdrh testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 1922505ae9deSdrh testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 1923505ae9deSdrh testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 1924505ae9deSdrh testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 192515750a26Sdan } 19266f82e85aSdrh 1927f761d937Sdrh if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){ 1928fa17e134Sdrh sqlite3VdbeAddOp3(v, OP_SeekHit, iIdxCur, nEq, nEq); 19298c2b6d78Sdrh } 19308c2b6d78Sdrh 19316f82e85aSdrh /* Seek the table cursor, if required */ 193247df8a2cSdrh omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 193347df8a2cSdrh && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; 19346f82e85aSdrh if( omitTable ){ 19356f82e85aSdrh /* pIdx is a covering index. No need to access the main table. */ 19366f82e85aSdrh }else if( HasRowid(pIdx->pTable) ){ 1937784c1b93Sdrh codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); 19386f82e85aSdrh }else if( iCur!=iIdxCur ){ 19396f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); 19406f82e85aSdrh iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); 19416f82e85aSdrh for(j=0; j<pPk->nKeyCol; j++){ 1942b9bcf7caSdrh k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]); 19436f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); 19446f82e85aSdrh } 19456f82e85aSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, 19466f82e85aSdrh iRowidReg, pPk->nKeyCol); VdbeCoverage(v); 19476f82e85aSdrh } 19486f82e85aSdrh 1949db535390Sdrh if( pLevel->iLeftJoin==0 ){ 1950eac5fc04Sdrh /* If pIdx is an index on one or more expressions, then look through 1951eac5fc04Sdrh ** all the expressions in pWInfo and try to transform matching expressions 1952c7476735Sdrh ** into reference to index columns. Also attempt to translate references 1953c7476735Sdrh ** to virtual columns in the table into references to (stored) columns 1954c7476735Sdrh ** of the index. 19554da04f78Sdan ** 19564da04f78Sdan ** Do not do this for the RHS of a LEFT JOIN. This is because the 19574da04f78Sdan ** expression may be evaluated after OP_NullRow has been executed on 19584da04f78Sdan ** the cursor. In this case it is important to do the full evaluation, 19594da04f78Sdan ** as the result of the expression may not be NULL, even if all table 19605776c139Sdrh ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a 19618851e100Sdrh ** 19628851e100Sdrh ** Also, do not do this when processing one index an a multi-index 19638851e100Sdrh ** OR clause, since the transformation will become invalid once we 19648851e100Sdrh ** move forward to the next index. 19658851e100Sdrh ** https://sqlite.org/src/info/4e8e4857d32d401f 1966eac5fc04Sdrh */ 1967db535390Sdrh if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ 1968aca19e19Sdrh whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo); 19694da04f78Sdan } 1970aca19e19Sdrh 1971b531aa8fSdrh /* If a partial index is driving the loop, try to eliminate WHERE clause 1972b531aa8fSdrh ** terms from the query that must be true due to the WHERE clause of 1973db535390Sdrh ** the partial index. 1974db535390Sdrh ** 1975db535390Sdrh ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work 1976db535390Sdrh ** for a LEFT JOIN. 1977b531aa8fSdrh */ 1978b531aa8fSdrh if( pIdx->pPartIdxWhere ){ 1979b531aa8fSdrh whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC); 1980b531aa8fSdrh } 1981db535390Sdrh }else{ 1982db535390Sdrh testcase( pIdx->pPartIdxWhere ); 198306fc2455Sdrh /* The following assert() is not a requirement, merely an observation: 198406fc2455Sdrh ** The OR-optimization doesn't work for the right hand table of 198506fc2455Sdrh ** a LEFT JOIN: */ 198606fc2455Sdrh assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ); 1987db535390Sdrh } 1988b531aa8fSdrh 198971c57db0Sdan /* Record the instruction used to terminate the loop. */ 19906f82e85aSdrh if( pLoop->wsFlags & WHERE_ONEROW ){ 19916f82e85aSdrh pLevel->op = OP_Noop; 19926f82e85aSdrh }else if( bRev ){ 19936f82e85aSdrh pLevel->op = OP_Prev; 19946f82e85aSdrh }else{ 19956f82e85aSdrh pLevel->op = OP_Next; 19966f82e85aSdrh } 19976f82e85aSdrh pLevel->p1 = iIdxCur; 19986f82e85aSdrh pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; 19996f82e85aSdrh if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ 20006f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 20016f82e85aSdrh }else{ 20026f82e85aSdrh assert( pLevel->p5==0 ); 20036f82e85aSdrh } 20046f654a40Sdan if( omitTable ) pIdx = 0; 20056f82e85aSdrh }else 20066f82e85aSdrh 20076f82e85aSdrh #ifndef SQLITE_OMIT_OR_OPTIMIZATION 20086f82e85aSdrh if( pLoop->wsFlags & WHERE_MULTI_OR ){ 20096f82e85aSdrh /* Case 5: Two or more separately indexed terms connected by OR 20106f82e85aSdrh ** 20116f82e85aSdrh ** Example: 20126f82e85aSdrh ** 20136f82e85aSdrh ** CREATE TABLE t1(a,b,c,d); 20146f82e85aSdrh ** CREATE INDEX i1 ON t1(a); 20156f82e85aSdrh ** CREATE INDEX i2 ON t1(b); 20166f82e85aSdrh ** CREATE INDEX i3 ON t1(c); 20176f82e85aSdrh ** 20186f82e85aSdrh ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) 20196f82e85aSdrh ** 20206f82e85aSdrh ** In the example, there are three indexed terms connected by OR. 20216f82e85aSdrh ** The top of the loop looks like this: 20226f82e85aSdrh ** 20236f82e85aSdrh ** Null 1 # Zero the rowset in reg 1 20246f82e85aSdrh ** 20256f82e85aSdrh ** Then, for each indexed term, the following. The arguments to 20266f82e85aSdrh ** RowSetTest are such that the rowid of the current row is inserted 20276f82e85aSdrh ** into the RowSet. If it is already present, control skips the 20286f82e85aSdrh ** Gosub opcode and jumps straight to the code generated by WhereEnd(). 20296f82e85aSdrh ** 20306f82e85aSdrh ** sqlite3WhereBegin(<term>) 20316f82e85aSdrh ** RowSetTest # Insert rowid into rowset 20326f82e85aSdrh ** Gosub 2 A 20336f82e85aSdrh ** sqlite3WhereEnd() 20346f82e85aSdrh ** 20356f82e85aSdrh ** Following the above, code to terminate the loop. Label A, the target 20366f82e85aSdrh ** of the Gosub above, jumps to the instruction right after the Goto. 20376f82e85aSdrh ** 20386f82e85aSdrh ** Null 1 # Zero the rowset in reg 1 20396f82e85aSdrh ** Goto B # The loop is finished. 20406f82e85aSdrh ** 20416f82e85aSdrh ** A: <loop body> # Return data, whatever. 20426f82e85aSdrh ** 20436f82e85aSdrh ** Return 2 # Jump back to the Gosub 20446f82e85aSdrh ** 20456f82e85aSdrh ** B: <after the loop> 20466f82e85aSdrh ** 20476f82e85aSdrh ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then 20486f82e85aSdrh ** use an ephemeral index instead of a RowSet to record the primary 20496f82e85aSdrh ** keys of the rows we have already seen. 20506f82e85aSdrh ** 20516f82e85aSdrh */ 20526f82e85aSdrh WhereClause *pOrWc; /* The OR-clause broken out into subterms */ 20536f82e85aSdrh SrcList *pOrTab; /* Shortened table list or OR-clause generation */ 20546f82e85aSdrh Index *pCov = 0; /* Potential covering index (or NULL) */ 20556f82e85aSdrh int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ 20566f82e85aSdrh 20576f82e85aSdrh int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ 20586f82e85aSdrh int regRowset = 0; /* Register for RowSet object */ 20596f82e85aSdrh int regRowid = 0; /* Register holding rowid */ 2060ec4ccdbcSdrh int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */ 20616f82e85aSdrh int iRetInit; /* Address of regReturn init */ 20626f82e85aSdrh int untestedTerms = 0; /* Some terms not completely tested */ 20636f82e85aSdrh int ii; /* Loop counter */ 20646f82e85aSdrh Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ 20656f82e85aSdrh Table *pTab = pTabItem->pTab; 20666f82e85aSdrh 20676f82e85aSdrh pTerm = pLoop->aLTerm[0]; 20686f82e85aSdrh assert( pTerm!=0 ); 20696f82e85aSdrh assert( pTerm->eOperator & WO_OR ); 20706f82e85aSdrh assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); 20716f82e85aSdrh pOrWc = &pTerm->u.pOrInfo->wc; 20726f82e85aSdrh pLevel->op = OP_Return; 20736f82e85aSdrh pLevel->p1 = regReturn; 20746f82e85aSdrh 20756f82e85aSdrh /* Set up a new SrcList in pOrTab containing the table being scanned 20766f82e85aSdrh ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. 20776f82e85aSdrh ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). 20786f82e85aSdrh */ 20796f82e85aSdrh if( pWInfo->nLevel>1 ){ 20806f82e85aSdrh int nNotReady; /* The number of notReady tables */ 20817601294aSdrh SrcItem *origSrc; /* Original list of tables */ 20826f82e85aSdrh nNotReady = pWInfo->nLevel - iLevel - 1; 20836f82e85aSdrh pOrTab = sqlite3StackAllocRaw(db, 20846f82e85aSdrh sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); 20856f82e85aSdrh if( pOrTab==0 ) return notReady; 20866f82e85aSdrh pOrTab->nAlloc = (u8)(nNotReady + 1); 20876f82e85aSdrh pOrTab->nSrc = pOrTab->nAlloc; 20886f82e85aSdrh memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); 20896f82e85aSdrh origSrc = pWInfo->pTabList->a; 20906f82e85aSdrh for(k=1; k<=nNotReady; k++){ 20916f82e85aSdrh memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); 20926f82e85aSdrh } 20936f82e85aSdrh }else{ 20946f82e85aSdrh pOrTab = pWInfo->pTabList; 20956f82e85aSdrh } 20966f82e85aSdrh 20976f82e85aSdrh /* Initialize the rowset register to contain NULL. An SQL NULL is 20986f82e85aSdrh ** equivalent to an empty rowset. Or, create an ephemeral index 20996f82e85aSdrh ** capable of holding primary keys in the case of a WITHOUT ROWID. 21006f82e85aSdrh ** 21016f82e85aSdrh ** Also initialize regReturn to contain the address of the instruction 21026f82e85aSdrh ** immediately following the OP_Return at the bottom of the loop. This 21036f82e85aSdrh ** is required in a few obscure LEFT JOIN cases where control jumps 21046f82e85aSdrh ** over the top of the loop into the body of it. In this case the 21056f82e85aSdrh ** correct response for the end-of-loop code (the OP_Return) is to 21066f82e85aSdrh ** fall through to the next instruction, just as an OP_Next does if 21076f82e85aSdrh ** called on an uninitialized cursor. 21086f82e85aSdrh */ 21096f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 21106f82e85aSdrh if( HasRowid(pTab) ){ 21116f82e85aSdrh regRowset = ++pParse->nMem; 21126f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); 21136f82e85aSdrh }else{ 21146f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 21156f82e85aSdrh regRowset = pParse->nTab++; 21166f82e85aSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); 21176f82e85aSdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk); 21186f82e85aSdrh } 21196f82e85aSdrh regRowid = ++pParse->nMem; 21206f82e85aSdrh } 21216f82e85aSdrh iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); 21226f82e85aSdrh 21236f82e85aSdrh /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y 21246f82e85aSdrh ** Then for every term xN, evaluate as the subexpression: xN AND z 21256f82e85aSdrh ** That way, terms in y that are factored into the disjunction will 21266f82e85aSdrh ** be picked up by the recursive calls to sqlite3WhereBegin() below. 21276f82e85aSdrh ** 21286f82e85aSdrh ** Actually, each subexpression is converted to "xN AND w" where w is 21296f82e85aSdrh ** the "interesting" terms of z - terms that did not originate in the 21306f82e85aSdrh ** ON or USING clause of a LEFT JOIN, and terms that are usable as 21316f82e85aSdrh ** indices. 21326f82e85aSdrh ** 21336f82e85aSdrh ** This optimization also only applies if the (x1 OR x2 OR ...) term 21346f82e85aSdrh ** is not contained in the ON clause of a LEFT JOIN. 21356f82e85aSdrh ** See ticket http://www.sqlite.org/src/info/f2369304e4 21366f82e85aSdrh */ 21376f82e85aSdrh if( pWC->nTerm>1 ){ 21386f82e85aSdrh int iTerm; 21396f82e85aSdrh for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ 21406f82e85aSdrh Expr *pExpr = pWC->a[iTerm].pExpr; 21416f82e85aSdrh if( &pWC->a[iTerm] == pTerm ) continue; 21423b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); 21433b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); 21443b83f0cdSdrh if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; 21456f82e85aSdrh if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; 21466f82e85aSdrh testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); 21476f82e85aSdrh pExpr = sqlite3ExprDup(db, pExpr, 0); 2148d5c851c1Sdrh pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr); 21496f82e85aSdrh } 21506f82e85aSdrh if( pAndExpr ){ 2151f1722baaSdrh /* The extra 0x10000 bit on the opcode is masked off and does not 2152f1722baaSdrh ** become part of the new Expr.op. However, it does make the 2153f1722baaSdrh ** op==TK_AND comparison inside of sqlite3PExpr() false, and this 2154f1722baaSdrh ** prevents sqlite3PExpr() from implementing AND short-circuit 2155f1722baaSdrh ** optimization, which we do not want here. */ 2156f1722baaSdrh pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr); 21576f82e85aSdrh } 21586f82e85aSdrh } 21596f82e85aSdrh 21606f82e85aSdrh /* Run a separate WHERE clause for each term of the OR clause. After 21616f82e85aSdrh ** eliminating duplicates from other WHERE clauses, the action for each 21626f82e85aSdrh ** sub-WHERE clause is to to invoke the main loop body as a subroutine. 21636f82e85aSdrh */ 21645d72d924Sdrh ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR")); 21656f82e85aSdrh for(ii=0; ii<pOrWc->nTerm; ii++){ 21666f82e85aSdrh WhereTerm *pOrTerm = &pOrWc->a[ii]; 21676f82e85aSdrh if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ 21686f82e85aSdrh WhereInfo *pSubWInfo; /* Info for single OR-term scan */ 21696f82e85aSdrh Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ 2170728e0f91Sdrh int jmp1 = 0; /* Address of jump operation */ 21713b8eb08bSdrh testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0 21723b8eb08bSdrh && !ExprHasProperty(pOrExpr, EP_FromJoin) 21733b8eb08bSdrh ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */ 2174820fcd2cSdan if( pAndExpr ){ 21756f82e85aSdrh pAndExpr->pLeft = pOrExpr; 21766f82e85aSdrh pOrExpr = pAndExpr; 21776f82e85aSdrh } 21786f82e85aSdrh /* Loop through table entries that match term pOrTerm. */ 2179bd462bccSdrh ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1)); 21806f82e85aSdrh WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); 21816f82e85aSdrh pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 218268c0c710Sdrh WHERE_OR_SUBCLAUSE, iCovCur); 21836f82e85aSdrh assert( pSubWInfo || pParse->nErr || db->mallocFailed ); 21846f82e85aSdrh if( pSubWInfo ){ 21856f82e85aSdrh WhereLoop *pSubLoop; 21866f82e85aSdrh int addrExplain = sqlite3WhereExplainOneScan( 2187e2188f0bSdrh pParse, pOrTab, &pSubWInfo->a[0], 0 21886f82e85aSdrh ); 21896f82e85aSdrh sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); 21906f82e85aSdrh 21916f82e85aSdrh /* This is the sub-WHERE clause body. First skip over 21926f82e85aSdrh ** duplicate rows from prior sub-WHERE clauses, and record the 21936f82e85aSdrh ** rowid (or PRIMARY KEY) for the current row so that the same 21946f82e85aSdrh ** row will be skipped in subsequent sub-WHERE clauses. 21956f82e85aSdrh */ 21966f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 21976f82e85aSdrh int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); 21986f82e85aSdrh if( HasRowid(pTab) ){ 21996df9c4b9Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid); 2200728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, 22018c607191Sdrh regRowid, iSet); 22026f82e85aSdrh VdbeCoverage(v); 22036f82e85aSdrh }else{ 22046f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab); 22056f82e85aSdrh int nPk = pPk->nKeyCol; 22066f82e85aSdrh int iPk; 22078c607191Sdrh int r; 22086f82e85aSdrh 22096f82e85aSdrh /* Read the PK into an array of temp registers. */ 22106f82e85aSdrh r = sqlite3GetTempRange(pParse, nPk); 22116f82e85aSdrh for(iPk=0; iPk<nPk; iPk++){ 22126f82e85aSdrh int iCol = pPk->aiColumn[iPk]; 22136df9c4b9Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk); 22146f82e85aSdrh } 22156f82e85aSdrh 22166f82e85aSdrh /* Check if the temp table already contains this key. If so, 22176f82e85aSdrh ** the row has already been included in the result set and 22186f82e85aSdrh ** can be ignored (by jumping past the Gosub below). Otherwise, 22196f82e85aSdrh ** insert the key into the temp table and proceed with processing 22206f82e85aSdrh ** the row. 22216f82e85aSdrh ** 22226f82e85aSdrh ** Use some of the same optimizations as OP_RowSetTest: If iSet 22236f82e85aSdrh ** is zero, assume that the key cannot already be present in 22246f82e85aSdrh ** the temp table. And if iSet is -1, assume that there is no 22256f82e85aSdrh ** need to insert the key into the temp table, as it will never 22266f82e85aSdrh ** be tested for. */ 22276f82e85aSdrh if( iSet ){ 2228728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); 22296f82e85aSdrh VdbeCoverage(v); 22306f82e85aSdrh } 22316f82e85aSdrh if( iSet>=0 ){ 22326f82e85aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); 22339b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, 22349b4eaebcSdrh r, nPk); 22356f82e85aSdrh if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 22366f82e85aSdrh } 22376f82e85aSdrh 22386f82e85aSdrh /* Release the array of temp registers */ 22396f82e85aSdrh sqlite3ReleaseTempRange(pParse, r, nPk); 22406f82e85aSdrh } 22416f82e85aSdrh } 22426f82e85aSdrh 22436f82e85aSdrh /* Invoke the main loop body as a subroutine */ 22446f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); 22456f82e85aSdrh 22466f82e85aSdrh /* Jump here (skipping the main loop body subroutine) if the 22476f82e85aSdrh ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ 2248728e0f91Sdrh if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); 22496f82e85aSdrh 22506f82e85aSdrh /* The pSubWInfo->untestedTerms flag means that this OR term 22516f82e85aSdrh ** contained one or more AND term from a notReady table. The 22526f82e85aSdrh ** terms from the notReady table could not be tested and will 22536f82e85aSdrh ** need to be tested later. 22546f82e85aSdrh */ 22556f82e85aSdrh if( pSubWInfo->untestedTerms ) untestedTerms = 1; 22566f82e85aSdrh 22576f82e85aSdrh /* If all of the OR-connected terms are optimized using the same 22586f82e85aSdrh ** index, and the index is opened using the same cursor number 22596f82e85aSdrh ** by each call to sqlite3WhereBegin() made by this loop, it may 22606f82e85aSdrh ** be possible to use that index as a covering index. 22616f82e85aSdrh ** 22626f82e85aSdrh ** If the call to sqlite3WhereBegin() above resulted in a scan that 22636f82e85aSdrh ** uses an index, and this is either the first OR-connected term 22646f82e85aSdrh ** processed or the index is the same as that used by all previous 22656f82e85aSdrh ** terms, set pCov to the candidate covering index. Otherwise, set 22666f82e85aSdrh ** pCov to NULL to indicate that no candidate covering index will 22676f82e85aSdrh ** be available. 22686f82e85aSdrh */ 22696f82e85aSdrh pSubLoop = pSubWInfo->a[0].pWLoop; 22706f82e85aSdrh assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 22716f82e85aSdrh if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 22726f82e85aSdrh && (ii==0 || pSubLoop->u.btree.pIndex==pCov) 22736f82e85aSdrh && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) 22746f82e85aSdrh ){ 22756f82e85aSdrh assert( pSubWInfo->a[0].iIdxCur==iCovCur ); 22766f82e85aSdrh pCov = pSubLoop->u.btree.pIndex; 22776f82e85aSdrh }else{ 22786f82e85aSdrh pCov = 0; 22796f82e85aSdrh } 228068c0c710Sdrh if( sqlite3WhereUsesDeferredSeek(pSubWInfo) ){ 228168c0c710Sdrh pWInfo->bDeferredSeek = 1; 228268c0c710Sdrh } 22836f82e85aSdrh 22846f82e85aSdrh /* Finish the loop through table entries that match term pOrTerm. */ 22856f82e85aSdrh sqlite3WhereEnd(pSubWInfo); 2286bd462bccSdrh ExplainQueryPlanPop(pParse); 22876f82e85aSdrh } 22886f82e85aSdrh } 22896f82e85aSdrh } 22905d72d924Sdrh ExplainQueryPlanPop(pParse); 22916f82e85aSdrh pLevel->u.pCovidx = pCov; 22926f82e85aSdrh if( pCov ) pLevel->iIdxCur = iCovCur; 22936f82e85aSdrh if( pAndExpr ){ 22946f82e85aSdrh pAndExpr->pLeft = 0; 22956f82e85aSdrh sqlite3ExprDelete(db, pAndExpr); 22966f82e85aSdrh } 22976f82e85aSdrh sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); 2298076e85f5Sdrh sqlite3VdbeGoto(v, pLevel->addrBrk); 22996f82e85aSdrh sqlite3VdbeResolveLabel(v, iLoopBody); 23006f82e85aSdrh 2301dd2d9a3dSdrh if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); } 23026f82e85aSdrh if( !untestedTerms ) disableTerm(pLevel, pTerm); 23036f82e85aSdrh }else 23046f82e85aSdrh #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 23056f82e85aSdrh 23066f82e85aSdrh { 23076f82e85aSdrh /* Case 6: There is no usable index. We must do a complete 23086f82e85aSdrh ** scan of the entire table. 23096f82e85aSdrh */ 23106f82e85aSdrh static const u8 aStep[] = { OP_Next, OP_Prev }; 23116f82e85aSdrh static const u8 aStart[] = { OP_Rewind, OP_Last }; 23126f82e85aSdrh assert( bRev==0 || bRev==1 ); 23138a48b9c0Sdrh if( pTabItem->fg.isRecursive ){ 23146f82e85aSdrh /* Tables marked isRecursive have only a single row that is stored in 23156f82e85aSdrh ** a pseudo-cursor. No need to Rewind or Next such cursors. */ 23166f82e85aSdrh pLevel->op = OP_Noop; 23176f82e85aSdrh }else{ 2318b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, 0); 23196f82e85aSdrh pLevel->op = aStep[bRev]; 23206f82e85aSdrh pLevel->p1 = iCur; 23213a3b420aSdrh pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt); 23226f82e85aSdrh VdbeCoverageIf(v, bRev==0); 23236f82e85aSdrh VdbeCoverageIf(v, bRev!=0); 23246f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 23256f82e85aSdrh } 23266f82e85aSdrh } 23276f82e85aSdrh 23286f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 23296f82e85aSdrh pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); 23306f82e85aSdrh #endif 23316f82e85aSdrh 23326f82e85aSdrh /* Insert code to test every subexpression that can be completely 23336f82e85aSdrh ** computed using the current set of tables. 23346f654a40Sdan ** 2335ebc63013Sdan ** This loop may run between one and three times, depending on the 2336ebc63013Sdan ** constraints to be generated. The value of stack variable iLoop 2337ebc63013Sdan ** determines the constraints coded by each iteration, as follows: 2338ebc63013Sdan ** 2339ebc63013Sdan ** iLoop==1: Code only expressions that are entirely covered by pIdx. 2340ebc63013Sdan ** iLoop==2: Code remaining expressions that do not contain correlated 2341ebc63013Sdan ** sub-queries. 2342ebc63013Sdan ** iLoop==3: Code all remaining expressions. 2343ebc63013Sdan ** 2344ebc63013Sdan ** An effort is made to skip unnecessary iterations of the loop. 23456ab3eb5dSdrh */ 2346ebc63013Sdan iLoop = (pIdx ? 1 : 2); 23476ab3eb5dSdrh do{ 2348ebc63013Sdan int iNext = 0; /* Next value for iLoop */ 23496f82e85aSdrh for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 23506f82e85aSdrh Expr *pE; 23516f82e85aSdrh int skipLikeAddr = 0; 23526f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 23536f82e85aSdrh testcase( pTerm->wtFlags & TERM_CODED ); 23546f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 23556f82e85aSdrh if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 23566f82e85aSdrh testcase( pWInfo->untestedTerms==0 2357ce943bc8Sdrh && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); 23586f82e85aSdrh pWInfo->untestedTerms = 1; 23596f82e85aSdrh continue; 23606f82e85aSdrh } 23616f82e85aSdrh pE = pTerm->pExpr; 23626f82e85aSdrh assert( pE!=0 ); 2363820fcd2cSdan if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){ 23646f654a40Sdan continue; 23656f654a40Sdan } 2366ebc63013Sdan 23678674ec5aSdan if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){ 2368ebc63013Sdan iNext = 2; 23696f82e85aSdrh continue; 23706f82e85aSdrh } 2371d3930b12Sdan if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){ 2372ebc63013Sdan if( iNext==0 ) iNext = 3; 2373ebc63013Sdan continue; 2374ebc63013Sdan } 2375ebc63013Sdan 23764de3353dSdrh if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){ 237744aebff2Sdrh /* If the TERM_LIKECOND flag is set, that means that the range search 237844aebff2Sdrh ** is sufficient to guarantee that the LIKE operator is true, so we 237944aebff2Sdrh ** can skip the call to the like(A,B) function. But this only works 238044aebff2Sdrh ** for strings. So do not skip the call to the function on the pass 238144aebff2Sdrh ** that compares BLOBs. */ 238241d2e66eSdrh #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 238341d2e66eSdrh continue; 238441d2e66eSdrh #else 238544aebff2Sdrh u32 x = pLevel->iLikeRepCntr; 23864de3353dSdrh if( x>0 ){ 238744aebff2Sdrh skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1)); 23886f88359dSdrh VdbeCoverageIf(v, (x&1)==1); 23896f88359dSdrh VdbeCoverageIf(v, (x&1)==0); 23904de3353dSdrh } 239141d2e66eSdrh #endif 23926f82e85aSdrh } 239366a0bf31Sdrh #ifdef WHERETRACE_ENABLED /* 0xffff */ 239466a0bf31Sdrh if( sqlite3WhereTrace ){ 239566a0bf31Sdrh VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d", 239666a0bf31Sdrh pWC->nTerm-j, pTerm, iLoop)); 239766a0bf31Sdrh } 2398118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){ 2399118efd16Sdrh sqlite3DebugPrintf("Coding auxiliary constraint:\n"); 2400118efd16Sdrh sqlite3WhereTermPrint(pTerm, pWC->nTerm-j); 2401118efd16Sdrh } 240266a0bf31Sdrh #endif 24036f82e85aSdrh sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); 24046f82e85aSdrh if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); 24056f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 24066f82e85aSdrh } 2407ebc63013Sdan iLoop = iNext; 2408ebc63013Sdan }while( iLoop>0 ); 24096f82e85aSdrh 24106f82e85aSdrh /* Insert code to test for implied constraints based on transitivity 24116f82e85aSdrh ** of the "==" operator. 24126f82e85aSdrh ** 24136f82e85aSdrh ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" 24146f82e85aSdrh ** and we are coding the t1 loop and the t2 loop has not yet coded, 24156f82e85aSdrh ** then we cannot use the "t1.a=t2.b" constraint, but we can code 24166f82e85aSdrh ** the implied "t1.a=123" constraint. 24176f82e85aSdrh */ 24186f82e85aSdrh for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 2419cb43a937Sdrh Expr *pE, sEAlt; 24206f82e85aSdrh WhereTerm *pAlt; 24216f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 24226f82e85aSdrh if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; 24236f82e85aSdrh if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; 24246f82e85aSdrh if( pTerm->leftCursor!=iCur ) continue; 2425a4b2df5cSdrh if( pTabItem->fg.jointype & JT_LEFT ) continue; 24266f82e85aSdrh pE = pTerm->pExpr; 2427118efd16Sdrh #ifdef WHERETRACE_ENABLED /* 0x800 */ 2428118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){ 2429118efd16Sdrh sqlite3DebugPrintf("Coding transitive constraint:\n"); 2430118efd16Sdrh sqlite3WhereTermPrint(pTerm, pWC->nTerm-j); 2431118efd16Sdrh } 2432118efd16Sdrh #endif 2433f1bb31e2Sdrh assert( !ExprHasProperty(pE, EP_FromJoin) ); 24346f82e85aSdrh assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); 243575fa2663Sdrh pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady, 24366f82e85aSdrh WO_EQ|WO_IN|WO_IS, 0); 24376f82e85aSdrh if( pAlt==0 ) continue; 24386f82e85aSdrh if( pAlt->wtFlags & (TERM_CODED) ) continue; 2439a916b570Sdan if( (pAlt->eOperator & WO_IN) 2440a916b570Sdan && (pAlt->pExpr->flags & EP_xIsSelect) 2441a599e150Sdrh && (pAlt->pExpr->x.pSelect->pEList->nExpr>1) 2442a916b570Sdan ){ 2443a916b570Sdan continue; 2444a916b570Sdan } 24456f82e85aSdrh testcase( pAlt->eOperator & WO_EQ ); 24466f82e85aSdrh testcase( pAlt->eOperator & WO_IS ); 24476f82e85aSdrh testcase( pAlt->eOperator & WO_IN ); 24486f82e85aSdrh VdbeModuleComment((v, "begin transitive constraint")); 2449cb43a937Sdrh sEAlt = *pAlt->pExpr; 2450cb43a937Sdrh sEAlt.pLeft = pE->pLeft; 2451cb43a937Sdrh sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); 2452240e36c0Sdan pAlt->wtFlags |= TERM_CODED; 24536f82e85aSdrh } 24546f82e85aSdrh 24556f82e85aSdrh /* For a LEFT OUTER JOIN, generate code that will record the fact that 24566f82e85aSdrh ** at least one row of the right table has matched the left table. 24576f82e85aSdrh */ 24586f82e85aSdrh if( pLevel->iLeftJoin ){ 24596f82e85aSdrh pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); 24606f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); 24616f82e85aSdrh VdbeComment((v, "record LEFT JOIN hit")); 24626f82e85aSdrh for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ 24636f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL ); 24646f82e85aSdrh testcase( pTerm->wtFlags & TERM_CODED ); 24656f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 24666f82e85aSdrh if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 24676f82e85aSdrh assert( pWInfo->untestedTerms ); 24686f82e85aSdrh continue; 24696f82e85aSdrh } 24706f82e85aSdrh assert( pTerm->pExpr ); 24716f82e85aSdrh sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 24726f82e85aSdrh pTerm->wtFlags |= TERM_CODED; 24736f82e85aSdrh } 24746f82e85aSdrh } 24756f82e85aSdrh 2476118efd16Sdrh #if WHERETRACE_ENABLED /* 0x20800 */ 2477118efd16Sdrh if( sqlite3WhereTrace & 0x20000 ){ 2478f1bb31e2Sdrh sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n", 2479f1bb31e2Sdrh iLevel); 2480118efd16Sdrh sqlite3WhereClausePrint(pWC); 2481118efd16Sdrh } 2482118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){ 2483118efd16Sdrh sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n", 2484118efd16Sdrh iLevel, (u64)pLevel->notReady); 2485118efd16Sdrh } 2486118efd16Sdrh #endif 24876f82e85aSdrh return pLevel->notReady; 24886f82e85aSdrh } 2489