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