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