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 */
explainIndexColumnName(Index * pIdx,int i)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";
32cf9d36d1Sdrh return pIdx->pTable->aCol[i].zCnName;
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 */
explainAppendTerm(StrAccum * pStr,Index * pIdx,int nTerm,int iTerm,int bAnd,const char * zOp)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 */
explainIndexRange(StrAccum * pStr,WhereLoop * pLoop)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 */
sqlite3WhereExplainOneScan(Parse * pParse,SrcList * pTabList,WhereLevel * pLevel,u16 wctrlFlags)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 ){
1793bd7cd73Sdrh char cRangeOp;
1803bd7cd73Sdrh #if 0 /* Better output, but breaks many tests */
1813bd7cd73Sdrh const Table *pTab = pItem->pTab;
1823bd7cd73Sdrh const char *zRowid = pTab->iPKey>=0 ? pTab->aCol[pTab->iPKey].zCnName:
1833bd7cd73Sdrh "rowid";
1843bd7cd73Sdrh #else
1853bd7cd73Sdrh const char *zRowid = "rowid";
1863bd7cd73Sdrh #endif
1873bd7cd73Sdrh sqlite3_str_appendf(&str, " USING INTEGER PRIMARY KEY (%s", zRowid);
1886f82e85aSdrh if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
1893bd7cd73Sdrh cRangeOp = '=';
1906f82e85aSdrh }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
1913bd7cd73Sdrh sqlite3_str_appendf(&str, ">? AND %s", zRowid);
1923bd7cd73Sdrh cRangeOp = '<';
1936f82e85aSdrh }else if( flags&WHERE_BTM_LIMIT ){
1943bd7cd73Sdrh cRangeOp = '>';
1956f82e85aSdrh }else{
1966f82e85aSdrh assert( flags&WHERE_TOP_LIMIT);
1973bd7cd73Sdrh cRangeOp = '<';
1986f82e85aSdrh }
1993bd7cd73Sdrh sqlite3_str_appendf(&str, "%c?)", cRangeOp);
2006f82e85aSdrh }
2016f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
2026f82e85aSdrh else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
2030cdbe1aeSdrh sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
2046f82e85aSdrh pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
2056f82e85aSdrh }
2066f82e85aSdrh #endif
207c583719bSdrh if( pItem->fg.jointype & JT_LEFT ){
208c583719bSdrh sqlite3_str_appendf(&str, " LEFT-JOIN");
209c583719bSdrh }
2106f82e85aSdrh #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
2116f82e85aSdrh if( pLoop->nOut>=10 ){
2120cdbe1aeSdrh sqlite3_str_appendf(&str, " (~%llu rows)",
2130cdbe1aeSdrh sqlite3LogEstToInt(pLoop->nOut));
2146f82e85aSdrh }else{
2150cdbe1aeSdrh sqlite3_str_append(&str, " (~1 row)", 9);
2166f82e85aSdrh }
2176f82e85aSdrh #endif
2186f82e85aSdrh zMsg = sqlite3StrAccumFinish(&str);
219bd462bccSdrh sqlite3ExplainBreakpoint("",zMsg);
220e2ca99c9Sdrh ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
221e2ca99c9Sdrh pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
2226f82e85aSdrh }
2236f82e85aSdrh return ret;
2246f82e85aSdrh }
2256ae49e67Sdrh
2266ae49e67Sdrh /*
2276ae49e67Sdrh ** Add a single OP_Explain opcode that describes a Bloom filter.
2286ae49e67Sdrh **
2296ae49e67Sdrh ** Or if not processing EXPLAIN QUERY PLAN and not in a SQLITE_DEBUG and/or
2306ae49e67Sdrh ** SQLITE_ENABLE_STMT_SCANSTATUS build, then OP_Explain opcodes are not
2316ae49e67Sdrh ** required and this routine is a no-op.
2326ae49e67Sdrh **
2336ae49e67Sdrh ** If an OP_Explain opcode is added to the VM, its address is returned.
2346ae49e67Sdrh ** Otherwise, if no OP_Explain is coded, zero is returned.
2356ae49e67Sdrh */
sqlite3WhereExplainBloomFilter(const Parse * pParse,const WhereInfo * pWInfo,const WhereLevel * pLevel)2366ae49e67Sdrh int sqlite3WhereExplainBloomFilter(
2376ae49e67Sdrh const Parse *pParse, /* Parse context */
2386ae49e67Sdrh const WhereInfo *pWInfo, /* WHERE clause */
2396ae49e67Sdrh const WhereLevel *pLevel /* Bloom filter on this level */
2406ae49e67Sdrh ){
2416ae49e67Sdrh int ret = 0;
2426ae49e67Sdrh SrcItem *pItem = &pWInfo->pTabList->a[pLevel->iFrom];
2436ae49e67Sdrh Vdbe *v = pParse->pVdbe; /* VM being constructed */
2446ae49e67Sdrh sqlite3 *db = pParse->db; /* Database handle */
2456ae49e67Sdrh char *zMsg; /* Text to add to EQP output */
2466ae49e67Sdrh int i; /* Loop counter */
2476ae49e67Sdrh WhereLoop *pLoop; /* The where loop */
2486ae49e67Sdrh StrAccum str; /* EQP output string */
2496ae49e67Sdrh char zBuf[100]; /* Initial space for EQP output string */
2506ae49e67Sdrh
2516ae49e67Sdrh sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
2526ae49e67Sdrh str.printfFlags = SQLITE_PRINTF_INTERNAL;
2536ae49e67Sdrh sqlite3_str_appendf(&str, "BLOOM FILTER ON %S (", pItem);
2546ae49e67Sdrh pLoop = pLevel->pWLoop;
2553bd7cd73Sdrh if( pLoop->wsFlags & WHERE_IPK ){
2563bd7cd73Sdrh const Table *pTab = pItem->pTab;
2573bd7cd73Sdrh if( pTab->iPKey>=0 ){
2583bd7cd73Sdrh sqlite3_str_appendf(&str, "%s=?", pTab->aCol[pTab->iPKey].zCnName);
2593bd7cd73Sdrh }else{
2603bd7cd73Sdrh sqlite3_str_appendf(&str, "rowid=?");
2613bd7cd73Sdrh }
2623bd7cd73Sdrh }else{
2636ae49e67Sdrh for(i=pLoop->nSkip; i<pLoop->u.btree.nEq; i++){
2643bd7cd73Sdrh const char *z = explainIndexColumnName(pLoop->u.btree.pIndex, i);
2656ae49e67Sdrh if( i>pLoop->nSkip ) sqlite3_str_append(&str, " AND ", 5);
2666ae49e67Sdrh sqlite3_str_appendf(&str, "%s=?", z);
2676ae49e67Sdrh }
2683bd7cd73Sdrh }
2696ae49e67Sdrh sqlite3_str_append(&str, ")", 1);
2706ae49e67Sdrh zMsg = sqlite3StrAccumFinish(&str);
2716ae49e67Sdrh ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
2726ae49e67Sdrh pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
2736ae49e67Sdrh return ret;
2746ae49e67Sdrh }
2756f82e85aSdrh #endif /* SQLITE_OMIT_EXPLAIN */
2766f82e85aSdrh
2776f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2786f82e85aSdrh /*
2796f82e85aSdrh ** Configure the VM passed as the first argument with an
2806f82e85aSdrh ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
2816f82e85aSdrh ** implement level pLvl. Argument pSrclist is a pointer to the FROM
2826f82e85aSdrh ** clause that the scan reads data from.
2836f82e85aSdrh **
2846f82e85aSdrh ** If argument addrExplain is not 0, it must be the address of an
2856f82e85aSdrh ** OP_Explain instruction that describes the same loop.
2866f82e85aSdrh */
sqlite3WhereAddScanStatus(Vdbe * v,SrcList * pSrclist,WhereLevel * pLvl,int addrExplain)2876f82e85aSdrh void sqlite3WhereAddScanStatus(
2886f82e85aSdrh Vdbe *v, /* Vdbe to add scanstatus entry to */
2896f82e85aSdrh SrcList *pSrclist, /* FROM clause pLvl reads data from */
2906f82e85aSdrh WhereLevel *pLvl, /* Level to add scanstatus() entry for */
2916f82e85aSdrh int addrExplain /* Address of OP_Explain (or 0) */
2926f82e85aSdrh ){
2936f82e85aSdrh const char *zObj = 0;
2946f82e85aSdrh WhereLoop *pLoop = pLvl->pWLoop;
2956f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
2966f82e85aSdrh zObj = pLoop->u.btree.pIndex->zName;
2976f82e85aSdrh }else{
2986f82e85aSdrh zObj = pSrclist->a[pLvl->iFrom].zName;
2996f82e85aSdrh }
3006f82e85aSdrh sqlite3VdbeScanStatus(
3016f82e85aSdrh v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
3026f82e85aSdrh );
3036f82e85aSdrh }
3046f82e85aSdrh #endif
3056f82e85aSdrh
3066f82e85aSdrh
3076f82e85aSdrh /*
3086f82e85aSdrh ** Disable a term in the WHERE clause. Except, do not disable the term
3096f82e85aSdrh ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
3106f82e85aSdrh ** or USING clause of that join.
3116f82e85aSdrh **
3126f82e85aSdrh ** Consider the term t2.z='ok' in the following queries:
3136f82e85aSdrh **
3146f82e85aSdrh ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
3156f82e85aSdrh ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
3166f82e85aSdrh ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
3176f82e85aSdrh **
3186f82e85aSdrh ** The t2.z='ok' is disabled in the in (2) because it originates
3196f82e85aSdrh ** in the ON clause. The term is disabled in (3) because it is not part
3206f82e85aSdrh ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
3216f82e85aSdrh **
3226f82e85aSdrh ** Disabling a term causes that term to not be tested in the inner loop
3236f82e85aSdrh ** of the join. Disabling is an optimization. When terms are satisfied
3246f82e85aSdrh ** by indices, we disable them to prevent redundant tests in the inner
3256f82e85aSdrh ** loop. We would get the correct results if nothing were ever disabled,
3266f82e85aSdrh ** but joins might run a little slower. The trick is to disable as much
3276f82e85aSdrh ** as we can without disabling too much. If we disabled in (1), we'd get
3286f82e85aSdrh ** the wrong answer. See ticket #813.
3296f82e85aSdrh **
3306f82e85aSdrh ** If all the children of a term are disabled, then that term is also
3316f82e85aSdrh ** automatically disabled. In this way, terms get disabled if derived
3326f82e85aSdrh ** virtual terms are tested first. For example:
3336f82e85aSdrh **
3346f82e85aSdrh ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
3356f82e85aSdrh ** \___________/ \______/ \_____/
3366f82e85aSdrh ** parent child1 child2
3376f82e85aSdrh **
3386f82e85aSdrh ** Only the parent term was in the original WHERE clause. The child1
3396f82e85aSdrh ** and child2 terms were added by the LIKE optimization. If both of
3406f82e85aSdrh ** the virtual child terms are valid, then testing of the parent can be
3416f82e85aSdrh ** skipped.
3426f82e85aSdrh **
3436f82e85aSdrh ** Usually the parent term is marked as TERM_CODED. But if the parent
3446f82e85aSdrh ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
3456f82e85aSdrh ** The TERM_LIKECOND marking indicates that the term should be coded inside
3466f82e85aSdrh ** a conditional such that is only evaluated on the second pass of a
3476f82e85aSdrh ** LIKE-optimization loop, when scanning BLOBs instead of strings.
3486f82e85aSdrh */
disableTerm(WhereLevel * pLevel,WhereTerm * pTerm)3496f82e85aSdrh static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
3506f82e85aSdrh int nLoop = 0;
3519d9c41e2Sdrh assert( pTerm!=0 );
3529d9c41e2Sdrh while( (pTerm->wtFlags & TERM_CODED)==0
35367a99dbeSdrh && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_OuterON))
3546f82e85aSdrh && (pLevel->notReady & pTerm->prereqAll)==0
3556f82e85aSdrh ){
3566f82e85aSdrh if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
3576f82e85aSdrh pTerm->wtFlags |= TERM_LIKECOND;
3586f82e85aSdrh }else{
3596f82e85aSdrh pTerm->wtFlags |= TERM_CODED;
3606f82e85aSdrh }
36123634898Sdrh #ifdef WHERETRACE_ENABLED
36223634898Sdrh if( sqlite3WhereTrace & 0x20000 ){
36323634898Sdrh sqlite3DebugPrintf("DISABLE-");
36423634898Sdrh sqlite3WhereTermPrint(pTerm, (int)(pTerm - (pTerm->pWC->a)));
36523634898Sdrh }
36623634898Sdrh #endif
3676f82e85aSdrh if( pTerm->iParent<0 ) break;
3686f82e85aSdrh pTerm = &pTerm->pWC->a[pTerm->iParent];
3699d9c41e2Sdrh assert( pTerm!=0 );
3706f82e85aSdrh pTerm->nChild--;
3716f82e85aSdrh if( pTerm->nChild!=0 ) break;
3726f82e85aSdrh nLoop++;
3736f82e85aSdrh }
3746f82e85aSdrh }
3756f82e85aSdrh
3766f82e85aSdrh /*
3776f82e85aSdrh ** Code an OP_Affinity opcode to apply the column affinity string zAff
3786f82e85aSdrh ** to the n registers starting at base.
3796f82e85aSdrh **
38096fb16eeSdrh ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
38196fb16eeSdrh ** are no-ops) at the beginning and end of zAff are ignored. If all entries
38296fb16eeSdrh ** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.
3836f82e85aSdrh **
3846f82e85aSdrh ** This routine makes its own copy of zAff so that the caller is free
3856f82e85aSdrh ** to modify zAff after this routine returns.
3866f82e85aSdrh */
codeApplyAffinity(Parse * pParse,int base,int n,char * zAff)3876f82e85aSdrh static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
3886f82e85aSdrh Vdbe *v = pParse->pVdbe;
3896f82e85aSdrh if( zAff==0 ){
3906f82e85aSdrh assert( pParse->db->mallocFailed );
3916f82e85aSdrh return;
3926f82e85aSdrh }
3936f82e85aSdrh assert( v!=0 );
3946f82e85aSdrh
39596fb16eeSdrh /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE
39696fb16eeSdrh ** entries at the beginning and end of the affinity string.
3976f82e85aSdrh */
39896fb16eeSdrh assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );
39996fb16eeSdrh while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){
4006f82e85aSdrh n--;
4016f82e85aSdrh base++;
4026f82e85aSdrh zAff++;
4036f82e85aSdrh }
40496fb16eeSdrh while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){
4056f82e85aSdrh n--;
4066f82e85aSdrh }
4076f82e85aSdrh
4086f82e85aSdrh /* Code the OP_Affinity opcode if there is anything left to do. */
4096f82e85aSdrh if( n>0 ){
4109b34abeeSdrh sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
4116f82e85aSdrh }
4126f82e85aSdrh }
4136f82e85aSdrh
414b7ca2177Sdan /*
415b7ca2177Sdan ** Expression pRight, which is the RHS of a comparison operation, is
416b7ca2177Sdan ** either a vector of n elements or, if n==1, a scalar expression.
417b7ca2177Sdan ** Before the comparison operation, affinity zAff is to be applied
418b7ca2177Sdan ** to the pRight values. This function modifies characters within the
419b7ca2177Sdan ** affinity string to SQLITE_AFF_BLOB if either:
420b7ca2177Sdan **
421b7ca2177Sdan ** * the comparison will be performed with no affinity, or
422b7ca2177Sdan ** * the affinity change in zAff is guaranteed not to change the value.
423b7ca2177Sdan */
updateRangeAffinityStr(Expr * pRight,int n,char * zAff)424b7ca2177Sdan static void updateRangeAffinityStr(
425b7ca2177Sdan Expr *pRight, /* RHS of comparison */
426b7ca2177Sdan int n, /* Number of vector elements in comparison */
427b7ca2177Sdan char *zAff /* Affinity string to modify */
428b7ca2177Sdan ){
429b7ca2177Sdan int i;
430b7ca2177Sdan for(i=0; i<n; i++){
431b7ca2177Sdan Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
432b7ca2177Sdan if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
433b7ca2177Sdan || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
434b7ca2177Sdan ){
435b7ca2177Sdan zAff[i] = SQLITE_AFF_BLOB;
436b7ca2177Sdan }
437b7ca2177Sdan }
438b7ca2177Sdan }
4396f82e85aSdrh
4402410243eSdrh
4412410243eSdrh /*
4422410243eSdrh ** pX is an expression of the form: (vector) IN (SELECT ...)
4432410243eSdrh ** In other words, it is a vector IN operator with a SELECT clause on the
4442410243eSdrh ** LHS. But not all terms in the vector are indexable and the terms might
4452410243eSdrh ** not be in the correct order for indexing.
4469b1ecb67Sdrh **
4472410243eSdrh ** This routine makes a copy of the input pX expression and then adjusts
4482410243eSdrh ** the vector on the LHS with corresponding changes to the SELECT so that
4492410243eSdrh ** the vector contains only index terms and those terms are in the correct
4502410243eSdrh ** order. The modified IN expression is returned. The caller is responsible
4512410243eSdrh ** for deleting the returned expression.
4522410243eSdrh **
4532410243eSdrh ** Example:
4542410243eSdrh **
4552410243eSdrh ** CREATE TABLE t1(a,b,c,d,e,f);
4562410243eSdrh ** CREATE INDEX t1x1 ON t1(e,c);
4572410243eSdrh ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
4582410243eSdrh ** \_______________________________________/
4592410243eSdrh ** The pX expression
4602410243eSdrh **
4612410243eSdrh ** Since only columns e and c can be used with the index, in that order,
4622410243eSdrh ** the modified IN expression that is returned will be:
4632410243eSdrh **
4642410243eSdrh ** (e,c) IN (SELECT z,x FROM t2)
4652410243eSdrh **
4662410243eSdrh ** The reduced pX is different from the original (obviously) and thus is
4672410243eSdrh ** only used for indexing, to improve performance. The original unaltered
4682410243eSdrh ** IN expression must also be run on each output row for correctness.
4699b1ecb67Sdrh */
removeUnindexableInClauseTerms(Parse * pParse,int iEq,WhereLoop * pLoop,Expr * pX)4702410243eSdrh static Expr *removeUnindexableInClauseTerms(
4712410243eSdrh Parse *pParse, /* The parsing context */
4722410243eSdrh int iEq, /* Look at loop terms starting here */
4732410243eSdrh WhereLoop *pLoop, /* The current loop */
4742410243eSdrh Expr *pX /* The IN expression to be reduced */
4752410243eSdrh ){
4762410243eSdrh sqlite3 *db = pParse->db;
47769843342Sdan Expr *pNew;
47869843342Sdan pNew = sqlite3ExprDup(db, pX, 0);
4792410243eSdrh if( db->mallocFailed==0 ){
480a4eeccdfSdrh ExprList *pOrigRhs; /* Original unmodified RHS */
481a4eeccdfSdrh ExprList *pOrigLhs; /* Original unmodified LHS */
4822410243eSdrh ExprList *pRhs = 0; /* New RHS after modifications */
4832410243eSdrh ExprList *pLhs = 0; /* New LHS after mods */
4842410243eSdrh int i; /* Loop counter */
4852410243eSdrh Select *pSelect; /* Pointer to the SELECT on the RHS */
4862410243eSdrh
487a4eeccdfSdrh assert( ExprUseXSelect(pNew) );
488a4eeccdfSdrh pOrigRhs = pNew->x.pSelect->pEList;
489a4eeccdfSdrh assert( pNew->pLeft!=0 );
490a4eeccdfSdrh assert( ExprUseXList(pNew->pLeft) );
491a4eeccdfSdrh pOrigLhs = pNew->pLeft->x.pList;
4922410243eSdrh for(i=iEq; i<pLoop->nLTerm; i++){
4932410243eSdrh if( pLoop->aLTerm[i]->pExpr==pX ){
494220f0d6fSdrh int iField;
495220f0d6fSdrh assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
496220f0d6fSdrh iField = pLoop->aLTerm[i]->u.x.iField - 1;
497c6e519f3Sdrh if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
4982410243eSdrh pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
4992410243eSdrh pOrigRhs->a[iField].pExpr = 0;
5002410243eSdrh assert( pOrigLhs->a[iField].pExpr!=0 );
5012410243eSdrh pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
5022410243eSdrh pOrigLhs->a[iField].pExpr = 0;
5039b1ecb67Sdrh }
5049b1ecb67Sdrh }
5052410243eSdrh sqlite3ExprListDelete(db, pOrigRhs);
5062410243eSdrh sqlite3ExprListDelete(db, pOrigLhs);
5072410243eSdrh pNew->pLeft->x.pList = pLhs;
5082410243eSdrh pNew->x.pSelect->pEList = pRhs;
5092410243eSdrh if( pLhs && pLhs->nExpr==1 ){
5102410243eSdrh /* Take care here not to generate a TK_VECTOR containing only a
5112410243eSdrh ** single value. Since the parser never creates such a vector, some
5122410243eSdrh ** of the subroutines do not handle this case. */
5132410243eSdrh Expr *p = pLhs->a[0].pExpr;
5142410243eSdrh pLhs->a[0].pExpr = 0;
5152410243eSdrh sqlite3ExprDelete(db, pNew->pLeft);
5162410243eSdrh pNew->pLeft = p;
5179b1ecb67Sdrh }
5182410243eSdrh pSelect = pNew->x.pSelect;
5192410243eSdrh if( pSelect->pOrderBy ){
5202410243eSdrh /* If the SELECT statement has an ORDER BY clause, zero the
5212410243eSdrh ** iOrderByCol variables. These are set to non-zero when an
5222410243eSdrh ** ORDER BY term exactly matches one of the terms of the
5232410243eSdrh ** result-set. Since the result-set of the SELECT statement may
5242410243eSdrh ** have been modified or reordered, these variables are no longer
5252410243eSdrh ** set correctly. Since setting them is just an optimization,
5262410243eSdrh ** it's easiest just to zero them here. */
5272410243eSdrh ExprList *pOrderBy = pSelect->pOrderBy;
5282410243eSdrh for(i=0; i<pOrderBy->nExpr; i++){
5292410243eSdrh pOrderBy->a[i].u.x.iOrderByCol = 0;
5302410243eSdrh }
5312410243eSdrh }
5322410243eSdrh
5332410243eSdrh #if 0
5342410243eSdrh printf("For indexing, change the IN expr:\n");
5352410243eSdrh sqlite3TreeViewExpr(0, pX, 0);
5362410243eSdrh printf("Into:\n");
5372410243eSdrh sqlite3TreeViewExpr(0, pNew, 0);
5382410243eSdrh #endif
5392410243eSdrh }
5402410243eSdrh return pNew;
5412410243eSdrh }
5429b1ecb67Sdrh
5439b1ecb67Sdrh
5446f82e85aSdrh /*
5456f82e85aSdrh ** Generate code for a single equality term of the WHERE clause. An equality
5466f82e85aSdrh ** term can be either X=expr or X IN (...). pTerm is the term to be
5476f82e85aSdrh ** coded.
5486f82e85aSdrh **
549099a0f5fSdrh ** The current value for the constraint is left in a register, the index
550099a0f5fSdrh ** of which is returned. An attempt is made store the result in iTarget but
551099a0f5fSdrh ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
552099a0f5fSdrh ** constraint is a TK_EQ or TK_IS, then the current value might be left in
553099a0f5fSdrh ** some other register and it is the caller's responsibility to compensate.
5546f82e85aSdrh **
5554602b8e8Sdrh ** For a constraint of the form X=expr, the expression is evaluated in
5564602b8e8Sdrh ** straight-line code. For constraints of the form X IN (...)
5576f82e85aSdrh ** this routine sets up a loop that will iterate over all values of X.
5586f82e85aSdrh */
codeEqualityTerm(Parse * pParse,WhereTerm * pTerm,WhereLevel * pLevel,int iEq,int bRev,int iTarget)5596f82e85aSdrh static int codeEqualityTerm(
5606f82e85aSdrh Parse *pParse, /* The parsing context */
5616f82e85aSdrh WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
5626f82e85aSdrh WhereLevel *pLevel, /* The level of the FROM clause we are working on */
5636f82e85aSdrh int iEq, /* Index of the equality term within this level */
5646f82e85aSdrh int bRev, /* True for reverse-order IN operations */
5656f82e85aSdrh int iTarget /* Attempt to leave results in this register */
5666f82e85aSdrh ){
5676f82e85aSdrh Expr *pX = pTerm->pExpr;
5686f82e85aSdrh Vdbe *v = pParse->pVdbe;
5696f82e85aSdrh int iReg; /* Register holding results */
5706f82e85aSdrh
5718da209b1Sdan assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
5726f82e85aSdrh assert( iTarget>0 );
5736f82e85aSdrh if( pX->op==TK_EQ || pX->op==TK_IS ){
574fc7f27b9Sdrh iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
5756f82e85aSdrh }else if( pX->op==TK_ISNULL ){
5766f82e85aSdrh iReg = iTarget;
5776f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
5786f82e85aSdrh #ifndef SQLITE_OMIT_SUBQUERY
5796f82e85aSdrh }else{
580ac6b47d1Sdrh int eType = IN_INDEX_NOOP;
5816f82e85aSdrh int iTab;
5826f82e85aSdrh struct InLoop *pIn;
5836f82e85aSdrh WhereLoop *pLoop = pLevel->pWLoop;
5848da209b1Sdan int i;
5858da209b1Sdan int nEq = 0;
5868da209b1Sdan int *aiMap = 0;
5876f82e85aSdrh
5886f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
5896f82e85aSdrh && pLoop->u.btree.pIndex!=0
5906f82e85aSdrh && pLoop->u.btree.pIndex->aSortOrder[iEq]
5916f82e85aSdrh ){
5926f82e85aSdrh testcase( iEq==0 );
5936f82e85aSdrh testcase( bRev );
5946f82e85aSdrh bRev = !bRev;
5956f82e85aSdrh }
5966f82e85aSdrh assert( pX->op==TK_IN );
5976f82e85aSdrh iReg = iTarget;
5988da209b1Sdan
5998da209b1Sdan for(i=0; i<iEq; i++){
6008da209b1Sdan if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
6018da209b1Sdan disableTerm(pLevel, pTerm);
6028da209b1Sdan return iTarget;
6038da209b1Sdan }
6048da209b1Sdan }
6058da209b1Sdan for(i=iEq;i<pLoop->nLTerm; i++){
6062410243eSdrh assert( pLoop->aLTerm[i]!=0 );
6072410243eSdrh if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
6088da209b1Sdan }
6098da209b1Sdan
6102c04131cSdrh iTab = 0;
611a4eeccdfSdrh if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
6122c04131cSdrh eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
613a25bbaf7Sdrh }else{
614a25bbaf7Sdrh Expr *pExpr = pTerm->pExpr;
615a25bbaf7Sdrh if( pExpr->iTable==0 || !ExprHasProperty(pExpr, EP_Subrtn) ){
6168da209b1Sdan sqlite3 *db = pParse->db;
6172410243eSdrh pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
618ac6b47d1Sdrh if( !db->mallocFailed ){
619c7a77ae1Sdrh aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
6202c04131cSdrh eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap,&iTab);
621a25bbaf7Sdrh pExpr->iTable = iTab;
622ac6b47d1Sdrh }
6232410243eSdrh sqlite3ExprDelete(db, pX);
624a25bbaf7Sdrh }else{
6253a17e2e5Sdrh int n = sqlite3ExprVectorSize(pX->pLeft);
6263a17e2e5Sdrh aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*MAX(nEq,n));
627f69dad8cSdrh eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
628a25bbaf7Sdrh }
629a25bbaf7Sdrh pX = pExpr;
6308da209b1Sdan }
6318da209b1Sdan
6326f82e85aSdrh if( eType==IN_INDEX_INDEX_DESC ){
6336f82e85aSdrh testcase( bRev );
6346f82e85aSdrh bRev = !bRev;
6356f82e85aSdrh }
6366f82e85aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
6376f82e85aSdrh VdbeCoverageIf(v, bRev);
6386f82e85aSdrh VdbeCoverageIf(v, !bRev);
6398da209b1Sdan
6400475629dSdrh assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
6416f82e85aSdrh pLoop->wsFlags |= WHERE_IN_ABLE;
6426f82e85aSdrh if( pLevel->u.in.nIn==0 ){
643ec4ccdbcSdrh pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
6446f82e85aSdrh }
64546f0f4e5Sdrh if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
646fa17e134Sdrh pLoop->wsFlags |= WHERE_IN_EARLYOUT;
647fa17e134Sdrh }
6488da209b1Sdan
6498da209b1Sdan i = pLevel->u.in.nIn;
6508da209b1Sdan pLevel->u.in.nIn += nEq;
6516f82e85aSdrh pLevel->u.in.aInLoop =
652f8bdcfa3Sdrh sqlite3WhereRealloc(pTerm->pWC->pWInfo,
653f8bdcfa3Sdrh pLevel->u.in.aInLoop,
6546f82e85aSdrh sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
6556f82e85aSdrh pIn = pLevel->u.in.aInLoop;
6566f82e85aSdrh if( pIn ){
6578da209b1Sdan int iMap = 0; /* Index in aiMap[] */
6588da209b1Sdan pIn += i;
6597887d7f2Sdan for(i=iEq;i<pLoop->nLTerm; i++){
6608da209b1Sdan if( pLoop->aLTerm[i]->pExpr==pX ){
661edc3537cSdan int iOut = iReg + i - iEq;
6626f82e85aSdrh if( eType==IN_INDEX_ROWID ){
663edc3537cSdan pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
6646f82e85aSdrh }else{
6658da209b1Sdan int iCol = aiMap ? aiMap[iMap++] : 0;
6668da209b1Sdan pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
6676f82e85aSdrh }
66803181c8cSdrh sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
6698da209b1Sdan if( i==iEq ){
6708da209b1Sdan pIn->iCur = iTab;
671f1949b66Sdrh pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
67274ebaadcSdan if( iEq>0 ){
673a0368d93Sdrh pIn->iBase = iReg - i;
674a0368d93Sdrh pIn->nPrefix = i;
6758da209b1Sdan }else{
67686d0ea75Sdrh pIn->nPrefix = 0;
67786d0ea75Sdrh }
67886d0ea75Sdrh }else{
6798da209b1Sdan pIn->eEndLoopOp = OP_Noop;
6808da209b1Sdan }
6817887d7f2Sdan pIn++;
6828da209b1Sdan }
6838da209b1Sdan }
68467306cb3Sdrh testcase( iEq>0
68567306cb3Sdrh && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
68667306cb3Sdrh && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
68767306cb3Sdrh if( iEq>0
68867306cb3Sdrh && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
68967306cb3Sdrh ){
690fa17e134Sdrh sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
691fa17e134Sdrh }
6926f82e85aSdrh }else{
6936f82e85aSdrh pLevel->u.in.nIn = 0;
6946f82e85aSdrh }
6958da209b1Sdan sqlite3DbFree(pParse->db, aiMap);
6966f82e85aSdrh #endif
6976f82e85aSdrh }
69867656ac7Sdrh
69967656ac7Sdrh /* As an optimization, try to disable the WHERE clause term that is
70067656ac7Sdrh ** driving the index as it will always be true. The correct answer is
70167656ac7Sdrh ** obtained regardless, but we might get the answer with fewer CPU cycles
70267656ac7Sdrh ** by omitting the term.
70367656ac7Sdrh **
70467656ac7Sdrh ** But do not disable the term unless we are certain that the term is
70567656ac7Sdrh ** not a transitive constraint. For an example of where that does not
70667656ac7Sdrh ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
70767656ac7Sdrh */
70867656ac7Sdrh if( (pLevel->pWLoop->wsFlags & WHERE_TRANSCONS)==0
70967656ac7Sdrh || (pTerm->eOperator & WO_EQUIV)==0
71067656ac7Sdrh ){
7116f82e85aSdrh disableTerm(pLevel, pTerm);
71267656ac7Sdrh }
71367656ac7Sdrh
7146f82e85aSdrh return iReg;
7156f82e85aSdrh }
7166f82e85aSdrh
7176f82e85aSdrh /*
7186f82e85aSdrh ** Generate code that will evaluate all == and IN constraints for an
7196f82e85aSdrh ** index scan.
7206f82e85aSdrh **
7216f82e85aSdrh ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
7226f82e85aSdrh ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
7236f82e85aSdrh ** The index has as many as three equality constraints, but in this
7246f82e85aSdrh ** example, the third "c" value is an inequality. So only two
7256f82e85aSdrh ** constraints are coded. This routine will generate code to evaluate
7266f82e85aSdrh ** a==5 and b IN (1,2,3). The current values for a and b will be stored
7276f82e85aSdrh ** in consecutive registers and the index of the first register is returned.
7286f82e85aSdrh **
7296f82e85aSdrh ** In the example above nEq==2. But this subroutine works for any value
7306f82e85aSdrh ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
7316f82e85aSdrh ** The only thing it does is allocate the pLevel->iMem memory cell and
7326f82e85aSdrh ** compute the affinity string.
7336f82e85aSdrh **
7346f82e85aSdrh ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
7356f82e85aSdrh ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
7366f82e85aSdrh ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
7376f82e85aSdrh ** occurs after the nEq quality constraints.
7386f82e85aSdrh **
7396f82e85aSdrh ** This routine allocates a range of nEq+nExtraReg memory cells and returns
7406f82e85aSdrh ** the index of the first memory cell in that range. The code that
7416f82e85aSdrh ** calls this routine will use that memory range to store keys for
7426f82e85aSdrh ** start and termination conditions of the loop.
7436f82e85aSdrh ** key value of the loop. If one or more IN operators appear, then
7446f82e85aSdrh ** this routine allocates an additional nEq memory cells for internal
7456f82e85aSdrh ** use.
7466f82e85aSdrh **
7476f82e85aSdrh ** Before returning, *pzAff is set to point to a buffer containing a
7486f82e85aSdrh ** copy of the column affinity string of the index allocated using
7496f82e85aSdrh ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
7506f82e85aSdrh ** with equality constraints that use BLOB or NONE affinity are set to
7516f82e85aSdrh ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
7526f82e85aSdrh **
7536f82e85aSdrh ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
7546f82e85aSdrh ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
7556f82e85aSdrh **
7566f82e85aSdrh ** In the example above, the index on t1(a) has TEXT affinity. But since
7576f82e85aSdrh ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
7586f82e85aSdrh ** no conversion should be attempted before using a t2.b value as part of
7596f82e85aSdrh ** a key to search the index. Hence the first byte in the returned affinity
7606f82e85aSdrh ** string in this example would be set to SQLITE_AFF_BLOB.
7616f82e85aSdrh */
codeAllEqualityTerms(Parse * pParse,WhereLevel * pLevel,int bRev,int nExtraReg,char ** pzAff)7626f82e85aSdrh static int codeAllEqualityTerms(
7636f82e85aSdrh Parse *pParse, /* Parsing context */
7646f82e85aSdrh WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
7656f82e85aSdrh int bRev, /* Reverse the order of IN operators */
7666f82e85aSdrh int nExtraReg, /* Number of extra registers to allocate */
7676f82e85aSdrh char **pzAff /* OUT: Set to point to affinity string */
7686f82e85aSdrh ){
7696f82e85aSdrh u16 nEq; /* The number of == or IN constraints to code */
7706f82e85aSdrh u16 nSkip; /* Number of left-most columns to skip */
7716f82e85aSdrh Vdbe *v = pParse->pVdbe; /* The vm under construction */
7726f82e85aSdrh Index *pIdx; /* The index being used for this loop */
7736f82e85aSdrh WhereTerm *pTerm; /* A single constraint term */
7746f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object */
7756f82e85aSdrh int j; /* Loop counter */
7766f82e85aSdrh int regBase; /* Base register */
7776f82e85aSdrh int nReg; /* Number of registers to allocate */
7786f82e85aSdrh char *zAff; /* Affinity string to return */
7796f82e85aSdrh
7806f82e85aSdrh /* This module is only called on query plans that use an index. */
7816f82e85aSdrh pLoop = pLevel->pWLoop;
7826f82e85aSdrh assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
7836f82e85aSdrh nEq = pLoop->u.btree.nEq;
7846f82e85aSdrh nSkip = pLoop->nSkip;
7856f82e85aSdrh pIdx = pLoop->u.btree.pIndex;
7866f82e85aSdrh assert( pIdx!=0 );
7876f82e85aSdrh
7886f82e85aSdrh /* Figure out how many memory cells we will need then allocate them.
7896f82e85aSdrh */
7906f82e85aSdrh regBase = pParse->nMem + 1;
7916f82e85aSdrh nReg = pLoop->u.btree.nEq + nExtraReg;
7926f82e85aSdrh pParse->nMem += nReg;
7936f82e85aSdrh
794e9107698Sdrh zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
7954df86af3Sdrh assert( zAff!=0 || pParse->db->mallocFailed );
7966f82e85aSdrh
7976f82e85aSdrh if( nSkip ){
7986f82e85aSdrh int iIdxCur = pLevel->iIdxCur;
79931536304Sdrh sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1);
8006f82e85aSdrh sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
8016f82e85aSdrh VdbeCoverageIf(v, bRev==0);
8026f82e85aSdrh VdbeCoverageIf(v, bRev!=0);
8036f82e85aSdrh VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
8046f82e85aSdrh j = sqlite3VdbeAddOp0(v, OP_Goto);
80556945695Sdrh assert( pLevel->addrSkip==0 );
8066f82e85aSdrh pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
8076f82e85aSdrh iIdxCur, 0, regBase, nSkip);
8086f82e85aSdrh VdbeCoverageIf(v, bRev==0);
8096f82e85aSdrh VdbeCoverageIf(v, bRev!=0);
8106f82e85aSdrh sqlite3VdbeJumpHere(v, j);
8116f82e85aSdrh for(j=0; j<nSkip; j++){
8126f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
8134b92f98cSdrh testcase( pIdx->aiColumn[j]==XN_EXPR );
814e63e8a6cSdrh VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
8156f82e85aSdrh }
8166f82e85aSdrh }
8176f82e85aSdrh
8186f82e85aSdrh /* Evaluate the equality constraints
8196f82e85aSdrh */
8206f82e85aSdrh assert( zAff==0 || (int)strlen(zAff)>=nEq );
8216f82e85aSdrh for(j=nSkip; j<nEq; j++){
8226f82e85aSdrh int r1;
8236f82e85aSdrh pTerm = pLoop->aLTerm[j];
8246f82e85aSdrh assert( pTerm!=0 );
8256f82e85aSdrh /* The following testcase is true for indices with redundant columns.
8266f82e85aSdrh ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
8276f82e85aSdrh testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
8286f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL );
8296f82e85aSdrh r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
8306f82e85aSdrh if( r1!=regBase+j ){
8316f82e85aSdrh if( nReg==1 ){
8326f82e85aSdrh sqlite3ReleaseTempReg(pParse, regBase);
8336f82e85aSdrh regBase = r1;
8346f82e85aSdrh }else{
835e9de6520Sdrh sqlite3VdbeAddOp2(v, OP_Copy, r1, regBase+j);
8366f82e85aSdrh }
8376f82e85aSdrh }
838e482fde6Sdrh }
839e482fde6Sdrh for(j=nSkip; j<nEq; j++){
840e482fde6Sdrh pTerm = pLoop->aLTerm[j];
84127189603Sdan if( pTerm->eOperator & WO_IN ){
84227189603Sdan if( pTerm->pExpr->flags & EP_xIsSelect ){
8431c12657fSdan /* No affinity ever needs to be (or should be) applied to a value
8441c12657fSdan ** from the RHS of an "? IN (SELECT ...)" expression. The
8451c12657fSdan ** sqlite3FindInIndex() routine has already ensured that the
8461c12657fSdan ** affinity of the comparison has been applied to the value. */
847aaf8a064Sdrh if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
84827189603Sdan }
849c097e122Sdrh }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
8501c12657fSdan Expr *pRight = pTerm->pExpr->pRight;
8516f82e85aSdrh if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
8526f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
8536f82e85aSdrh VdbeCoverage(v);
8546f82e85aSdrh }
8550c7d3d39Sdrh if( pParse->nErr==0 ){
8560c7d3d39Sdrh assert( pParse->db->mallocFailed==0 );
8576f82e85aSdrh if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
8586f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB;
8596f82e85aSdrh }
8606f82e85aSdrh if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
8616f82e85aSdrh zAff[j] = SQLITE_AFF_BLOB;
8626f82e85aSdrh }
8636f82e85aSdrh }
8646f82e85aSdrh }
8656f82e85aSdrh }
8666f82e85aSdrh *pzAff = zAff;
8676f82e85aSdrh return regBase;
8686f82e85aSdrh }
8696f82e85aSdrh
87041d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
8716f82e85aSdrh /*
87244aebff2Sdrh ** If the most recently coded instruction is a constant range constraint
87344aebff2Sdrh ** (a string literal) that originated from the LIKE optimization, then
87444aebff2Sdrh ** set P3 and P5 on the OP_String opcode so that the string will be cast
87544aebff2Sdrh ** to a BLOB at appropriate times.
8766f82e85aSdrh **
8776f82e85aSdrh ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
8786f82e85aSdrh ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
8796f82e85aSdrh ** scan loop run twice, once for strings and a second time for BLOBs.
8806f82e85aSdrh ** The OP_String opcodes on the second pass convert the upper and lower
881e234cfd1Smistachkin ** bound string constants to blobs. This routine makes the necessary changes
8826f82e85aSdrh ** to the OP_String opcodes for that to happen.
88341d2e66eSdrh **
88441d2e66eSdrh ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
88541d2e66eSdrh ** only the one pass through the string space is required, so this routine
88641d2e66eSdrh ** becomes a no-op.
8876f82e85aSdrh */
whereLikeOptimizationStringFixup(Vdbe * v,WhereLevel * pLevel,WhereTerm * pTerm)8886f82e85aSdrh static void whereLikeOptimizationStringFixup(
8896f82e85aSdrh Vdbe *v, /* prepared statement under construction */
8906f82e85aSdrh WhereLevel *pLevel, /* The loop that contains the LIKE operator */
8916f82e85aSdrh WhereTerm *pTerm /* The upper or lower bound just coded */
8926f82e85aSdrh ){
8936f82e85aSdrh if( pTerm->wtFlags & TERM_LIKEOPT ){
8946f82e85aSdrh VdbeOp *pOp;
8956f82e85aSdrh assert( pLevel->iLikeRepCntr>0 );
896058e9950Sdrh pOp = sqlite3VdbeGetLastOp(v);
8976f82e85aSdrh assert( pOp!=0 );
8986f82e85aSdrh assert( pOp->opcode==OP_String8
8996f82e85aSdrh || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
90044aebff2Sdrh pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
90144aebff2Sdrh pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
9026f82e85aSdrh }
9036f82e85aSdrh }
90441d2e66eSdrh #else
90541d2e66eSdrh # define whereLikeOptimizationStringFixup(A,B,C)
90641d2e66eSdrh #endif
9076f82e85aSdrh
908bec2476aSdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
9092f2b0278Sdrh /*
9102f2b0278Sdrh ** Information is passed from codeCursorHint() down to individual nodes of
9112f2b0278Sdrh ** the expression tree (by sqlite3WalkExpr()) using an instance of this
9122f2b0278Sdrh ** structure.
9132f2b0278Sdrh */
9142f2b0278Sdrh struct CCurHint {
9152f2b0278Sdrh int iTabCur; /* Cursor for the main table */
9162f2b0278Sdrh int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
9172f2b0278Sdrh Index *pIdx; /* The index used to access the table */
9182f2b0278Sdrh };
9192f2b0278Sdrh
9202f2b0278Sdrh /*
9212f2b0278Sdrh ** This function is called for every node of an expression that is a candidate
9222f2b0278Sdrh ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
9232f2b0278Sdrh ** the table CCurHint.iTabCur, verify that the same column can be
9242f2b0278Sdrh ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
9252f2b0278Sdrh */
codeCursorHintCheckExpr(Walker * pWalker,Expr * pExpr)9262f2b0278Sdrh static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
9272f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint;
9282f2b0278Sdrh assert( pHint->pIdx!=0 );
9292f2b0278Sdrh if( pExpr->op==TK_COLUMN
9302f2b0278Sdrh && pExpr->iTable==pHint->iTabCur
931b9bcf7caSdrh && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
9322f2b0278Sdrh ){
9332f2b0278Sdrh pWalker->eCode = 1;
9342f2b0278Sdrh }
9352f2b0278Sdrh return WRC_Continue;
9362f2b0278Sdrh }
9372f2b0278Sdrh
938e6912fd8Sdan /*
939e6912fd8Sdan ** Test whether or not expression pExpr, which was part of a WHERE clause,
940e6912fd8Sdan ** should be included in the cursor-hint for a table that is on the rhs
941e6912fd8Sdan ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
942e6912fd8Sdan ** expression is not suitable.
943e6912fd8Sdan **
944e6912fd8Sdan ** An expression is unsuitable if it might evaluate to non NULL even if
945e6912fd8Sdan ** a TK_COLUMN node that does affect the value of the expression is set
946e6912fd8Sdan ** to NULL. For example:
947e6912fd8Sdan **
948e6912fd8Sdan ** col IS NULL
949e6912fd8Sdan ** col IS NOT NULL
950e6912fd8Sdan ** coalesce(col, 1)
951e6912fd8Sdan ** CASE WHEN col THEN 0 ELSE 1 END
952e6912fd8Sdan */
codeCursorHintIsOrFunction(Walker * pWalker,Expr * pExpr)953e6912fd8Sdan static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
9542b693d63Sdan if( pExpr->op==TK_IS
955e6912fd8Sdan || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
956e6912fd8Sdan || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
957e6912fd8Sdan ){
958e6912fd8Sdan pWalker->eCode = 1;
9592b693d63Sdan }else if( pExpr->op==TK_FUNCTION ){
9602b693d63Sdan int d1;
9611d42ea71Sdrh char d2[4];
9622b693d63Sdan if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
9632b693d63Sdan pWalker->eCode = 1;
964e6912fd8Sdan }
9652b693d63Sdan }
9662b693d63Sdan
967e6912fd8Sdan return WRC_Continue;
968e6912fd8Sdan }
969e6912fd8Sdan
970bec2476aSdrh
971bec2476aSdrh /*
972bec2476aSdrh ** This function is called on every node of an expression tree used as an
973bec2476aSdrh ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
9742f2b0278Sdrh ** that accesses any table other than the one identified by
9752f2b0278Sdrh ** CCurHint.iTabCur, then do the following:
976bec2476aSdrh **
977bec2476aSdrh ** 1) allocate a register and code an OP_Column instruction to read
978bec2476aSdrh ** the specified column into the new register, and
979bec2476aSdrh **
980bec2476aSdrh ** 2) transform the expression node to a TK_REGISTER node that reads
981bec2476aSdrh ** from the newly populated register.
9822f2b0278Sdrh **
9832f2b0278Sdrh ** Also, if the node is a TK_COLUMN that does access the table idenified
9842f2b0278Sdrh ** by pCCurHint.iTabCur, and an index is being used (which we will
9852f2b0278Sdrh ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
9862f2b0278Sdrh ** an access of the index rather than the original table.
987bec2476aSdrh */
codeCursorHintFixExpr(Walker * pWalker,Expr * pExpr)988bec2476aSdrh static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
989bec2476aSdrh int rc = WRC_Continue;
9902f2b0278Sdrh struct CCurHint *pHint = pWalker->u.pCCurHint;
991be312ae9Sdan if( pExpr->op==TK_COLUMN ){
9922f2b0278Sdrh if( pExpr->iTable!=pHint->iTabCur ){
993bec2476aSdrh int reg = ++pWalker->pParse->nMem; /* Register for column value */
994e3e79213Sdan sqlite3ExprCode(pWalker->pParse, pExpr, reg);
995bec2476aSdrh pExpr->op = TK_REGISTER;
996bec2476aSdrh pExpr->iTable = reg;
9972f2b0278Sdrh }else if( pHint->pIdx!=0 ){
9982f2b0278Sdrh pExpr->iTable = pHint->iIdxCur;
999b9bcf7caSdrh pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
10002f2b0278Sdrh assert( pExpr->iColumn>=0 );
10012f2b0278Sdrh }
1002bec2476aSdrh }else if( pExpr->op==TK_AGG_FUNCTION ){
1003bec2476aSdrh /* An aggregate function in the WHERE clause of a query means this must
1004bec2476aSdrh ** be a correlated sub-query, and expression pExpr is an aggregate from
1005bec2476aSdrh ** the parent context. Do not walk the function arguments in this case.
1006bec2476aSdrh **
1007bec2476aSdrh ** todo: It should be possible to replace this node with a TK_REGISTER
1008bec2476aSdrh ** expression, as the result of the expression must be stored in a
1009bec2476aSdrh ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
1010bec2476aSdrh rc = WRC_Prune;
1011bec2476aSdrh }
1012bec2476aSdrh return rc;
1013bec2476aSdrh }
1014bec2476aSdrh
1015bec2476aSdrh /*
1016bec2476aSdrh ** Insert an OP_CursorHint instruction if it is appropriate to do so.
1017bec2476aSdrh */
codeCursorHint(SrcItem * pTabItem,WhereInfo * pWInfo,WhereLevel * pLevel,WhereTerm * pEndRange)1018bec2476aSdrh static void codeCursorHint(
10197601294aSdrh SrcItem *pTabItem, /* FROM clause item */
1020b413a546Sdrh WhereInfo *pWInfo, /* The where clause */
1021b413a546Sdrh WhereLevel *pLevel, /* Which loop to provide hints for */
1022b413a546Sdrh WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
1023bec2476aSdrh ){
1024bec2476aSdrh Parse *pParse = pWInfo->pParse;
1025bec2476aSdrh sqlite3 *db = pParse->db;
1026bec2476aSdrh Vdbe *v = pParse->pVdbe;
1027bec2476aSdrh Expr *pExpr = 0;
10282f2b0278Sdrh WhereLoop *pLoop = pLevel->pWLoop;
1029bec2476aSdrh int iCur;
1030bec2476aSdrh WhereClause *pWC;
1031bec2476aSdrh WhereTerm *pTerm;
1032b413a546Sdrh int i, j;
10332f2b0278Sdrh struct CCurHint sHint;
10342f2b0278Sdrh Walker sWalker;
1035bec2476aSdrh
1036bec2476aSdrh if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
10372f2b0278Sdrh iCur = pLevel->iTabCur;
10382f2b0278Sdrh assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
10392f2b0278Sdrh sHint.iTabCur = iCur;
10402f2b0278Sdrh sHint.iIdxCur = pLevel->iIdxCur;
10412f2b0278Sdrh sHint.pIdx = pLoop->u.btree.pIndex;
10422f2b0278Sdrh memset(&sWalker, 0, sizeof(sWalker));
10432f2b0278Sdrh sWalker.pParse = pParse;
10442f2b0278Sdrh sWalker.u.pCCurHint = &sHint;
1045bec2476aSdrh pWC = &pWInfo->sWC;
1046132f96fcSdrh for(i=0; i<pWC->nBase; i++){
1047bec2476aSdrh pTerm = &pWC->a[i];
1048bec2476aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1049bec2476aSdrh if( pTerm->prereqAll & pLevel->notReady ) continue;
1050b324cf75Sdan
1051b324cf75Sdan /* Any terms specified as part of the ON(...) clause for any LEFT
1052b324cf75Sdan ** JOIN for which the current table is not the rhs are omitted
1053b324cf75Sdan ** from the cursor-hint.
1054b324cf75Sdan **
1055e6912fd8Sdan ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
1056e6912fd8Sdan ** that were specified as part of the WHERE clause must be excluded.
1057e6912fd8Sdan ** This is to address the following:
1058b324cf75Sdan **
1059b324cf75Sdan ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
1060b324cf75Sdan **
1061e6912fd8Sdan ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
1062e6912fd8Sdan ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
1063e6912fd8Sdan ** pushed down to the cursor, this row is filtered out, causing
1064e6912fd8Sdan ** SQLite to synthesize a row of NULL values. Which does match the
1065e6912fd8Sdan ** WHERE clause, and so the query returns a row. Which is incorrect.
1066e6912fd8Sdan **
1067e6912fd8Sdan ** For the same reason, WHERE terms such as:
1068e6912fd8Sdan **
1069e6912fd8Sdan ** WHERE 1 = (t2.c IS NULL)
1070e6912fd8Sdan **
1071e6912fd8Sdan ** are also excluded. See codeCursorHintIsOrFunction() for details.
1072b324cf75Sdan */
1073b324cf75Sdan if( pTabItem->fg.jointype & JT_LEFT ){
1074e6912fd8Sdan Expr *pExpr = pTerm->pExpr;
107567a99dbeSdrh if( !ExprHasProperty(pExpr, EP_OuterON)
1076d1985262Sdrh || pExpr->w.iJoin!=pTabItem->iCursor
1077b324cf75Sdan ){
1078e6912fd8Sdan sWalker.eCode = 0;
1079e6912fd8Sdan sWalker.xExprCallback = codeCursorHintIsOrFunction;
1080e6912fd8Sdan sqlite3WalkExpr(&sWalker, pTerm->pExpr);
1081e6912fd8Sdan if( sWalker.eCode ) continue;
1082b324cf75Sdan }
1083b324cf75Sdan }else{
108467a99dbeSdrh if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) continue;
1085b324cf75Sdan }
1086b413a546Sdrh
1087b413a546Sdrh /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
1088bcf40a7fSdrh ** the cursor. These terms are not needed as hints for a pure range
1089bcf40a7fSdrh ** scan (that has no == terms) so omit them. */
1090bcf40a7fSdrh if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
1091bcf40a7fSdrh for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
1092bcf40a7fSdrh if( j<pLoop->nLTerm ) continue;
1093b413a546Sdrh }
1094b413a546Sdrh
1095b413a546Sdrh /* No subqueries or non-deterministic functions allowed */
1096bec2476aSdrh if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
1097b413a546Sdrh
1098b413a546Sdrh /* For an index scan, make sure referenced columns are actually in
1099b413a546Sdrh ** the index. */
11002f2b0278Sdrh if( sHint.pIdx!=0 ){
11012f2b0278Sdrh sWalker.eCode = 0;
11022f2b0278Sdrh sWalker.xExprCallback = codeCursorHintCheckExpr;
11032f2b0278Sdrh sqlite3WalkExpr(&sWalker, pTerm->pExpr);
11042f2b0278Sdrh if( sWalker.eCode ) continue;
11052f2b0278Sdrh }
1106b413a546Sdrh
1107b413a546Sdrh /* If we survive all prior tests, that means this term is worth hinting */
1108d5c851c1Sdrh pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
1109bec2476aSdrh }
1110bec2476aSdrh if( pExpr!=0 ){
1111bec2476aSdrh sWalker.xExprCallback = codeCursorHintFixExpr;
1112bec2476aSdrh sqlite3WalkExpr(&sWalker, pExpr);
11132f2b0278Sdrh sqlite3VdbeAddOp4(v, OP_CursorHint,
11142f2b0278Sdrh (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
11152f2b0278Sdrh (const char*)pExpr, P4_EXPR);
1116bec2476aSdrh }
1117bec2476aSdrh }
1118bec2476aSdrh #else
1119b324cf75Sdan # define codeCursorHint(A,B,C,D) /* No-op */
1120bec2476aSdrh #endif /* SQLITE_ENABLE_CURSOR_HINTS */
11216f82e85aSdrh
11226f82e85aSdrh /*
1123de892d96Sdan ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
1124de892d96Sdan ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
1125de892d96Sdan ** function generates code to do a deferred seek of cursor iCur to the
1126de892d96Sdan ** rowid stored in register iRowid.
1127de892d96Sdan **
1128de892d96Sdan ** Normally, this is just:
1129de892d96Sdan **
1130170ad68aSdrh ** OP_DeferredSeek $iCur $iRowid
1131de892d96Sdan **
11327fd6a776Sdrh ** Which causes a seek on $iCur to the row with rowid $iRowid.
11337fd6a776Sdrh **
1134de892d96Sdan ** However, if the scan currently being coded is a branch of an OR-loop and
11357fd6a776Sdrh ** the statement currently being coded is a SELECT, then additional information
11367fd6a776Sdrh ** is added that might allow OP_Column to omit the seek and instead do its
11377fd6a776Sdrh ** lookup on the index, thus avoiding an expensive seek operation. To
11387fd6a776Sdrh ** enable this optimization, the P3 of OP_DeferredSeek is set to iIdxCur
11397fd6a776Sdrh ** and P4 is set to an array of integers containing one entry for each column
11407fd6a776Sdrh ** in the table. For each table column, if the column is the i'th
11417fd6a776Sdrh ** column of the index, then the corresponding array entry is set to (i+1).
11427fd6a776Sdrh ** If the column does not appear in the index at all, the array entry is set
11437fd6a776Sdrh ** to 0. The OP_Column opcode can check this array to see if the column it
11447fd6a776Sdrh ** wants is in the index and if it is, it will substitute the index cursor
11457fd6a776Sdrh ** and column number and continue with those new values, rather than seeking
11467fd6a776Sdrh ** the table cursor.
1147de892d96Sdan */
codeDeferredSeek(WhereInfo * pWInfo,Index * pIdx,int iCur,int iIdxCur)1148de892d96Sdan static void codeDeferredSeek(
1149de892d96Sdan WhereInfo *pWInfo, /* Where clause context */
1150de892d96Sdan Index *pIdx, /* Index scan is using */
1151de892d96Sdan int iCur, /* Cursor for IPK b-tree */
1152de892d96Sdan int iIdxCur /* Index cursor */
1153de892d96Sdan ){
1154de892d96Sdan Parse *pParse = pWInfo->pParse; /* Parse context */
1155de892d96Sdan Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
1156de892d96Sdan
1157de892d96Sdan assert( iIdxCur>0 );
1158de892d96Sdan assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
1159de892d96Sdan
1160be3da241Sdrh pWInfo->bDeferredSeek = 1;
1161170ad68aSdrh sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
1162c583719bSdrh if( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
1163cddb6ba0Sdan && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
1164de892d96Sdan ){
1165de892d96Sdan int i;
1166de892d96Sdan Table *pTab = pIdx->pTable;
1167abc38158Sdrh u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1));
1168de892d96Sdan if( ai ){
1169b1702026Sdrh ai[0] = pTab->nCol;
1170de892d96Sdan for(i=0; i<pIdx->nColumn-1; i++){
11714fb24c82Sdrh int x1, x2;
1172de892d96Sdan assert( pIdx->aiColumn[i]<pTab->nCol );
11734fb24c82Sdrh x1 = pIdx->aiColumn[i];
11744fb24c82Sdrh x2 = sqlite3TableColumnToStorage(pTab, x1);
11754fb24c82Sdrh testcase( x1!=x2 );
1176bde3a4f6Smistachkin if( x1>=0 ) ai[x2+1] = i+1;
1177de892d96Sdan }
1178de892d96Sdan sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
1179de892d96Sdan }
1180de892d96Sdan }
1181de892d96Sdan }
1182de892d96Sdan
1183553168c7Sdan /*
1184553168c7Sdan ** If the expression passed as the second argument is a vector, generate
1185553168c7Sdan ** code to write the first nReg elements of the vector into an array
1186553168c7Sdan ** of registers starting with iReg.
1187553168c7Sdan **
1188553168c7Sdan ** If the expression is not a vector, then nReg must be passed 1. In
1189553168c7Sdan ** this case, generate code to evaluate the expression and leave the
1190553168c7Sdan ** result in register iReg.
1191553168c7Sdan */
codeExprOrVector(Parse * pParse,Expr * p,int iReg,int nReg)119271c57db0Sdan static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
119371c57db0Sdan assert( nReg>0 );
1194d03024d8Sdan if( p && sqlite3ExprIsVector(p) ){
1195f9b2e05cSdan #ifndef SQLITE_OMIT_SUBQUERY
1196a4eeccdfSdrh if( ExprUseXSelect(p) ){
1197f9b2e05cSdan Vdbe *v = pParse->pVdbe;
119885bcdce2Sdrh int iSelect;
119985bcdce2Sdrh assert( p->op==TK_SELECT );
120085bcdce2Sdrh iSelect = sqlite3CodeSubselect(pParse, p);
1201f9b2e05cSdan sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
1202f9b2e05cSdan }else
1203f9b2e05cSdan #endif
1204f9b2e05cSdan {
120571c57db0Sdan int i;
1206a4eeccdfSdrh const ExprList *pList;
1207a4eeccdfSdrh assert( ExprUseXList(p) );
1208a4eeccdfSdrh pList = p->x.pList;
120971c57db0Sdan assert( nReg<=pList->nExpr );
121071c57db0Sdan for(i=0; i<nReg; i++){
121171c57db0Sdan sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
121271c57db0Sdan }
121371c57db0Sdan }
121471c57db0Sdan }else{
1215151446e7Sdan assert( nReg==1 || pParse->nErr );
121671c57db0Sdan sqlite3ExprCode(pParse, p, iReg);
121771c57db0Sdan }
121871c57db0Sdan }
121971c57db0Sdan
1220de892d96Sdan /*
1221610f11deSdrh ** The pTruth expression is always true because it is the WHERE clause
1222b531aa8fSdrh ** a partial index that is driving a query loop. Look through all of the
1223b531aa8fSdrh ** WHERE clause terms on the query, and if any of those terms must be
1224b531aa8fSdrh ** true because pTruth is true, then mark those WHERE clause terms as
1225b531aa8fSdrh ** coded.
1226b531aa8fSdrh */
whereApplyPartialIndexConstraints(Expr * pTruth,int iTabCur,WhereClause * pWC)1227b531aa8fSdrh static void whereApplyPartialIndexConstraints(
1228b531aa8fSdrh Expr *pTruth,
1229b531aa8fSdrh int iTabCur,
1230b531aa8fSdrh WhereClause *pWC
1231b531aa8fSdrh ){
1232b531aa8fSdrh int i;
1233b531aa8fSdrh WhereTerm *pTerm;
1234b531aa8fSdrh while( pTruth->op==TK_AND ){
1235b531aa8fSdrh whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
1236b531aa8fSdrh pTruth = pTruth->pRight;
1237b531aa8fSdrh }
1238b531aa8fSdrh for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1239b531aa8fSdrh Expr *pExpr;
1240b531aa8fSdrh if( pTerm->wtFlags & TERM_CODED ) continue;
1241b531aa8fSdrh pExpr = pTerm->pExpr;
1242b531aa8fSdrh if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){
1243b531aa8fSdrh pTerm->wtFlags |= TERM_CODED;
1244b531aa8fSdrh }
1245b531aa8fSdrh }
1246b531aa8fSdrh }
1247b531aa8fSdrh
124835685d3eSdrh /*
12496ae49e67Sdrh ** This routine is called right after An OP_Filter has been generated and
12506ae49e67Sdrh ** before the corresponding index search has been performed. This routine
12516ae49e67Sdrh ** checks to see if there are additional Bloom filters in inner loops that
12526ae49e67Sdrh ** can be checked prior to doing the index lookup. If there are available
12536ae49e67Sdrh ** inner-loop Bloom filters, then evaluate those filters now, before the
12546ae49e67Sdrh ** index lookup. The idea is that a Bloom filter check is way faster than
12556ae49e67Sdrh ** an index lookup, and the Bloom filter might return false, meaning that
12566ae49e67Sdrh ** the index lookup can be skipped.
12576ae49e67Sdrh **
12586ae49e67Sdrh ** We know that an inner loop uses a Bloom filter because it has the
12596ae49e67Sdrh ** WhereLevel.regFilter set. If an inner-loop Bloom filter is checked,
12605a4ac1ccSdrh ** then clear the WhereLevel.regFilter value to prevent the Bloom filter
12616ae49e67Sdrh ** from being checked a second time when the inner loop is evaluated.
126235685d3eSdrh */
filterPullDown(Parse * pParse,WhereInfo * pWInfo,int iLevel,int addrNxt,Bitmask notReady)126335685d3eSdrh static SQLITE_NOINLINE void filterPullDown(
126435685d3eSdrh Parse *pParse, /* Parsing context */
126535685d3eSdrh WhereInfo *pWInfo, /* Complete information about the WHERE clause */
126635685d3eSdrh int iLevel, /* Which level of pWInfo->a[] should be coded */
126735685d3eSdrh int addrNxt, /* Jump here to bypass inner loops */
126835685d3eSdrh Bitmask notReady /* Loops that are not ready */
126935685d3eSdrh ){
127035685d3eSdrh while( ++iLevel < pWInfo->nLevel ){
127135685d3eSdrh WhereLevel *pLevel = &pWInfo->a[iLevel];
127235685d3eSdrh WhereLoop *pLoop = pLevel->pWLoop;
12736ae49e67Sdrh if( pLevel->regFilter==0 ) continue;
127456945695Sdrh if( pLevel->pWLoop->nSkip ) continue;
127527a9e1f6Sdrh /* ,--- Because sqlite3ConstructBloomFilter() has will not have set
1276a11c5e22Sdrh ** vvvvv--' pLevel->regFilter if this were true. */
1277a11c5e22Sdrh if( NEVER(pLoop->prereq & notReady) ) continue;
12788aa7f4d8Sdrh assert( pLevel->addrBrk==0 );
12798aa7f4d8Sdrh pLevel->addrBrk = addrNxt;
128035685d3eSdrh if( pLoop->wsFlags & WHERE_IPK ){
128135685d3eSdrh WhereTerm *pTerm = pLoop->aLTerm[0];
12827e910f64Sdrh int regRowid;
128335685d3eSdrh assert( pTerm!=0 );
128435685d3eSdrh assert( pTerm->pExpr!=0 );
128535685d3eSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL );
12867e910f64Sdrh regRowid = sqlite3GetTempReg(pParse);
12877e910f64Sdrh regRowid = codeEqualityTerm(pParse, pTerm, pLevel, 0, 0, regRowid);
128873ac958cSdan sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
128973ac958cSdan VdbeCoverage(pParse->pVdbe);
129035685d3eSdrh sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
129135685d3eSdrh addrNxt, regRowid, 1);
129235685d3eSdrh VdbeCoverage(pParse->pVdbe);
129335685d3eSdrh }else{
129435685d3eSdrh u16 nEq = pLoop->u.btree.nEq;
129535685d3eSdrh int r1;
129635685d3eSdrh char *zStartAff;
129735685d3eSdrh
129835685d3eSdrh assert( pLoop->wsFlags & WHERE_INDEXED );
1299dc56dc93Sdrh assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
130035685d3eSdrh r1 = codeAllEqualityTerms(pParse,pLevel,0,0,&zStartAff);
130135685d3eSdrh codeApplyAffinity(pParse, r1, nEq, zStartAff);
130235685d3eSdrh sqlite3DbFree(pParse->db, zStartAff);
130335685d3eSdrh sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
130435685d3eSdrh addrNxt, r1, nEq);
130535685d3eSdrh VdbeCoverage(pParse->pVdbe);
130635685d3eSdrh }
13076ae49e67Sdrh pLevel->regFilter = 0;
13088aa7f4d8Sdrh pLevel->addrBrk = 0;
130935685d3eSdrh }
131035685d3eSdrh }
131135685d3eSdrh
1312b531aa8fSdrh /*
13136f82e85aSdrh ** Generate code for the start of the iLevel-th loop in the WHERE clause
13146f82e85aSdrh ** implementation described by pWInfo.
13156f82e85aSdrh */
sqlite3WhereCodeOneLoopStart(Parse * pParse,Vdbe * v,WhereInfo * pWInfo,int iLevel,WhereLevel * pLevel,Bitmask notReady)13166f82e85aSdrh Bitmask sqlite3WhereCodeOneLoopStart(
131747df8a2cSdrh Parse *pParse, /* Parsing context */
131847df8a2cSdrh Vdbe *v, /* Prepared statement under construction */
13196f82e85aSdrh WhereInfo *pWInfo, /* Complete information about the WHERE clause */
13206f82e85aSdrh int iLevel, /* Which level of pWInfo->a[] should be coded */
132147df8a2cSdrh WhereLevel *pLevel, /* The current level pointer */
13226f82e85aSdrh Bitmask notReady /* Which tables are currently available */
13236f82e85aSdrh ){
13246f82e85aSdrh int j, k; /* Loop counters */
13256f82e85aSdrh int iCur; /* The VDBE cursor for the table */
13266f82e85aSdrh int addrNxt; /* Where to jump to continue with the next IN case */
13276f82e85aSdrh int bRev; /* True if we need to scan in reverse order */
13286f82e85aSdrh WhereLoop *pLoop; /* The WhereLoop object being coded */
13296f82e85aSdrh WhereClause *pWC; /* Decomposition of the entire WHERE clause */
13306f82e85aSdrh WhereTerm *pTerm; /* A WHERE clause term */
13316f82e85aSdrh sqlite3 *db; /* Database connection */
13327601294aSdrh SrcItem *pTabItem; /* FROM clause term being coded */
13336f82e85aSdrh int addrBrk; /* Jump here to break out of the loop */
13343a3b420aSdrh int addrHalt; /* addrBrk for the outermost loop */
13356f82e85aSdrh int addrCont; /* Jump here to continue with next cycle */
13366f82e85aSdrh int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
13376f82e85aSdrh int iReleaseReg = 0; /* Temp register to free before returning */
13386f654a40Sdan Index *pIdx = 0; /* Index used by loop (if any) */
1339ebc63013Sdan int iLoop; /* Iteration of constraint generator loop */
13406f82e85aSdrh
13416f82e85aSdrh pWC = &pWInfo->sWC;
13426f82e85aSdrh db = pParse->db;
13436f82e85aSdrh pLoop = pLevel->pWLoop;
13446f82e85aSdrh pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
13456f82e85aSdrh iCur = pTabItem->iCursor;
13466f82e85aSdrh pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
13476f82e85aSdrh bRev = (pWInfo->revMask>>iLevel)&1;
13486f82e85aSdrh VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
1349118efd16Sdrh #if WHERETRACE_ENABLED /* 0x20800 */
1350118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){
1351a4b2df5cSdrh sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n",
1352a4b2df5cSdrh iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
1353118efd16Sdrh sqlite3WhereLoopPrint(pLoop, pWC);
1354118efd16Sdrh }
1355118efd16Sdrh if( sqlite3WhereTrace & 0x20000 ){
1356f1bb31e2Sdrh if( iLevel==0 ){
1357f1bb31e2Sdrh sqlite3DebugPrintf("WHERE clause being coded:\n");
1358f1bb31e2Sdrh sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
1359f1bb31e2Sdrh }
1360f1bb31e2Sdrh sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
1361118efd16Sdrh sqlite3WhereClausePrint(pWC);
1362118efd16Sdrh }
1363118efd16Sdrh #endif
13646f82e85aSdrh
13656f82e85aSdrh /* Create labels for the "break" and "continue" instructions
13666f82e85aSdrh ** for the current loop. Jump to addrBrk to break out of a loop.
13676f82e85aSdrh ** Jump to cont to go immediately to the next iteration of the
13686f82e85aSdrh ** loop.
13696f82e85aSdrh **
13706f82e85aSdrh ** When there is an IN operator, we also have a "addrNxt" label that
13716f82e85aSdrh ** means to continue with the next IN value combination. When
13726f82e85aSdrh ** there are no IN operators in the constraints, the "addrNxt" label
13736f82e85aSdrh ** is the same as "addrBrk".
13746f82e85aSdrh */
1375ec4ccdbcSdrh addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
1376ec4ccdbcSdrh addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
13776f82e85aSdrh
13786f82e85aSdrh /* If this is the right table of a LEFT OUTER JOIN, allocate and
13796f82e85aSdrh ** initialize a memory cell that records if this table matches any
13806f82e85aSdrh ** row of the left table of the join.
13816f82e85aSdrh */
1382c583719bSdrh assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
1383820fcd2cSdan || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
1384820fcd2cSdan );
13858a48b9c0Sdrh if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
13866f82e85aSdrh pLevel->iLeftJoin = ++pParse->nMem;
13876f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
13886f82e85aSdrh VdbeComment((v, "init LEFT JOIN no-match flag"));
13896f82e85aSdrh }
13906f82e85aSdrh
13913a3b420aSdrh /* Compute a safe address to jump to if we discover that the table for
13923a3b420aSdrh ** this loop is empty and can never contribute content. */
1393d875c7eeSdrh for(j=iLevel; j>0; j--){
1394d875c7eeSdrh if( pWInfo->a[j].iLeftJoin ) break;
1395d875c7eeSdrh if( pWInfo->a[j].pRJ ) break;
1396d875c7eeSdrh }
13973a3b420aSdrh addrHalt = pWInfo->a[j].addrBrk;
13983a3b420aSdrh
13996f82e85aSdrh /* Special case of a FROM clause subquery implemented as a co-routine */
14008a48b9c0Sdrh if( pTabItem->fg.viaCoroutine ){
14016f82e85aSdrh int regYield = pTabItem->regReturn;
14026f82e85aSdrh sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
14036f82e85aSdrh pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
14046f82e85aSdrh VdbeCoverage(v);
1405fef37760Sdrh VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
14066f82e85aSdrh pLevel->op = OP_Goto;
14076f82e85aSdrh }else
14086f82e85aSdrh
14096f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
14106f82e85aSdrh if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
14116f82e85aSdrh /* Case 1: The table is a virtual-table. Use the VFilter and VNext
14126f82e85aSdrh ** to access the data.
14136f82e85aSdrh */
14146f82e85aSdrh int iReg; /* P3 Value for OP_VFilter */
14156f82e85aSdrh int addrNotFound;
14166f82e85aSdrh int nConstraint = pLoop->nLTerm;
14176f82e85aSdrh
14186f82e85aSdrh iReg = sqlite3GetTempRange(pParse, nConstraint+2);
14196f82e85aSdrh addrNotFound = pLevel->addrBrk;
14206f82e85aSdrh for(j=0; j<nConstraint; j++){
14216f82e85aSdrh int iTarget = iReg+j+2;
14226f82e85aSdrh pTerm = pLoop->aLTerm[j];
1423599d5764Sdrh if( NEVER(pTerm==0) ) continue;
14246f82e85aSdrh if( pTerm->eOperator & WO_IN ){
14250fe7e7d9Sdrh if( SMASKBIT32(j) & pLoop->u.vtab.mHandleIn ){
14260fe7e7d9Sdrh int iTab = pParse->nTab++;
14270fe7e7d9Sdrh int iCache = ++pParse->nMem;
14280fe7e7d9Sdrh sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab);
14290fe7e7d9Sdrh sqlite3VdbeAddOp3(v, OP_VInitIn, iTab, iTarget, iCache);
14300fe7e7d9Sdrh }else{
14316f82e85aSdrh codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
14326f82e85aSdrh addrNotFound = pLevel->addrNxt;
14330fe7e7d9Sdrh }
14346f82e85aSdrh }else{
14356256c1c2Sdan Expr *pRight = pTerm->pExpr->pRight;
14366256c1c2Sdan codeExprOrVector(pParse, pRight, iTarget, 1);
14378f2c0b59Sdrh if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET
14388f2c0b59Sdrh && pLoop->u.vtab.bOmitOffset
14398f2c0b59Sdrh ){
14408f2c0b59Sdrh assert( pTerm->eOperator==WO_AUX );
1441*f55a7dadSdrh assert( pWInfo->pSelect!=0 );
1442*f55a7dadSdrh assert( pWInfo->pSelect->iOffset>0 );
1443*f55a7dadSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, pWInfo->pSelect->iOffset);
14448f2c0b59Sdrh VdbeComment((v,"Zero OFFSET counter"));
14458f2c0b59Sdrh }
14466256c1c2Sdan }
14476f82e85aSdrh }
14486f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
14496f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
14506f82e85aSdrh sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
14516f82e85aSdrh pLoop->u.vtab.idxStr,
1452861b1307Sdrh pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
14536f82e85aSdrh VdbeCoverage(v);
14546f82e85aSdrh pLoop->u.vtab.needFree = 0;
1455bc2e9514Sdrh /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
1456bc2e9514Sdrh ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */
1457bc2e9514Sdrh if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0;
14586f82e85aSdrh pLevel->p1 = iCur;
1459354474adSdan pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
14606f82e85aSdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v);
14610475629dSdrh assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
14626d6ea42aSdrh
14636d6ea42aSdrh for(j=0; j<nConstraint; j++){
1464dbc49161Sdrh pTerm = pLoop->aLTerm[j];
1465dbc49161Sdrh if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
1466dbc49161Sdrh disableTerm(pLevel, pTerm);
14676d6ea42aSdrh continue;
14686d6ea42aSdrh }
14696d6ea42aSdrh if( (pTerm->eOperator & WO_IN)!=0
14706d6ea42aSdrh && (SMASKBIT32(j) & pLoop->u.vtab.mHandleIn)==0
14716d6ea42aSdrh && !db->mallocFailed
14726d6ea42aSdrh ){
1473dbc49161Sdrh Expr *pCompare; /* The comparison operator */
1474dbc49161Sdrh Expr *pRight; /* RHS of the comparison */
1475dbc49161Sdrh VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
14766d6ea42aSdrh int iIn; /* IN loop corresponding to the j-th constraint */
1477dbc49161Sdrh
1478dbc49161Sdrh /* Reload the constraint value into reg[iReg+j+2]. The same value
1479dbc49161Sdrh ** was loaded into the same register prior to the OP_VFilter, but
1480dbc49161Sdrh ** the xFilter implementation might have changed the datatype or
14816d6ea42aSdrh ** encoding of the value in the register, so it *must* be reloaded.
14826d6ea42aSdrh */
14836d6ea42aSdrh for(iIn=0; ALWAYS(iIn<pLevel->u.in.nIn); iIn++){
148468748ec5Sdrh pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
14856d6ea42aSdrh if( (pOp->opcode==OP_Column && pOp->p3==iReg+j+2)
14866d6ea42aSdrh || (pOp->opcode==OP_Rowid && pOp->p2==iReg+j+2)
14876d6ea42aSdrh ){
1488dbc49161Sdrh testcase( pOp->opcode==OP_Rowid );
1489dbc49161Sdrh sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
14906d6ea42aSdrh break;
14916d6ea42aSdrh }
1492dbc49161Sdrh }
1493dbc49161Sdrh
1494dbc49161Sdrh /* Generate code that will continue to the next row if
14956d6ea42aSdrh ** the IN constraint is not satisfied
14966d6ea42aSdrh */
1497abfd35eaSdrh pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
14986d6ea42aSdrh if( !db->mallocFailed ){
14996d6ea42aSdrh int iFld = pTerm->u.x.iField;
15006d6ea42aSdrh Expr *pLeft = pTerm->pExpr->pLeft;
15016d6ea42aSdrh assert( pLeft!=0 );
15026d6ea42aSdrh if( iFld>0 ){
15036d6ea42aSdrh assert( pLeft->op==TK_VECTOR );
15046d6ea42aSdrh assert( ExprUseXList(pLeft) );
15056d6ea42aSdrh assert( iFld<=pLeft->x.pList->nExpr );
15066d6ea42aSdrh pCompare->pLeft = pLeft->x.pList->a[iFld-1].pExpr;
15076d6ea42aSdrh }else{
15086d6ea42aSdrh pCompare->pLeft = pLeft;
15096d6ea42aSdrh }
1510dbc49161Sdrh pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
1511237b2b71Sdrh if( pRight ){
1512237b2b71Sdrh pRight->iTable = iReg+j+2;
1513d03f77aeSdan sqlite3ExprIfFalse(
1514d03f77aeSdan pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
1515d03f77aeSdan );
1516237b2b71Sdrh }
1517dbc49161Sdrh pCompare->pLeft = 0;
15186d6ea42aSdrh }
1519dbc49161Sdrh sqlite3ExprDelete(db, pCompare);
1520dbc49161Sdrh }
1521dbc49161Sdrh }
15226d6ea42aSdrh
1523ba26faa3Sdrh /* These registers need to be preserved in case there is an IN operator
1524ba26faa3Sdrh ** loop. So we could deallocate the registers here (and potentially
1525ba26faa3Sdrh ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
1526ba26faa3Sdrh ** simpler and safer to simply not reuse the registers.
1527ba26faa3Sdrh **
1528ba26faa3Sdrh ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
1529ba26faa3Sdrh */
15306f82e85aSdrh }else
15316f82e85aSdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */
15326f82e85aSdrh
15336f82e85aSdrh if( (pLoop->wsFlags & WHERE_IPK)!=0
15346f82e85aSdrh && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
15356f82e85aSdrh ){
15366f82e85aSdrh /* Case 2: We can directly reference a single row using an
15376f82e85aSdrh ** equality comparison against the ROWID field. Or
15386f82e85aSdrh ** we reference multiple rows using a "rowid IN (...)"
15396f82e85aSdrh ** construct.
15406f82e85aSdrh */
15416f82e85aSdrh assert( pLoop->u.btree.nEq==1 );
15426f82e85aSdrh pTerm = pLoop->aLTerm[0];
15436f82e85aSdrh assert( pTerm!=0 );
15446f82e85aSdrh assert( pTerm->pExpr!=0 );
15456f82e85aSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL );
15466f82e85aSdrh iReleaseReg = ++pParse->nMem;
15476f82e85aSdrh iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
15486f82e85aSdrh if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
15496f82e85aSdrh addrNxt = pLevel->addrNxt;
15502db144c3Sdrh if( pLevel->regFilter ){
155173ac958cSdan sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
155273ac958cSdan VdbeCoverage(v);
15532db144c3Sdrh sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
15542db144c3Sdrh iRowidReg, 1);
1555067c60cfSdrh VdbeCoverage(v);
155635685d3eSdrh filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
15572db144c3Sdrh }
1558eeb9565aSdrh sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
15596f82e85aSdrh VdbeCoverage(v);
15606f82e85aSdrh pLevel->op = OP_Noop;
15616f82e85aSdrh }else if( (pLoop->wsFlags & WHERE_IPK)!=0
15626f82e85aSdrh && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
15636f82e85aSdrh ){
15646f82e85aSdrh /* Case 3: We have an inequality comparison against the ROWID field.
15656f82e85aSdrh */
15666f82e85aSdrh int testOp = OP_Noop;
15676f82e85aSdrh int start;
15686f82e85aSdrh int memEndValue = 0;
15696f82e85aSdrh WhereTerm *pStart, *pEnd;
15706f82e85aSdrh
15716f82e85aSdrh j = 0;
15726f82e85aSdrh pStart = pEnd = 0;
15736f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
15746f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
15756f82e85aSdrh assert( pStart!=0 || pEnd!=0 );
15766f82e85aSdrh if( bRev ){
15776f82e85aSdrh pTerm = pStart;
15786f82e85aSdrh pStart = pEnd;
15796f82e85aSdrh pEnd = pTerm;
15806f82e85aSdrh }
1581b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
15826f82e85aSdrh if( pStart ){
15836f82e85aSdrh Expr *pX; /* The expression that defines the start bound */
15846f82e85aSdrh int r1, rTemp; /* Registers for holding the start boundary */
158519ff12ddSdan int op; /* Cursor seek operation */
15866f82e85aSdrh
15876f82e85aSdrh /* The following constant maps TK_xx codes into corresponding
15886f82e85aSdrh ** seek opcodes. It depends on a particular ordering of TK_xx
15896f82e85aSdrh */
15906f82e85aSdrh const u8 aMoveOp[] = {
15916f82e85aSdrh /* TK_GT */ OP_SeekGT,
15926f82e85aSdrh /* TK_LE */ OP_SeekLE,
15936f82e85aSdrh /* TK_LT */ OP_SeekLT,
15946f82e85aSdrh /* TK_GE */ OP_SeekGE
15956f82e85aSdrh };
15966f82e85aSdrh assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
15976f82e85aSdrh assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
15986f82e85aSdrh assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
15996f82e85aSdrh
16006f82e85aSdrh assert( (pStart->wtFlags & TERM_VNULL)==0 );
16016f82e85aSdrh testcase( pStart->wtFlags & TERM_VIRTUAL );
16026f82e85aSdrh pX = pStart->pExpr;
16036f82e85aSdrh assert( pX!=0 );
16046f82e85aSdrh testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
1605625015e0Sdan if( sqlite3ExprIsVector(pX->pRight) ){
160619ff12ddSdan r1 = rTemp = sqlite3GetTempReg(pParse);
160719ff12ddSdan codeExprOrVector(pParse, pX->pRight, r1, 1);
16084d1c6845Sdrh testcase( pX->op==TK_GT );
16094d1c6845Sdrh testcase( pX->op==TK_GE );
16104d1c6845Sdrh testcase( pX->op==TK_LT );
16114d1c6845Sdrh testcase( pX->op==TK_LE );
16124d1c6845Sdrh op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
16134d1c6845Sdrh assert( pX->op!=TK_GT || op==OP_SeekGE );
16144d1c6845Sdrh assert( pX->op!=TK_GE || op==OP_SeekGE );
16154d1c6845Sdrh assert( pX->op!=TK_LT || op==OP_SeekLE );
16164d1c6845Sdrh assert( pX->op!=TK_LE || op==OP_SeekLE );
161719ff12ddSdan }else{
16186f82e85aSdrh r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
161919ff12ddSdan disableTerm(pLevel, pStart);
162019ff12ddSdan op = aMoveOp[(pX->op - TK_GT)];
162119ff12ddSdan }
162219ff12ddSdan sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
16236f82e85aSdrh VdbeComment((v, "pk"));
16246f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GT);
16256f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LE);
16266f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_LT);
16276f82e85aSdrh VdbeCoverageIf(v, pX->op==TK_GE);
16286f82e85aSdrh sqlite3ReleaseTempReg(pParse, rTemp);
16296f82e85aSdrh }else{
16303a3b420aSdrh sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
16316f82e85aSdrh VdbeCoverageIf(v, bRev==0);
16326f82e85aSdrh VdbeCoverageIf(v, bRev!=0);
16336f82e85aSdrh }
16346f82e85aSdrh if( pEnd ){
16356f82e85aSdrh Expr *pX;
16366f82e85aSdrh pX = pEnd->pExpr;
16376f82e85aSdrh assert( pX!=0 );
16386f82e85aSdrh assert( (pEnd->wtFlags & TERM_VNULL)==0 );
16396f82e85aSdrh testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
16406f82e85aSdrh testcase( pEnd->wtFlags & TERM_VIRTUAL );
16416f82e85aSdrh memEndValue = ++pParse->nMem;
164219ff12ddSdan codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
1643625015e0Sdan if( 0==sqlite3ExprIsVector(pX->pRight)
1644625015e0Sdan && (pX->op==TK_LT || pX->op==TK_GT)
1645625015e0Sdan ){
16466f82e85aSdrh testOp = bRev ? OP_Le : OP_Ge;
16476f82e85aSdrh }else{
16486f82e85aSdrh testOp = bRev ? OP_Lt : OP_Gt;
16496f82e85aSdrh }
1650553168c7Sdan if( 0==sqlite3ExprIsVector(pX->pRight) ){
16516f82e85aSdrh disableTerm(pLevel, pEnd);
16526f82e85aSdrh }
1653553168c7Sdan }
16546f82e85aSdrh start = sqlite3VdbeCurrentAddr(v);
16556f82e85aSdrh pLevel->op = bRev ? OP_Prev : OP_Next;
16566f82e85aSdrh pLevel->p1 = iCur;
16576f82e85aSdrh pLevel->p2 = start;
16586f82e85aSdrh assert( pLevel->p5==0 );
16596f82e85aSdrh if( testOp!=OP_Noop ){
16606f82e85aSdrh iRowidReg = ++pParse->nMem;
16616f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
16626f82e85aSdrh sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
16636f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Le);
16646f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Lt);
16656f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Ge);
16666f82e85aSdrh VdbeCoverageIf(v, testOp==OP_Gt);
16676f82e85aSdrh sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
16686f82e85aSdrh }
16696f82e85aSdrh }else if( pLoop->wsFlags & WHERE_INDEXED ){
16706f82e85aSdrh /* Case 4: A scan using an index.
16716f82e85aSdrh **
16726f82e85aSdrh ** The WHERE clause may contain zero or more equality
16736f82e85aSdrh ** terms ("==" or "IN" operators) that refer to the N
16746f82e85aSdrh ** left-most columns of the index. It may also contain
16756f82e85aSdrh ** inequality constraints (>, <, >= or <=) on the indexed
16766f82e85aSdrh ** column that immediately follows the N equalities. Only
16776f82e85aSdrh ** the right-most column can be an inequality - the rest must
16786f82e85aSdrh ** use the "==" and "IN" operators. For example, if the
16796f82e85aSdrh ** index is on (x,y,z), then the following clauses are all
16806f82e85aSdrh ** optimized:
16816f82e85aSdrh **
16826f82e85aSdrh ** x=5
16836f82e85aSdrh ** x=5 AND y=10
16846f82e85aSdrh ** x=5 AND y<10
16856f82e85aSdrh ** x=5 AND y>5 AND y<10
16866f82e85aSdrh ** x=5 AND y=5 AND z<=10
16876f82e85aSdrh **
16886f82e85aSdrh ** The z<10 term of the following cannot be used, only
16896f82e85aSdrh ** the x=5 term:
16906f82e85aSdrh **
16916f82e85aSdrh ** x=5 AND z<10
16926f82e85aSdrh **
16936f82e85aSdrh ** N may be zero if there are inequality constraints.
16946f82e85aSdrh ** If there are no inequality constraints, then N is at
16956f82e85aSdrh ** least one.
16966f82e85aSdrh **
16976f82e85aSdrh ** This case is also used when there are no WHERE clause
16986f82e85aSdrh ** constraints but an index is selected anyway, in order
16996f82e85aSdrh ** to force the output order to conform to an ORDER BY.
17006f82e85aSdrh */
17016f82e85aSdrh static const u8 aStartOp[] = {
17026f82e85aSdrh 0,
17036f82e85aSdrh 0,
17046f82e85aSdrh OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
17056f82e85aSdrh OP_Last, /* 3: (!start_constraints && startEq && bRev) */
17066f82e85aSdrh OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
17076f82e85aSdrh OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
17086f82e85aSdrh OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
17096f82e85aSdrh OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
17106f82e85aSdrh };
17116f82e85aSdrh static const u8 aEndOp[] = {
17126f82e85aSdrh OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
17136f82e85aSdrh OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
17146f82e85aSdrh OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
17156f82e85aSdrh OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
17166f82e85aSdrh };
17176f82e85aSdrh u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
171871c57db0Sdan u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
171971c57db0Sdan u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
17206f82e85aSdrh int regBase; /* Base register holding constraint values */
17216f82e85aSdrh WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
17226f82e85aSdrh WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
17236f82e85aSdrh int startEq; /* True if range start uses ==, >= or <= */
17246f82e85aSdrh int endEq; /* True if range end uses ==, >= or <= */
17256f82e85aSdrh int start_constraints; /* Start of range is constrained */
17266f82e85aSdrh int nConstraint; /* Number of constraint terms */
17276f82e85aSdrh int iIdxCur; /* The VDBE cursor for the index */
17286f82e85aSdrh int nExtraReg = 0; /* Number of extra registers needed */
17296f82e85aSdrh int op; /* Instruction opcode */
17306f82e85aSdrh char *zStartAff; /* Affinity for start of range constraint */
1731b7ca2177Sdan char *zEndAff = 0; /* Affinity for end of range constraint */
17326f82e85aSdrh u8 bSeekPastNull = 0; /* True to seek past initial nulls */
17336f82e85aSdrh u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
173447df8a2cSdrh int omitTable; /* True if we use the index only */
173574e1b861Sdrh int regBignull = 0; /* big-null flag register */
173604e70ce0Sdrh int addrSeekScan = 0; /* Opcode of the OP_SeekScan, if any */
17376f82e85aSdrh
17386f82e85aSdrh pIdx = pLoop->u.btree.pIndex;
17396f82e85aSdrh iIdxCur = pLevel->iIdxCur;
17406f82e85aSdrh assert( nEq>=pLoop->nSkip );
17416f82e85aSdrh
17426f82e85aSdrh /* Find any inequality constraint terms for the start and end
17436f82e85aSdrh ** of the range.
17446f82e85aSdrh */
17456f82e85aSdrh j = nEq;
17466f82e85aSdrh if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
17476f82e85aSdrh pRangeStart = pLoop->aLTerm[j++];
174871c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
17496f82e85aSdrh /* Like optimization range constraints always occur in pairs */
17506f82e85aSdrh assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
17516f82e85aSdrh (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
17526f82e85aSdrh }
17536f82e85aSdrh if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
17546f82e85aSdrh pRangeEnd = pLoop->aLTerm[j++];
175571c57db0Sdan nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
175641d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17576f82e85aSdrh if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
17586f82e85aSdrh assert( pRangeStart!=0 ); /* LIKE opt constraints */
17596f82e85aSdrh assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
176044aebff2Sdrh pLevel->iLikeRepCntr = (u32)++pParse->nMem;
176144aebff2Sdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
17626f82e85aSdrh VdbeComment((v, "LIKE loop counter"));
17636f82e85aSdrh pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
176444aebff2Sdrh /* iLikeRepCntr actually stores 2x the counter register number. The
176544aebff2Sdrh ** bottom bit indicates whether the search order is ASC or DESC. */
176644aebff2Sdrh testcase( bRev );
176744aebff2Sdrh testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
176844aebff2Sdrh assert( (bRev & ~1)==0 );
176944aebff2Sdrh pLevel->iLikeRepCntr <<=1;
177044aebff2Sdrh pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
17716f82e85aSdrh }
177241d2e66eSdrh #endif
177348590fcbSdrh if( pRangeStart==0 ){
177448590fcbSdrh j = pIdx->aiColumn[nEq];
177548590fcbSdrh if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
17766f82e85aSdrh bSeekPastNull = 1;
17776f82e85aSdrh }
17786f82e85aSdrh }
177948590fcbSdrh }
17806f82e85aSdrh assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
17816f82e85aSdrh
178215750a26Sdan /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
178315750a26Sdan ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
178415750a26Sdan ** FIRST). In both cases separate ordered scans are made of those
178515750a26Sdan ** index entries for which the column is null and for those for which
178615750a26Sdan ** it is not. For an ASC sort, the non-NULL entries are scanned first.
178715750a26Sdan ** For DESC, NULL entries are scanned first.
178815750a26Sdan */
178915750a26Sdan if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
179015750a26Sdan && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
179115750a26Sdan ){
179215750a26Sdan assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
179315750a26Sdan assert( pRangeEnd==0 && pRangeStart==0 );
17944adb1d00Sdan testcase( pLoop->nSkip>0 );
179515750a26Sdan nExtraReg = 1;
179615750a26Sdan bSeekPastNull = 1;
179715750a26Sdan pLevel->regBignull = regBignull = ++pParse->nMem;
17987f05d52cSdrh if( pLevel->iLeftJoin ){
17997f05d52cSdrh sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull);
18007f05d52cSdrh }
1801cc491f4bSdan pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
180215750a26Sdan }
180315750a26Sdan
18046f82e85aSdrh /* If we are doing a reverse order scan on an ascending index, or
18056f82e85aSdrh ** a forward order scan on a descending index, interchange the
18066f82e85aSdrh ** start and end terms (pRangeStart and pRangeEnd).
18076f82e85aSdrh */
18087ffb16b4Sdrh if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) ){
18096f82e85aSdrh SWAP(WhereTerm *, pRangeEnd, pRangeStart);
18106f82e85aSdrh SWAP(u8, bSeekPastNull, bStopAtNull);
181171c57db0Sdan SWAP(u8, nBtm, nTop);
18126f82e85aSdrh }
18136f82e85aSdrh
1814df1b52e7Sdan if( iLevel>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 ){
1815df1b52e7Sdan /* In case OP_SeekScan is used, ensure that the index cursor does not
1816df1b52e7Sdan ** point to a valid row for the first iteration of this loop. */
1817df1b52e7Sdan sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
1818df1b52e7Sdan }
1819df1b52e7Sdan
1820bcf40a7fSdrh /* Generate code to evaluate all constraint terms using == or IN
1821bcf40a7fSdrh ** and store the values of those terms in an array of registers
1822bcf40a7fSdrh ** starting at regBase.
1823bcf40a7fSdrh */
1824b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
1825bcf40a7fSdrh regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
1826bcf40a7fSdrh assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
1827b7ca2177Sdan if( zStartAff && nTop ){
1828b7ca2177Sdan zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
1829b7ca2177Sdan }
1830cc491f4bSdan addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);
1831bcf40a7fSdrh
18326f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
18336f82e85aSdrh testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
18346f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
18356f82e85aSdrh testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
18366f82e85aSdrh startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
18376f82e85aSdrh endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
18386f82e85aSdrh start_constraints = pRangeStart || nEq>0;
18396f82e85aSdrh
18406f82e85aSdrh /* Seek the index cursor to the start of the range. */
18416f82e85aSdrh nConstraint = nEq;
18426f82e85aSdrh if( pRangeStart ){
18436f82e85aSdrh Expr *pRight = pRangeStart->pExpr->pRight;
184471c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
18456f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
1846395a60daSdrh if( (pRangeStart->wtFlags & TERM_VNULL)==0
18476f82e85aSdrh && sqlite3ExprCanBeNull(pRight)
18486f82e85aSdrh ){
18496f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
18506f82e85aSdrh VdbeCoverage(v);
18516f82e85aSdrh }
18526f82e85aSdrh if( zStartAff ){
1853e3c6b61cSdrh updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
18546f82e85aSdrh }
185571c57db0Sdan nConstraint += nBtm;
18566f82e85aSdrh testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
1857625015e0Sdan if( sqlite3ExprIsVector(pRight)==0 ){
185871c57db0Sdan disableTerm(pLevel, pRangeStart);
185971c57db0Sdan }else{
186071c57db0Sdan startEq = 1;
186171c57db0Sdan }
1862426f4ab0Sdrh bSeekPastNull = 0;
18636f82e85aSdrh }else if( bSeekPastNull ){
18646f82e85aSdrh startEq = 0;
18650086e078Sdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
18666f82e85aSdrh start_constraints = 1;
18670086e078Sdrh nConstraint++;
186815750a26Sdan }else if( regBignull ){
186915750a26Sdan sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
187015750a26Sdan start_constraints = 1;
187115750a26Sdan nConstraint++;
18726f82e85aSdrh }
18736f82e85aSdrh codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
18740bf2ad6aSdrh if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
18750bf2ad6aSdrh /* The skip-scan logic inside the call to codeAllEqualityConstraints()
18760bf2ad6aSdrh ** above has already left the cursor sitting on the correct row,
18770bf2ad6aSdrh ** so no further seeking is needed */
18780bf2ad6aSdrh }else{
187915750a26Sdan if( regBignull ){
1880ec3dda5bSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
1881a31d3554Sdrh VdbeComment((v, "NULL-scan pass ctr"));
188215750a26Sdan }
18832db144c3Sdrh if( pLevel->regFilter ){
18842db144c3Sdrh sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
1885770dade2Sdrh regBase, nEq);
1886067c60cfSdrh VdbeCoverage(v);
188735685d3eSdrh filterPullDown(pParse, pWInfo, iLevel, addrNxt, notReady);
18882db144c3Sdrh }
188915750a26Sdan
18906f82e85aSdrh op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
18916f82e85aSdrh assert( op!=0 );
18927d14ffe4Sdrh if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){
189368cf0aceSdrh assert( regBignull==0 );
18944f65b3bbSdrh /* TUNING: The OP_SeekScan opcode seeks to reduce the number
18954f65b3bbSdrh ** of expensive seek operations by replacing a single seek with
18964f65b3bbSdrh ** 1 or more step operations. The question is, how many steps
18974f65b3bbSdrh ** should we try before giving up and going with a seek. The cost
18984f65b3bbSdrh ** of a seek is proportional to the logarithm of the of the number
18994f65b3bbSdrh ** of entries in the tree, so basing the number of steps to try
19004f65b3bbSdrh ** on the estimated number of rows in the btree seems like a good
19014f65b3bbSdrh ** guess. */
190204e70ce0Sdrh addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan,
190304e70ce0Sdrh (pIdx->aiRowLogEst[0]+9)/10);
190473c586bcSdan if( pRangeStart ){
190573c586bcSdan sqlite3VdbeChangeP5(v, 1);
190673c586bcSdan sqlite3VdbeChangeP2(v, addrSeekScan, sqlite3VdbeCurrentAddr(v)+1);
190773c586bcSdan addrSeekScan = 0;
190873c586bcSdan }
19094f65b3bbSdrh VdbeCoverage(v);
191068cf0aceSdrh }
19116f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
19126f82e85aSdrh VdbeCoverage(v);
19136f82e85aSdrh VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
19146f82e85aSdrh VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
19156f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
19166f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
19176f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
19186f82e85aSdrh VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
1919ddd7421cSdan
19200086e078Sdrh assert( bSeekPastNull==0 || bStopAtNull==0 );
192115750a26Sdan if( regBignull ){
19220086e078Sdrh assert( bSeekPastNull==1 || bStopAtNull==1 );
19235f6a4ea2Sdrh assert( bSeekPastNull==!bStopAtNull );
19240086e078Sdrh assert( bStopAtNull==startEq );
1925ddd7421cSdan sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);
19260086e078Sdrh op = aStartOp[(nConstraint>1)*4 + 2 + bRev];
19270086e078Sdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
19280086e078Sdrh nConstraint-startEq);
1929505ae9deSdrh VdbeCoverage(v);
1930505ae9deSdrh VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
1931505ae9deSdrh VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
1932505ae9deSdrh VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
1933505ae9deSdrh VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
19340086e078Sdrh assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE);
1935ddd7421cSdan }
1936a6d2f8ebSdrh }
19376f82e85aSdrh
19386f82e85aSdrh /* Load the value for the inequality constraint at the end of the
19396f82e85aSdrh ** range (if any).
19406f82e85aSdrh */
19416f82e85aSdrh nConstraint = nEq;
19425d742e39Sdrh assert( pLevel->p2==0 );
19436f82e85aSdrh if( pRangeEnd ){
19446f82e85aSdrh Expr *pRight = pRangeEnd->pExpr->pRight;
19455d742e39Sdrh if( addrSeekScan ){
19465d742e39Sdrh /* For a seek-scan that has a range on the lowest term of the index,
19475d742e39Sdrh ** we have to make the top of the loop be code that sets the end
19485d742e39Sdrh ** condition of the range. Otherwise, the OP_SeekScan might jump
19495d742e39Sdrh ** over that initialization, leaving the range-end value set to the
19505d742e39Sdrh ** range-start value, resulting in a wrong answer.
19515d742e39Sdrh ** See ticket 5981a8c041a3c2f3 (2021-11-02).
19525d742e39Sdrh */
19535d742e39Sdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v);
19545d742e39Sdrh }
195571c57db0Sdan codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
19566f82e85aSdrh whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
1957395a60daSdrh if( (pRangeEnd->wtFlags & TERM_VNULL)==0
19586f82e85aSdrh && sqlite3ExprCanBeNull(pRight)
19596f82e85aSdrh ){
19606f82e85aSdrh sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
19616f82e85aSdrh VdbeCoverage(v);
19626f82e85aSdrh }
19630c36fca0Sdrh if( zEndAff ){
1964e3c6b61cSdrh updateRangeAffinityStr(pRight, nTop, zEndAff);
1965b7ca2177Sdan codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
19660c36fca0Sdrh }else{
19670c36fca0Sdrh assert( pParse->db->mallocFailed );
19680c36fca0Sdrh }
196971c57db0Sdan nConstraint += nTop;
19706f82e85aSdrh testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
197171c57db0Sdan
1972625015e0Sdan if( sqlite3ExprIsVector(pRight)==0 ){
197371c57db0Sdan disableTerm(pLevel, pRangeEnd);
197471c57db0Sdan }else{
197571c57db0Sdan endEq = 1;
197671c57db0Sdan }
19776f82e85aSdrh }else if( bStopAtNull ){
197815750a26Sdan if( regBignull==0 ){
19796f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
19806f82e85aSdrh endEq = 0;
198115750a26Sdan }
19826f82e85aSdrh nConstraint++;
19836f82e85aSdrh }
198441ce47c4Sdrh if( zStartAff ) sqlite3DbNNFreeNN(db, zStartAff);
198541ce47c4Sdrh if( zEndAff ) sqlite3DbNNFreeNN(db, zEndAff);
19866f82e85aSdrh
19876f82e85aSdrh /* Top of the loop body */
19885d742e39Sdrh if( pLevel->p2==0 ) pLevel->p2 = sqlite3VdbeCurrentAddr(v);
19896f82e85aSdrh
19906f82e85aSdrh /* Check if the index cursor is past the end of the range. */
19916f82e85aSdrh if( nConstraint ){
199215750a26Sdan if( regBignull ){
19935f6a4ea2Sdrh /* Except, skip the end-of-range check while doing the NULL-scan */
1994ec3dda5bSdrh sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);
1995a31d3554Sdrh VdbeComment((v, "If NULL-scan 2nd pass"));
1996505ae9deSdrh VdbeCoverage(v);
199715750a26Sdan }
19986f82e85aSdrh op = aEndOp[bRev*2 + endEq];
19996f82e85aSdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
20006f82e85aSdrh testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
20016f82e85aSdrh testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
20026f82e85aSdrh testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
20036f82e85aSdrh testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
200404e70ce0Sdrh if( addrSeekScan ) sqlite3VdbeJumpHere(v, addrSeekScan);
20056f82e85aSdrh }
200615750a26Sdan if( regBignull ){
20075f6a4ea2Sdrh /* During a NULL-scan, check to see if we have reached the end of
20085f6a4ea2Sdrh ** the NULLs */
20095f6a4ea2Sdrh assert( bSeekPastNull==!bStopAtNull );
20105f6a4ea2Sdrh assert( bSeekPastNull+bStopAtNull==1 );
20115f6a4ea2Sdrh assert( nConstraint+bSeekPastNull>0 );
2012ec3dda5bSdrh sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2);
2013a31d3554Sdrh VdbeComment((v, "If NULL-scan 1st pass"));
2014505ae9deSdrh VdbeCoverage(v);
20155f6a4ea2Sdrh op = aEndOp[bRev*2 + bSeekPastNull];
20165f6a4ea2Sdrh sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
20175f6a4ea2Sdrh nConstraint+bSeekPastNull);
2018505ae9deSdrh testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
2019505ae9deSdrh testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
2020505ae9deSdrh testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
2021505ae9deSdrh testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
202215750a26Sdan }
20236f82e85aSdrh
2024f761d937Sdrh if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){
2025fa17e134Sdrh sqlite3VdbeAddOp3(v, OP_SeekHit, iIdxCur, nEq, nEq);
20268c2b6d78Sdrh }
20278c2b6d78Sdrh
20286f82e85aSdrh /* Seek the table cursor, if required */
202947df8a2cSdrh omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
2030c583719bSdrh && (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0;
20316f82e85aSdrh if( omitTable ){
20326f82e85aSdrh /* pIdx is a covering index. No need to access the main table. */
20336f82e85aSdrh }else if( HasRowid(pIdx->pTable) ){
2034784c1b93Sdrh codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
20356f82e85aSdrh }else if( iCur!=iIdxCur ){
20366f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
20376f82e85aSdrh iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
20386f82e85aSdrh for(j=0; j<pPk->nKeyCol; j++){
2039b9bcf7caSdrh k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
20406f82e85aSdrh sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
20416f82e85aSdrh }
20426f82e85aSdrh sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
20436f82e85aSdrh iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
20446f82e85aSdrh }
20456f82e85aSdrh
2046db535390Sdrh if( pLevel->iLeftJoin==0 ){
2047b531aa8fSdrh /* If a partial index is driving the loop, try to eliminate WHERE clause
2048b531aa8fSdrh ** terms from the query that must be true due to the WHERE clause of
2049db535390Sdrh ** the partial index.
2050db535390Sdrh **
2051db535390Sdrh ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
2052db535390Sdrh ** for a LEFT JOIN.
2053b531aa8fSdrh */
2054b531aa8fSdrh if( pIdx->pPartIdxWhere ){
2055b531aa8fSdrh whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
2056b531aa8fSdrh }
2057db535390Sdrh }else{
2058db535390Sdrh testcase( pIdx->pPartIdxWhere );
205906fc2455Sdrh /* The following assert() is not a requirement, merely an observation:
206006fc2455Sdrh ** The OR-optimization doesn't work for the right hand table of
206106fc2455Sdrh ** a LEFT JOIN: */
2062c583719bSdrh assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0 );
2063db535390Sdrh }
2064b531aa8fSdrh
206571c57db0Sdan /* Record the instruction used to terminate the loop. */
20666f82e85aSdrh if( pLoop->wsFlags & WHERE_ONEROW ){
20676f82e85aSdrh pLevel->op = OP_Noop;
20686f82e85aSdrh }else if( bRev ){
20696f82e85aSdrh pLevel->op = OP_Prev;
20706f82e85aSdrh }else{
20716f82e85aSdrh pLevel->op = OP_Next;
20726f82e85aSdrh }
20736f82e85aSdrh pLevel->p1 = iIdxCur;
20746f82e85aSdrh pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
20756f82e85aSdrh if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
20766f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
20776f82e85aSdrh }else{
20786f82e85aSdrh assert( pLevel->p5==0 );
20796f82e85aSdrh }
20806f654a40Sdan if( omitTable ) pIdx = 0;
20816f82e85aSdrh }else
20826f82e85aSdrh
20836f82e85aSdrh #ifndef SQLITE_OMIT_OR_OPTIMIZATION
20846f82e85aSdrh if( pLoop->wsFlags & WHERE_MULTI_OR ){
20856f82e85aSdrh /* Case 5: Two or more separately indexed terms connected by OR
20866f82e85aSdrh **
20876f82e85aSdrh ** Example:
20886f82e85aSdrh **
20896f82e85aSdrh ** CREATE TABLE t1(a,b,c,d);
20906f82e85aSdrh ** CREATE INDEX i1 ON t1(a);
20916f82e85aSdrh ** CREATE INDEX i2 ON t1(b);
20926f82e85aSdrh ** CREATE INDEX i3 ON t1(c);
20936f82e85aSdrh **
20946f82e85aSdrh ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
20956f82e85aSdrh **
20966f82e85aSdrh ** In the example, there are three indexed terms connected by OR.
20976f82e85aSdrh ** The top of the loop looks like this:
20986f82e85aSdrh **
20996f82e85aSdrh ** Null 1 # Zero the rowset in reg 1
21006f82e85aSdrh **
21016f82e85aSdrh ** Then, for each indexed term, the following. The arguments to
21026f82e85aSdrh ** RowSetTest are such that the rowid of the current row is inserted
21036f82e85aSdrh ** into the RowSet. If it is already present, control skips the
21046f82e85aSdrh ** Gosub opcode and jumps straight to the code generated by WhereEnd().
21056f82e85aSdrh **
21066f82e85aSdrh ** sqlite3WhereBegin(<term>)
21076f82e85aSdrh ** RowSetTest # Insert rowid into rowset
21086f82e85aSdrh ** Gosub 2 A
21096f82e85aSdrh ** sqlite3WhereEnd()
21106f82e85aSdrh **
21116f82e85aSdrh ** Following the above, code to terminate the loop. Label A, the target
21126f82e85aSdrh ** of the Gosub above, jumps to the instruction right after the Goto.
21136f82e85aSdrh **
21146f82e85aSdrh ** Null 1 # Zero the rowset in reg 1
21156f82e85aSdrh ** Goto B # The loop is finished.
21166f82e85aSdrh **
21176f82e85aSdrh ** A: <loop body> # Return data, whatever.
21186f82e85aSdrh **
21196f82e85aSdrh ** Return 2 # Jump back to the Gosub
21206f82e85aSdrh **
21216f82e85aSdrh ** B: <after the loop>
21226f82e85aSdrh **
21236f82e85aSdrh ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
21246f82e85aSdrh ** use an ephemeral index instead of a RowSet to record the primary
21256f82e85aSdrh ** keys of the rows we have already seen.
21266f82e85aSdrh **
21276f82e85aSdrh */
21286f82e85aSdrh WhereClause *pOrWc; /* The OR-clause broken out into subterms */
21296f82e85aSdrh SrcList *pOrTab; /* Shortened table list or OR-clause generation */
21306f82e85aSdrh Index *pCov = 0; /* Potential covering index (or NULL) */
21316f82e85aSdrh int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
21326f82e85aSdrh
21336f82e85aSdrh int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
21346f82e85aSdrh int regRowset = 0; /* Register for RowSet object */
21356f82e85aSdrh int regRowid = 0; /* Register holding rowid */
2136ec4ccdbcSdrh int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
21376f82e85aSdrh int iRetInit; /* Address of regReturn init */
21386f82e85aSdrh int untestedTerms = 0; /* Some terms not completely tested */
21396f82e85aSdrh int ii; /* Loop counter */
21406f82e85aSdrh Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
21416f82e85aSdrh Table *pTab = pTabItem->pTab;
21426f82e85aSdrh
21436f82e85aSdrh pTerm = pLoop->aLTerm[0];
21446f82e85aSdrh assert( pTerm!=0 );
21456f82e85aSdrh assert( pTerm->eOperator & WO_OR );
21466f82e85aSdrh assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
21476f82e85aSdrh pOrWc = &pTerm->u.pOrInfo->wc;
21486f82e85aSdrh pLevel->op = OP_Return;
21496f82e85aSdrh pLevel->p1 = regReturn;
21506f82e85aSdrh
21516f82e85aSdrh /* Set up a new SrcList in pOrTab containing the table being scanned
21526f82e85aSdrh ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
21536f82e85aSdrh ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
21546f82e85aSdrh */
21556f82e85aSdrh if( pWInfo->nLevel>1 ){
21566f82e85aSdrh int nNotReady; /* The number of notReady tables */
21577601294aSdrh SrcItem *origSrc; /* Original list of tables */
21586f82e85aSdrh nNotReady = pWInfo->nLevel - iLevel - 1;
2159135c9ff6Sdrh pOrTab = sqlite3DbMallocRawNN(db,
21606f82e85aSdrh sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
21616f82e85aSdrh if( pOrTab==0 ) return notReady;
21626f82e85aSdrh pOrTab->nAlloc = (u8)(nNotReady + 1);
21636f82e85aSdrh pOrTab->nSrc = pOrTab->nAlloc;
21646f82e85aSdrh memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
21656f82e85aSdrh origSrc = pWInfo->pTabList->a;
21666f82e85aSdrh for(k=1; k<=nNotReady; k++){
21676f82e85aSdrh memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
21686f82e85aSdrh }
21696f82e85aSdrh }else{
21706f82e85aSdrh pOrTab = pWInfo->pTabList;
21716f82e85aSdrh }
21726f82e85aSdrh
21736f82e85aSdrh /* Initialize the rowset register to contain NULL. An SQL NULL is
21746f82e85aSdrh ** equivalent to an empty rowset. Or, create an ephemeral index
21756f82e85aSdrh ** capable of holding primary keys in the case of a WITHOUT ROWID.
21766f82e85aSdrh **
21776f82e85aSdrh ** Also initialize regReturn to contain the address of the instruction
21786f82e85aSdrh ** immediately following the OP_Return at the bottom of the loop. This
21796f82e85aSdrh ** is required in a few obscure LEFT JOIN cases where control jumps
21806f82e85aSdrh ** over the top of the loop into the body of it. In this case the
21816f82e85aSdrh ** correct response for the end-of-loop code (the OP_Return) is to
21826f82e85aSdrh ** fall through to the next instruction, just as an OP_Next does if
21836f82e85aSdrh ** called on an uninitialized cursor.
21846f82e85aSdrh */
21856f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
21866f82e85aSdrh if( HasRowid(pTab) ){
21876f82e85aSdrh regRowset = ++pParse->nMem;
21886f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
21896f82e85aSdrh }else{
21906f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab);
21916f82e85aSdrh regRowset = pParse->nTab++;
21926f82e85aSdrh sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
21936f82e85aSdrh sqlite3VdbeSetP4KeyInfo(pParse, pPk);
21946f82e85aSdrh }
21956f82e85aSdrh regRowid = ++pParse->nMem;
21966f82e85aSdrh }
21976f82e85aSdrh iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
21986f82e85aSdrh
21996f82e85aSdrh /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
220002e3e041Sdrh ** Then for every term xN, evaluate as the subexpression: xN AND y
22016f82e85aSdrh ** That way, terms in y that are factored into the disjunction will
22026f82e85aSdrh ** be picked up by the recursive calls to sqlite3WhereBegin() below.
22036f82e85aSdrh **
22046f82e85aSdrh ** Actually, each subexpression is converted to "xN AND w" where w is
22056f82e85aSdrh ** the "interesting" terms of z - terms that did not originate in the
22066f82e85aSdrh ** ON or USING clause of a LEFT JOIN, and terms that are usable as
22076f82e85aSdrh ** indices.
22086f82e85aSdrh **
22096f82e85aSdrh ** This optimization also only applies if the (x1 OR x2 OR ...) term
22106f82e85aSdrh ** is not contained in the ON clause of a LEFT JOIN.
22116f82e85aSdrh ** See ticket http://www.sqlite.org/src/info/f2369304e4
221202e3e041Sdrh **
221302e3e041Sdrh ** 2022-02-04: Do not push down slices of a row-value comparison.
221402e3e041Sdrh ** In other words, "w" or "y" may not be a slice of a vector. Otherwise,
221502e3e041Sdrh ** the initialization of the right-hand operand of the vector comparison
221602e3e041Sdrh ** might not occur, or might occur only in an OR branch that is not
221702e3e041Sdrh ** taken. dbsqlfuzz 80a9fade844b4fb43564efc972bcb2c68270f5d1.
2218c9bcc5aaSdrh **
2219c9bcc5aaSdrh ** 2022-03-03: Do not push down expressions that involve subqueries.
2220c9bcc5aaSdrh ** The subquery might get coded as a subroutine. Any table-references
2221c9bcc5aaSdrh ** in the subquery might be resolved to index-references for the index on
2222c9bcc5aaSdrh ** the OR branch in which the subroutine is coded. But if the subroutine
2223c9bcc5aaSdrh ** is invoked from a different OR branch that uses a different index, such
2224c9bcc5aaSdrh ** index-references will not work. tag-20220303a
2225c9bcc5aaSdrh ** https://sqlite.org/forum/forumpost/36937b197273d403
22266f82e85aSdrh */
22276f82e85aSdrh if( pWC->nTerm>1 ){
22286f82e85aSdrh int iTerm;
22296f82e85aSdrh for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
22306f82e85aSdrh Expr *pExpr = pWC->a[iTerm].pExpr;
22316f82e85aSdrh if( &pWC->a[iTerm] == pTerm ) continue;
22323b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
22333b83f0cdSdrh testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
223402e3e041Sdrh testcase( pWC->a[iTerm].wtFlags & TERM_SLICE );
223502e3e041Sdrh if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED|TERM_SLICE))!=0 ){
223602e3e041Sdrh continue;
223702e3e041Sdrh }
223807559b27Sdrh if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
2239c9bcc5aaSdrh if( ExprHasProperty(pExpr, EP_Subquery) ) continue; /* tag-20220303a */
22406f82e85aSdrh pExpr = sqlite3ExprDup(db, pExpr, 0);
2241d5c851c1Sdrh pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);
22426f82e85aSdrh }
22436f82e85aSdrh if( pAndExpr ){
2244f1722baaSdrh /* The extra 0x10000 bit on the opcode is masked off and does not
2245f1722baaSdrh ** become part of the new Expr.op. However, it does make the
2246f1722baaSdrh ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
224793ffb50fSdrh ** prevents sqlite3PExpr() from applying the AND short-circuit
2248f1722baaSdrh ** optimization, which we do not want here. */
2249f1722baaSdrh pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
22506f82e85aSdrh }
22516f82e85aSdrh }
22526f82e85aSdrh
22536f82e85aSdrh /* Run a separate WHERE clause for each term of the OR clause. After
22546f82e85aSdrh ** eliminating duplicates from other WHERE clauses, the action for each
22556f82e85aSdrh ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
22566f82e85aSdrh */
22575d72d924Sdrh ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
22586f82e85aSdrh for(ii=0; ii<pOrWc->nTerm; ii++){
22596f82e85aSdrh WhereTerm *pOrTerm = &pOrWc->a[ii];
22606f82e85aSdrh if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
22616f82e85aSdrh WhereInfo *pSubWInfo; /* Info for single OR-term scan */
22626f82e85aSdrh Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
226393ffb50fSdrh Expr *pDelete; /* Local copy of OR clause term */
2264728e0f91Sdrh int jmp1 = 0; /* Address of jump operation */
22653b8eb08bSdrh testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0
226667a99dbeSdrh && !ExprHasProperty(pOrExpr, EP_OuterON)
22673b8eb08bSdrh ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
226893ffb50fSdrh pDelete = pOrExpr = sqlite3ExprDup(db, pOrExpr, 0);
226993ffb50fSdrh if( db->mallocFailed ){
227093ffb50fSdrh sqlite3ExprDelete(db, pDelete);
227193ffb50fSdrh continue;
227293ffb50fSdrh }
2273820fcd2cSdan if( pAndExpr ){
22746f82e85aSdrh pAndExpr->pLeft = pOrExpr;
22756f82e85aSdrh pOrExpr = pAndExpr;
22766f82e85aSdrh }
22776f82e85aSdrh /* Loop through table entries that match term pOrTerm. */
2278bd462bccSdrh ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
22796f82e85aSdrh WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
2280895bab33Sdrh pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 0,
228168c0c710Sdrh WHERE_OR_SUBCLAUSE, iCovCur);
22820c7d3d39Sdrh assert( pSubWInfo || pParse->nErr );
22836f82e85aSdrh if( pSubWInfo ){
22846f82e85aSdrh WhereLoop *pSubLoop;
22856f82e85aSdrh int addrExplain = sqlite3WhereExplainOneScan(
2286e2188f0bSdrh pParse, pOrTab, &pSubWInfo->a[0], 0
22876f82e85aSdrh );
22886f82e85aSdrh sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
22896f82e85aSdrh
22906f82e85aSdrh /* This is the sub-WHERE clause body. First skip over
22916f82e85aSdrh ** duplicate rows from prior sub-WHERE clauses, and record the
22926f82e85aSdrh ** rowid (or PRIMARY KEY) for the current row so that the same
22936f82e85aSdrh ** row will be skipped in subsequent sub-WHERE clauses.
22946f82e85aSdrh */
22956f82e85aSdrh if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
22966f82e85aSdrh int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
22976f82e85aSdrh if( HasRowid(pTab) ){
22986df9c4b9Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
2299728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
23008c607191Sdrh regRowid, iSet);
23016f82e85aSdrh VdbeCoverage(v);
23026f82e85aSdrh }else{
23036f82e85aSdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab);
23046f82e85aSdrh int nPk = pPk->nKeyCol;
23056f82e85aSdrh int iPk;
23068c607191Sdrh int r;
23076f82e85aSdrh
23086f82e85aSdrh /* Read the PK into an array of temp registers. */
23096f82e85aSdrh r = sqlite3GetTempRange(pParse, nPk);
23106f82e85aSdrh for(iPk=0; iPk<nPk; iPk++){
23116f82e85aSdrh int iCol = pPk->aiColumn[iPk];
23126df9c4b9Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
23136f82e85aSdrh }
23146f82e85aSdrh
23156f82e85aSdrh /* Check if the temp table already contains this key. If so,
23166f82e85aSdrh ** the row has already been included in the result set and
23176f82e85aSdrh ** can be ignored (by jumping past the Gosub below). Otherwise,
23186f82e85aSdrh ** insert the key into the temp table and proceed with processing
23196f82e85aSdrh ** the row.
23206f82e85aSdrh **
23216f82e85aSdrh ** Use some of the same optimizations as OP_RowSetTest: If iSet
23226f82e85aSdrh ** is zero, assume that the key cannot already be present in
23236f82e85aSdrh ** the temp table. And if iSet is -1, assume that there is no
23246f82e85aSdrh ** need to insert the key into the temp table, as it will never
23256f82e85aSdrh ** be tested for. */
23266f82e85aSdrh if( iSet ){
2327728e0f91Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
23286f82e85aSdrh VdbeCoverage(v);
23296f82e85aSdrh }
23306f82e85aSdrh if( iSet>=0 ){
23316f82e85aSdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
23329b4eaebcSdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
23339b4eaebcSdrh r, nPk);
23346f82e85aSdrh if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
23356f82e85aSdrh }
23366f82e85aSdrh
23376f82e85aSdrh /* Release the array of temp registers */
23386f82e85aSdrh sqlite3ReleaseTempRange(pParse, r, nPk);
23396f82e85aSdrh }
23406f82e85aSdrh }
23416f82e85aSdrh
23426f82e85aSdrh /* Invoke the main loop body as a subroutine */
23436f82e85aSdrh sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
23446f82e85aSdrh
23456f82e85aSdrh /* Jump here (skipping the main loop body subroutine) if the
23466f82e85aSdrh ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
2347728e0f91Sdrh if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
23486f82e85aSdrh
23496f82e85aSdrh /* The pSubWInfo->untestedTerms flag means that this OR term
23506f82e85aSdrh ** contained one or more AND term from a notReady table. The
23516f82e85aSdrh ** terms from the notReady table could not be tested and will
23526f82e85aSdrh ** need to be tested later.
23536f82e85aSdrh */
23546f82e85aSdrh if( pSubWInfo->untestedTerms ) untestedTerms = 1;
23556f82e85aSdrh
23566f82e85aSdrh /* If all of the OR-connected terms are optimized using the same
23576f82e85aSdrh ** index, and the index is opened using the same cursor number
23586f82e85aSdrh ** by each call to sqlite3WhereBegin() made by this loop, it may
23596f82e85aSdrh ** be possible to use that index as a covering index.
23606f82e85aSdrh **
23616f82e85aSdrh ** If the call to sqlite3WhereBegin() above resulted in a scan that
23626f82e85aSdrh ** uses an index, and this is either the first OR-connected term
23636f82e85aSdrh ** processed or the index is the same as that used by all previous
23646f82e85aSdrh ** terms, set pCov to the candidate covering index. Otherwise, set
23656f82e85aSdrh ** pCov to NULL to indicate that no candidate covering index will
23666f82e85aSdrh ** be available.
23676f82e85aSdrh */
23686f82e85aSdrh pSubLoop = pSubWInfo->a[0].pWLoop;
23696f82e85aSdrh assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
23706f82e85aSdrh if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
23716f82e85aSdrh && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
23726f82e85aSdrh && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
23736f82e85aSdrh ){
23746f82e85aSdrh assert( pSubWInfo->a[0].iIdxCur==iCovCur );
23756f82e85aSdrh pCov = pSubLoop->u.btree.pIndex;
23766f82e85aSdrh }else{
23776f82e85aSdrh pCov = 0;
23786f82e85aSdrh }
237968c0c710Sdrh if( sqlite3WhereUsesDeferredSeek(pSubWInfo) ){
238068c0c710Sdrh pWInfo->bDeferredSeek = 1;
238168c0c710Sdrh }
23826f82e85aSdrh
23836f82e85aSdrh /* Finish the loop through table entries that match term pOrTerm. */
23846f82e85aSdrh sqlite3WhereEnd(pSubWInfo);
2385bd462bccSdrh ExplainQueryPlanPop(pParse);
23866f82e85aSdrh }
238793ffb50fSdrh sqlite3ExprDelete(db, pDelete);
23886f82e85aSdrh }
23896f82e85aSdrh }
23905d72d924Sdrh ExplainQueryPlanPop(pParse);
23910475629dSdrh assert( pLevel->pWLoop==pLoop );
23920475629dSdrh assert( (pLoop->wsFlags & WHERE_MULTI_OR)!=0 );
23930475629dSdrh assert( (pLoop->wsFlags & WHERE_IN_ABLE)==0 );
23940475629dSdrh pLevel->u.pCoveringIdx = pCov;
23956f82e85aSdrh if( pCov ) pLevel->iIdxCur = iCovCur;
23966f82e85aSdrh if( pAndExpr ){
23976f82e85aSdrh pAndExpr->pLeft = 0;
23986f82e85aSdrh sqlite3ExprDelete(db, pAndExpr);
23996f82e85aSdrh }
24006f82e85aSdrh sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
2401076e85f5Sdrh sqlite3VdbeGoto(v, pLevel->addrBrk);
24026f82e85aSdrh sqlite3VdbeResolveLabel(v, iLoopBody);
24036f82e85aSdrh
2404e603ab00Sdrh /* Set the P2 operand of the OP_Return opcode that will end the current
2405e603ab00Sdrh ** loop to point to this spot, which is the top of the next containing
2406e603ab00Sdrh ** loop. The byte-code formatter will use that P2 value as a hint to
2407e603ab00Sdrh ** indent everything in between the this point and the final OP_Return.
2408e603ab00Sdrh ** See tag-20220407a in vdbe.c and shell.c */
2409e603ab00Sdrh assert( pLevel->op==OP_Return );
2410e603ab00Sdrh pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2411e603ab00Sdrh
2412135c9ff6Sdrh if( pWInfo->nLevel>1 ){ sqlite3DbFreeNN(db, pOrTab); }
24136f82e85aSdrh if( !untestedTerms ) disableTerm(pLevel, pTerm);
24146f82e85aSdrh }else
24156f82e85aSdrh #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
24166f82e85aSdrh
24176f82e85aSdrh {
24186f82e85aSdrh /* Case 6: There is no usable index. We must do a complete
24196f82e85aSdrh ** scan of the entire table.
24206f82e85aSdrh */
24216f82e85aSdrh static const u8 aStep[] = { OP_Next, OP_Prev };
24226f82e85aSdrh static const u8 aStart[] = { OP_Rewind, OP_Last };
24236f82e85aSdrh assert( bRev==0 || bRev==1 );
24248a48b9c0Sdrh if( pTabItem->fg.isRecursive ){
24256f82e85aSdrh /* Tables marked isRecursive have only a single row that is stored in
24266f82e85aSdrh ** a pseudo-cursor. No need to Rewind or Next such cursors. */
24276f82e85aSdrh pLevel->op = OP_Noop;
24286f82e85aSdrh }else{
2429b324cf75Sdan codeCursorHint(pTabItem, pWInfo, pLevel, 0);
24306f82e85aSdrh pLevel->op = aStep[bRev];
24316f82e85aSdrh pLevel->p1 = iCur;
24323a3b420aSdrh pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
24336f82e85aSdrh VdbeCoverageIf(v, bRev==0);
24346f82e85aSdrh VdbeCoverageIf(v, bRev!=0);
24356f82e85aSdrh pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
24366f82e85aSdrh }
24376f82e85aSdrh }
24386f82e85aSdrh
24396f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
24406f82e85aSdrh pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
24416f82e85aSdrh #endif
24426f82e85aSdrh
24436f82e85aSdrh /* Insert code to test every subexpression that can be completely
24446f82e85aSdrh ** computed using the current set of tables.
24456f654a40Sdan **
2446ebc63013Sdan ** This loop may run between one and three times, depending on the
2447ebc63013Sdan ** constraints to be generated. The value of stack variable iLoop
2448ebc63013Sdan ** determines the constraints coded by each iteration, as follows:
2449ebc63013Sdan **
2450ebc63013Sdan ** iLoop==1: Code only expressions that are entirely covered by pIdx.
2451ebc63013Sdan ** iLoop==2: Code remaining expressions that do not contain correlated
2452ebc63013Sdan ** sub-queries.
2453ebc63013Sdan ** iLoop==3: Code all remaining expressions.
2454ebc63013Sdan **
2455ebc63013Sdan ** An effort is made to skip unnecessary iterations of the loop.
24566ab3eb5dSdrh */
2457ebc63013Sdan iLoop = (pIdx ? 1 : 2);
24586ab3eb5dSdrh do{
2459ebc63013Sdan int iNext = 0; /* Next value for iLoop */
24606f82e85aSdrh for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
24616f82e85aSdrh Expr *pE;
24626f82e85aSdrh int skipLikeAddr = 0;
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 testcase( pWInfo->untestedTerms==0
2468ce943bc8Sdrh && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
24696f82e85aSdrh pWInfo->untestedTerms = 1;
24706f82e85aSdrh continue;
24716f82e85aSdrh }
24726f82e85aSdrh pE = pTerm->pExpr;
24736f82e85aSdrh assert( pE!=0 );
2474c93bf1d4Sdrh if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){
2475c93bf1d4Sdrh if( !ExprHasProperty(pE,EP_OuterON|EP_InnerON) ){
2476767bc8deSdrh /* Defer processing WHERE clause constraints until after outer
2477767bc8deSdrh ** join processing. tag-20220513a */
24786f654a40Sdan continue;
2479404bf6baSdrh }else if( (pTabItem->fg.jointype & JT_LEFT)==JT_LEFT
2480404bf6baSdrh && !ExprHasProperty(pE,EP_OuterON) ){
2481c93bf1d4Sdrh continue;
2482c9dfe2b8Sdrh }else{
2483c9dfe2b8Sdrh Bitmask m = sqlite3WhereGetMask(&pWInfo->sMaskSet, pE->w.iJoin);
2484c9dfe2b8Sdrh if( m & pLevel->notReady ){
2485c9dfe2b8Sdrh /* An ON clause that is not ripe */
2486c9dfe2b8Sdrh continue;
2487c9dfe2b8Sdrh }
24886f654a40Sdan }
2489c93bf1d4Sdrh }
24908674ec5aSdan if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
2491ebc63013Sdan iNext = 2;
24926f82e85aSdrh continue;
24936f82e85aSdrh }
2494d3930b12Sdan if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
2495ebc63013Sdan if( iNext==0 ) iNext = 3;
2496ebc63013Sdan continue;
2497ebc63013Sdan }
2498ebc63013Sdan
24994de3353dSdrh if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
250044aebff2Sdrh /* If the TERM_LIKECOND flag is set, that means that the range search
250144aebff2Sdrh ** is sufficient to guarantee that the LIKE operator is true, so we
250244aebff2Sdrh ** can skip the call to the like(A,B) function. But this only works
250344aebff2Sdrh ** for strings. So do not skip the call to the function on the pass
250444aebff2Sdrh ** that compares BLOBs. */
250541d2e66eSdrh #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
250641d2e66eSdrh continue;
250741d2e66eSdrh #else
250844aebff2Sdrh u32 x = pLevel->iLikeRepCntr;
25094de3353dSdrh if( x>0 ){
251044aebff2Sdrh skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
25116f88359dSdrh VdbeCoverageIf(v, (x&1)==1);
25126f88359dSdrh VdbeCoverageIf(v, (x&1)==0);
25134de3353dSdrh }
251441d2e66eSdrh #endif
25156f82e85aSdrh }
251666a0bf31Sdrh #ifdef WHERETRACE_ENABLED /* 0xffff */
251766a0bf31Sdrh if( sqlite3WhereTrace ){
251866a0bf31Sdrh VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
251966a0bf31Sdrh pWC->nTerm-j, pTerm, iLoop));
252066a0bf31Sdrh }
2521118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){
2522118efd16Sdrh sqlite3DebugPrintf("Coding auxiliary constraint:\n");
2523118efd16Sdrh sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
2524118efd16Sdrh }
252566a0bf31Sdrh #endif
25266f82e85aSdrh sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
25276f82e85aSdrh if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
25286f82e85aSdrh pTerm->wtFlags |= TERM_CODED;
25296f82e85aSdrh }
2530ebc63013Sdan iLoop = iNext;
2531ebc63013Sdan }while( iLoop>0 );
25326f82e85aSdrh
25336f82e85aSdrh /* Insert code to test for implied constraints based on transitivity
25346f82e85aSdrh ** of the "==" operator.
25356f82e85aSdrh **
25366f82e85aSdrh ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
25376f82e85aSdrh ** and we are coding the t1 loop and the t2 loop has not yet coded,
25386f82e85aSdrh ** then we cannot use the "t1.a=t2.b" constraint, but we can code
25396f82e85aSdrh ** the implied "t1.a=123" constraint.
25406f82e85aSdrh */
2541132f96fcSdrh for(pTerm=pWC->a, j=pWC->nBase; j>0; j--, pTerm++){
2542cb43a937Sdrh Expr *pE, sEAlt;
25436f82e85aSdrh WhereTerm *pAlt;
25446f82e85aSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
25456f82e85aSdrh if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
25466f82e85aSdrh if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
25476f82e85aSdrh if( pTerm->leftCursor!=iCur ) continue;
2548556527a1Sdrh if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ) continue;
25496f82e85aSdrh pE = pTerm->pExpr;
2550118efd16Sdrh #ifdef WHERETRACE_ENABLED /* 0x800 */
2551118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){
2552118efd16Sdrh sqlite3DebugPrintf("Coding transitive constraint:\n");
2553118efd16Sdrh sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
2554118efd16Sdrh }
2555118efd16Sdrh #endif
255667a99dbeSdrh assert( !ExprHasProperty(pE, EP_OuterON) );
25576f82e85aSdrh assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
2558220f0d6fSdrh assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
255975fa2663Sdrh pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
25606f82e85aSdrh WO_EQ|WO_IN|WO_IS, 0);
25616f82e85aSdrh if( pAlt==0 ) continue;
25626f82e85aSdrh if( pAlt->wtFlags & (TERM_CODED) ) continue;
2563a916b570Sdan if( (pAlt->eOperator & WO_IN)
2564a4eeccdfSdrh && ExprUseXSelect(pAlt->pExpr)
2565a599e150Sdrh && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
2566a916b570Sdan ){
2567a916b570Sdan continue;
2568a916b570Sdan }
25696f82e85aSdrh testcase( pAlt->eOperator & WO_EQ );
25706f82e85aSdrh testcase( pAlt->eOperator & WO_IS );
25716f82e85aSdrh testcase( pAlt->eOperator & WO_IN );
25726f82e85aSdrh VdbeModuleComment((v, "begin transitive constraint"));
2573cb43a937Sdrh sEAlt = *pAlt->pExpr;
2574cb43a937Sdrh sEAlt.pLeft = pE->pLeft;
2575cb43a937Sdrh sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
2576240e36c0Sdan pAlt->wtFlags |= TERM_CODED;
25776f82e85aSdrh }
25786f82e85aSdrh
2579c2308ad2Sdrh /* For a RIGHT OUTER JOIN, record the fact that the current row has
2580c2308ad2Sdrh ** been matched at least once.
2581c2308ad2Sdrh */
25827c1734b0Sdrh if( pLevel->pRJ ){
2583c2308ad2Sdrh Table *pTab;
2584c2308ad2Sdrh int nPk;
2585c2308ad2Sdrh int r;
2586c2308ad2Sdrh int jmp1 = 0;
25877c1734b0Sdrh WhereRightJoin *pRJ = pLevel->pRJ;
2588c2308ad2Sdrh
25897c1734b0Sdrh /* pTab is the right-hand table of the RIGHT JOIN. Generate code that
25907c1734b0Sdrh ** will record that the current row of that table has been matched at
25917c1734b0Sdrh ** least once. This is accomplished by storing the PK for the row in
25927c1734b0Sdrh ** both the iMatch index and the regBloom Bloom filter.
25937c1734b0Sdrh */
2594c2308ad2Sdrh pTab = pWInfo->pTabList->a[pLevel->iFrom].pTab;
2595c2308ad2Sdrh if( HasRowid(pTab) ){
2596c2308ad2Sdrh r = sqlite3GetTempRange(pParse, 2);
2597c2308ad2Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, pLevel->iTabCur, -1, r+1);
2598c2308ad2Sdrh nPk = 1;
2599c2308ad2Sdrh }else{
2600c2308ad2Sdrh int iPk;
2601c2308ad2Sdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab);
2602c2308ad2Sdrh nPk = pPk->nKeyCol;
2603c2308ad2Sdrh r = sqlite3GetTempRange(pParse, nPk+1);
2604c2308ad2Sdrh for(iPk=0; iPk<nPk; iPk++){
2605c2308ad2Sdrh int iCol = pPk->aiColumn[iPk];
2606c2308ad2Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+1+iPk);
2607c2308ad2Sdrh }
2608c2308ad2Sdrh }
26097c1734b0Sdrh jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
2610c2308ad2Sdrh VdbeCoverage(v);
26112e1bcc9dSdrh VdbeComment((v, "match against %s", pTab->zName));
2612c2308ad2Sdrh sqlite3VdbeAddOp3(v, OP_MakeRecord, r+1, nPk, r);
26137c1734b0Sdrh sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
26147c1734b0Sdrh sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
2615c2308ad2Sdrh sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2616c2308ad2Sdrh sqlite3VdbeJumpHere(v, jmp1);
2617c2308ad2Sdrh sqlite3ReleaseTempRange(pParse, r, nPk+1);
26182e1bcc9dSdrh }
26197c1734b0Sdrh
26202e1bcc9dSdrh /* For a LEFT OUTER JOIN, generate code that will record the fact that
26212e1bcc9dSdrh ** at least one row of the right table has matched the left table.
26222e1bcc9dSdrh */
26232e1bcc9dSdrh if( pLevel->iLeftJoin ){
26242e1bcc9dSdrh pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
26252e1bcc9dSdrh sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
26262e1bcc9dSdrh VdbeComment((v, "record LEFT JOIN hit"));
2627767bc8deSdrh if( pLevel->pRJ==0 ){
2628767bc8deSdrh goto code_outer_join_constraints; /* WHERE clause constraints */
26292e1bcc9dSdrh }
26302e1bcc9dSdrh }
26312e1bcc9dSdrh
26322e1bcc9dSdrh if( pLevel->pRJ ){
26337c1734b0Sdrh /* Create a subroutine used to process all interior loops and code
26347c1734b0Sdrh ** of the RIGHT JOIN. During normal operation, the subroutine will
26357c1734b0Sdrh ** be in-line with the rest of the code. But at the end, a separate
26367c1734b0Sdrh ** loop will run that invokes this subroutine for unmatched rows
26377c1734b0Sdrh ** of pTab, with all tables to left begin set to NULL.
26387c1734b0Sdrh */
26392e1bcc9dSdrh WhereRightJoin *pRJ = pLevel->pRJ;
26407c1734b0Sdrh sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pRJ->regReturn);
26417c1734b0Sdrh pRJ->addrSubrtn = sqlite3VdbeCurrentAddr(v);
26422c31c00bSdrh assert( pParse->withinRJSubrtn < 255 );
26432c31c00bSdrh pParse->withinRJSubrtn++;
2644767bc8deSdrh
2645767bc8deSdrh /* WHERE clause constraints must be deferred until after outer join
2646767bc8deSdrh ** row elimination has completed, since WHERE clause constraints apply
2647767bc8deSdrh ** to the results of the OUTER JOIN. The following loop generates the
2648767bc8deSdrh ** appropriate WHERE clause constraint checks. tag-20220513a.
2649767bc8deSdrh */
2650767bc8deSdrh code_outer_join_constraints:
2651767bc8deSdrh for(pTerm=pWC->a, j=0; j<pWC->nBase; j++, pTerm++){
2652767bc8deSdrh testcase( pTerm->wtFlags & TERM_VIRTUAL );
2653767bc8deSdrh testcase( pTerm->wtFlags & TERM_CODED );
2654767bc8deSdrh if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
2655767bc8deSdrh if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
2656767bc8deSdrh assert( pWInfo->untestedTerms );
2657767bc8deSdrh continue;
2658767bc8deSdrh }
2659767bc8deSdrh if( pTabItem->fg.jointype & JT_LTORJ ) continue;
2660767bc8deSdrh assert( pTerm->pExpr );
2661767bc8deSdrh sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
2662767bc8deSdrh pTerm->wtFlags |= TERM_CODED;
2663767bc8deSdrh }
2664c2308ad2Sdrh }
2665c2308ad2Sdrh
2666118efd16Sdrh #if WHERETRACE_ENABLED /* 0x20800 */
2667118efd16Sdrh if( sqlite3WhereTrace & 0x20000 ){
2668f1bb31e2Sdrh sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
2669f1bb31e2Sdrh iLevel);
2670118efd16Sdrh sqlite3WhereClausePrint(pWC);
2671118efd16Sdrh }
2672118efd16Sdrh if( sqlite3WhereTrace & 0x800 ){
2673118efd16Sdrh sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n",
2674118efd16Sdrh iLevel, (u64)pLevel->notReady);
2675118efd16Sdrh }
2676118efd16Sdrh #endif
26776f82e85aSdrh return pLevel->notReady;
26786f82e85aSdrh }
2679949e2ab4Sdrh
2680949e2ab4Sdrh /*
2681949e2ab4Sdrh ** Generate the code for the loop that finds all non-matched terms
2682949e2ab4Sdrh ** for a RIGHT JOIN.
2683949e2ab4Sdrh */
sqlite3WhereRightJoinLoop(WhereInfo * pWInfo,int iLevel,WhereLevel * pLevel)2684949e2ab4Sdrh SQLITE_NOINLINE void sqlite3WhereRightJoinLoop(
2685949e2ab4Sdrh WhereInfo *pWInfo,
2686949e2ab4Sdrh int iLevel,
2687949e2ab4Sdrh WhereLevel *pLevel
2688949e2ab4Sdrh ){
2689949e2ab4Sdrh Parse *pParse = pWInfo->pParse;
2690949e2ab4Sdrh Vdbe *v = pParse->pVdbe;
2691949e2ab4Sdrh WhereRightJoin *pRJ = pLevel->pRJ;
2692949e2ab4Sdrh Expr *pSubWhere = 0;
2693949e2ab4Sdrh WhereClause *pWC = &pWInfo->sWC;
2694949e2ab4Sdrh WhereInfo *pSubWInfo;
2695949e2ab4Sdrh WhereLoop *pLoop = pLevel->pWLoop;
2696949e2ab4Sdrh SrcItem *pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
2697949e2ab4Sdrh SrcList sFrom;
2698949e2ab4Sdrh Bitmask mAll = 0;
2699949e2ab4Sdrh int k;
2700949e2ab4Sdrh
2701f7ecd956Sdrh ExplainQueryPlan((pParse, 1, "RIGHT-JOIN %s", pTabItem->pTab->zName));
2702b77c3129Sdrh sqlite3VdbeNoJumpsOutsideSubrtn(v, pRJ->addrSubrtn, pRJ->endSubrtn,
2703b77c3129Sdrh pRJ->regReturn);
2704949e2ab4Sdrh for(k=0; k<iLevel; k++){
2705949e2ab4Sdrh int iIdxCur;
2706949e2ab4Sdrh mAll |= pWInfo->a[k].pWLoop->maskSelf;
2707949e2ab4Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, pWInfo->a[k].iTabCur);
2708949e2ab4Sdrh iIdxCur = pWInfo->a[k].iIdxCur;
2709949e2ab4Sdrh if( iIdxCur ){
2710949e2ab4Sdrh sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur);
2711949e2ab4Sdrh }
2712949e2ab4Sdrh }
27137348ca4eSdrh if( (pTabItem->fg.jointype & JT_LTORJ)==0 ){
2714949e2ab4Sdrh mAll |= pLoop->maskSelf;
2715949e2ab4Sdrh for(k=0; k<pWC->nTerm; k++){
2716949e2ab4Sdrh WhereTerm *pTerm = &pWC->a[k];
27170f4b534bSdrh if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_SLICE))!=0
27180f4b534bSdrh && pTerm->eOperator!=WO_ROWVAL
27190f4b534bSdrh ){
27200f4b534bSdrh break;
27210f4b534bSdrh }
2722949e2ab4Sdrh if( pTerm->prereqAll & ~mAll ) continue;
272367a99dbeSdrh if( ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON) ) continue;
2724949e2ab4Sdrh pSubWhere = sqlite3ExprAnd(pParse, pSubWhere,
2725949e2ab4Sdrh sqlite3ExprDup(pParse->db, pTerm->pExpr, 0));
2726949e2ab4Sdrh }
27272e1bcc9dSdrh }
2728949e2ab4Sdrh sFrom.nSrc = 1;
2729949e2ab4Sdrh sFrom.nAlloc = 1;
2730949e2ab4Sdrh memcpy(&sFrom.a[0], pTabItem, sizeof(SrcItem));
2731949e2ab4Sdrh sFrom.a[0].fg.jointype = 0;
2732503ad9c7Sdrh assert( pParse->withinRJSubrtn < 100 );
2733503ad9c7Sdrh pParse->withinRJSubrtn++;
2734949e2ab4Sdrh pSubWInfo = sqlite3WhereBegin(pParse, &sFrom, pSubWhere, 0, 0, 0,
2735949e2ab4Sdrh WHERE_RIGHT_JOIN, 0);
2736949e2ab4Sdrh if( pSubWInfo ){
2737949e2ab4Sdrh int iCur = pLevel->iTabCur;
2738949e2ab4Sdrh int r = ++pParse->nMem;
2739949e2ab4Sdrh int nPk;
2740949e2ab4Sdrh int jmp;
2741949e2ab4Sdrh int addrCont = sqlite3WhereContinueLabel(pSubWInfo);
2742949e2ab4Sdrh Table *pTab = pTabItem->pTab;
2743949e2ab4Sdrh if( HasRowid(pTab) ){
2744949e2ab4Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r);
2745949e2ab4Sdrh nPk = 1;
2746949e2ab4Sdrh }else{
2747949e2ab4Sdrh int iPk;
2748949e2ab4Sdrh Index *pPk = sqlite3PrimaryKeyIndex(pTab);
2749949e2ab4Sdrh nPk = pPk->nKeyCol;
2750949e2ab4Sdrh pParse->nMem += nPk - 1;
2751949e2ab4Sdrh for(iPk=0; iPk<nPk; iPk++){
2752949e2ab4Sdrh int iCol = pPk->aiColumn[iPk];
2753949e2ab4Sdrh sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
2754949e2ab4Sdrh }
2755949e2ab4Sdrh }
2756949e2ab4Sdrh jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk);
2757146e64d2Sdrh VdbeCoverage(v);
2758949e2ab4Sdrh sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk);
2759146e64d2Sdrh VdbeCoverage(v);
2760949e2ab4Sdrh sqlite3VdbeJumpHere(v, jmp);
2761949e2ab4Sdrh sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn);
2762949e2ab4Sdrh sqlite3WhereEnd(pSubWInfo);
2763949e2ab4Sdrh }
2764949e2ab4Sdrh sqlite3ExprDelete(pParse->db, pSubWhere);
2765949e2ab4Sdrh ExplainQueryPlanPop(pParse);
2766503ad9c7Sdrh assert( pParse->withinRJSubrtn>0 );
2767503ad9c7Sdrh pParse->withinRJSubrtn--;
2768949e2ab4Sdrh }
2769