xref: /sqlite-3.40.0/src/wherecode.c (revision 6f82e85a)
1*6f82e85aSdrh /*
2*6f82e85aSdrh ** 2015-06-06
3*6f82e85aSdrh **
4*6f82e85aSdrh ** The author disclaims copyright to this source code.  In place of
5*6f82e85aSdrh ** a legal notice, here is a blessing:
6*6f82e85aSdrh **
7*6f82e85aSdrh **    May you do good and not evil.
8*6f82e85aSdrh **    May you find forgiveness for yourself and forgive others.
9*6f82e85aSdrh **    May you share freely, never taking more than you give.
10*6f82e85aSdrh **
11*6f82e85aSdrh *************************************************************************
12*6f82e85aSdrh ** This module contains C code that generates VDBE code used to process
13*6f82e85aSdrh ** the WHERE clause of SQL statements.
14*6f82e85aSdrh **
15*6f82e85aSdrh ** This file was split off from where.c on 2015-06-06 in order to reduce the
16*6f82e85aSdrh ** size of where.c and make it easier to edit.  This file contains the routines
17*6f82e85aSdrh ** that actually generate the bulk of the WHERE loop code.  The original where.c
18*6f82e85aSdrh ** file retains the code that does query planning and analysis.
19*6f82e85aSdrh */
20*6f82e85aSdrh #include "sqliteInt.h"
21*6f82e85aSdrh #include "whereInt.h"
22*6f82e85aSdrh 
23*6f82e85aSdrh #ifndef SQLITE_OMIT_EXPLAIN
24*6f82e85aSdrh /*
25*6f82e85aSdrh ** This routine is a helper for explainIndexRange() below
26*6f82e85aSdrh **
27*6f82e85aSdrh ** pStr holds the text of an expression that we are building up one term
28*6f82e85aSdrh ** at a time.  This routine adds a new term to the end of the expression.
29*6f82e85aSdrh ** Terms are separated by AND so add the "AND" text for second and subsequent
30*6f82e85aSdrh ** terms only.
31*6f82e85aSdrh */
32*6f82e85aSdrh static void explainAppendTerm(
33*6f82e85aSdrh   StrAccum *pStr,             /* The text expression being built */
34*6f82e85aSdrh   int iTerm,                  /* Index of this term.  First is zero */
35*6f82e85aSdrh   const char *zColumn,        /* Name of the column */
36*6f82e85aSdrh   const char *zOp             /* Name of the operator */
37*6f82e85aSdrh ){
38*6f82e85aSdrh   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
39*6f82e85aSdrh   sqlite3StrAccumAppendAll(pStr, zColumn);
40*6f82e85aSdrh   sqlite3StrAccumAppend(pStr, zOp, 1);
41*6f82e85aSdrh   sqlite3StrAccumAppend(pStr, "?", 1);
42*6f82e85aSdrh }
43*6f82e85aSdrh 
44*6f82e85aSdrh /*
45*6f82e85aSdrh ** Argument pLevel describes a strategy for scanning table pTab. This
46*6f82e85aSdrh ** function appends text to pStr that describes the subset of table
47*6f82e85aSdrh ** rows scanned by the strategy in the form of an SQL expression.
48*6f82e85aSdrh **
49*6f82e85aSdrh ** For example, if the query:
50*6f82e85aSdrh **
51*6f82e85aSdrh **   SELECT * FROM t1 WHERE a=1 AND b>2;
52*6f82e85aSdrh **
53*6f82e85aSdrh ** is run and there is an index on (a, b), then this function returns a
54*6f82e85aSdrh ** string similar to:
55*6f82e85aSdrh **
56*6f82e85aSdrh **   "a=? AND b>?"
57*6f82e85aSdrh */
58*6f82e85aSdrh static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
59*6f82e85aSdrh   Index *pIndex = pLoop->u.btree.pIndex;
60*6f82e85aSdrh   u16 nEq = pLoop->u.btree.nEq;
61*6f82e85aSdrh   u16 nSkip = pLoop->nSkip;
62*6f82e85aSdrh   int i, j;
63*6f82e85aSdrh   Column *aCol = pTab->aCol;
64*6f82e85aSdrh   i16 *aiColumn = pIndex->aiColumn;
65*6f82e85aSdrh 
66*6f82e85aSdrh   if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
67*6f82e85aSdrh   sqlite3StrAccumAppend(pStr, " (", 2);
68*6f82e85aSdrh   for(i=0; i<nEq; i++){
69*6f82e85aSdrh     char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
70*6f82e85aSdrh     if( i>=nSkip ){
71*6f82e85aSdrh       explainAppendTerm(pStr, i, z, "=");
72*6f82e85aSdrh     }else{
73*6f82e85aSdrh       if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
74*6f82e85aSdrh       sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
75*6f82e85aSdrh     }
76*6f82e85aSdrh   }
77*6f82e85aSdrh 
78*6f82e85aSdrh   j = i;
79*6f82e85aSdrh   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
80*6f82e85aSdrh     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
81*6f82e85aSdrh     explainAppendTerm(pStr, i++, z, ">");
82*6f82e85aSdrh   }
83*6f82e85aSdrh   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
84*6f82e85aSdrh     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
85*6f82e85aSdrh     explainAppendTerm(pStr, i, z, "<");
86*6f82e85aSdrh   }
87*6f82e85aSdrh   sqlite3StrAccumAppend(pStr, ")", 1);
88*6f82e85aSdrh }
89*6f82e85aSdrh 
90*6f82e85aSdrh /*
91*6f82e85aSdrh ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
92*6f82e85aSdrh ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
93*6f82e85aSdrh ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
94*6f82e85aSdrh ** is added to the output to describe the table scan strategy in pLevel.
95*6f82e85aSdrh **
96*6f82e85aSdrh ** If an OP_Explain opcode is added to the VM, its address is returned.
97*6f82e85aSdrh ** Otherwise, if no OP_Explain is coded, zero is returned.
98*6f82e85aSdrh */
99*6f82e85aSdrh int sqlite3WhereExplainOneScan(
100*6f82e85aSdrh   Parse *pParse,                  /* Parse context */
101*6f82e85aSdrh   SrcList *pTabList,              /* Table list this loop refers to */
102*6f82e85aSdrh   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
103*6f82e85aSdrh   int iLevel,                     /* Value for "level" column of output */
104*6f82e85aSdrh   int iFrom,                      /* Value for "from" column of output */
105*6f82e85aSdrh   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
106*6f82e85aSdrh ){
107*6f82e85aSdrh   int ret = 0;
108*6f82e85aSdrh #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
109*6f82e85aSdrh   if( pParse->explain==2 )
110*6f82e85aSdrh #endif
111*6f82e85aSdrh   {
112*6f82e85aSdrh     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
113*6f82e85aSdrh     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
114*6f82e85aSdrh     sqlite3 *db = pParse->db;     /* Database handle */
115*6f82e85aSdrh     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
116*6f82e85aSdrh     int isSearch;                 /* True for a SEARCH. False for SCAN. */
117*6f82e85aSdrh     WhereLoop *pLoop;             /* The controlling WhereLoop object */
118*6f82e85aSdrh     u32 flags;                    /* Flags that describe this loop */
119*6f82e85aSdrh     char *zMsg;                   /* Text to add to EQP output */
120*6f82e85aSdrh     StrAccum str;                 /* EQP output string */
121*6f82e85aSdrh     char zBuf[100];               /* Initial space for EQP output string */
122*6f82e85aSdrh 
123*6f82e85aSdrh     pLoop = pLevel->pWLoop;
124*6f82e85aSdrh     flags = pLoop->wsFlags;
125*6f82e85aSdrh     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
126*6f82e85aSdrh 
127*6f82e85aSdrh     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
128*6f82e85aSdrh             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
129*6f82e85aSdrh             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
130*6f82e85aSdrh 
131*6f82e85aSdrh     sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
132*6f82e85aSdrh     sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
133*6f82e85aSdrh     if( pItem->pSelect ){
134*6f82e85aSdrh       sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
135*6f82e85aSdrh     }else{
136*6f82e85aSdrh       sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
137*6f82e85aSdrh     }
138*6f82e85aSdrh 
139*6f82e85aSdrh     if( pItem->zAlias ){
140*6f82e85aSdrh       sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
141*6f82e85aSdrh     }
142*6f82e85aSdrh     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
143*6f82e85aSdrh       const char *zFmt = 0;
144*6f82e85aSdrh       Index *pIdx;
145*6f82e85aSdrh 
146*6f82e85aSdrh       assert( pLoop->u.btree.pIndex!=0 );
147*6f82e85aSdrh       pIdx = pLoop->u.btree.pIndex;
148*6f82e85aSdrh       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
149*6f82e85aSdrh       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
150*6f82e85aSdrh         if( isSearch ){
151*6f82e85aSdrh           zFmt = "PRIMARY KEY";
152*6f82e85aSdrh         }
153*6f82e85aSdrh       }else if( flags & WHERE_PARTIALIDX ){
154*6f82e85aSdrh         zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
155*6f82e85aSdrh       }else if( flags & WHERE_AUTO_INDEX ){
156*6f82e85aSdrh         zFmt = "AUTOMATIC COVERING INDEX";
157*6f82e85aSdrh       }else if( flags & WHERE_IDX_ONLY ){
158*6f82e85aSdrh         zFmt = "COVERING INDEX %s";
159*6f82e85aSdrh       }else{
160*6f82e85aSdrh         zFmt = "INDEX %s";
161*6f82e85aSdrh       }
162*6f82e85aSdrh       if( zFmt ){
163*6f82e85aSdrh         sqlite3StrAccumAppend(&str, " USING ", 7);
164*6f82e85aSdrh         sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
165*6f82e85aSdrh         explainIndexRange(&str, pLoop, pItem->pTab);
166*6f82e85aSdrh       }
167*6f82e85aSdrh     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
168*6f82e85aSdrh       const char *zRange;
169*6f82e85aSdrh       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
170*6f82e85aSdrh         zRange = "(rowid=?)";
171*6f82e85aSdrh       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
172*6f82e85aSdrh         zRange = "(rowid>? AND rowid<?)";
173*6f82e85aSdrh       }else if( flags&WHERE_BTM_LIMIT ){
174*6f82e85aSdrh         zRange = "(rowid>?)";
175*6f82e85aSdrh       }else{
176*6f82e85aSdrh         assert( flags&WHERE_TOP_LIMIT);
177*6f82e85aSdrh         zRange = "(rowid<?)";
178*6f82e85aSdrh       }
179*6f82e85aSdrh       sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
180*6f82e85aSdrh       sqlite3StrAccumAppendAll(&str, zRange);
181*6f82e85aSdrh     }
182*6f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
183*6f82e85aSdrh     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
184*6f82e85aSdrh       sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
185*6f82e85aSdrh                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
186*6f82e85aSdrh     }
187*6f82e85aSdrh #endif
188*6f82e85aSdrh #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
189*6f82e85aSdrh     if( pLoop->nOut>=10 ){
190*6f82e85aSdrh       sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
191*6f82e85aSdrh     }else{
192*6f82e85aSdrh       sqlite3StrAccumAppend(&str, " (~1 row)", 9);
193*6f82e85aSdrh     }
194*6f82e85aSdrh #endif
195*6f82e85aSdrh     zMsg = sqlite3StrAccumFinish(&str);
196*6f82e85aSdrh     ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
197*6f82e85aSdrh   }
198*6f82e85aSdrh   return ret;
199*6f82e85aSdrh }
200*6f82e85aSdrh #endif /* SQLITE_OMIT_EXPLAIN */
201*6f82e85aSdrh 
202*6f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
203*6f82e85aSdrh /*
204*6f82e85aSdrh ** Configure the VM passed as the first argument with an
205*6f82e85aSdrh ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
206*6f82e85aSdrh ** implement level pLvl. Argument pSrclist is a pointer to the FROM
207*6f82e85aSdrh ** clause that the scan reads data from.
208*6f82e85aSdrh **
209*6f82e85aSdrh ** If argument addrExplain is not 0, it must be the address of an
210*6f82e85aSdrh ** OP_Explain instruction that describes the same loop.
211*6f82e85aSdrh */
212*6f82e85aSdrh void sqlite3WhereAddScanStatus(
213*6f82e85aSdrh   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
214*6f82e85aSdrh   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
215*6f82e85aSdrh   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
216*6f82e85aSdrh   int addrExplain                 /* Address of OP_Explain (or 0) */
217*6f82e85aSdrh ){
218*6f82e85aSdrh   const char *zObj = 0;
219*6f82e85aSdrh   WhereLoop *pLoop = pLvl->pWLoop;
220*6f82e85aSdrh   if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
221*6f82e85aSdrh     zObj = pLoop->u.btree.pIndex->zName;
222*6f82e85aSdrh   }else{
223*6f82e85aSdrh     zObj = pSrclist->a[pLvl->iFrom].zName;
224*6f82e85aSdrh   }
225*6f82e85aSdrh   sqlite3VdbeScanStatus(
226*6f82e85aSdrh       v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
227*6f82e85aSdrh   );
228*6f82e85aSdrh }
229*6f82e85aSdrh #endif
230*6f82e85aSdrh 
231*6f82e85aSdrh 
232*6f82e85aSdrh /*
233*6f82e85aSdrh ** Disable a term in the WHERE clause.  Except, do not disable the term
234*6f82e85aSdrh ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
235*6f82e85aSdrh ** or USING clause of that join.
236*6f82e85aSdrh **
237*6f82e85aSdrh ** Consider the term t2.z='ok' in the following queries:
238*6f82e85aSdrh **
239*6f82e85aSdrh **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
240*6f82e85aSdrh **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
241*6f82e85aSdrh **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
242*6f82e85aSdrh **
243*6f82e85aSdrh ** The t2.z='ok' is disabled in the in (2) because it originates
244*6f82e85aSdrh ** in the ON clause.  The term is disabled in (3) because it is not part
245*6f82e85aSdrh ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
246*6f82e85aSdrh **
247*6f82e85aSdrh ** Disabling a term causes that term to not be tested in the inner loop
248*6f82e85aSdrh ** of the join.  Disabling is an optimization.  When terms are satisfied
249*6f82e85aSdrh ** by indices, we disable them to prevent redundant tests in the inner
250*6f82e85aSdrh ** loop.  We would get the correct results if nothing were ever disabled,
251*6f82e85aSdrh ** but joins might run a little slower.  The trick is to disable as much
252*6f82e85aSdrh ** as we can without disabling too much.  If we disabled in (1), we'd get
253*6f82e85aSdrh ** the wrong answer.  See ticket #813.
254*6f82e85aSdrh **
255*6f82e85aSdrh ** If all the children of a term are disabled, then that term is also
256*6f82e85aSdrh ** automatically disabled.  In this way, terms get disabled if derived
257*6f82e85aSdrh ** virtual terms are tested first.  For example:
258*6f82e85aSdrh **
259*6f82e85aSdrh **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
260*6f82e85aSdrh **      \___________/     \______/     \_____/
261*6f82e85aSdrh **         parent          child1       child2
262*6f82e85aSdrh **
263*6f82e85aSdrh ** Only the parent term was in the original WHERE clause.  The child1
264*6f82e85aSdrh ** and child2 terms were added by the LIKE optimization.  If both of
265*6f82e85aSdrh ** the virtual child terms are valid, then testing of the parent can be
266*6f82e85aSdrh ** skipped.
267*6f82e85aSdrh **
268*6f82e85aSdrh ** Usually the parent term is marked as TERM_CODED.  But if the parent
269*6f82e85aSdrh ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
270*6f82e85aSdrh ** The TERM_LIKECOND marking indicates that the term should be coded inside
271*6f82e85aSdrh ** a conditional such that is only evaluated on the second pass of a
272*6f82e85aSdrh ** LIKE-optimization loop, when scanning BLOBs instead of strings.
273*6f82e85aSdrh */
274*6f82e85aSdrh static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
275*6f82e85aSdrh   int nLoop = 0;
276*6f82e85aSdrh   while( pTerm
277*6f82e85aSdrh       && (pTerm->wtFlags & TERM_CODED)==0
278*6f82e85aSdrh       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
279*6f82e85aSdrh       && (pLevel->notReady & pTerm->prereqAll)==0
280*6f82e85aSdrh   ){
281*6f82e85aSdrh     if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
282*6f82e85aSdrh       pTerm->wtFlags |= TERM_LIKECOND;
283*6f82e85aSdrh     }else{
284*6f82e85aSdrh       pTerm->wtFlags |= TERM_CODED;
285*6f82e85aSdrh     }
286*6f82e85aSdrh     if( pTerm->iParent<0 ) break;
287*6f82e85aSdrh     pTerm = &pTerm->pWC->a[pTerm->iParent];
288*6f82e85aSdrh     pTerm->nChild--;
289*6f82e85aSdrh     if( pTerm->nChild!=0 ) break;
290*6f82e85aSdrh     nLoop++;
291*6f82e85aSdrh   }
292*6f82e85aSdrh }
293*6f82e85aSdrh 
294*6f82e85aSdrh /*
295*6f82e85aSdrh ** Code an OP_Affinity opcode to apply the column affinity string zAff
296*6f82e85aSdrh ** to the n registers starting at base.
297*6f82e85aSdrh **
298*6f82e85aSdrh ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
299*6f82e85aSdrh ** beginning and end of zAff are ignored.  If all entries in zAff are
300*6f82e85aSdrh ** SQLITE_AFF_BLOB, then no code gets generated.
301*6f82e85aSdrh **
302*6f82e85aSdrh ** This routine makes its own copy of zAff so that the caller is free
303*6f82e85aSdrh ** to modify zAff after this routine returns.
304*6f82e85aSdrh */
305*6f82e85aSdrh static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
306*6f82e85aSdrh   Vdbe *v = pParse->pVdbe;
307*6f82e85aSdrh   if( zAff==0 ){
308*6f82e85aSdrh     assert( pParse->db->mallocFailed );
309*6f82e85aSdrh     return;
310*6f82e85aSdrh   }
311*6f82e85aSdrh   assert( v!=0 );
312*6f82e85aSdrh 
313*6f82e85aSdrh   /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
314*6f82e85aSdrh   ** and end of the affinity string.
315*6f82e85aSdrh   */
316*6f82e85aSdrh   while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
317*6f82e85aSdrh     n--;
318*6f82e85aSdrh     base++;
319*6f82e85aSdrh     zAff++;
320*6f82e85aSdrh   }
321*6f82e85aSdrh   while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
322*6f82e85aSdrh     n--;
323*6f82e85aSdrh   }
324*6f82e85aSdrh 
325*6f82e85aSdrh   /* Code the OP_Affinity opcode if there is anything left to do. */
326*6f82e85aSdrh   if( n>0 ){
327*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
328*6f82e85aSdrh     sqlite3VdbeChangeP4(v, -1, zAff, n);
329*6f82e85aSdrh     sqlite3ExprCacheAffinityChange(pParse, base, n);
330*6f82e85aSdrh   }
331*6f82e85aSdrh }
332*6f82e85aSdrh 
333*6f82e85aSdrh 
334*6f82e85aSdrh /*
335*6f82e85aSdrh ** Generate code for a single equality term of the WHERE clause.  An equality
336*6f82e85aSdrh ** term can be either X=expr or X IN (...).   pTerm is the term to be
337*6f82e85aSdrh ** coded.
338*6f82e85aSdrh **
339*6f82e85aSdrh ** The current value for the constraint is left in register iReg.
340*6f82e85aSdrh **
341*6f82e85aSdrh ** For a constraint of the form X=expr, the expression is evaluated and its
342*6f82e85aSdrh ** result is left on the stack.  For constraints of the form X IN (...)
343*6f82e85aSdrh ** this routine sets up a loop that will iterate over all values of X.
344*6f82e85aSdrh */
345*6f82e85aSdrh static int codeEqualityTerm(
346*6f82e85aSdrh   Parse *pParse,      /* The parsing context */
347*6f82e85aSdrh   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
348*6f82e85aSdrh   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
349*6f82e85aSdrh   int iEq,            /* Index of the equality term within this level */
350*6f82e85aSdrh   int bRev,           /* True for reverse-order IN operations */
351*6f82e85aSdrh   int iTarget         /* Attempt to leave results in this register */
352*6f82e85aSdrh ){
353*6f82e85aSdrh   Expr *pX = pTerm->pExpr;
354*6f82e85aSdrh   Vdbe *v = pParse->pVdbe;
355*6f82e85aSdrh   int iReg;                  /* Register holding results */
356*6f82e85aSdrh 
357*6f82e85aSdrh   assert( iTarget>0 );
358*6f82e85aSdrh   if( pX->op==TK_EQ || pX->op==TK_IS ){
359*6f82e85aSdrh     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
360*6f82e85aSdrh   }else if( pX->op==TK_ISNULL ){
361*6f82e85aSdrh     iReg = iTarget;
362*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
363*6f82e85aSdrh #ifndef SQLITE_OMIT_SUBQUERY
364*6f82e85aSdrh   }else{
365*6f82e85aSdrh     int eType;
366*6f82e85aSdrh     int iTab;
367*6f82e85aSdrh     struct InLoop *pIn;
368*6f82e85aSdrh     WhereLoop *pLoop = pLevel->pWLoop;
369*6f82e85aSdrh 
370*6f82e85aSdrh     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
371*6f82e85aSdrh       && pLoop->u.btree.pIndex!=0
372*6f82e85aSdrh       && pLoop->u.btree.pIndex->aSortOrder[iEq]
373*6f82e85aSdrh     ){
374*6f82e85aSdrh       testcase( iEq==0 );
375*6f82e85aSdrh       testcase( bRev );
376*6f82e85aSdrh       bRev = !bRev;
377*6f82e85aSdrh     }
378*6f82e85aSdrh     assert( pX->op==TK_IN );
379*6f82e85aSdrh     iReg = iTarget;
380*6f82e85aSdrh     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
381*6f82e85aSdrh     if( eType==IN_INDEX_INDEX_DESC ){
382*6f82e85aSdrh       testcase( bRev );
383*6f82e85aSdrh       bRev = !bRev;
384*6f82e85aSdrh     }
385*6f82e85aSdrh     iTab = pX->iTable;
386*6f82e85aSdrh     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
387*6f82e85aSdrh     VdbeCoverageIf(v, bRev);
388*6f82e85aSdrh     VdbeCoverageIf(v, !bRev);
389*6f82e85aSdrh     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
390*6f82e85aSdrh     pLoop->wsFlags |= WHERE_IN_ABLE;
391*6f82e85aSdrh     if( pLevel->u.in.nIn==0 ){
392*6f82e85aSdrh       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
393*6f82e85aSdrh     }
394*6f82e85aSdrh     pLevel->u.in.nIn++;
395*6f82e85aSdrh     pLevel->u.in.aInLoop =
396*6f82e85aSdrh        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
397*6f82e85aSdrh                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
398*6f82e85aSdrh     pIn = pLevel->u.in.aInLoop;
399*6f82e85aSdrh     if( pIn ){
400*6f82e85aSdrh       pIn += pLevel->u.in.nIn - 1;
401*6f82e85aSdrh       pIn->iCur = iTab;
402*6f82e85aSdrh       if( eType==IN_INDEX_ROWID ){
403*6f82e85aSdrh         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
404*6f82e85aSdrh       }else{
405*6f82e85aSdrh         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
406*6f82e85aSdrh       }
407*6f82e85aSdrh       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
408*6f82e85aSdrh       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
409*6f82e85aSdrh     }else{
410*6f82e85aSdrh       pLevel->u.in.nIn = 0;
411*6f82e85aSdrh     }
412*6f82e85aSdrh #endif
413*6f82e85aSdrh   }
414*6f82e85aSdrh   disableTerm(pLevel, pTerm);
415*6f82e85aSdrh   return iReg;
416*6f82e85aSdrh }
417*6f82e85aSdrh 
418*6f82e85aSdrh /*
419*6f82e85aSdrh ** Generate code that will evaluate all == and IN constraints for an
420*6f82e85aSdrh ** index scan.
421*6f82e85aSdrh **
422*6f82e85aSdrh ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
423*6f82e85aSdrh ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
424*6f82e85aSdrh ** The index has as many as three equality constraints, but in this
425*6f82e85aSdrh ** example, the third "c" value is an inequality.  So only two
426*6f82e85aSdrh ** constraints are coded.  This routine will generate code to evaluate
427*6f82e85aSdrh ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
428*6f82e85aSdrh ** in consecutive registers and the index of the first register is returned.
429*6f82e85aSdrh **
430*6f82e85aSdrh ** In the example above nEq==2.  But this subroutine works for any value
431*6f82e85aSdrh ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
432*6f82e85aSdrh ** The only thing it does is allocate the pLevel->iMem memory cell and
433*6f82e85aSdrh ** compute the affinity string.
434*6f82e85aSdrh **
435*6f82e85aSdrh ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
436*6f82e85aSdrh ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
437*6f82e85aSdrh ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
438*6f82e85aSdrh ** occurs after the nEq quality constraints.
439*6f82e85aSdrh **
440*6f82e85aSdrh ** This routine allocates a range of nEq+nExtraReg memory cells and returns
441*6f82e85aSdrh ** the index of the first memory cell in that range. The code that
442*6f82e85aSdrh ** calls this routine will use that memory range to store keys for
443*6f82e85aSdrh ** start and termination conditions of the loop.
444*6f82e85aSdrh ** key value of the loop.  If one or more IN operators appear, then
445*6f82e85aSdrh ** this routine allocates an additional nEq memory cells for internal
446*6f82e85aSdrh ** use.
447*6f82e85aSdrh **
448*6f82e85aSdrh ** Before returning, *pzAff is set to point to a buffer containing a
449*6f82e85aSdrh ** copy of the column affinity string of the index allocated using
450*6f82e85aSdrh ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
451*6f82e85aSdrh ** with equality constraints that use BLOB or NONE affinity are set to
452*6f82e85aSdrh ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
453*6f82e85aSdrh **
454*6f82e85aSdrh **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
455*6f82e85aSdrh **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
456*6f82e85aSdrh **
457*6f82e85aSdrh ** In the example above, the index on t1(a) has TEXT affinity. But since
458*6f82e85aSdrh ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
459*6f82e85aSdrh ** no conversion should be attempted before using a t2.b value as part of
460*6f82e85aSdrh ** a key to search the index. Hence the first byte in the returned affinity
461*6f82e85aSdrh ** string in this example would be set to SQLITE_AFF_BLOB.
462*6f82e85aSdrh */
463*6f82e85aSdrh static int codeAllEqualityTerms(
464*6f82e85aSdrh   Parse *pParse,        /* Parsing context */
465*6f82e85aSdrh   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
466*6f82e85aSdrh   int bRev,             /* Reverse the order of IN operators */
467*6f82e85aSdrh   int nExtraReg,        /* Number of extra registers to allocate */
468*6f82e85aSdrh   char **pzAff          /* OUT: Set to point to affinity string */
469*6f82e85aSdrh ){
470*6f82e85aSdrh   u16 nEq;                      /* The number of == or IN constraints to code */
471*6f82e85aSdrh   u16 nSkip;                    /* Number of left-most columns to skip */
472*6f82e85aSdrh   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
473*6f82e85aSdrh   Index *pIdx;                  /* The index being used for this loop */
474*6f82e85aSdrh   WhereTerm *pTerm;             /* A single constraint term */
475*6f82e85aSdrh   WhereLoop *pLoop;             /* The WhereLoop object */
476*6f82e85aSdrh   int j;                        /* Loop counter */
477*6f82e85aSdrh   int regBase;                  /* Base register */
478*6f82e85aSdrh   int nReg;                     /* Number of registers to allocate */
479*6f82e85aSdrh   char *zAff;                   /* Affinity string to return */
480*6f82e85aSdrh 
481*6f82e85aSdrh   /* This module is only called on query plans that use an index. */
482*6f82e85aSdrh   pLoop = pLevel->pWLoop;
483*6f82e85aSdrh   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
484*6f82e85aSdrh   nEq = pLoop->u.btree.nEq;
485*6f82e85aSdrh   nSkip = pLoop->nSkip;
486*6f82e85aSdrh   pIdx = pLoop->u.btree.pIndex;
487*6f82e85aSdrh   assert( pIdx!=0 );
488*6f82e85aSdrh 
489*6f82e85aSdrh   /* Figure out how many memory cells we will need then allocate them.
490*6f82e85aSdrh   */
491*6f82e85aSdrh   regBase = pParse->nMem + 1;
492*6f82e85aSdrh   nReg = pLoop->u.btree.nEq + nExtraReg;
493*6f82e85aSdrh   pParse->nMem += nReg;
494*6f82e85aSdrh 
495*6f82e85aSdrh   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
496*6f82e85aSdrh   if( !zAff ){
497*6f82e85aSdrh     pParse->db->mallocFailed = 1;
498*6f82e85aSdrh   }
499*6f82e85aSdrh 
500*6f82e85aSdrh   if( nSkip ){
501*6f82e85aSdrh     int iIdxCur = pLevel->iIdxCur;
502*6f82e85aSdrh     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
503*6f82e85aSdrh     VdbeCoverageIf(v, bRev==0);
504*6f82e85aSdrh     VdbeCoverageIf(v, bRev!=0);
505*6f82e85aSdrh     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
506*6f82e85aSdrh     j = sqlite3VdbeAddOp0(v, OP_Goto);
507*6f82e85aSdrh     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
508*6f82e85aSdrh                             iIdxCur, 0, regBase, nSkip);
509*6f82e85aSdrh     VdbeCoverageIf(v, bRev==0);
510*6f82e85aSdrh     VdbeCoverageIf(v, bRev!=0);
511*6f82e85aSdrh     sqlite3VdbeJumpHere(v, j);
512*6f82e85aSdrh     for(j=0; j<nSkip; j++){
513*6f82e85aSdrh       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
514*6f82e85aSdrh       assert( pIdx->aiColumn[j]>=0 );
515*6f82e85aSdrh       VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
516*6f82e85aSdrh     }
517*6f82e85aSdrh   }
518*6f82e85aSdrh 
519*6f82e85aSdrh   /* Evaluate the equality constraints
520*6f82e85aSdrh   */
521*6f82e85aSdrh   assert( zAff==0 || (int)strlen(zAff)>=nEq );
522*6f82e85aSdrh   for(j=nSkip; j<nEq; j++){
523*6f82e85aSdrh     int r1;
524*6f82e85aSdrh     pTerm = pLoop->aLTerm[j];
525*6f82e85aSdrh     assert( pTerm!=0 );
526*6f82e85aSdrh     /* The following testcase is true for indices with redundant columns.
527*6f82e85aSdrh     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
528*6f82e85aSdrh     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
529*6f82e85aSdrh     testcase( pTerm->wtFlags & TERM_VIRTUAL );
530*6f82e85aSdrh     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
531*6f82e85aSdrh     if( r1!=regBase+j ){
532*6f82e85aSdrh       if( nReg==1 ){
533*6f82e85aSdrh         sqlite3ReleaseTempReg(pParse, regBase);
534*6f82e85aSdrh         regBase = r1;
535*6f82e85aSdrh       }else{
536*6f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
537*6f82e85aSdrh       }
538*6f82e85aSdrh     }
539*6f82e85aSdrh     testcase( pTerm->eOperator & WO_ISNULL );
540*6f82e85aSdrh     testcase( pTerm->eOperator & WO_IN );
541*6f82e85aSdrh     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
542*6f82e85aSdrh       Expr *pRight = pTerm->pExpr->pRight;
543*6f82e85aSdrh       if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
544*6f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
545*6f82e85aSdrh         VdbeCoverage(v);
546*6f82e85aSdrh       }
547*6f82e85aSdrh       if( zAff ){
548*6f82e85aSdrh         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
549*6f82e85aSdrh           zAff[j] = SQLITE_AFF_BLOB;
550*6f82e85aSdrh         }
551*6f82e85aSdrh         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
552*6f82e85aSdrh           zAff[j] = SQLITE_AFF_BLOB;
553*6f82e85aSdrh         }
554*6f82e85aSdrh       }
555*6f82e85aSdrh     }
556*6f82e85aSdrh   }
557*6f82e85aSdrh   *pzAff = zAff;
558*6f82e85aSdrh   return regBase;
559*6f82e85aSdrh }
560*6f82e85aSdrh 
561*6f82e85aSdrh /*
562*6f82e85aSdrh ** If the most recently coded instruction is a constant range contraint
563*6f82e85aSdrh ** that originated from the LIKE optimization, then change the P3 to be
564*6f82e85aSdrh ** pLoop->iLikeRepCntr and set P5.
565*6f82e85aSdrh **
566*6f82e85aSdrh ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
567*6f82e85aSdrh ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
568*6f82e85aSdrh ** scan loop run twice, once for strings and a second time for BLOBs.
569*6f82e85aSdrh ** The OP_String opcodes on the second pass convert the upper and lower
570*6f82e85aSdrh ** bound string contants to blobs.  This routine makes the necessary changes
571*6f82e85aSdrh ** to the OP_String opcodes for that to happen.
572*6f82e85aSdrh */
573*6f82e85aSdrh static void whereLikeOptimizationStringFixup(
574*6f82e85aSdrh   Vdbe *v,                /* prepared statement under construction */
575*6f82e85aSdrh   WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
576*6f82e85aSdrh   WhereTerm *pTerm        /* The upper or lower bound just coded */
577*6f82e85aSdrh ){
578*6f82e85aSdrh   if( pTerm->wtFlags & TERM_LIKEOPT ){
579*6f82e85aSdrh     VdbeOp *pOp;
580*6f82e85aSdrh     assert( pLevel->iLikeRepCntr>0 );
581*6f82e85aSdrh     pOp = sqlite3VdbeGetOp(v, -1);
582*6f82e85aSdrh     assert( pOp!=0 );
583*6f82e85aSdrh     assert( pOp->opcode==OP_String8
584*6f82e85aSdrh             || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
585*6f82e85aSdrh     pOp->p3 = pLevel->iLikeRepCntr;
586*6f82e85aSdrh     pOp->p5 = 1;
587*6f82e85aSdrh   }
588*6f82e85aSdrh }
589*6f82e85aSdrh 
590*6f82e85aSdrh 
591*6f82e85aSdrh /*
592*6f82e85aSdrh ** Generate code for the start of the iLevel-th loop in the WHERE clause
593*6f82e85aSdrh ** implementation described by pWInfo.
594*6f82e85aSdrh */
595*6f82e85aSdrh Bitmask sqlite3WhereCodeOneLoopStart(
596*6f82e85aSdrh   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
597*6f82e85aSdrh   int iLevel,          /* Which level of pWInfo->a[] should be coded */
598*6f82e85aSdrh   Bitmask notReady     /* Which tables are currently available */
599*6f82e85aSdrh ){
600*6f82e85aSdrh   int j, k;            /* Loop counters */
601*6f82e85aSdrh   int iCur;            /* The VDBE cursor for the table */
602*6f82e85aSdrh   int addrNxt;         /* Where to jump to continue with the next IN case */
603*6f82e85aSdrh   int omitTable;       /* True if we use the index only */
604*6f82e85aSdrh   int bRev;            /* True if we need to scan in reverse order */
605*6f82e85aSdrh   WhereLevel *pLevel;  /* The where level to be coded */
606*6f82e85aSdrh   WhereLoop *pLoop;    /* The WhereLoop object being coded */
607*6f82e85aSdrh   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
608*6f82e85aSdrh   WhereTerm *pTerm;               /* A WHERE clause term */
609*6f82e85aSdrh   Parse *pParse;                  /* Parsing context */
610*6f82e85aSdrh   sqlite3 *db;                    /* Database connection */
611*6f82e85aSdrh   Vdbe *v;                        /* The prepared stmt under constructions */
612*6f82e85aSdrh   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
613*6f82e85aSdrh   int addrBrk;                    /* Jump here to break out of the loop */
614*6f82e85aSdrh   int addrCont;                   /* Jump here to continue with next cycle */
615*6f82e85aSdrh   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
616*6f82e85aSdrh   int iReleaseReg = 0;      /* Temp register to free before returning */
617*6f82e85aSdrh 
618*6f82e85aSdrh   pParse = pWInfo->pParse;
619*6f82e85aSdrh   v = pParse->pVdbe;
620*6f82e85aSdrh   pWC = &pWInfo->sWC;
621*6f82e85aSdrh   db = pParse->db;
622*6f82e85aSdrh   pLevel = &pWInfo->a[iLevel];
623*6f82e85aSdrh   pLoop = pLevel->pWLoop;
624*6f82e85aSdrh   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
625*6f82e85aSdrh   iCur = pTabItem->iCursor;
626*6f82e85aSdrh   pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
627*6f82e85aSdrh   bRev = (pWInfo->revMask>>iLevel)&1;
628*6f82e85aSdrh   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
629*6f82e85aSdrh            && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
630*6f82e85aSdrh   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
631*6f82e85aSdrh 
632*6f82e85aSdrh   /* Create labels for the "break" and "continue" instructions
633*6f82e85aSdrh   ** for the current loop.  Jump to addrBrk to break out of a loop.
634*6f82e85aSdrh   ** Jump to cont to go immediately to the next iteration of the
635*6f82e85aSdrh   ** loop.
636*6f82e85aSdrh   **
637*6f82e85aSdrh   ** When there is an IN operator, we also have a "addrNxt" label that
638*6f82e85aSdrh   ** means to continue with the next IN value combination.  When
639*6f82e85aSdrh   ** there are no IN operators in the constraints, the "addrNxt" label
640*6f82e85aSdrh   ** is the same as "addrBrk".
641*6f82e85aSdrh   */
642*6f82e85aSdrh   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
643*6f82e85aSdrh   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
644*6f82e85aSdrh 
645*6f82e85aSdrh   /* If this is the right table of a LEFT OUTER JOIN, allocate and
646*6f82e85aSdrh   ** initialize a memory cell that records if this table matches any
647*6f82e85aSdrh   ** row of the left table of the join.
648*6f82e85aSdrh   */
649*6f82e85aSdrh   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
650*6f82e85aSdrh     pLevel->iLeftJoin = ++pParse->nMem;
651*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
652*6f82e85aSdrh     VdbeComment((v, "init LEFT JOIN no-match flag"));
653*6f82e85aSdrh   }
654*6f82e85aSdrh 
655*6f82e85aSdrh   /* Special case of a FROM clause subquery implemented as a co-routine */
656*6f82e85aSdrh   if( pTabItem->viaCoroutine ){
657*6f82e85aSdrh     int regYield = pTabItem->regReturn;
658*6f82e85aSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
659*6f82e85aSdrh     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
660*6f82e85aSdrh     VdbeCoverage(v);
661*6f82e85aSdrh     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
662*6f82e85aSdrh     pLevel->op = OP_Goto;
663*6f82e85aSdrh   }else
664*6f82e85aSdrh 
665*6f82e85aSdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
666*6f82e85aSdrh   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
667*6f82e85aSdrh     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
668*6f82e85aSdrh     **          to access the data.
669*6f82e85aSdrh     */
670*6f82e85aSdrh     int iReg;   /* P3 Value for OP_VFilter */
671*6f82e85aSdrh     int addrNotFound;
672*6f82e85aSdrh     int nConstraint = pLoop->nLTerm;
673*6f82e85aSdrh 
674*6f82e85aSdrh     sqlite3ExprCachePush(pParse);
675*6f82e85aSdrh     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
676*6f82e85aSdrh     addrNotFound = pLevel->addrBrk;
677*6f82e85aSdrh     for(j=0; j<nConstraint; j++){
678*6f82e85aSdrh       int iTarget = iReg+j+2;
679*6f82e85aSdrh       pTerm = pLoop->aLTerm[j];
680*6f82e85aSdrh       if( pTerm==0 ) continue;
681*6f82e85aSdrh       if( pTerm->eOperator & WO_IN ){
682*6f82e85aSdrh         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
683*6f82e85aSdrh         addrNotFound = pLevel->addrNxt;
684*6f82e85aSdrh       }else{
685*6f82e85aSdrh         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
686*6f82e85aSdrh       }
687*6f82e85aSdrh     }
688*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
689*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
690*6f82e85aSdrh     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
691*6f82e85aSdrh                       pLoop->u.vtab.idxStr,
692*6f82e85aSdrh                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
693*6f82e85aSdrh     VdbeCoverage(v);
694*6f82e85aSdrh     pLoop->u.vtab.needFree = 0;
695*6f82e85aSdrh     for(j=0; j<nConstraint && j<16; j++){
696*6f82e85aSdrh       if( (pLoop->u.vtab.omitMask>>j)&1 ){
697*6f82e85aSdrh         disableTerm(pLevel, pLoop->aLTerm[j]);
698*6f82e85aSdrh       }
699*6f82e85aSdrh     }
700*6f82e85aSdrh     pLevel->op = OP_VNext;
701*6f82e85aSdrh     pLevel->p1 = iCur;
702*6f82e85aSdrh     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
703*6f82e85aSdrh     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
704*6f82e85aSdrh     sqlite3ExprCachePop(pParse);
705*6f82e85aSdrh   }else
706*6f82e85aSdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */
707*6f82e85aSdrh 
708*6f82e85aSdrh   if( (pLoop->wsFlags & WHERE_IPK)!=0
709*6f82e85aSdrh    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
710*6f82e85aSdrh   ){
711*6f82e85aSdrh     /* Case 2:  We can directly reference a single row using an
712*6f82e85aSdrh     **          equality comparison against the ROWID field.  Or
713*6f82e85aSdrh     **          we reference multiple rows using a "rowid IN (...)"
714*6f82e85aSdrh     **          construct.
715*6f82e85aSdrh     */
716*6f82e85aSdrh     assert( pLoop->u.btree.nEq==1 );
717*6f82e85aSdrh     pTerm = pLoop->aLTerm[0];
718*6f82e85aSdrh     assert( pTerm!=0 );
719*6f82e85aSdrh     assert( pTerm->pExpr!=0 );
720*6f82e85aSdrh     assert( omitTable==0 );
721*6f82e85aSdrh     testcase( pTerm->wtFlags & TERM_VIRTUAL );
722*6f82e85aSdrh     iReleaseReg = ++pParse->nMem;
723*6f82e85aSdrh     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
724*6f82e85aSdrh     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
725*6f82e85aSdrh     addrNxt = pLevel->addrNxt;
726*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
727*6f82e85aSdrh     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
728*6f82e85aSdrh     VdbeCoverage(v);
729*6f82e85aSdrh     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
730*6f82e85aSdrh     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
731*6f82e85aSdrh     VdbeComment((v, "pk"));
732*6f82e85aSdrh     pLevel->op = OP_Noop;
733*6f82e85aSdrh   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
734*6f82e85aSdrh          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
735*6f82e85aSdrh   ){
736*6f82e85aSdrh     /* Case 3:  We have an inequality comparison against the ROWID field.
737*6f82e85aSdrh     */
738*6f82e85aSdrh     int testOp = OP_Noop;
739*6f82e85aSdrh     int start;
740*6f82e85aSdrh     int memEndValue = 0;
741*6f82e85aSdrh     WhereTerm *pStart, *pEnd;
742*6f82e85aSdrh 
743*6f82e85aSdrh     assert( omitTable==0 );
744*6f82e85aSdrh     j = 0;
745*6f82e85aSdrh     pStart = pEnd = 0;
746*6f82e85aSdrh     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
747*6f82e85aSdrh     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
748*6f82e85aSdrh     assert( pStart!=0 || pEnd!=0 );
749*6f82e85aSdrh     if( bRev ){
750*6f82e85aSdrh       pTerm = pStart;
751*6f82e85aSdrh       pStart = pEnd;
752*6f82e85aSdrh       pEnd = pTerm;
753*6f82e85aSdrh     }
754*6f82e85aSdrh     if( pStart ){
755*6f82e85aSdrh       Expr *pX;             /* The expression that defines the start bound */
756*6f82e85aSdrh       int r1, rTemp;        /* Registers for holding the start boundary */
757*6f82e85aSdrh 
758*6f82e85aSdrh       /* The following constant maps TK_xx codes into corresponding
759*6f82e85aSdrh       ** seek opcodes.  It depends on a particular ordering of TK_xx
760*6f82e85aSdrh       */
761*6f82e85aSdrh       const u8 aMoveOp[] = {
762*6f82e85aSdrh            /* TK_GT */  OP_SeekGT,
763*6f82e85aSdrh            /* TK_LE */  OP_SeekLE,
764*6f82e85aSdrh            /* TK_LT */  OP_SeekLT,
765*6f82e85aSdrh            /* TK_GE */  OP_SeekGE
766*6f82e85aSdrh       };
767*6f82e85aSdrh       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
768*6f82e85aSdrh       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
769*6f82e85aSdrh       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
770*6f82e85aSdrh 
771*6f82e85aSdrh       assert( (pStart->wtFlags & TERM_VNULL)==0 );
772*6f82e85aSdrh       testcase( pStart->wtFlags & TERM_VIRTUAL );
773*6f82e85aSdrh       pX = pStart->pExpr;
774*6f82e85aSdrh       assert( pX!=0 );
775*6f82e85aSdrh       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
776*6f82e85aSdrh       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
777*6f82e85aSdrh       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
778*6f82e85aSdrh       VdbeComment((v, "pk"));
779*6f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_GT);
780*6f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_LE);
781*6f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_LT);
782*6f82e85aSdrh       VdbeCoverageIf(v, pX->op==TK_GE);
783*6f82e85aSdrh       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
784*6f82e85aSdrh       sqlite3ReleaseTempReg(pParse, rTemp);
785*6f82e85aSdrh       disableTerm(pLevel, pStart);
786*6f82e85aSdrh     }else{
787*6f82e85aSdrh       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
788*6f82e85aSdrh       VdbeCoverageIf(v, bRev==0);
789*6f82e85aSdrh       VdbeCoverageIf(v, bRev!=0);
790*6f82e85aSdrh     }
791*6f82e85aSdrh     if( pEnd ){
792*6f82e85aSdrh       Expr *pX;
793*6f82e85aSdrh       pX = pEnd->pExpr;
794*6f82e85aSdrh       assert( pX!=0 );
795*6f82e85aSdrh       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
796*6f82e85aSdrh       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
797*6f82e85aSdrh       testcase( pEnd->wtFlags & TERM_VIRTUAL );
798*6f82e85aSdrh       memEndValue = ++pParse->nMem;
799*6f82e85aSdrh       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
800*6f82e85aSdrh       if( pX->op==TK_LT || pX->op==TK_GT ){
801*6f82e85aSdrh         testOp = bRev ? OP_Le : OP_Ge;
802*6f82e85aSdrh       }else{
803*6f82e85aSdrh         testOp = bRev ? OP_Lt : OP_Gt;
804*6f82e85aSdrh       }
805*6f82e85aSdrh       disableTerm(pLevel, pEnd);
806*6f82e85aSdrh     }
807*6f82e85aSdrh     start = sqlite3VdbeCurrentAddr(v);
808*6f82e85aSdrh     pLevel->op = bRev ? OP_Prev : OP_Next;
809*6f82e85aSdrh     pLevel->p1 = iCur;
810*6f82e85aSdrh     pLevel->p2 = start;
811*6f82e85aSdrh     assert( pLevel->p5==0 );
812*6f82e85aSdrh     if( testOp!=OP_Noop ){
813*6f82e85aSdrh       iRowidReg = ++pParse->nMem;
814*6f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
815*6f82e85aSdrh       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
816*6f82e85aSdrh       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
817*6f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Le);
818*6f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Lt);
819*6f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Ge);
820*6f82e85aSdrh       VdbeCoverageIf(v, testOp==OP_Gt);
821*6f82e85aSdrh       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
822*6f82e85aSdrh     }
823*6f82e85aSdrh   }else if( pLoop->wsFlags & WHERE_INDEXED ){
824*6f82e85aSdrh     /* Case 4: A scan using an index.
825*6f82e85aSdrh     **
826*6f82e85aSdrh     **         The WHERE clause may contain zero or more equality
827*6f82e85aSdrh     **         terms ("==" or "IN" operators) that refer to the N
828*6f82e85aSdrh     **         left-most columns of the index. It may also contain
829*6f82e85aSdrh     **         inequality constraints (>, <, >= or <=) on the indexed
830*6f82e85aSdrh     **         column that immediately follows the N equalities. Only
831*6f82e85aSdrh     **         the right-most column can be an inequality - the rest must
832*6f82e85aSdrh     **         use the "==" and "IN" operators. For example, if the
833*6f82e85aSdrh     **         index is on (x,y,z), then the following clauses are all
834*6f82e85aSdrh     **         optimized:
835*6f82e85aSdrh     **
836*6f82e85aSdrh     **            x=5
837*6f82e85aSdrh     **            x=5 AND y=10
838*6f82e85aSdrh     **            x=5 AND y<10
839*6f82e85aSdrh     **            x=5 AND y>5 AND y<10
840*6f82e85aSdrh     **            x=5 AND y=5 AND z<=10
841*6f82e85aSdrh     **
842*6f82e85aSdrh     **         The z<10 term of the following cannot be used, only
843*6f82e85aSdrh     **         the x=5 term:
844*6f82e85aSdrh     **
845*6f82e85aSdrh     **            x=5 AND z<10
846*6f82e85aSdrh     **
847*6f82e85aSdrh     **         N may be zero if there are inequality constraints.
848*6f82e85aSdrh     **         If there are no inequality constraints, then N is at
849*6f82e85aSdrh     **         least one.
850*6f82e85aSdrh     **
851*6f82e85aSdrh     **         This case is also used when there are no WHERE clause
852*6f82e85aSdrh     **         constraints but an index is selected anyway, in order
853*6f82e85aSdrh     **         to force the output order to conform to an ORDER BY.
854*6f82e85aSdrh     */
855*6f82e85aSdrh     static const u8 aStartOp[] = {
856*6f82e85aSdrh       0,
857*6f82e85aSdrh       0,
858*6f82e85aSdrh       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
859*6f82e85aSdrh       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
860*6f82e85aSdrh       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
861*6f82e85aSdrh       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
862*6f82e85aSdrh       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
863*6f82e85aSdrh       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
864*6f82e85aSdrh     };
865*6f82e85aSdrh     static const u8 aEndOp[] = {
866*6f82e85aSdrh       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
867*6f82e85aSdrh       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
868*6f82e85aSdrh       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
869*6f82e85aSdrh       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
870*6f82e85aSdrh     };
871*6f82e85aSdrh     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
872*6f82e85aSdrh     int regBase;                 /* Base register holding constraint values */
873*6f82e85aSdrh     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
874*6f82e85aSdrh     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
875*6f82e85aSdrh     int startEq;                 /* True if range start uses ==, >= or <= */
876*6f82e85aSdrh     int endEq;                   /* True if range end uses ==, >= or <= */
877*6f82e85aSdrh     int start_constraints;       /* Start of range is constrained */
878*6f82e85aSdrh     int nConstraint;             /* Number of constraint terms */
879*6f82e85aSdrh     Index *pIdx;                 /* The index we will be using */
880*6f82e85aSdrh     int iIdxCur;                 /* The VDBE cursor for the index */
881*6f82e85aSdrh     int nExtraReg = 0;           /* Number of extra registers needed */
882*6f82e85aSdrh     int op;                      /* Instruction opcode */
883*6f82e85aSdrh     char *zStartAff;             /* Affinity for start of range constraint */
884*6f82e85aSdrh     char cEndAff = 0;            /* Affinity for end of range constraint */
885*6f82e85aSdrh     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
886*6f82e85aSdrh     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
887*6f82e85aSdrh 
888*6f82e85aSdrh     pIdx = pLoop->u.btree.pIndex;
889*6f82e85aSdrh     iIdxCur = pLevel->iIdxCur;
890*6f82e85aSdrh     assert( nEq>=pLoop->nSkip );
891*6f82e85aSdrh 
892*6f82e85aSdrh     /* If this loop satisfies a sort order (pOrderBy) request that
893*6f82e85aSdrh     ** was passed to this function to implement a "SELECT min(x) ..."
894*6f82e85aSdrh     ** query, then the caller will only allow the loop to run for
895*6f82e85aSdrh     ** a single iteration. This means that the first row returned
896*6f82e85aSdrh     ** should not have a NULL value stored in 'x'. If column 'x' is
897*6f82e85aSdrh     ** the first one after the nEq equality constraints in the index,
898*6f82e85aSdrh     ** this requires some special handling.
899*6f82e85aSdrh     */
900*6f82e85aSdrh     assert( pWInfo->pOrderBy==0
901*6f82e85aSdrh          || pWInfo->pOrderBy->nExpr==1
902*6f82e85aSdrh          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
903*6f82e85aSdrh     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
904*6f82e85aSdrh      && pWInfo->nOBSat>0
905*6f82e85aSdrh      && (pIdx->nKeyCol>nEq)
906*6f82e85aSdrh     ){
907*6f82e85aSdrh       assert( pLoop->nSkip==0 );
908*6f82e85aSdrh       bSeekPastNull = 1;
909*6f82e85aSdrh       nExtraReg = 1;
910*6f82e85aSdrh     }
911*6f82e85aSdrh 
912*6f82e85aSdrh     /* Find any inequality constraint terms for the start and end
913*6f82e85aSdrh     ** of the range.
914*6f82e85aSdrh     */
915*6f82e85aSdrh     j = nEq;
916*6f82e85aSdrh     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
917*6f82e85aSdrh       pRangeStart = pLoop->aLTerm[j++];
918*6f82e85aSdrh       nExtraReg = 1;
919*6f82e85aSdrh       /* Like optimization range constraints always occur in pairs */
920*6f82e85aSdrh       assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
921*6f82e85aSdrh               (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
922*6f82e85aSdrh     }
923*6f82e85aSdrh     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
924*6f82e85aSdrh       pRangeEnd = pLoop->aLTerm[j++];
925*6f82e85aSdrh       nExtraReg = 1;
926*6f82e85aSdrh       if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
927*6f82e85aSdrh         assert( pRangeStart!=0 );                     /* LIKE opt constraints */
928*6f82e85aSdrh         assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
929*6f82e85aSdrh         pLevel->iLikeRepCntr = ++pParse->nMem;
930*6f82e85aSdrh         testcase( bRev );
931*6f82e85aSdrh         testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
932*6f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_Integer,
933*6f82e85aSdrh                           bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
934*6f82e85aSdrh                           pLevel->iLikeRepCntr);
935*6f82e85aSdrh         VdbeComment((v, "LIKE loop counter"));
936*6f82e85aSdrh         pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
937*6f82e85aSdrh       }
938*6f82e85aSdrh       if( pRangeStart==0
939*6f82e85aSdrh        && (j = pIdx->aiColumn[nEq])>=0
940*6f82e85aSdrh        && pIdx->pTable->aCol[j].notNull==0
941*6f82e85aSdrh       ){
942*6f82e85aSdrh         bSeekPastNull = 1;
943*6f82e85aSdrh       }
944*6f82e85aSdrh     }
945*6f82e85aSdrh     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
946*6f82e85aSdrh 
947*6f82e85aSdrh     /* Generate code to evaluate all constraint terms using == or IN
948*6f82e85aSdrh     ** and store the values of those terms in an array of registers
949*6f82e85aSdrh     ** starting at regBase.
950*6f82e85aSdrh     */
951*6f82e85aSdrh     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
952*6f82e85aSdrh     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
953*6f82e85aSdrh     if( zStartAff ) cEndAff = zStartAff[nEq];
954*6f82e85aSdrh     addrNxt = pLevel->addrNxt;
955*6f82e85aSdrh 
956*6f82e85aSdrh     /* If we are doing a reverse order scan on an ascending index, or
957*6f82e85aSdrh     ** a forward order scan on a descending index, interchange the
958*6f82e85aSdrh     ** start and end terms (pRangeStart and pRangeEnd).
959*6f82e85aSdrh     */
960*6f82e85aSdrh     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
961*6f82e85aSdrh      || (bRev && pIdx->nKeyCol==nEq)
962*6f82e85aSdrh     ){
963*6f82e85aSdrh       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
964*6f82e85aSdrh       SWAP(u8, bSeekPastNull, bStopAtNull);
965*6f82e85aSdrh     }
966*6f82e85aSdrh 
967*6f82e85aSdrh     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
968*6f82e85aSdrh     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
969*6f82e85aSdrh     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
970*6f82e85aSdrh     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
971*6f82e85aSdrh     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
972*6f82e85aSdrh     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
973*6f82e85aSdrh     start_constraints = pRangeStart || nEq>0;
974*6f82e85aSdrh 
975*6f82e85aSdrh     /* Seek the index cursor to the start of the range. */
976*6f82e85aSdrh     nConstraint = nEq;
977*6f82e85aSdrh     if( pRangeStart ){
978*6f82e85aSdrh       Expr *pRight = pRangeStart->pExpr->pRight;
979*6f82e85aSdrh       sqlite3ExprCode(pParse, pRight, regBase+nEq);
980*6f82e85aSdrh       whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
981*6f82e85aSdrh       if( (pRangeStart->wtFlags & TERM_VNULL)==0
982*6f82e85aSdrh        && sqlite3ExprCanBeNull(pRight)
983*6f82e85aSdrh       ){
984*6f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
985*6f82e85aSdrh         VdbeCoverage(v);
986*6f82e85aSdrh       }
987*6f82e85aSdrh       if( zStartAff ){
988*6f82e85aSdrh         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
989*6f82e85aSdrh           /* Since the comparison is to be performed with no conversions
990*6f82e85aSdrh           ** applied to the operands, set the affinity to apply to pRight to
991*6f82e85aSdrh           ** SQLITE_AFF_BLOB.  */
992*6f82e85aSdrh           zStartAff[nEq] = SQLITE_AFF_BLOB;
993*6f82e85aSdrh         }
994*6f82e85aSdrh         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
995*6f82e85aSdrh           zStartAff[nEq] = SQLITE_AFF_BLOB;
996*6f82e85aSdrh         }
997*6f82e85aSdrh       }
998*6f82e85aSdrh       nConstraint++;
999*6f82e85aSdrh       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
1000*6f82e85aSdrh     }else if( bSeekPastNull ){
1001*6f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1002*6f82e85aSdrh       nConstraint++;
1003*6f82e85aSdrh       startEq = 0;
1004*6f82e85aSdrh       start_constraints = 1;
1005*6f82e85aSdrh     }
1006*6f82e85aSdrh     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
1007*6f82e85aSdrh     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
1008*6f82e85aSdrh     assert( op!=0 );
1009*6f82e85aSdrh     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1010*6f82e85aSdrh     VdbeCoverage(v);
1011*6f82e85aSdrh     VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
1012*6f82e85aSdrh     VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
1013*6f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
1014*6f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
1015*6f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
1016*6f82e85aSdrh     VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
1017*6f82e85aSdrh 
1018*6f82e85aSdrh     /* Load the value for the inequality constraint at the end of the
1019*6f82e85aSdrh     ** range (if any).
1020*6f82e85aSdrh     */
1021*6f82e85aSdrh     nConstraint = nEq;
1022*6f82e85aSdrh     if( pRangeEnd ){
1023*6f82e85aSdrh       Expr *pRight = pRangeEnd->pExpr->pRight;
1024*6f82e85aSdrh       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
1025*6f82e85aSdrh       sqlite3ExprCode(pParse, pRight, regBase+nEq);
1026*6f82e85aSdrh       whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
1027*6f82e85aSdrh       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
1028*6f82e85aSdrh        && sqlite3ExprCanBeNull(pRight)
1029*6f82e85aSdrh       ){
1030*6f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
1031*6f82e85aSdrh         VdbeCoverage(v);
1032*6f82e85aSdrh       }
1033*6f82e85aSdrh       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
1034*6f82e85aSdrh        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
1035*6f82e85aSdrh       ){
1036*6f82e85aSdrh         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
1037*6f82e85aSdrh       }
1038*6f82e85aSdrh       nConstraint++;
1039*6f82e85aSdrh       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
1040*6f82e85aSdrh     }else if( bStopAtNull ){
1041*6f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
1042*6f82e85aSdrh       endEq = 0;
1043*6f82e85aSdrh       nConstraint++;
1044*6f82e85aSdrh     }
1045*6f82e85aSdrh     sqlite3DbFree(db, zStartAff);
1046*6f82e85aSdrh 
1047*6f82e85aSdrh     /* Top of the loop body */
1048*6f82e85aSdrh     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
1049*6f82e85aSdrh 
1050*6f82e85aSdrh     /* Check if the index cursor is past the end of the range. */
1051*6f82e85aSdrh     if( nConstraint ){
1052*6f82e85aSdrh       op = aEndOp[bRev*2 + endEq];
1053*6f82e85aSdrh       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
1054*6f82e85aSdrh       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
1055*6f82e85aSdrh       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
1056*6f82e85aSdrh       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
1057*6f82e85aSdrh       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
1058*6f82e85aSdrh     }
1059*6f82e85aSdrh 
1060*6f82e85aSdrh     /* Seek the table cursor, if required */
1061*6f82e85aSdrh     disableTerm(pLevel, pRangeStart);
1062*6f82e85aSdrh     disableTerm(pLevel, pRangeEnd);
1063*6f82e85aSdrh     if( omitTable ){
1064*6f82e85aSdrh       /* pIdx is a covering index.  No need to access the main table. */
1065*6f82e85aSdrh     }else if( HasRowid(pIdx->pTable) ){
1066*6f82e85aSdrh       iRowidReg = ++pParse->nMem;
1067*6f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
1068*6f82e85aSdrh       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
1069*6f82e85aSdrh       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
1070*6f82e85aSdrh     }else if( iCur!=iIdxCur ){
1071*6f82e85aSdrh       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1072*6f82e85aSdrh       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1073*6f82e85aSdrh       for(j=0; j<pPk->nKeyCol; j++){
1074*6f82e85aSdrh         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
1075*6f82e85aSdrh         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
1076*6f82e85aSdrh       }
1077*6f82e85aSdrh       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
1078*6f82e85aSdrh                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
1079*6f82e85aSdrh     }
1080*6f82e85aSdrh 
1081*6f82e85aSdrh     /* Record the instruction used to terminate the loop. Disable
1082*6f82e85aSdrh     ** WHERE clause terms made redundant by the index range scan.
1083*6f82e85aSdrh     */
1084*6f82e85aSdrh     if( pLoop->wsFlags & WHERE_ONEROW ){
1085*6f82e85aSdrh       pLevel->op = OP_Noop;
1086*6f82e85aSdrh     }else if( bRev ){
1087*6f82e85aSdrh       pLevel->op = OP_Prev;
1088*6f82e85aSdrh     }else{
1089*6f82e85aSdrh       pLevel->op = OP_Next;
1090*6f82e85aSdrh     }
1091*6f82e85aSdrh     pLevel->p1 = iIdxCur;
1092*6f82e85aSdrh     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
1093*6f82e85aSdrh     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
1094*6f82e85aSdrh       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1095*6f82e85aSdrh     }else{
1096*6f82e85aSdrh       assert( pLevel->p5==0 );
1097*6f82e85aSdrh     }
1098*6f82e85aSdrh   }else
1099*6f82e85aSdrh 
1100*6f82e85aSdrh #ifndef SQLITE_OMIT_OR_OPTIMIZATION
1101*6f82e85aSdrh   if( pLoop->wsFlags & WHERE_MULTI_OR ){
1102*6f82e85aSdrh     /* Case 5:  Two or more separately indexed terms connected by OR
1103*6f82e85aSdrh     **
1104*6f82e85aSdrh     ** Example:
1105*6f82e85aSdrh     **
1106*6f82e85aSdrh     **   CREATE TABLE t1(a,b,c,d);
1107*6f82e85aSdrh     **   CREATE INDEX i1 ON t1(a);
1108*6f82e85aSdrh     **   CREATE INDEX i2 ON t1(b);
1109*6f82e85aSdrh     **   CREATE INDEX i3 ON t1(c);
1110*6f82e85aSdrh     **
1111*6f82e85aSdrh     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
1112*6f82e85aSdrh     **
1113*6f82e85aSdrh     ** In the example, there are three indexed terms connected by OR.
1114*6f82e85aSdrh     ** The top of the loop looks like this:
1115*6f82e85aSdrh     **
1116*6f82e85aSdrh     **          Null       1                # Zero the rowset in reg 1
1117*6f82e85aSdrh     **
1118*6f82e85aSdrh     ** Then, for each indexed term, the following. The arguments to
1119*6f82e85aSdrh     ** RowSetTest are such that the rowid of the current row is inserted
1120*6f82e85aSdrh     ** into the RowSet. If it is already present, control skips the
1121*6f82e85aSdrh     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
1122*6f82e85aSdrh     **
1123*6f82e85aSdrh     **        sqlite3WhereBegin(<term>)
1124*6f82e85aSdrh     **          RowSetTest                  # Insert rowid into rowset
1125*6f82e85aSdrh     **          Gosub      2 A
1126*6f82e85aSdrh     **        sqlite3WhereEnd()
1127*6f82e85aSdrh     **
1128*6f82e85aSdrh     ** Following the above, code to terminate the loop. Label A, the target
1129*6f82e85aSdrh     ** of the Gosub above, jumps to the instruction right after the Goto.
1130*6f82e85aSdrh     **
1131*6f82e85aSdrh     **          Null       1                # Zero the rowset in reg 1
1132*6f82e85aSdrh     **          Goto       B                # The loop is finished.
1133*6f82e85aSdrh     **
1134*6f82e85aSdrh     **       A: <loop body>                 # Return data, whatever.
1135*6f82e85aSdrh     **
1136*6f82e85aSdrh     **          Return     2                # Jump back to the Gosub
1137*6f82e85aSdrh     **
1138*6f82e85aSdrh     **       B: <after the loop>
1139*6f82e85aSdrh     **
1140*6f82e85aSdrh     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
1141*6f82e85aSdrh     ** use an ephemeral index instead of a RowSet to record the primary
1142*6f82e85aSdrh     ** keys of the rows we have already seen.
1143*6f82e85aSdrh     **
1144*6f82e85aSdrh     */
1145*6f82e85aSdrh     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
1146*6f82e85aSdrh     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
1147*6f82e85aSdrh     Index *pCov = 0;             /* Potential covering index (or NULL) */
1148*6f82e85aSdrh     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
1149*6f82e85aSdrh 
1150*6f82e85aSdrh     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
1151*6f82e85aSdrh     int regRowset = 0;                        /* Register for RowSet object */
1152*6f82e85aSdrh     int regRowid = 0;                         /* Register holding rowid */
1153*6f82e85aSdrh     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
1154*6f82e85aSdrh     int iRetInit;                             /* Address of regReturn init */
1155*6f82e85aSdrh     int untestedTerms = 0;             /* Some terms not completely tested */
1156*6f82e85aSdrh     int ii;                            /* Loop counter */
1157*6f82e85aSdrh     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
1158*6f82e85aSdrh     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
1159*6f82e85aSdrh     Table *pTab = pTabItem->pTab;
1160*6f82e85aSdrh 
1161*6f82e85aSdrh     pTerm = pLoop->aLTerm[0];
1162*6f82e85aSdrh     assert( pTerm!=0 );
1163*6f82e85aSdrh     assert( pTerm->eOperator & WO_OR );
1164*6f82e85aSdrh     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
1165*6f82e85aSdrh     pOrWc = &pTerm->u.pOrInfo->wc;
1166*6f82e85aSdrh     pLevel->op = OP_Return;
1167*6f82e85aSdrh     pLevel->p1 = regReturn;
1168*6f82e85aSdrh 
1169*6f82e85aSdrh     /* Set up a new SrcList in pOrTab containing the table being scanned
1170*6f82e85aSdrh     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
1171*6f82e85aSdrh     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
1172*6f82e85aSdrh     */
1173*6f82e85aSdrh     if( pWInfo->nLevel>1 ){
1174*6f82e85aSdrh       int nNotReady;                 /* The number of notReady tables */
1175*6f82e85aSdrh       struct SrcList_item *origSrc;     /* Original list of tables */
1176*6f82e85aSdrh       nNotReady = pWInfo->nLevel - iLevel - 1;
1177*6f82e85aSdrh       pOrTab = sqlite3StackAllocRaw(db,
1178*6f82e85aSdrh                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
1179*6f82e85aSdrh       if( pOrTab==0 ) return notReady;
1180*6f82e85aSdrh       pOrTab->nAlloc = (u8)(nNotReady + 1);
1181*6f82e85aSdrh       pOrTab->nSrc = pOrTab->nAlloc;
1182*6f82e85aSdrh       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
1183*6f82e85aSdrh       origSrc = pWInfo->pTabList->a;
1184*6f82e85aSdrh       for(k=1; k<=nNotReady; k++){
1185*6f82e85aSdrh         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
1186*6f82e85aSdrh       }
1187*6f82e85aSdrh     }else{
1188*6f82e85aSdrh       pOrTab = pWInfo->pTabList;
1189*6f82e85aSdrh     }
1190*6f82e85aSdrh 
1191*6f82e85aSdrh     /* Initialize the rowset register to contain NULL. An SQL NULL is
1192*6f82e85aSdrh     ** equivalent to an empty rowset.  Or, create an ephemeral index
1193*6f82e85aSdrh     ** capable of holding primary keys in the case of a WITHOUT ROWID.
1194*6f82e85aSdrh     **
1195*6f82e85aSdrh     ** Also initialize regReturn to contain the address of the instruction
1196*6f82e85aSdrh     ** immediately following the OP_Return at the bottom of the loop. This
1197*6f82e85aSdrh     ** is required in a few obscure LEFT JOIN cases where control jumps
1198*6f82e85aSdrh     ** over the top of the loop into the body of it. In this case the
1199*6f82e85aSdrh     ** correct response for the end-of-loop code (the OP_Return) is to
1200*6f82e85aSdrh     ** fall through to the next instruction, just as an OP_Next does if
1201*6f82e85aSdrh     ** called on an uninitialized cursor.
1202*6f82e85aSdrh     */
1203*6f82e85aSdrh     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1204*6f82e85aSdrh       if( HasRowid(pTab) ){
1205*6f82e85aSdrh         regRowset = ++pParse->nMem;
1206*6f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
1207*6f82e85aSdrh       }else{
1208*6f82e85aSdrh         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1209*6f82e85aSdrh         regRowset = pParse->nTab++;
1210*6f82e85aSdrh         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
1211*6f82e85aSdrh         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
1212*6f82e85aSdrh       }
1213*6f82e85aSdrh       regRowid = ++pParse->nMem;
1214*6f82e85aSdrh     }
1215*6f82e85aSdrh     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
1216*6f82e85aSdrh 
1217*6f82e85aSdrh     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
1218*6f82e85aSdrh     ** Then for every term xN, evaluate as the subexpression: xN AND z
1219*6f82e85aSdrh     ** That way, terms in y that are factored into the disjunction will
1220*6f82e85aSdrh     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
1221*6f82e85aSdrh     **
1222*6f82e85aSdrh     ** Actually, each subexpression is converted to "xN AND w" where w is
1223*6f82e85aSdrh     ** the "interesting" terms of z - terms that did not originate in the
1224*6f82e85aSdrh     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
1225*6f82e85aSdrh     ** indices.
1226*6f82e85aSdrh     **
1227*6f82e85aSdrh     ** This optimization also only applies if the (x1 OR x2 OR ...) term
1228*6f82e85aSdrh     ** is not contained in the ON clause of a LEFT JOIN.
1229*6f82e85aSdrh     ** See ticket http://www.sqlite.org/src/info/f2369304e4
1230*6f82e85aSdrh     */
1231*6f82e85aSdrh     if( pWC->nTerm>1 ){
1232*6f82e85aSdrh       int iTerm;
1233*6f82e85aSdrh       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
1234*6f82e85aSdrh         Expr *pExpr = pWC->a[iTerm].pExpr;
1235*6f82e85aSdrh         if( &pWC->a[iTerm] == pTerm ) continue;
1236*6f82e85aSdrh         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
1237*6f82e85aSdrh         if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
1238*6f82e85aSdrh         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
1239*6f82e85aSdrh         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
1240*6f82e85aSdrh         pExpr = sqlite3ExprDup(db, pExpr, 0);
1241*6f82e85aSdrh         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
1242*6f82e85aSdrh       }
1243*6f82e85aSdrh       if( pAndExpr ){
1244*6f82e85aSdrh         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
1245*6f82e85aSdrh       }
1246*6f82e85aSdrh     }
1247*6f82e85aSdrh 
1248*6f82e85aSdrh     /* Run a separate WHERE clause for each term of the OR clause.  After
1249*6f82e85aSdrh     ** eliminating duplicates from other WHERE clauses, the action for each
1250*6f82e85aSdrh     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
1251*6f82e85aSdrh     */
1252*6f82e85aSdrh     wctrlFlags =  WHERE_OMIT_OPEN_CLOSE
1253*6f82e85aSdrh                 | WHERE_FORCE_TABLE
1254*6f82e85aSdrh                 | WHERE_ONETABLE_ONLY
1255*6f82e85aSdrh                 | WHERE_NO_AUTOINDEX;
1256*6f82e85aSdrh     for(ii=0; ii<pOrWc->nTerm; ii++){
1257*6f82e85aSdrh       WhereTerm *pOrTerm = &pOrWc->a[ii];
1258*6f82e85aSdrh       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
1259*6f82e85aSdrh         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
1260*6f82e85aSdrh         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
1261*6f82e85aSdrh         int j1 = 0;                     /* Address of jump operation */
1262*6f82e85aSdrh         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
1263*6f82e85aSdrh           pAndExpr->pLeft = pOrExpr;
1264*6f82e85aSdrh           pOrExpr = pAndExpr;
1265*6f82e85aSdrh         }
1266*6f82e85aSdrh         /* Loop through table entries that match term pOrTerm. */
1267*6f82e85aSdrh         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
1268*6f82e85aSdrh         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
1269*6f82e85aSdrh                                       wctrlFlags, iCovCur);
1270*6f82e85aSdrh         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
1271*6f82e85aSdrh         if( pSubWInfo ){
1272*6f82e85aSdrh           WhereLoop *pSubLoop;
1273*6f82e85aSdrh           int addrExplain = sqlite3WhereExplainOneScan(
1274*6f82e85aSdrh               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
1275*6f82e85aSdrh           );
1276*6f82e85aSdrh           sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
1277*6f82e85aSdrh 
1278*6f82e85aSdrh           /* This is the sub-WHERE clause body.  First skip over
1279*6f82e85aSdrh           ** duplicate rows from prior sub-WHERE clauses, and record the
1280*6f82e85aSdrh           ** rowid (or PRIMARY KEY) for the current row so that the same
1281*6f82e85aSdrh           ** row will be skipped in subsequent sub-WHERE clauses.
1282*6f82e85aSdrh           */
1283*6f82e85aSdrh           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
1284*6f82e85aSdrh             int r;
1285*6f82e85aSdrh             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
1286*6f82e85aSdrh             if( HasRowid(pTab) ){
1287*6f82e85aSdrh               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
1288*6f82e85aSdrh               j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
1289*6f82e85aSdrh               VdbeCoverage(v);
1290*6f82e85aSdrh             }else{
1291*6f82e85aSdrh               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
1292*6f82e85aSdrh               int nPk = pPk->nKeyCol;
1293*6f82e85aSdrh               int iPk;
1294*6f82e85aSdrh 
1295*6f82e85aSdrh               /* Read the PK into an array of temp registers. */
1296*6f82e85aSdrh               r = sqlite3GetTempRange(pParse, nPk);
1297*6f82e85aSdrh               for(iPk=0; iPk<nPk; iPk++){
1298*6f82e85aSdrh                 int iCol = pPk->aiColumn[iPk];
1299*6f82e85aSdrh                 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
1300*6f82e85aSdrh               }
1301*6f82e85aSdrh 
1302*6f82e85aSdrh               /* Check if the temp table already contains this key. If so,
1303*6f82e85aSdrh               ** the row has already been included in the result set and
1304*6f82e85aSdrh               ** can be ignored (by jumping past the Gosub below). Otherwise,
1305*6f82e85aSdrh               ** insert the key into the temp table and proceed with processing
1306*6f82e85aSdrh               ** the row.
1307*6f82e85aSdrh               **
1308*6f82e85aSdrh               ** Use some of the same optimizations as OP_RowSetTest: If iSet
1309*6f82e85aSdrh               ** is zero, assume that the key cannot already be present in
1310*6f82e85aSdrh               ** the temp table. And if iSet is -1, assume that there is no
1311*6f82e85aSdrh               ** need to insert the key into the temp table, as it will never
1312*6f82e85aSdrh               ** be tested for.  */
1313*6f82e85aSdrh               if( iSet ){
1314*6f82e85aSdrh                 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
1315*6f82e85aSdrh                 VdbeCoverage(v);
1316*6f82e85aSdrh               }
1317*6f82e85aSdrh               if( iSet>=0 ){
1318*6f82e85aSdrh                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
1319*6f82e85aSdrh                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
1320*6f82e85aSdrh                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1321*6f82e85aSdrh               }
1322*6f82e85aSdrh 
1323*6f82e85aSdrh               /* Release the array of temp registers */
1324*6f82e85aSdrh               sqlite3ReleaseTempRange(pParse, r, nPk);
1325*6f82e85aSdrh             }
1326*6f82e85aSdrh           }
1327*6f82e85aSdrh 
1328*6f82e85aSdrh           /* Invoke the main loop body as a subroutine */
1329*6f82e85aSdrh           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
1330*6f82e85aSdrh 
1331*6f82e85aSdrh           /* Jump here (skipping the main loop body subroutine) if the
1332*6f82e85aSdrh           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
1333*6f82e85aSdrh           if( j1 ) sqlite3VdbeJumpHere(v, j1);
1334*6f82e85aSdrh 
1335*6f82e85aSdrh           /* The pSubWInfo->untestedTerms flag means that this OR term
1336*6f82e85aSdrh           ** contained one or more AND term from a notReady table.  The
1337*6f82e85aSdrh           ** terms from the notReady table could not be tested and will
1338*6f82e85aSdrh           ** need to be tested later.
1339*6f82e85aSdrh           */
1340*6f82e85aSdrh           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
1341*6f82e85aSdrh 
1342*6f82e85aSdrh           /* If all of the OR-connected terms are optimized using the same
1343*6f82e85aSdrh           ** index, and the index is opened using the same cursor number
1344*6f82e85aSdrh           ** by each call to sqlite3WhereBegin() made by this loop, it may
1345*6f82e85aSdrh           ** be possible to use that index as a covering index.
1346*6f82e85aSdrh           **
1347*6f82e85aSdrh           ** If the call to sqlite3WhereBegin() above resulted in a scan that
1348*6f82e85aSdrh           ** uses an index, and this is either the first OR-connected term
1349*6f82e85aSdrh           ** processed or the index is the same as that used by all previous
1350*6f82e85aSdrh           ** terms, set pCov to the candidate covering index. Otherwise, set
1351*6f82e85aSdrh           ** pCov to NULL to indicate that no candidate covering index will
1352*6f82e85aSdrh           ** be available.
1353*6f82e85aSdrh           */
1354*6f82e85aSdrh           pSubLoop = pSubWInfo->a[0].pWLoop;
1355*6f82e85aSdrh           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
1356*6f82e85aSdrh           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
1357*6f82e85aSdrh            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
1358*6f82e85aSdrh            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
1359*6f82e85aSdrh           ){
1360*6f82e85aSdrh             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
1361*6f82e85aSdrh             pCov = pSubLoop->u.btree.pIndex;
1362*6f82e85aSdrh             wctrlFlags |= WHERE_REOPEN_IDX;
1363*6f82e85aSdrh           }else{
1364*6f82e85aSdrh             pCov = 0;
1365*6f82e85aSdrh           }
1366*6f82e85aSdrh 
1367*6f82e85aSdrh           /* Finish the loop through table entries that match term pOrTerm. */
1368*6f82e85aSdrh           sqlite3WhereEnd(pSubWInfo);
1369*6f82e85aSdrh         }
1370*6f82e85aSdrh       }
1371*6f82e85aSdrh     }
1372*6f82e85aSdrh     pLevel->u.pCovidx = pCov;
1373*6f82e85aSdrh     if( pCov ) pLevel->iIdxCur = iCovCur;
1374*6f82e85aSdrh     if( pAndExpr ){
1375*6f82e85aSdrh       pAndExpr->pLeft = 0;
1376*6f82e85aSdrh       sqlite3ExprDelete(db, pAndExpr);
1377*6f82e85aSdrh     }
1378*6f82e85aSdrh     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
1379*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
1380*6f82e85aSdrh     sqlite3VdbeResolveLabel(v, iLoopBody);
1381*6f82e85aSdrh 
1382*6f82e85aSdrh     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
1383*6f82e85aSdrh     if( !untestedTerms ) disableTerm(pLevel, pTerm);
1384*6f82e85aSdrh   }else
1385*6f82e85aSdrh #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1386*6f82e85aSdrh 
1387*6f82e85aSdrh   {
1388*6f82e85aSdrh     /* Case 6:  There is no usable index.  We must do a complete
1389*6f82e85aSdrh     **          scan of the entire table.
1390*6f82e85aSdrh     */
1391*6f82e85aSdrh     static const u8 aStep[] = { OP_Next, OP_Prev };
1392*6f82e85aSdrh     static const u8 aStart[] = { OP_Rewind, OP_Last };
1393*6f82e85aSdrh     assert( bRev==0 || bRev==1 );
1394*6f82e85aSdrh     if( pTabItem->isRecursive ){
1395*6f82e85aSdrh       /* Tables marked isRecursive have only a single row that is stored in
1396*6f82e85aSdrh       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
1397*6f82e85aSdrh       pLevel->op = OP_Noop;
1398*6f82e85aSdrh     }else{
1399*6f82e85aSdrh       pLevel->op = aStep[bRev];
1400*6f82e85aSdrh       pLevel->p1 = iCur;
1401*6f82e85aSdrh       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
1402*6f82e85aSdrh       VdbeCoverageIf(v, bRev==0);
1403*6f82e85aSdrh       VdbeCoverageIf(v, bRev!=0);
1404*6f82e85aSdrh       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
1405*6f82e85aSdrh     }
1406*6f82e85aSdrh   }
1407*6f82e85aSdrh 
1408*6f82e85aSdrh #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1409*6f82e85aSdrh   pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
1410*6f82e85aSdrh #endif
1411*6f82e85aSdrh 
1412*6f82e85aSdrh   /* Insert code to test every subexpression that can be completely
1413*6f82e85aSdrh   ** computed using the current set of tables.
1414*6f82e85aSdrh   */
1415*6f82e85aSdrh   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1416*6f82e85aSdrh     Expr *pE;
1417*6f82e85aSdrh     int skipLikeAddr = 0;
1418*6f82e85aSdrh     testcase( pTerm->wtFlags & TERM_VIRTUAL );
1419*6f82e85aSdrh     testcase( pTerm->wtFlags & TERM_CODED );
1420*6f82e85aSdrh     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1421*6f82e85aSdrh     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1422*6f82e85aSdrh       testcase( pWInfo->untestedTerms==0
1423*6f82e85aSdrh                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
1424*6f82e85aSdrh       pWInfo->untestedTerms = 1;
1425*6f82e85aSdrh       continue;
1426*6f82e85aSdrh     }
1427*6f82e85aSdrh     pE = pTerm->pExpr;
1428*6f82e85aSdrh     assert( pE!=0 );
1429*6f82e85aSdrh     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
1430*6f82e85aSdrh       continue;
1431*6f82e85aSdrh     }
1432*6f82e85aSdrh     if( pTerm->wtFlags & TERM_LIKECOND ){
1433*6f82e85aSdrh       assert( pLevel->iLikeRepCntr>0 );
1434*6f82e85aSdrh       skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
1435*6f82e85aSdrh       VdbeCoverage(v);
1436*6f82e85aSdrh     }
1437*6f82e85aSdrh     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
1438*6f82e85aSdrh     if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
1439*6f82e85aSdrh     pTerm->wtFlags |= TERM_CODED;
1440*6f82e85aSdrh   }
1441*6f82e85aSdrh 
1442*6f82e85aSdrh   /* Insert code to test for implied constraints based on transitivity
1443*6f82e85aSdrh   ** of the "==" operator.
1444*6f82e85aSdrh   **
1445*6f82e85aSdrh   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
1446*6f82e85aSdrh   ** and we are coding the t1 loop and the t2 loop has not yet coded,
1447*6f82e85aSdrh   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
1448*6f82e85aSdrh   ** the implied "t1.a=123" constraint.
1449*6f82e85aSdrh   */
1450*6f82e85aSdrh   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
1451*6f82e85aSdrh     Expr *pE, *pEAlt;
1452*6f82e85aSdrh     WhereTerm *pAlt;
1453*6f82e85aSdrh     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1454*6f82e85aSdrh     if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
1455*6f82e85aSdrh     if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
1456*6f82e85aSdrh     if( pTerm->leftCursor!=iCur ) continue;
1457*6f82e85aSdrh     if( pLevel->iLeftJoin ) continue;
1458*6f82e85aSdrh     pE = pTerm->pExpr;
1459*6f82e85aSdrh     assert( !ExprHasProperty(pE, EP_FromJoin) );
1460*6f82e85aSdrh     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
1461*6f82e85aSdrh     pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
1462*6f82e85aSdrh                     WO_EQ|WO_IN|WO_IS, 0);
1463*6f82e85aSdrh     if( pAlt==0 ) continue;
1464*6f82e85aSdrh     if( pAlt->wtFlags & (TERM_CODED) ) continue;
1465*6f82e85aSdrh     testcase( pAlt->eOperator & WO_EQ );
1466*6f82e85aSdrh     testcase( pAlt->eOperator & WO_IS );
1467*6f82e85aSdrh     testcase( pAlt->eOperator & WO_IN );
1468*6f82e85aSdrh     VdbeModuleComment((v, "begin transitive constraint"));
1469*6f82e85aSdrh     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
1470*6f82e85aSdrh     if( pEAlt ){
1471*6f82e85aSdrh       *pEAlt = *pAlt->pExpr;
1472*6f82e85aSdrh       pEAlt->pLeft = pE->pLeft;
1473*6f82e85aSdrh       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
1474*6f82e85aSdrh       sqlite3StackFree(db, pEAlt);
1475*6f82e85aSdrh     }
1476*6f82e85aSdrh   }
1477*6f82e85aSdrh 
1478*6f82e85aSdrh   /* For a LEFT OUTER JOIN, generate code that will record the fact that
1479*6f82e85aSdrh   ** at least one row of the right table has matched the left table.
1480*6f82e85aSdrh   */
1481*6f82e85aSdrh   if( pLevel->iLeftJoin ){
1482*6f82e85aSdrh     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
1483*6f82e85aSdrh     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
1484*6f82e85aSdrh     VdbeComment((v, "record LEFT JOIN hit"));
1485*6f82e85aSdrh     sqlite3ExprCacheClear(pParse);
1486*6f82e85aSdrh     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
1487*6f82e85aSdrh       testcase( pTerm->wtFlags & TERM_VIRTUAL );
1488*6f82e85aSdrh       testcase( pTerm->wtFlags & TERM_CODED );
1489*6f82e85aSdrh       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
1490*6f82e85aSdrh       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
1491*6f82e85aSdrh         assert( pWInfo->untestedTerms );
1492*6f82e85aSdrh         continue;
1493*6f82e85aSdrh       }
1494*6f82e85aSdrh       assert( pTerm->pExpr );
1495*6f82e85aSdrh       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1496*6f82e85aSdrh       pTerm->wtFlags |= TERM_CODED;
1497*6f82e85aSdrh     }
1498*6f82e85aSdrh   }
1499*6f82e85aSdrh 
1500*6f82e85aSdrh   return pLevel->notReady;
1501*6f82e85aSdrh }
1502