xref: /sqlite-3.40.0/src/wherecode.c (revision d37bea5b)
16f82e85aSdrh /*
26f82e85aSdrh ** 2015-06-06
36f82e85aSdrh **
46f82e85aSdrh ** The author disclaims copyright to this source code.  In place of
56f82e85aSdrh ** a legal notice, here is a blessing:
66f82e85aSdrh **
76f82e85aSdrh **    May you do good and not evil.
86f82e85aSdrh **    May you find forgiveness for yourself and forgive others.
96f82e85aSdrh **    May you share freely, never taking more than you give.
106f82e85aSdrh **
116f82e85aSdrh *************************************************************************
126f82e85aSdrh ** This module contains C code that generates VDBE code used to process
136f82e85aSdrh ** the WHERE clause of SQL statements.
146f82e85aSdrh **
156f82e85aSdrh ** This file was split off from where.c on 2015-06-06 in order to reduce the
166f82e85aSdrh ** size of where.c and make it easier to edit.  This file contains the routines
176f82e85aSdrh ** that actually generate the bulk of the WHERE loop code.  The original where.c
186f82e85aSdrh ** file retains the code that does query planning and analysis.
196f82e85aSdrh */
206f82e85aSdrh #include "sqliteInt.h"
216f82e85aSdrh #include "whereInt.h"
226f82e85aSdrh 
236f82e85aSdrh #ifndef SQLITE_OMIT_EXPLAIN
246f82e85aSdrh /*
256f82e85aSdrh ** This routine is a helper for explainIndexRange() below
266f82e85aSdrh **
276f82e85aSdrh ** pStr holds the text of an expression that we are building up one term
286f82e85aSdrh ** at a time.  This routine adds a new term to the end of the expression.
296f82e85aSdrh ** Terms are separated by AND so add the "AND" text for second and subsequent
306f82e85aSdrh ** terms only.
316f82e85aSdrh */
326f82e85aSdrh static void explainAppendTerm(
336f82e85aSdrh   StrAccum *pStr,             /* The text expression being built */
346f82e85aSdrh   int iTerm,                  /* Index of this term.  First is zero */
356f82e85aSdrh   const char *zColumn,        /* Name of the column */
366f82e85aSdrh   const char *zOp             /* Name of the operator */
376f82e85aSdrh ){
386f82e85aSdrh   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
396f82e85aSdrh   sqlite3StrAccumAppendAll(pStr, zColumn);
406f82e85aSdrh   sqlite3StrAccumAppend(pStr, zOp, 1);
416f82e85aSdrh   sqlite3StrAccumAppend(pStr, "?", 1);
426f82e85aSdrh }
436f82e85aSdrh 
446f82e85aSdrh /*
456f82e85aSdrh ** Argument pLevel describes a strategy for scanning table pTab. This
466f82e85aSdrh ** function appends text to pStr that describes the subset of table
476f82e85aSdrh ** rows scanned by the strategy in the form of an SQL expression.
486f82e85aSdrh **
496f82e85aSdrh ** For example, if the query:
506f82e85aSdrh **
516f82e85aSdrh **   SELECT * FROM t1 WHERE a=1 AND b>2;
526f82e85aSdrh **
536f82e85aSdrh ** is run and there is an index on (a, b), then this function returns a
546f82e85aSdrh ** string similar to:
556f82e85aSdrh **
566f82e85aSdrh **   "a=? AND b>?"
576f82e85aSdrh */
586f82e85aSdrh static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
596f82e85aSdrh   Index *pIndex = pLoop->u.btree.pIndex;
606f82e85aSdrh   u16 nEq = pLoop->u.btree.nEq;
616f82e85aSdrh   u16 nSkip = pLoop->nSkip;
626f82e85aSdrh   int i, j;
636f82e85aSdrh   Column *aCol = pTab->aCol;
646f82e85aSdrh   i16 *aiColumn = pIndex->aiColumn;
656f82e85aSdrh 
666f82e85aSdrh   if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
676f82e85aSdrh   sqlite3StrAccumAppend(pStr, " (", 2);
686f82e85aSdrh   for(i=0; i<nEq; i++){
696f82e85aSdrh     char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
706f82e85aSdrh     if( i>=nSkip ){
716f82e85aSdrh       explainAppendTerm(pStr, i, z, "=");
726f82e85aSdrh     }else{
736f82e85aSdrh       if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
746f82e85aSdrh       sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
756f82e85aSdrh     }
766f82e85aSdrh   }
776f82e85aSdrh 
786f82e85aSdrh   j = i;
796f82e85aSdrh   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
806f82e85aSdrh     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
816f82e85aSdrh     explainAppendTerm(pStr, i++, z, ">");
826f82e85aSdrh   }
836f82e85aSdrh   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
846f82e85aSdrh     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
856f82e85aSdrh     explainAppendTerm(pStr, i, z, "<");
866f82e85aSdrh   }
876f82e85aSdrh   sqlite3StrAccumAppend(pStr, ")", 1);
886f82e85aSdrh }
896f82e85aSdrh 
906f82e85aSdrh /*
916f82e85aSdrh ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
926f82e85aSdrh ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
936f82e85aSdrh ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
946f82e85aSdrh ** is added to the output to describe the table scan strategy in pLevel.
956f82e85aSdrh **
966f82e85aSdrh ** If an OP_Explain opcode is added to the VM, its address is returned.
976f82e85aSdrh ** Otherwise, if no OP_Explain is coded, zero is returned.
986f82e85aSdrh */
996f82e85aSdrh int sqlite3WhereExplainOneScan(
1006f82e85aSdrh   Parse *pParse,                  /* Parse context */
1016f82e85aSdrh   SrcList *pTabList,              /* Table list this loop refers to */
1026f82e85aSdrh   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
1036f82e85aSdrh   int iLevel,                     /* Value for "level" column of output */
1046f82e85aSdrh   int iFrom,                      /* Value for "from" column of output */
1056f82e85aSdrh   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
1066f82e85aSdrh ){
1076f82e85aSdrh   int ret = 0;
1086f82e85aSdrh #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
1096f82e85aSdrh   if( pParse->explain==2 )
1106f82e85aSdrh #endif
1116f82e85aSdrh   {
1126f82e85aSdrh     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
1136f82e85aSdrh     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
1146f82e85aSdrh     sqlite3 *db = pParse->db;     /* Database handle */
1156f82e85aSdrh     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
1166f82e85aSdrh     int isSearch;                 /* True for a SEARCH. False for SCAN. */
1176f82e85aSdrh     WhereLoop *pLoop;             /* The controlling WhereLoop object */
1186f82e85aSdrh     u32 flags;                    /* Flags that describe this loop */
1196f82e85aSdrh     char *zMsg;                   /* Text to add to EQP output */
1206f82e85aSdrh     StrAccum str;                 /* EQP output string */
1216f82e85aSdrh     char zBuf[100];               /* Initial space for EQP output string */
1226f82e85aSdrh 
1236f82e85aSdrh     pLoop = pLevel->pWLoop;
1246f82e85aSdrh     flags = pLoop->wsFlags;
1256f82e85aSdrh     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
1266f82e85aSdrh 
1276f82e85aSdrh     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
1286f82e85aSdrh             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
1296f82e85aSdrh             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
1306f82e85aSdrh 
1316f82e85aSdrh     sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
1326f82e85aSdrh     sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
1336f82e85aSdrh     if( pItem->pSelect ){
1346f82e85aSdrh       sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
1356f82e85aSdrh     }else{
1366f82e85aSdrh       sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
1376f82e85aSdrh     }
1386f82e85aSdrh 
1396f82e85aSdrh     if( pItem->zAlias ){
1406f82e85aSdrh       sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
1416f82e85aSdrh     }
1426f82e85aSdrh     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
1436f82e85aSdrh       const char *zFmt = 0;
1446f82e85aSdrh       Index *pIdx;
1456f82e85aSdrh 
1466f82e85aSdrh       assert( pLoop->u.btree.pIndex!=0 );
1476f82e85aSdrh       pIdx = pLoop->u.btree.pIndex;
1486f82e85aSdrh       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
1496f82e85aSdrh       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
1506f82e85aSdrh         if( isSearch ){
1516f82e85aSdrh           zFmt = "PRIMARY KEY";
1526f82e85aSdrh         }
1536f82e85aSdrh       }else if( flags & WHERE_PARTIALIDX ){
1546f82e85aSdrh         zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
1556f82e85aSdrh       }else if( flags & WHERE_AUTO_INDEX ){
1566f82e85aSdrh         zFmt = "AUTOMATIC COVERING INDEX";
1576f82e85aSdrh       }else if( flags & WHERE_IDX_ONLY ){
1586f82e85aSdrh         zFmt = "COVERING INDEX %s";
1596f82e85aSdrh       }else{
1606f82e85aSdrh         zFmt = "INDEX %s";
1616f82e85aSdrh       }
1626f82e85aSdrh       if( zFmt ){
1636f82e85aSdrh         sqlite3StrAccumAppend(&str, " USING ", 7);
1646f82e85aSdrh         sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
1656f82e85aSdrh         explainIndexRange(&str, pLoop, pItem->pTab);
1666f82e85aSdrh       }
1676f82e85aSdrh     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
168*d37bea5bSdrh       const char *zRangeOp;
1696f82e85aSdrh       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
170*d37bea5bSdrh         zRangeOp = "=";
1716f82e85aSdrh       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
172*d37bea5bSdrh         zRangeOp = ">? AND rowid<";
1736f82e85aSdrh       }else if( flags&WHERE_BTM_LIMIT ){
174*d37bea5bSdrh         zRangeOp = ">";
1756f82e85aSdrh       }else{
1766f82e85aSdrh         assert( flags&WHERE_TOP_LIMIT);
177*d37bea5bSdrh         zRangeOp = "<";
1786f82e85aSdrh       }
179*d37bea5bSdrh       sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
1806f82e85aSdrh     }
1816f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
1826f82e85aSdrh     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
1836f82e85aSdrh       sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
1846f82e85aSdrh                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
1856f82e85aSdrh     }
1866f82e85aSdrh #endif
1876f82e85aSdrh #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
1886f82e85aSdrh     if( pLoop->nOut>=10 ){
1896f82e85aSdrh       sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
1906f82e85aSdrh     }else{
1916f82e85aSdrh       sqlite3StrAccumAppend(&str, " (~1 row)", 9);
1926f82e85aSdrh     }
1936f82e85aSdrh #endif
1946f82e85aSdrh     zMsg = sqlite3StrAccumFinish(&str);
1956f82e85aSdrh     ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
1966f82e85aSdrh   }
1976f82e85aSdrh   return ret;
1986f82e85aSdrh }
1996f82e85aSdrh #endif /* SQLITE_OMIT_EXPLAIN */
2006f82e85aSdrh 
2016f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
2026f82e85aSdrh /*
2036f82e85aSdrh ** Configure the VM passed as the first argument with an
2046f82e85aSdrh ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
2056f82e85aSdrh ** implement level pLvl. Argument pSrclist is a pointer to the FROM
2066f82e85aSdrh ** clause that the scan reads data from.
2076f82e85aSdrh **
2086f82e85aSdrh ** If argument addrExplain is not 0, it must be the address of an
2096f82e85aSdrh ** OP_Explain instruction that describes the same loop.
2106f82e85aSdrh */
2116f82e85aSdrh void sqlite3WhereAddScanStatus(
2126f82e85aSdrh   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
2136f82e85aSdrh   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
2146f82e85aSdrh   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
2156f82e85aSdrh   int addrExplain                 /* Address of OP_Explain (or 0) */
2166f82e85aSdrh ){
2176f82e85aSdrh   const char *zObj = 0;
2186f82e85aSdrh   WhereLoop *pLoop = pLvl->pWLoop;
2196f82e85aSdrh   if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
2206f82e85aSdrh     zObj = pLoop->u.btree.pIndex->zName;
2216f82e85aSdrh   }else{
2226f82e85aSdrh     zObj = pSrclist->a[pLvl->iFrom].zName;
2236f82e85aSdrh   }
2246f82e85aSdrh   sqlite3VdbeScanStatus(
2256f82e85aSdrh       v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
2266f82e85aSdrh   );
2276f82e85aSdrh }
2286f82e85aSdrh #endif
2296f82e85aSdrh 
2306f82e85aSdrh 
2316f82e85aSdrh /*
2326f82e85aSdrh ** Disable a term in the WHERE clause.  Except, do not disable the term
2336f82e85aSdrh ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2346f82e85aSdrh ** or USING clause of that join.
2356f82e85aSdrh **
2366f82e85aSdrh ** Consider the term t2.z='ok' in the following queries:
2376f82e85aSdrh **
2386f82e85aSdrh **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2396f82e85aSdrh **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2406f82e85aSdrh **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2416f82e85aSdrh **
2426f82e85aSdrh ** The t2.z='ok' is disabled in the in (2) because it originates
2436f82e85aSdrh ** in the ON clause.  The term is disabled in (3) because it is not part
2446f82e85aSdrh ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
2456f82e85aSdrh **
2466f82e85aSdrh ** Disabling a term causes that term to not be tested in the inner loop
2476f82e85aSdrh ** of the join.  Disabling is an optimization.  When terms are satisfied
2486f82e85aSdrh ** by indices, we disable them to prevent redundant tests in the inner
2496f82e85aSdrh ** loop.  We would get the correct results if nothing were ever disabled,
2506f82e85aSdrh ** but joins might run a little slower.  The trick is to disable as much
2516f82e85aSdrh ** as we can without disabling too much.  If we disabled in (1), we'd get
2526f82e85aSdrh ** the wrong answer.  See ticket #813.
2536f82e85aSdrh **
2546f82e85aSdrh ** If all the children of a term are disabled, then that term is also
2556f82e85aSdrh ** automatically disabled.  In this way, terms get disabled if derived
2566f82e85aSdrh ** virtual terms are tested first.  For example:
2576f82e85aSdrh **
2586f82e85aSdrh **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
2596f82e85aSdrh **      \___________/     \______/     \_____/
2606f82e85aSdrh **         parent          child1       child2
2616f82e85aSdrh **
2626f82e85aSdrh ** Only the parent term was in the original WHERE clause.  The child1
2636f82e85aSdrh ** and child2 terms were added by the LIKE optimization.  If both of
2646f82e85aSdrh ** the virtual child terms are valid, then testing of the parent can be
2656f82e85aSdrh ** skipped.
2666f82e85aSdrh **
2676f82e85aSdrh ** Usually the parent term is marked as TERM_CODED.  But if the parent
2686f82e85aSdrh ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
2696f82e85aSdrh ** The TERM_LIKECOND marking indicates that the term should be coded inside
2706f82e85aSdrh ** a conditional such that is only evaluated on the second pass of a
2716f82e85aSdrh ** LIKE-optimization loop, when scanning BLOBs instead of strings.
2726f82e85aSdrh */
2736f82e85aSdrh static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2746f82e85aSdrh   int nLoop = 0;
2756f82e85aSdrh   while( pTerm
2766f82e85aSdrh       && (pTerm->wtFlags & TERM_CODED)==0
2776f82e85aSdrh       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
2786f82e85aSdrh       && (pLevel->notReady & pTerm->prereqAll)==0
2796f82e85aSdrh   ){
2806f82e85aSdrh     if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
2816f82e85aSdrh       pTerm->wtFlags |= TERM_LIKECOND;
2826f82e85aSdrh     }else{
2836f82e85aSdrh       pTerm->wtFlags |= TERM_CODED;
2846f82e85aSdrh     }
2856f82e85aSdrh     if( pTerm->iParent<0 ) break;
2866f82e85aSdrh     pTerm = &pTerm->pWC->a[pTerm->iParent];
2876f82e85aSdrh     pTerm->nChild--;
2886f82e85aSdrh     if( pTerm->nChild!=0 ) break;
2896f82e85aSdrh     nLoop++;
2906f82e85aSdrh   }
2916f82e85aSdrh }
2926f82e85aSdrh 
2936f82e85aSdrh /*
2946f82e85aSdrh ** Code an OP_Affinity opcode to apply the column affinity string zAff
2956f82e85aSdrh ** to the n registers starting at base.
2966f82e85aSdrh **
2976f82e85aSdrh ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
2986f82e85aSdrh ** beginning and end of zAff are ignored.  If all entries in zAff are
2996f82e85aSdrh ** SQLITE_AFF_BLOB, then no code gets generated.
3006f82e85aSdrh **
3016f82e85aSdrh ** This routine makes its own copy of zAff so that the caller is free
3026f82e85aSdrh ** to modify zAff after this routine returns.
3036f82e85aSdrh */
3046f82e85aSdrh static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
3056f82e85aSdrh   Vdbe *v = pParse->pVdbe;
3066f82e85aSdrh   if( zAff==0 ){
3076f82e85aSdrh     assert( pParse->db->mallocFailed );
3086f82e85aSdrh     return;
3096f82e85aSdrh   }
3106f82e85aSdrh   assert( v!=0 );
3116f82e85aSdrh 
3126f82e85aSdrh   /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
3136f82e85aSdrh   ** and end of the affinity string.
3146f82e85aSdrh   */
3156f82e85aSdrh   while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
3166f82e85aSdrh     n--;
3176f82e85aSdrh     base++;
3186f82e85aSdrh     zAff++;
3196f82e85aSdrh   }
3206f82e85aSdrh   while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
3216f82e85aSdrh     n--;
3226f82e85aSdrh   }
3236f82e85aSdrh 
3246f82e85aSdrh   /* Code the OP_Affinity opcode if there is anything left to do. */
3256f82e85aSdrh   if( n>0 ){
3266f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
3276f82e85aSdrh     sqlite3VdbeChangeP4(v, -1, zAff, n);
3286f82e85aSdrh     sqlite3ExprCacheAffinityChange(pParse, base, n);
3296f82e85aSdrh   }
3306f82e85aSdrh }
3316f82e85aSdrh 
3326f82e85aSdrh 
3336f82e85aSdrh /*
3346f82e85aSdrh ** Generate code for a single equality term of the WHERE clause.  An equality
3356f82e85aSdrh ** term can be either X=expr or X IN (...).   pTerm is the term to be
3366f82e85aSdrh ** coded.
3376f82e85aSdrh **
3386f82e85aSdrh ** The current value for the constraint is left in register iReg.
3396f82e85aSdrh **
3406f82e85aSdrh ** For a constraint of the form X=expr, the expression is evaluated and its
3416f82e85aSdrh ** result is left on the stack.  For constraints of the form X IN (...)
3426f82e85aSdrh ** this routine sets up a loop that will iterate over all values of X.
3436f82e85aSdrh */
3446f82e85aSdrh static int codeEqualityTerm(
3456f82e85aSdrh   Parse *pParse,      /* The parsing context */
3466f82e85aSdrh   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
3476f82e85aSdrh   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
3486f82e85aSdrh   int iEq,            /* Index of the equality term within this level */
3496f82e85aSdrh   int bRev,           /* True for reverse-order IN operations */
3506f82e85aSdrh   int iTarget         /* Attempt to leave results in this register */
3516f82e85aSdrh ){
3526f82e85aSdrh   Expr *pX = pTerm->pExpr;
3536f82e85aSdrh   Vdbe *v = pParse->pVdbe;
3546f82e85aSdrh   int iReg;                  /* Register holding results */
3556f82e85aSdrh 
3566f82e85aSdrh   assert( iTarget>0 );
3576f82e85aSdrh   if( pX->op==TK_EQ || pX->op==TK_IS ){
3586f82e85aSdrh     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
3596f82e85aSdrh   }else if( pX->op==TK_ISNULL ){
3606f82e85aSdrh     iReg = iTarget;
3616f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
3626f82e85aSdrh #ifndef SQLITE_OMIT_SUBQUERY
3636f82e85aSdrh   }else{
3646f82e85aSdrh     int eType;
3656f82e85aSdrh     int iTab;
3666f82e85aSdrh     struct InLoop *pIn;
3676f82e85aSdrh     WhereLoop *pLoop = pLevel->pWLoop;
3686f82e85aSdrh 
3696f82e85aSdrh     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
3706f82e85aSdrh       && pLoop->u.btree.pIndex!=0
3716f82e85aSdrh       && pLoop->u.btree.pIndex->aSortOrder[iEq]
3726f82e85aSdrh     ){
3736f82e85aSdrh       testcase( iEq==0 );
3746f82e85aSdrh       testcase( bRev );
3756f82e85aSdrh       bRev = !bRev;
3766f82e85aSdrh     }
3776f82e85aSdrh     assert( pX->op==TK_IN );
3786f82e85aSdrh     iReg = iTarget;
3796f82e85aSdrh     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
3806f82e85aSdrh     if( eType==IN_INDEX_INDEX_DESC ){
3816f82e85aSdrh       testcase( bRev );
3826f82e85aSdrh       bRev = !bRev;
3836f82e85aSdrh     }
3846f82e85aSdrh     iTab = pX->iTable;
3856f82e85aSdrh     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
3866f82e85aSdrh     VdbeCoverageIf(v, bRev);
3876f82e85aSdrh     VdbeCoverageIf(v, !bRev);
3886f82e85aSdrh     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
3896f82e85aSdrh     pLoop->wsFlags |= WHERE_IN_ABLE;
3906f82e85aSdrh     if( pLevel->u.in.nIn==0 ){
3916f82e85aSdrh       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3926f82e85aSdrh     }
3936f82e85aSdrh     pLevel->u.in.nIn++;
3946f82e85aSdrh     pLevel->u.in.aInLoop =
3956f82e85aSdrh        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
3966f82e85aSdrh                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
3976f82e85aSdrh     pIn = pLevel->u.in.aInLoop;
3986f82e85aSdrh     if( pIn ){
3996f82e85aSdrh       pIn += pLevel->u.in.nIn - 1;
4006f82e85aSdrh       pIn->iCur = iTab;
4016f82e85aSdrh       if( eType==IN_INDEX_ROWID ){
4026f82e85aSdrh         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
4036f82e85aSdrh       }else{
4046f82e85aSdrh         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
4056f82e85aSdrh       }
4066f82e85aSdrh       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
4076f82e85aSdrh       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
4086f82e85aSdrh     }else{
4096f82e85aSdrh       pLevel->u.in.nIn = 0;
4106f82e85aSdrh     }
4116f82e85aSdrh #endif
4126f82e85aSdrh   }
4136f82e85aSdrh   disableTerm(pLevel, pTerm);
4146f82e85aSdrh   return iReg;
4156f82e85aSdrh }
4166f82e85aSdrh 
4176f82e85aSdrh /*
4186f82e85aSdrh ** Generate code that will evaluate all == and IN constraints for an
4196f82e85aSdrh ** index scan.
4206f82e85aSdrh **
4216f82e85aSdrh ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
4226f82e85aSdrh ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
4236f82e85aSdrh ** The index has as many as three equality constraints, but in this
4246f82e85aSdrh ** example, the third "c" value is an inequality.  So only two
4256f82e85aSdrh ** constraints are coded.  This routine will generate code to evaluate
4266f82e85aSdrh ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
4276f82e85aSdrh ** in consecutive registers and the index of the first register is returned.
4286f82e85aSdrh **
4296f82e85aSdrh ** In the example above nEq==2.  But this subroutine works for any value
4306f82e85aSdrh ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
4316f82e85aSdrh ** The only thing it does is allocate the pLevel->iMem memory cell and
4326f82e85aSdrh ** compute the affinity string.
4336f82e85aSdrh **
4346f82e85aSdrh ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
4356f82e85aSdrh ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
4366f82e85aSdrh ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
4376f82e85aSdrh ** occurs after the nEq quality constraints.
4386f82e85aSdrh **
4396f82e85aSdrh ** This routine allocates a range of nEq+nExtraReg memory cells and returns
4406f82e85aSdrh ** the index of the first memory cell in that range. The code that
4416f82e85aSdrh ** calls this routine will use that memory range to store keys for
4426f82e85aSdrh ** start and termination conditions of the loop.
4436f82e85aSdrh ** key value of the loop.  If one or more IN operators appear, then
4446f82e85aSdrh ** this routine allocates an additional nEq memory cells for internal
4456f82e85aSdrh ** use.
4466f82e85aSdrh **
4476f82e85aSdrh ** Before returning, *pzAff is set to point to a buffer containing a
4486f82e85aSdrh ** copy of the column affinity string of the index allocated using
4496f82e85aSdrh ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
4506f82e85aSdrh ** with equality constraints that use BLOB or NONE affinity are set to
4516f82e85aSdrh ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
4526f82e85aSdrh **
4536f82e85aSdrh **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
4546f82e85aSdrh **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
4556f82e85aSdrh **
4566f82e85aSdrh ** In the example above, the index on t1(a) has TEXT affinity. But since
4576f82e85aSdrh ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
4586f82e85aSdrh ** no conversion should be attempted before using a t2.b value as part of
4596f82e85aSdrh ** a key to search the index. Hence the first byte in the returned affinity
4606f82e85aSdrh ** string in this example would be set to SQLITE_AFF_BLOB.
4616f82e85aSdrh */
4626f82e85aSdrh static int codeAllEqualityTerms(
4636f82e85aSdrh   Parse *pParse,        /* Parsing context */
4646f82e85aSdrh   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
4656f82e85aSdrh   int bRev,             /* Reverse the order of IN operators */
4666f82e85aSdrh   int nExtraReg,        /* Number of extra registers to allocate */
4676f82e85aSdrh   char **pzAff          /* OUT: Set to point to affinity string */
4686f82e85aSdrh ){
4696f82e85aSdrh   u16 nEq;                      /* The number of == or IN constraints to code */
4706f82e85aSdrh   u16 nSkip;                    /* Number of left-most columns to skip */
4716f82e85aSdrh   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
4726f82e85aSdrh   Index *pIdx;                  /* The index being used for this loop */
4736f82e85aSdrh   WhereTerm *pTerm;             /* A single constraint term */
4746f82e85aSdrh   WhereLoop *pLoop;             /* The WhereLoop object */
4756f82e85aSdrh   int j;                        /* Loop counter */
4766f82e85aSdrh   int regBase;                  /* Base register */
4776f82e85aSdrh   int nReg;                     /* Number of registers to allocate */
4786f82e85aSdrh   char *zAff;                   /* Affinity string to return */
4796f82e85aSdrh 
4806f82e85aSdrh   /* This module is only called on query plans that use an index. */
4816f82e85aSdrh   pLoop = pLevel->pWLoop;
4826f82e85aSdrh   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
4836f82e85aSdrh   nEq = pLoop->u.btree.nEq;
4846f82e85aSdrh   nSkip = pLoop->nSkip;
4856f82e85aSdrh   pIdx = pLoop->u.btree.pIndex;
4866f82e85aSdrh   assert( pIdx!=0 );
4876f82e85aSdrh 
4886f82e85aSdrh   /* Figure out how many memory cells we will need then allocate them.
4896f82e85aSdrh   */
4906f82e85aSdrh   regBase = pParse->nMem + 1;
4916f82e85aSdrh   nReg = pLoop->u.btree.nEq + nExtraReg;
4926f82e85aSdrh   pParse->nMem += nReg;
4936f82e85aSdrh 
494e9107698Sdrh   zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
4956f82e85aSdrh   if( !zAff ){
4966f82e85aSdrh     pParse->db->mallocFailed = 1;
4976f82e85aSdrh   }
4986f82e85aSdrh 
4996f82e85aSdrh   if( nSkip ){
5006f82e85aSdrh     int iIdxCur = pLevel->iIdxCur;
5016f82e85aSdrh     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
5026f82e85aSdrh     VdbeCoverageIf(v, bRev==0);
5036f82e85aSdrh     VdbeCoverageIf(v, bRev!=0);
5046f82e85aSdrh     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
5056f82e85aSdrh     j = sqlite3VdbeAddOp0(v, OP_Goto);
5066f82e85aSdrh     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
5076f82e85aSdrh                             iIdxCur, 0, regBase, nSkip);
5086f82e85aSdrh     VdbeCoverageIf(v, bRev==0);
5096f82e85aSdrh     VdbeCoverageIf(v, bRev!=0);
5106f82e85aSdrh     sqlite3VdbeJumpHere(v, j);
5116f82e85aSdrh     for(j=0; j<nSkip; j++){
5126f82e85aSdrh       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
5136f82e85aSdrh       assert( pIdx->aiColumn[j]>=0 );
5146f82e85aSdrh       VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
5156f82e85aSdrh     }
5166f82e85aSdrh   }
5176f82e85aSdrh 
5186f82e85aSdrh   /* Evaluate the equality constraints
5196f82e85aSdrh   */
5206f82e85aSdrh   assert( zAff==0 || (int)strlen(zAff)>=nEq );
5216f82e85aSdrh   for(j=nSkip; j<nEq; j++){
5226f82e85aSdrh     int r1;
5236f82e85aSdrh     pTerm = pLoop->aLTerm[j];
5246f82e85aSdrh     assert( pTerm!=0 );
5256f82e85aSdrh     /* The following testcase is true for indices with redundant columns.
5266f82e85aSdrh     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
5276f82e85aSdrh     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
5286f82e85aSdrh     testcase( pTerm->wtFlags & TERM_VIRTUAL );
5296f82e85aSdrh     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
5306f82e85aSdrh     if( r1!=regBase+j ){
5316f82e85aSdrh       if( nReg==1 ){
5326f82e85aSdrh         sqlite3ReleaseTempReg(pParse, regBase);
5336f82e85aSdrh         regBase = r1;
5346f82e85aSdrh       }else{
5356f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
5366f82e85aSdrh       }
5376f82e85aSdrh     }
5386f82e85aSdrh     testcase( pTerm->eOperator & WO_ISNULL );
5396f82e85aSdrh     testcase( pTerm->eOperator & WO_IN );
5406f82e85aSdrh     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
5416f82e85aSdrh       Expr *pRight = pTerm->pExpr->pRight;
5426f82e85aSdrh       if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
5436f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
5446f82e85aSdrh         VdbeCoverage(v);
5456f82e85aSdrh       }
5466f82e85aSdrh       if( zAff ){
5476f82e85aSdrh         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
5486f82e85aSdrh           zAff[j] = SQLITE_AFF_BLOB;
5496f82e85aSdrh         }
5506f82e85aSdrh         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
5516f82e85aSdrh           zAff[j] = SQLITE_AFF_BLOB;
5526f82e85aSdrh         }
5536f82e85aSdrh       }
5546f82e85aSdrh     }
5556f82e85aSdrh   }
5566f82e85aSdrh   *pzAff = zAff;
5576f82e85aSdrh   return regBase;
5586f82e85aSdrh }
5596f82e85aSdrh 
5606f82e85aSdrh /*
5616f82e85aSdrh ** If the most recently coded instruction is a constant range contraint
5626f82e85aSdrh ** that originated from the LIKE optimization, then change the P3 to be
5636f82e85aSdrh ** pLoop->iLikeRepCntr and set P5.
5646f82e85aSdrh **
5656f82e85aSdrh ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
5666f82e85aSdrh ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
5676f82e85aSdrh ** scan loop run twice, once for strings and a second time for BLOBs.
5686f82e85aSdrh ** The OP_String opcodes on the second pass convert the upper and lower
5696f82e85aSdrh ** bound string contants to blobs.  This routine makes the necessary changes
5706f82e85aSdrh ** to the OP_String opcodes for that to happen.
5716f82e85aSdrh */
5726f82e85aSdrh static void whereLikeOptimizationStringFixup(
5736f82e85aSdrh   Vdbe *v,                /* prepared statement under construction */
5746f82e85aSdrh   WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
5756f82e85aSdrh   WhereTerm *pTerm        /* The upper or lower bound just coded */
5766f82e85aSdrh ){
5776f82e85aSdrh   if( pTerm->wtFlags & TERM_LIKEOPT ){
5786f82e85aSdrh     VdbeOp *pOp;
5796f82e85aSdrh     assert( pLevel->iLikeRepCntr>0 );
5806f82e85aSdrh     pOp = sqlite3VdbeGetOp(v, -1);
5816f82e85aSdrh     assert( pOp!=0 );
5826f82e85aSdrh     assert( pOp->opcode==OP_String8
5836f82e85aSdrh             || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
5846f82e85aSdrh     pOp->p3 = pLevel->iLikeRepCntr;
5856f82e85aSdrh     pOp->p5 = 1;
5866f82e85aSdrh   }
5876f82e85aSdrh }
5886f82e85aSdrh 
5896f82e85aSdrh 
5906f82e85aSdrh /*
5916f82e85aSdrh ** Generate code for the start of the iLevel-th loop in the WHERE clause
5926f82e85aSdrh ** implementation described by pWInfo.
5936f82e85aSdrh */
5946f82e85aSdrh Bitmask sqlite3WhereCodeOneLoopStart(
5956f82e85aSdrh   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
5966f82e85aSdrh   int iLevel,          /* Which level of pWInfo->a[] should be coded */
5976f82e85aSdrh   Bitmask notReady     /* Which tables are currently available */
5986f82e85aSdrh ){
5996f82e85aSdrh   int j, k;            /* Loop counters */
6006f82e85aSdrh   int iCur;            /* The VDBE cursor for the table */
6016f82e85aSdrh   int addrNxt;         /* Where to jump to continue with the next IN case */
6026f82e85aSdrh   int omitTable;       /* True if we use the index only */
6036f82e85aSdrh   int bRev;            /* True if we need to scan in reverse order */
6046f82e85aSdrh   WhereLevel *pLevel;  /* The where level to be coded */
6056f82e85aSdrh   WhereLoop *pLoop;    /* The WhereLoop object being coded */
6066f82e85aSdrh   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
6076f82e85aSdrh   WhereTerm *pTerm;               /* A WHERE clause term */
6086f82e85aSdrh   Parse *pParse;                  /* Parsing context */
6096f82e85aSdrh   sqlite3 *db;                    /* Database connection */
6106f82e85aSdrh   Vdbe *v;                        /* The prepared stmt under constructions */
6116f82e85aSdrh   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
6126f82e85aSdrh   int addrBrk;                    /* Jump here to break out of the loop */
6136f82e85aSdrh   int addrCont;                   /* Jump here to continue with next cycle */
6146f82e85aSdrh   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
6156f82e85aSdrh   int iReleaseReg = 0;      /* Temp register to free before returning */
6166f82e85aSdrh 
6176f82e85aSdrh   pParse = pWInfo->pParse;
6186f82e85aSdrh   v = pParse->pVdbe;
6196f82e85aSdrh   pWC = &pWInfo->sWC;
6206f82e85aSdrh   db = pParse->db;
6216f82e85aSdrh   pLevel = &pWInfo->a[iLevel];
6226f82e85aSdrh   pLoop = pLevel->pWLoop;
6236f82e85aSdrh   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
6246f82e85aSdrh   iCur = pTabItem->iCursor;
6256f82e85aSdrh   pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
6266f82e85aSdrh   bRev = (pWInfo->revMask>>iLevel)&1;
6276f82e85aSdrh   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
6286f82e85aSdrh            && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
6296f82e85aSdrh   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
6306f82e85aSdrh 
6316f82e85aSdrh   /* Create labels for the "break" and "continue" instructions
6326f82e85aSdrh   ** for the current loop.  Jump to addrBrk to break out of a loop.
6336f82e85aSdrh   ** Jump to cont to go immediately to the next iteration of the
6346f82e85aSdrh   ** loop.
6356f82e85aSdrh   **
6366f82e85aSdrh   ** When there is an IN operator, we also have a "addrNxt" label that
6376f82e85aSdrh   ** means to continue with the next IN value combination.  When
6386f82e85aSdrh   ** there are no IN operators in the constraints, the "addrNxt" label
6396f82e85aSdrh   ** is the same as "addrBrk".
6406f82e85aSdrh   */
6416f82e85aSdrh   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
6426f82e85aSdrh   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
6436f82e85aSdrh 
6446f82e85aSdrh   /* If this is the right table of a LEFT OUTER JOIN, allocate and
6456f82e85aSdrh   ** initialize a memory cell that records if this table matches any
6466f82e85aSdrh   ** row of the left table of the join.
6476f82e85aSdrh   */
6488a48b9c0Sdrh   if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
6496f82e85aSdrh     pLevel->iLeftJoin = ++pParse->nMem;
6506f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
6516f82e85aSdrh     VdbeComment((v, "init LEFT JOIN no-match flag"));
6526f82e85aSdrh   }
6536f82e85aSdrh 
6546f82e85aSdrh   /* Special case of a FROM clause subquery implemented as a co-routine */
6558a48b9c0Sdrh   if( pTabItem->fg.viaCoroutine ){
6566f82e85aSdrh     int regYield = pTabItem->regReturn;
6576f82e85aSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
6586f82e85aSdrh     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
6596f82e85aSdrh     VdbeCoverage(v);
6606f82e85aSdrh     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
6616f82e85aSdrh     pLevel->op = OP_Goto;
6626f82e85aSdrh   }else
6636f82e85aSdrh 
6646f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
6656f82e85aSdrh   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
6666f82e85aSdrh     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
6676f82e85aSdrh     **          to access the data.
6686f82e85aSdrh     */
6696f82e85aSdrh     int iReg;   /* P3 Value for OP_VFilter */
6706f82e85aSdrh     int addrNotFound;
6716f82e85aSdrh     int nConstraint = pLoop->nLTerm;
6726f82e85aSdrh 
6736f82e85aSdrh     sqlite3ExprCachePush(pParse);
6746f82e85aSdrh     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
6756f82e85aSdrh     addrNotFound = pLevel->addrBrk;
6766f82e85aSdrh     for(j=0; j<nConstraint; j++){
6776f82e85aSdrh       int iTarget = iReg+j+2;
6786f82e85aSdrh       pTerm = pLoop->aLTerm[j];
6796f82e85aSdrh       if( pTerm==0 ) continue;
6806f82e85aSdrh       if( pTerm->eOperator & WO_IN ){
6816f82e85aSdrh         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
6826f82e85aSdrh         addrNotFound = pLevel->addrNxt;
6836f82e85aSdrh       }else{
6846f82e85aSdrh         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
6856f82e85aSdrh       }
6866f82e85aSdrh     }
6876f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
6886f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
6896f82e85aSdrh     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
6906f82e85aSdrh                       pLoop->u.vtab.idxStr,
6916f82e85aSdrh                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
6926f82e85aSdrh     VdbeCoverage(v);
6936f82e85aSdrh     pLoop->u.vtab.needFree = 0;
6946f82e85aSdrh     for(j=0; j<nConstraint && j<16; j++){
6956f82e85aSdrh       if( (pLoop->u.vtab.omitMask>>j)&1 ){
6966f82e85aSdrh         disableTerm(pLevel, pLoop->aLTerm[j]);
6976f82e85aSdrh       }
6986f82e85aSdrh     }
6996f82e85aSdrh     pLevel->op = OP_VNext;
7006f82e85aSdrh     pLevel->p1 = iCur;
7016f82e85aSdrh     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
7026f82e85aSdrh     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
7036f82e85aSdrh     sqlite3ExprCachePop(pParse);
7046f82e85aSdrh   }else
7056f82e85aSdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */
7066f82e85aSdrh 
7076f82e85aSdrh   if( (pLoop->wsFlags & WHERE_IPK)!=0
7086f82e85aSdrh    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
7096f82e85aSdrh   ){
7106f82e85aSdrh     /* Case 2:  We can directly reference a single row using an
7116f82e85aSdrh     **          equality comparison against the ROWID field.  Or
7126f82e85aSdrh     **          we reference multiple rows using a "rowid IN (...)"
7136f82e85aSdrh     **          construct.
7146f82e85aSdrh     */
7156f82e85aSdrh     assert( pLoop->u.btree.nEq==1 );
7166f82e85aSdrh     pTerm = pLoop->aLTerm[0];
7176f82e85aSdrh     assert( pTerm!=0 );
7186f82e85aSdrh     assert( pTerm->pExpr!=0 );
7196f82e85aSdrh     assert( omitTable==0 );
7206f82e85aSdrh     testcase( pTerm->wtFlags & TERM_VIRTUAL );
7216f82e85aSdrh     iReleaseReg = ++pParse->nMem;
7226f82e85aSdrh     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
7236f82e85aSdrh     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
7246f82e85aSdrh     addrNxt = pLevel->addrNxt;
7256f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
7266f82e85aSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
7276f82e85aSdrh     VdbeCoverage(v);
7286f82e85aSdrh     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
7296f82e85aSdrh     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
7306f82e85aSdrh     VdbeComment((v, "pk"));
7316f82e85aSdrh     pLevel->op = OP_Noop;
7326f82e85aSdrh   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
7336f82e85aSdrh          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
7346f82e85aSdrh   ){
7356f82e85aSdrh     /* Case 3:  We have an inequality comparison against the ROWID field.
7366f82e85aSdrh     */
7376f82e85aSdrh     int testOp = OP_Noop;
7386f82e85aSdrh     int start;
7396f82e85aSdrh     int memEndValue = 0;
7406f82e85aSdrh     WhereTerm *pStart, *pEnd;
7416f82e85aSdrh 
7426f82e85aSdrh     assert( omitTable==0 );
7436f82e85aSdrh     j = 0;
7446f82e85aSdrh     pStart = pEnd = 0;
7456f82e85aSdrh     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
7466f82e85aSdrh     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
7476f82e85aSdrh     assert( pStart!=0 || pEnd!=0 );
7486f82e85aSdrh     if( bRev ){
7496f82e85aSdrh       pTerm = pStart;
7506f82e85aSdrh       pStart = pEnd;
7516f82e85aSdrh       pEnd = pTerm;
7526f82e85aSdrh     }
7536f82e85aSdrh     if( pStart ){
7546f82e85aSdrh       Expr *pX;             /* The expression that defines the start bound */
7556f82e85aSdrh       int r1, rTemp;        /* Registers for holding the start boundary */
7566f82e85aSdrh 
7576f82e85aSdrh       /* The following constant maps TK_xx codes into corresponding
7586f82e85aSdrh       ** seek opcodes.  It depends on a particular ordering of TK_xx
7596f82e85aSdrh       */
7606f82e85aSdrh       const u8 aMoveOp[] = {
7616f82e85aSdrh            /* TK_GT */  OP_SeekGT,
7626f82e85aSdrh            /* TK_LE */  OP_SeekLE,
7636f82e85aSdrh            /* TK_LT */  OP_SeekLT,
7646f82e85aSdrh            /* TK_GE */  OP_SeekGE
7656f82e85aSdrh       };
7666f82e85aSdrh       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
7676f82e85aSdrh       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
7686f82e85aSdrh       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
7696f82e85aSdrh 
7706f82e85aSdrh       assert( (pStart->wtFlags & TERM_VNULL)==0 );
7716f82e85aSdrh       testcase( pStart->wtFlags & TERM_VIRTUAL );
7726f82e85aSdrh       pX = pStart->pExpr;
7736f82e85aSdrh       assert( pX!=0 );
7746f82e85aSdrh       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
7756f82e85aSdrh       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
7766f82e85aSdrh       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
7776f82e85aSdrh       VdbeComment((v, "pk"));
7786f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_GT);
7796f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_LE);
7806f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_LT);
7816f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_GE);
7826f82e85aSdrh       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
7836f82e85aSdrh       sqlite3ReleaseTempReg(pParse, rTemp);
7846f82e85aSdrh       disableTerm(pLevel, pStart);
7856f82e85aSdrh     }else{
7866f82e85aSdrh       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
7876f82e85aSdrh       VdbeCoverageIf(v, bRev==0);
7886f82e85aSdrh       VdbeCoverageIf(v, bRev!=0);
7896f82e85aSdrh     }
7906f82e85aSdrh     if( pEnd ){
7916f82e85aSdrh       Expr *pX;
7926f82e85aSdrh       pX = pEnd->pExpr;
7936f82e85aSdrh       assert( pX!=0 );
7946f82e85aSdrh       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
7956f82e85aSdrh       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
7966f82e85aSdrh       testcase( pEnd->wtFlags & TERM_VIRTUAL );
7976f82e85aSdrh       memEndValue = ++pParse->nMem;
7986f82e85aSdrh       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
7996f82e85aSdrh       if( pX->op==TK_LT || pX->op==TK_GT ){
8006f82e85aSdrh         testOp = bRev ? OP_Le : OP_Ge;
8016f82e85aSdrh       }else{
8026f82e85aSdrh         testOp = bRev ? OP_Lt : OP_Gt;
8036f82e85aSdrh       }
8046f82e85aSdrh       disableTerm(pLevel, pEnd);
8056f82e85aSdrh     }
8066f82e85aSdrh     start = sqlite3VdbeCurrentAddr(v);
8076f82e85aSdrh     pLevel->op = bRev ? OP_Prev : OP_Next;
8086f82e85aSdrh     pLevel->p1 = iCur;
8096f82e85aSdrh     pLevel->p2 = start;
8106f82e85aSdrh     assert( pLevel->p5==0 );
8116f82e85aSdrh     if( testOp!=OP_Noop ){
8126f82e85aSdrh       iRowidReg = ++pParse->nMem;
8136f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
8146f82e85aSdrh       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
8156f82e85aSdrh       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
8166f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Le);
8176f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Lt);
8186f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Ge);
8196f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Gt);
8206f82e85aSdrh       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
8216f82e85aSdrh     }
8226f82e85aSdrh   }else if( pLoop->wsFlags & WHERE_INDEXED ){
8236f82e85aSdrh     /* Case 4: A scan using an index.
8246f82e85aSdrh     **
8256f82e85aSdrh     **         The WHERE clause may contain zero or more equality
8266f82e85aSdrh     **         terms ("==" or "IN" operators) that refer to the N
8276f82e85aSdrh     **         left-most columns of the index. It may also contain
8286f82e85aSdrh     **         inequality constraints (>, <, >= or <=) on the indexed
8296f82e85aSdrh     **         column that immediately follows the N equalities. Only
8306f82e85aSdrh     **         the right-most column can be an inequality - the rest must
8316f82e85aSdrh     **         use the "==" and "IN" operators. For example, if the
8326f82e85aSdrh     **         index is on (x,y,z), then the following clauses are all
8336f82e85aSdrh     **         optimized:
8346f82e85aSdrh     **
8356f82e85aSdrh     **            x=5
8366f82e85aSdrh     **            x=5 AND y=10
8376f82e85aSdrh     **            x=5 AND y<10
8386f82e85aSdrh     **            x=5 AND y>5 AND y<10
8396f82e85aSdrh     **            x=5 AND y=5 AND z<=10
8406f82e85aSdrh     **
8416f82e85aSdrh     **         The z<10 term of the following cannot be used, only
8426f82e85aSdrh     **         the x=5 term:
8436f82e85aSdrh     **
8446f82e85aSdrh     **            x=5 AND z<10
8456f82e85aSdrh     **
8466f82e85aSdrh     **         N may be zero if there are inequality constraints.
8476f82e85aSdrh     **         If there are no inequality constraints, then N is at
8486f82e85aSdrh     **         least one.
8496f82e85aSdrh     **
8506f82e85aSdrh     **         This case is also used when there are no WHERE clause
8516f82e85aSdrh     **         constraints but an index is selected anyway, in order
8526f82e85aSdrh     **         to force the output order to conform to an ORDER BY.
8536f82e85aSdrh     */
8546f82e85aSdrh     static const u8 aStartOp[] = {
8556f82e85aSdrh       0,
8566f82e85aSdrh       0,
8576f82e85aSdrh       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
8586f82e85aSdrh       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
8596f82e85aSdrh       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
8606f82e85aSdrh       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
8616f82e85aSdrh       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
8626f82e85aSdrh       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
8636f82e85aSdrh     };
8646f82e85aSdrh     static const u8 aEndOp[] = {
8656f82e85aSdrh       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
8666f82e85aSdrh       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
8676f82e85aSdrh       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
8686f82e85aSdrh       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
8696f82e85aSdrh     };
8706f82e85aSdrh     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
8716f82e85aSdrh     int regBase;                 /* Base register holding constraint values */
8726f82e85aSdrh     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
8736f82e85aSdrh     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
8746f82e85aSdrh     int startEq;                 /* True if range start uses ==, >= or <= */
8756f82e85aSdrh     int endEq;                   /* True if range end uses ==, >= or <= */
8766f82e85aSdrh     int start_constraints;       /* Start of range is constrained */
8776f82e85aSdrh     int nConstraint;             /* Number of constraint terms */
8786f82e85aSdrh     Index *pIdx;                 /* The index we will be using */
8796f82e85aSdrh     int iIdxCur;                 /* The VDBE cursor for the index */
8806f82e85aSdrh     int nExtraReg = 0;           /* Number of extra registers needed */
8816f82e85aSdrh     int op;                      /* Instruction opcode */
8826f82e85aSdrh     char *zStartAff;             /* Affinity for start of range constraint */
8836f82e85aSdrh     char cEndAff = 0;            /* Affinity for end of range constraint */
8846f82e85aSdrh     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
8856f82e85aSdrh     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
8866f82e85aSdrh 
8876f82e85aSdrh     pIdx = pLoop->u.btree.pIndex;
8886f82e85aSdrh     iIdxCur = pLevel->iIdxCur;
8896f82e85aSdrh     assert( nEq>=pLoop->nSkip );
8906f82e85aSdrh 
8916f82e85aSdrh     /* If this loop satisfies a sort order (pOrderBy) request that
8926f82e85aSdrh     ** was passed to this function to implement a "SELECT min(x) ..."
8936f82e85aSdrh     ** query, then the caller will only allow the loop to run for
8946f82e85aSdrh     ** a single iteration. This means that the first row returned
8956f82e85aSdrh     ** should not have a NULL value stored in 'x'. If column 'x' is
8966f82e85aSdrh     ** the first one after the nEq equality constraints in the index,
8976f82e85aSdrh     ** this requires some special handling.
8986f82e85aSdrh     */
8996f82e85aSdrh     assert( pWInfo->pOrderBy==0
9006f82e85aSdrh          || pWInfo->pOrderBy->nExpr==1
9016f82e85aSdrh          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
9026f82e85aSdrh     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
9036f82e85aSdrh      && pWInfo->nOBSat>0
9046f82e85aSdrh      && (pIdx->nKeyCol>nEq)
9056f82e85aSdrh     ){
9066f82e85aSdrh       assert( pLoop->nSkip==0 );
9076f82e85aSdrh       bSeekPastNull = 1;
9086f82e85aSdrh       nExtraReg = 1;
9096f82e85aSdrh     }
9106f82e85aSdrh 
9116f82e85aSdrh     /* Find any inequality constraint terms for the start and end
9126f82e85aSdrh     ** of the range.
9136f82e85aSdrh     */
9146f82e85aSdrh     j = nEq;
9156f82e85aSdrh     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
9166f82e85aSdrh       pRangeStart = pLoop->aLTerm[j++];
9176f82e85aSdrh       nExtraReg = 1;
9186f82e85aSdrh       /* Like optimization range constraints always occur in pairs */
9196f82e85aSdrh       assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
9206f82e85aSdrh               (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
9216f82e85aSdrh     }
9226f82e85aSdrh     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
9236f82e85aSdrh       pRangeEnd = pLoop->aLTerm[j++];
9246f82e85aSdrh       nExtraReg = 1;
9256f82e85aSdrh       if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
9266f82e85aSdrh         assert( pRangeStart!=0 );                     /* LIKE opt constraints */
9276f82e85aSdrh         assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
9286f82e85aSdrh         pLevel->iLikeRepCntr = ++pParse->nMem;
9296f82e85aSdrh         testcase( bRev );
9306f82e85aSdrh         testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
9316f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_Integer,
9326f82e85aSdrh                           bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
9336f82e85aSdrh                           pLevel->iLikeRepCntr);
9346f82e85aSdrh         VdbeComment((v, "LIKE loop counter"));
9356f82e85aSdrh         pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
9366f82e85aSdrh       }
9376f82e85aSdrh       if( pRangeStart==0
9386f82e85aSdrh        && (j = pIdx->aiColumn[nEq])>=0
9396f82e85aSdrh        && pIdx->pTable->aCol[j].notNull==0
9406f82e85aSdrh       ){
9416f82e85aSdrh         bSeekPastNull = 1;
9426f82e85aSdrh       }
9436f82e85aSdrh     }
9446f82e85aSdrh     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
9456f82e85aSdrh 
9466f82e85aSdrh     /* Generate code to evaluate all constraint terms using == or IN
9476f82e85aSdrh     ** and store the values of those terms in an array of registers
9486f82e85aSdrh     ** starting at regBase.
9496f82e85aSdrh     */
9506f82e85aSdrh     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
9516f82e85aSdrh     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
9526f82e85aSdrh     if( zStartAff ) cEndAff = zStartAff[nEq];
9536f82e85aSdrh     addrNxt = pLevel->addrNxt;
9546f82e85aSdrh 
9556f82e85aSdrh     /* If we are doing a reverse order scan on an ascending index, or
9566f82e85aSdrh     ** a forward order scan on a descending index, interchange the
9576f82e85aSdrh     ** start and end terms (pRangeStart and pRangeEnd).
9586f82e85aSdrh     */
9596f82e85aSdrh     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
9606f82e85aSdrh      || (bRev && pIdx->nKeyCol==nEq)
9616f82e85aSdrh     ){
9626f82e85aSdrh       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
9636f82e85aSdrh       SWAP(u8, bSeekPastNull, bStopAtNull);
9646f82e85aSdrh     }
9656f82e85aSdrh 
9666f82e85aSdrh     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
9676f82e85aSdrh     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
9686f82e85aSdrh     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
9696f82e85aSdrh     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
9706f82e85aSdrh     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
9716f82e85aSdrh     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
9726f82e85aSdrh     start_constraints = pRangeStart || nEq>0;
9736f82e85aSdrh 
9746f82e85aSdrh     /* Seek the index cursor to the start of the range. */
9756f82e85aSdrh     nConstraint = nEq;
9766f82e85aSdrh     if( pRangeStart ){
9776f82e85aSdrh       Expr *pRight = pRangeStart->pExpr->pRight;
9786f82e85aSdrh       sqlite3ExprCode(pParse, pRight, regBase+nEq);
9796f82e85aSdrh       whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
9806f82e85aSdrh       if( (pRangeStart->wtFlags & TERM_VNULL)==0
9816f82e85aSdrh        && sqlite3ExprCanBeNull(pRight)
9826f82e85aSdrh       ){
9836f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
9846f82e85aSdrh         VdbeCoverage(v);
9856f82e85aSdrh       }
9866f82e85aSdrh       if( zStartAff ){
9876f82e85aSdrh         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
9886f82e85aSdrh           /* Since the comparison is to be performed with no conversions
9896f82e85aSdrh           ** applied to the operands, set the affinity to apply to pRight to
9906f82e85aSdrh           ** SQLITE_AFF_BLOB.  */
9916f82e85aSdrh           zStartAff[nEq] = SQLITE_AFF_BLOB;
9926f82e85aSdrh         }
9936f82e85aSdrh         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
9946f82e85aSdrh           zStartAff[nEq] = SQLITE_AFF_BLOB;
9956f82e85aSdrh         }
9966f82e85aSdrh       }
9976f82e85aSdrh       nConstraint++;
9986f82e85aSdrh       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
9996f82e85aSdrh     }else if( bSeekPastNull ){
10006f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
10016f82e85aSdrh       nConstraint++;
10026f82e85aSdrh       startEq = 0;
10036f82e85aSdrh       start_constraints = 1;
10046f82e85aSdrh     }
10056f82e85aSdrh     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
10066f82e85aSdrh     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
10076f82e85aSdrh     assert( op!=0 );
10086f82e85aSdrh     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
10096f82e85aSdrh     VdbeCoverage(v);
10106f82e85aSdrh     VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
10116f82e85aSdrh     VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
10126f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
10136f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
10146f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
10156f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
10166f82e85aSdrh 
10176f82e85aSdrh     /* Load the value for the inequality constraint at the end of the
10186f82e85aSdrh     ** range (if any).
10196f82e85aSdrh     */
10206f82e85aSdrh     nConstraint = nEq;
10216f82e85aSdrh     if( pRangeEnd ){
10226f82e85aSdrh       Expr *pRight = pRangeEnd->pExpr->pRight;
10236f82e85aSdrh       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
10246f82e85aSdrh       sqlite3ExprCode(pParse, pRight, regBase+nEq);
10256f82e85aSdrh       whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
10266f82e85aSdrh       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
10276f82e85aSdrh        && sqlite3ExprCanBeNull(pRight)
10286f82e85aSdrh       ){
10296f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
10306f82e85aSdrh         VdbeCoverage(v);
10316f82e85aSdrh       }
10326f82e85aSdrh       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
10336f82e85aSdrh        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
10346f82e85aSdrh       ){
10356f82e85aSdrh         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
10366f82e85aSdrh       }
10376f82e85aSdrh       nConstraint++;
10386f82e85aSdrh       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
10396f82e85aSdrh     }else if( bStopAtNull ){
10406f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
10416f82e85aSdrh       endEq = 0;
10426f82e85aSdrh       nConstraint++;
10436f82e85aSdrh     }
10446f82e85aSdrh     sqlite3DbFree(db, zStartAff);
10456f82e85aSdrh 
10466f82e85aSdrh     /* Top of the loop body */
10476f82e85aSdrh     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
10486f82e85aSdrh 
10496f82e85aSdrh     /* Check if the index cursor is past the end of the range. */
10506f82e85aSdrh     if( nConstraint ){
10516f82e85aSdrh       op = aEndOp[bRev*2 + endEq];
10526f82e85aSdrh       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
10536f82e85aSdrh       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
10546f82e85aSdrh       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
10556f82e85aSdrh       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
10566f82e85aSdrh       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
10576f82e85aSdrh     }
10586f82e85aSdrh 
10596f82e85aSdrh     /* Seek the table cursor, if required */
10606f82e85aSdrh     disableTerm(pLevel, pRangeStart);
10616f82e85aSdrh     disableTerm(pLevel, pRangeEnd);
10626f82e85aSdrh     if( omitTable ){
10636f82e85aSdrh       /* pIdx is a covering index.  No need to access the main table. */
10646f82e85aSdrh     }else if( HasRowid(pIdx->pTable) ){
10656f82e85aSdrh       iRowidReg = ++pParse->nMem;
10666f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
10676f82e85aSdrh       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
10686f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
10696f82e85aSdrh     }else if( iCur!=iIdxCur ){
10706f82e85aSdrh       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
10716f82e85aSdrh       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
10726f82e85aSdrh       for(j=0; j<pPk->nKeyCol; j++){
10736f82e85aSdrh         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
10746f82e85aSdrh         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
10756f82e85aSdrh       }
10766f82e85aSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
10776f82e85aSdrh                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
10786f82e85aSdrh     }
10796f82e85aSdrh 
10806f82e85aSdrh     /* Record the instruction used to terminate the loop. Disable
10816f82e85aSdrh     ** WHERE clause terms made redundant by the index range scan.
10826f82e85aSdrh     */
10836f82e85aSdrh     if( pLoop->wsFlags & WHERE_ONEROW ){
10846f82e85aSdrh       pLevel->op = OP_Noop;
10856f82e85aSdrh     }else if( bRev ){
10866f82e85aSdrh       pLevel->op = OP_Prev;
10876f82e85aSdrh     }else{
10886f82e85aSdrh       pLevel->op = OP_Next;
10896f82e85aSdrh     }
10906f82e85aSdrh     pLevel->p1 = iIdxCur;
10916f82e85aSdrh     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
10926f82e85aSdrh     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
10936f82e85aSdrh       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
10946f82e85aSdrh     }else{
10956f82e85aSdrh       assert( pLevel->p5==0 );
10966f82e85aSdrh     }
10976f82e85aSdrh   }else
10986f82e85aSdrh 
10996f82e85aSdrh #ifndef SQLITE_OMIT_OR_OPTIMIZATION
11006f82e85aSdrh   if( pLoop->wsFlags & WHERE_MULTI_OR ){
11016f82e85aSdrh     /* Case 5:  Two or more separately indexed terms connected by OR
11026f82e85aSdrh     **
11036f82e85aSdrh     ** Example:
11046f82e85aSdrh     **
11056f82e85aSdrh     **   CREATE TABLE t1(a,b,c,d);
11066f82e85aSdrh     **   CREATE INDEX i1 ON t1(a);
11076f82e85aSdrh     **   CREATE INDEX i2 ON t1(b);
11086f82e85aSdrh     **   CREATE INDEX i3 ON t1(c);
11096f82e85aSdrh     **
11106f82e85aSdrh     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
11116f82e85aSdrh     **
11126f82e85aSdrh     ** In the example, there are three indexed terms connected by OR.
11136f82e85aSdrh     ** The top of the loop looks like this:
11146f82e85aSdrh     **
11156f82e85aSdrh     **          Null       1                # Zero the rowset in reg 1
11166f82e85aSdrh     **
11176f82e85aSdrh     ** Then, for each indexed term, the following. The arguments to
11186f82e85aSdrh     ** RowSetTest are such that the rowid of the current row is inserted
11196f82e85aSdrh     ** into the RowSet. If it is already present, control skips the
11206f82e85aSdrh     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
11216f82e85aSdrh     **
11226f82e85aSdrh     **        sqlite3WhereBegin(<term>)
11236f82e85aSdrh     **          RowSetTest                  # Insert rowid into rowset
11246f82e85aSdrh     **          Gosub      2 A
11256f82e85aSdrh     **        sqlite3WhereEnd()
11266f82e85aSdrh     **
11276f82e85aSdrh     ** Following the above, code to terminate the loop. Label A, the target
11286f82e85aSdrh     ** of the Gosub above, jumps to the instruction right after the Goto.
11296f82e85aSdrh     **
11306f82e85aSdrh     **          Null       1                # Zero the rowset in reg 1
11316f82e85aSdrh     **          Goto       B                # The loop is finished.
11326f82e85aSdrh     **
11336f82e85aSdrh     **       A: <loop body>                 # Return data, whatever.
11346f82e85aSdrh     **
11356f82e85aSdrh     **          Return     2                # Jump back to the Gosub
11366f82e85aSdrh     **
11376f82e85aSdrh     **       B: <after the loop>
11386f82e85aSdrh     **
11396f82e85aSdrh     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
11406f82e85aSdrh     ** use an ephemeral index instead of a RowSet to record the primary
11416f82e85aSdrh     ** keys of the rows we have already seen.
11426f82e85aSdrh     **
11436f82e85aSdrh     */
11446f82e85aSdrh     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
11456f82e85aSdrh     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
11466f82e85aSdrh     Index *pCov = 0;             /* Potential covering index (or NULL) */
11476f82e85aSdrh     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
11486f82e85aSdrh 
11496f82e85aSdrh     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
11506f82e85aSdrh     int regRowset = 0;                        /* Register for RowSet object */
11516f82e85aSdrh     int regRowid = 0;                         /* Register holding rowid */
11526f82e85aSdrh     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
11536f82e85aSdrh     int iRetInit;                             /* Address of regReturn init */
11546f82e85aSdrh     int untestedTerms = 0;             /* Some terms not completely tested */
11556f82e85aSdrh     int ii;                            /* Loop counter */
11566f82e85aSdrh     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
11576f82e85aSdrh     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
11586f82e85aSdrh     Table *pTab = pTabItem->pTab;
11596f82e85aSdrh 
11606f82e85aSdrh     pTerm = pLoop->aLTerm[0];
11616f82e85aSdrh     assert( pTerm!=0 );
11626f82e85aSdrh     assert( pTerm->eOperator & WO_OR );
11636f82e85aSdrh     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
11646f82e85aSdrh     pOrWc = &pTerm->u.pOrInfo->wc;
11656f82e85aSdrh     pLevel->op = OP_Return;
11666f82e85aSdrh     pLevel->p1 = regReturn;
11676f82e85aSdrh 
11686f82e85aSdrh     /* Set up a new SrcList in pOrTab containing the table being scanned
11696f82e85aSdrh     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
11706f82e85aSdrh     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
11716f82e85aSdrh     */
11726f82e85aSdrh     if( pWInfo->nLevel>1 ){
11736f82e85aSdrh       int nNotReady;                 /* The number of notReady tables */
11746f82e85aSdrh       struct SrcList_item *origSrc;     /* Original list of tables */
11756f82e85aSdrh       nNotReady = pWInfo->nLevel - iLevel - 1;
11766f82e85aSdrh       pOrTab = sqlite3StackAllocRaw(db,
11776f82e85aSdrh                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
11786f82e85aSdrh       if( pOrTab==0 ) return notReady;
11796f82e85aSdrh       pOrTab->nAlloc = (u8)(nNotReady + 1);
11806f82e85aSdrh       pOrTab->nSrc = pOrTab->nAlloc;
11816f82e85aSdrh       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
11826f82e85aSdrh       origSrc = pWInfo->pTabList->a;
11836f82e85aSdrh       for(k=1; k<=nNotReady; k++){
11846f82e85aSdrh         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
11856f82e85aSdrh       }
11866f82e85aSdrh     }else{
11876f82e85aSdrh       pOrTab = pWInfo->pTabList;
11886f82e85aSdrh     }
11896f82e85aSdrh 
11906f82e85aSdrh     /* Initialize the rowset register to contain NULL. An SQL NULL is
11916f82e85aSdrh     ** equivalent to an empty rowset.  Or, create an ephemeral index
11926f82e85aSdrh     ** capable of holding primary keys in the case of a WITHOUT ROWID.
11936f82e85aSdrh     **
11946f82e85aSdrh     ** Also initialize regReturn to contain the address of the instruction
11956f82e85aSdrh     ** immediately following the OP_Return at the bottom of the loop. This
11966f82e85aSdrh     ** is required in a few obscure LEFT JOIN cases where control jumps
11976f82e85aSdrh     ** over the top of the loop into the body of it. In this case the
11986f82e85aSdrh     ** correct response for the end-of-loop code (the OP_Return) is to
11996f82e85aSdrh     ** fall through to the next instruction, just as an OP_Next does if
12006f82e85aSdrh     ** called on an uninitialized cursor.
12016f82e85aSdrh     */
12026f82e85aSdrh     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
12036f82e85aSdrh       if( HasRowid(pTab) ){
12046f82e85aSdrh         regRowset = ++pParse->nMem;
12056f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
12066f82e85aSdrh       }else{
12076f82e85aSdrh         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
12086f82e85aSdrh         regRowset = pParse->nTab++;
12096f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
12106f82e85aSdrh         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
12116f82e85aSdrh       }
12126f82e85aSdrh       regRowid = ++pParse->nMem;
12136f82e85aSdrh     }
12146f82e85aSdrh     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
12156f82e85aSdrh 
12166f82e85aSdrh     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
12176f82e85aSdrh     ** Then for every term xN, evaluate as the subexpression: xN AND z
12186f82e85aSdrh     ** That way, terms in y that are factored into the disjunction will
12196f82e85aSdrh     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
12206f82e85aSdrh     **
12216f82e85aSdrh     ** Actually, each subexpression is converted to "xN AND w" where w is
12226f82e85aSdrh     ** the "interesting" terms of z - terms that did not originate in the
12236f82e85aSdrh     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
12246f82e85aSdrh     ** indices.
12256f82e85aSdrh     **
12266f82e85aSdrh     ** This optimization also only applies if the (x1 OR x2 OR ...) term
12276f82e85aSdrh     ** is not contained in the ON clause of a LEFT JOIN.
12286f82e85aSdrh     ** See ticket http://www.sqlite.org/src/info/f2369304e4
12296f82e85aSdrh     */
12306f82e85aSdrh     if( pWC->nTerm>1 ){
12316f82e85aSdrh       int iTerm;
12326f82e85aSdrh       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
12336f82e85aSdrh         Expr *pExpr = pWC->a[iTerm].pExpr;
12346f82e85aSdrh         if( &pWC->a[iTerm] == pTerm ) continue;
12356f82e85aSdrh         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
12366f82e85aSdrh         if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
12376f82e85aSdrh         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
12386f82e85aSdrh         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
12396f82e85aSdrh         pExpr = sqlite3ExprDup(db, pExpr, 0);
12406f82e85aSdrh         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
12416f82e85aSdrh       }
12426f82e85aSdrh       if( pAndExpr ){
12436f82e85aSdrh         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
12446f82e85aSdrh       }
12456f82e85aSdrh     }
12466f82e85aSdrh 
12476f82e85aSdrh     /* Run a separate WHERE clause for each term of the OR clause.  After
12486f82e85aSdrh     ** eliminating duplicates from other WHERE clauses, the action for each
12496f82e85aSdrh     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
12506f82e85aSdrh     */
12516f82e85aSdrh     wctrlFlags =  WHERE_OMIT_OPEN_CLOSE
12526f82e85aSdrh                 | WHERE_FORCE_TABLE
12536f82e85aSdrh                 | WHERE_ONETABLE_ONLY
12546f82e85aSdrh                 | WHERE_NO_AUTOINDEX;
12556f82e85aSdrh     for(ii=0; ii<pOrWc->nTerm; ii++){
12566f82e85aSdrh       WhereTerm *pOrTerm = &pOrWc->a[ii];
12576f82e85aSdrh       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
12586f82e85aSdrh         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
12596f82e85aSdrh         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
12606f82e85aSdrh         int j1 = 0;                     /* Address of jump operation */
12616f82e85aSdrh         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
12626f82e85aSdrh           pAndExpr->pLeft = pOrExpr;
12636f82e85aSdrh           pOrExpr = pAndExpr;
12646f82e85aSdrh         }
12656f82e85aSdrh         /* Loop through table entries that match term pOrTerm. */
12666f82e85aSdrh         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
12676f82e85aSdrh         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
12686f82e85aSdrh                                       wctrlFlags, iCovCur);
12696f82e85aSdrh         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
12706f82e85aSdrh         if( pSubWInfo ){
12716f82e85aSdrh           WhereLoop *pSubLoop;
12726f82e85aSdrh           int addrExplain = sqlite3WhereExplainOneScan(
12736f82e85aSdrh               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
12746f82e85aSdrh           );
12756f82e85aSdrh           sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
12766f82e85aSdrh 
12776f82e85aSdrh           /* This is the sub-WHERE clause body.  First skip over
12786f82e85aSdrh           ** duplicate rows from prior sub-WHERE clauses, and record the
12796f82e85aSdrh           ** rowid (or PRIMARY KEY) for the current row so that the same
12806f82e85aSdrh           ** row will be skipped in subsequent sub-WHERE clauses.
12816f82e85aSdrh           */
12826f82e85aSdrh           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
12836f82e85aSdrh             int r;
12846f82e85aSdrh             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
12856f82e85aSdrh             if( HasRowid(pTab) ){
12866f82e85aSdrh               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
12876f82e85aSdrh               j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
12886f82e85aSdrh               VdbeCoverage(v);
12896f82e85aSdrh             }else{
12906f82e85aSdrh               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
12916f82e85aSdrh               int nPk = pPk->nKeyCol;
12926f82e85aSdrh               int iPk;
12936f82e85aSdrh 
12946f82e85aSdrh               /* Read the PK into an array of temp registers. */
12956f82e85aSdrh               r = sqlite3GetTempRange(pParse, nPk);
12966f82e85aSdrh               for(iPk=0; iPk<nPk; iPk++){
12976f82e85aSdrh                 int iCol = pPk->aiColumn[iPk];
1298d3e3f0b4Sdrh                 int rx;
1299d3e3f0b4Sdrh                 rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0);
1300d3e3f0b4Sdrh                 if( rx!=r+iPk ){
1301d3e3f0b4Sdrh                   sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk);
1302d3e3f0b4Sdrh                 }
13036f82e85aSdrh               }
13046f82e85aSdrh 
13056f82e85aSdrh               /* Check if the temp table already contains this key. If so,
13066f82e85aSdrh               ** the row has already been included in the result set and
13076f82e85aSdrh               ** can be ignored (by jumping past the Gosub below). Otherwise,
13086f82e85aSdrh               ** insert the key into the temp table and proceed with processing
13096f82e85aSdrh               ** the row.
13106f82e85aSdrh               **
13116f82e85aSdrh               ** Use some of the same optimizations as OP_RowSetTest: If iSet
13126f82e85aSdrh               ** is zero, assume that the key cannot already be present in
13136f82e85aSdrh               ** the temp table. And if iSet is -1, assume that there is no
13146f82e85aSdrh               ** need to insert the key into the temp table, as it will never
13156f82e85aSdrh               ** be tested for.  */
13166f82e85aSdrh               if( iSet ){
13176f82e85aSdrh                 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
13186f82e85aSdrh                 VdbeCoverage(v);
13196f82e85aSdrh               }
13206f82e85aSdrh               if( iSet>=0 ){
13216f82e85aSdrh                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
13226f82e85aSdrh                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
13236f82e85aSdrh                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
13246f82e85aSdrh               }
13256f82e85aSdrh 
13266f82e85aSdrh               /* Release the array of temp registers */
13276f82e85aSdrh               sqlite3ReleaseTempRange(pParse, r, nPk);
13286f82e85aSdrh             }
13296f82e85aSdrh           }
13306f82e85aSdrh 
13316f82e85aSdrh           /* Invoke the main loop body as a subroutine */
13326f82e85aSdrh           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
13336f82e85aSdrh 
13346f82e85aSdrh           /* Jump here (skipping the main loop body subroutine) if the
13356f82e85aSdrh           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
13366f82e85aSdrh           if( j1 ) sqlite3VdbeJumpHere(v, j1);
13376f82e85aSdrh 
13386f82e85aSdrh           /* The pSubWInfo->untestedTerms flag means that this OR term
13396f82e85aSdrh           ** contained one or more AND term from a notReady table.  The
13406f82e85aSdrh           ** terms from the notReady table could not be tested and will
13416f82e85aSdrh           ** need to be tested later.
13426f82e85aSdrh           */
13436f82e85aSdrh           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
13446f82e85aSdrh 
13456f82e85aSdrh           /* If all of the OR-connected terms are optimized using the same
13466f82e85aSdrh           ** index, and the index is opened using the same cursor number
13476f82e85aSdrh           ** by each call to sqlite3WhereBegin() made by this loop, it may
13486f82e85aSdrh           ** be possible to use that index as a covering index.
13496f82e85aSdrh           **
13506f82e85aSdrh           ** If the call to sqlite3WhereBegin() above resulted in a scan that
13516f82e85aSdrh           ** uses an index, and this is either the first OR-connected term
13526f82e85aSdrh           ** processed or the index is the same as that used by all previous
13536f82e85aSdrh           ** terms, set pCov to the candidate covering index. Otherwise, set
13546f82e85aSdrh           ** pCov to NULL to indicate that no candidate covering index will
13556f82e85aSdrh           ** be available.
13566f82e85aSdrh           */
13576f82e85aSdrh           pSubLoop = pSubWInfo->a[0].pWLoop;
13586f82e85aSdrh           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
13596f82e85aSdrh           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
13606f82e85aSdrh            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
13616f82e85aSdrh            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
13626f82e85aSdrh           ){
13636f82e85aSdrh             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
13646f82e85aSdrh             pCov = pSubLoop->u.btree.pIndex;
13656f82e85aSdrh             wctrlFlags |= WHERE_REOPEN_IDX;
13666f82e85aSdrh           }else{
13676f82e85aSdrh             pCov = 0;
13686f82e85aSdrh           }
13696f82e85aSdrh 
13706f82e85aSdrh           /* Finish the loop through table entries that match term pOrTerm. */
13716f82e85aSdrh           sqlite3WhereEnd(pSubWInfo);
13726f82e85aSdrh         }
13736f82e85aSdrh       }
13746f82e85aSdrh     }
13756f82e85aSdrh     pLevel->u.pCovidx = pCov;
13766f82e85aSdrh     if( pCov ) pLevel->iIdxCur = iCovCur;
13776f82e85aSdrh     if( pAndExpr ){
13786f82e85aSdrh       pAndExpr->pLeft = 0;
13796f82e85aSdrh       sqlite3ExprDelete(db, pAndExpr);
13806f82e85aSdrh     }
13816f82e85aSdrh     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
13826f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
13836f82e85aSdrh     sqlite3VdbeResolveLabel(v, iLoopBody);
13846f82e85aSdrh 
13856f82e85aSdrh     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
13866f82e85aSdrh     if( !untestedTerms ) disableTerm(pLevel, pTerm);
13876f82e85aSdrh   }else
13886f82e85aSdrh #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
13896f82e85aSdrh 
13906f82e85aSdrh   {
13916f82e85aSdrh     /* Case 6:  There is no usable index.  We must do a complete
13926f82e85aSdrh     **          scan of the entire table.
13936f82e85aSdrh     */
13946f82e85aSdrh     static const u8 aStep[] = { OP_Next, OP_Prev };
13956f82e85aSdrh     static const u8 aStart[] = { OP_Rewind, OP_Last };
13966f82e85aSdrh     assert( bRev==0 || bRev==1 );
13978a48b9c0Sdrh     if( pTabItem->fg.isRecursive ){
13986f82e85aSdrh       /* Tables marked isRecursive have only a single row that is stored in
13996f82e85aSdrh       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
14006f82e85aSdrh       pLevel->op = OP_Noop;
14016f82e85aSdrh     }else{
14026f82e85aSdrh       pLevel->op = aStep[bRev];
14036f82e85aSdrh       pLevel->p1 = iCur;
14046f82e85aSdrh       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
14056f82e85aSdrh       VdbeCoverageIf(v, bRev==0);
14066f82e85aSdrh       VdbeCoverageIf(v, bRev!=0);
14076f82e85aSdrh       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
14086f82e85aSdrh     }
14096f82e85aSdrh   }
14106f82e85aSdrh 
14116f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
14126f82e85aSdrh   pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
14136f82e85aSdrh #endif
14146f82e85aSdrh 
14156f82e85aSdrh   /* Insert code to test every subexpression that can be completely
14166f82e85aSdrh   ** computed using the current set of tables.
14176f82e85aSdrh   */
14186f82e85aSdrh   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
14196f82e85aSdrh     Expr *pE;
14206f82e85aSdrh     int skipLikeAddr = 0;
14216f82e85aSdrh     testcase( pTerm->wtFlags & TERM_VIRTUAL );
14226f82e85aSdrh     testcase( pTerm->wtFlags & TERM_CODED );
14236f82e85aSdrh     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
14246f82e85aSdrh     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
14256f82e85aSdrh       testcase( pWInfo->untestedTerms==0
14266f82e85aSdrh                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
14276f82e85aSdrh       pWInfo->untestedTerms = 1;
14286f82e85aSdrh       continue;
14296f82e85aSdrh     }
14306f82e85aSdrh     pE = pTerm->pExpr;
14316f82e85aSdrh     assert( pE!=0 );
14326f82e85aSdrh     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
14336f82e85aSdrh       continue;
14346f82e85aSdrh     }
14356f82e85aSdrh     if( pTerm->wtFlags & TERM_LIKECOND ){
14366f82e85aSdrh       assert( pLevel->iLikeRepCntr>0 );
14376f82e85aSdrh       skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
14386f82e85aSdrh       VdbeCoverage(v);
14396f82e85aSdrh     }
14406f82e85aSdrh     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
14416f82e85aSdrh     if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
14426f82e85aSdrh     pTerm->wtFlags |= TERM_CODED;
14436f82e85aSdrh   }
14446f82e85aSdrh 
14456f82e85aSdrh   /* Insert code to test for implied constraints based on transitivity
14466f82e85aSdrh   ** of the "==" operator.
14476f82e85aSdrh   **
14486f82e85aSdrh   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
14496f82e85aSdrh   ** and we are coding the t1 loop and the t2 loop has not yet coded,
14506f82e85aSdrh   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
14516f82e85aSdrh   ** the implied "t1.a=123" constraint.
14526f82e85aSdrh   */
14536f82e85aSdrh   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
14546f82e85aSdrh     Expr *pE, *pEAlt;
14556f82e85aSdrh     WhereTerm *pAlt;
14566f82e85aSdrh     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
14576f82e85aSdrh     if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
14586f82e85aSdrh     if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
14596f82e85aSdrh     if( pTerm->leftCursor!=iCur ) continue;
14606f82e85aSdrh     if( pLevel->iLeftJoin ) continue;
14616f82e85aSdrh     pE = pTerm->pExpr;
14626f82e85aSdrh     assert( !ExprHasProperty(pE, EP_FromJoin) );
14636f82e85aSdrh     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
14646f82e85aSdrh     pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
14656f82e85aSdrh                     WO_EQ|WO_IN|WO_IS, 0);
14666f82e85aSdrh     if( pAlt==0 ) continue;
14676f82e85aSdrh     if( pAlt->wtFlags & (TERM_CODED) ) continue;
14686f82e85aSdrh     testcase( pAlt->eOperator & WO_EQ );
14696f82e85aSdrh     testcase( pAlt->eOperator & WO_IS );
14706f82e85aSdrh     testcase( pAlt->eOperator & WO_IN );
14716f82e85aSdrh     VdbeModuleComment((v, "begin transitive constraint"));
14726f82e85aSdrh     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
14736f82e85aSdrh     if( pEAlt ){
14746f82e85aSdrh       *pEAlt = *pAlt->pExpr;
14756f82e85aSdrh       pEAlt->pLeft = pE->pLeft;
14766f82e85aSdrh       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
14776f82e85aSdrh       sqlite3StackFree(db, pEAlt);
14786f82e85aSdrh     }
14796f82e85aSdrh   }
14806f82e85aSdrh 
14816f82e85aSdrh   /* For a LEFT OUTER JOIN, generate code that will record the fact that
14826f82e85aSdrh   ** at least one row of the right table has matched the left table.
14836f82e85aSdrh   */
14846f82e85aSdrh   if( pLevel->iLeftJoin ){
14856f82e85aSdrh     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
14866f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
14876f82e85aSdrh     VdbeComment((v, "record LEFT JOIN hit"));
14886f82e85aSdrh     sqlite3ExprCacheClear(pParse);
14896f82e85aSdrh     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
14906f82e85aSdrh       testcase( pTerm->wtFlags & TERM_VIRTUAL );
14916f82e85aSdrh       testcase( pTerm->wtFlags & TERM_CODED );
14926f82e85aSdrh       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
14936f82e85aSdrh       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
14946f82e85aSdrh         assert( pWInfo->untestedTerms );
14956f82e85aSdrh         continue;
14966f82e85aSdrh       }
14976f82e85aSdrh       assert( pTerm->pExpr );
14986f82e85aSdrh       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
14996f82e85aSdrh       pTerm->wtFlags |= TERM_CODED;
15006f82e85aSdrh     }
15016f82e85aSdrh   }
15026f82e85aSdrh 
15036f82e85aSdrh   return pLevel->notReady;
15046f82e85aSdrh }
1505