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