xref: /sqlite-3.40.0/src/where.c (revision 5665b3ea)
1 /*
2 ** 2001 September 15
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.  This module is reponsible for
14 ** generating the code that loops through a table looking for applicable
15 ** rows.  Indices are selected and used to speed the search when doing
16 ** so is applicable.  Because this module is responsible for selecting
17 ** indices, you might also think of this module as the "query optimizer".
18 **
19 ** $Id: where.c,v 1.253 2007/06/11 12:56:15 drh Exp $
20 */
21 #include "sqliteInt.h"
22 
23 /*
24 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
25 */
26 #define BMS  (sizeof(Bitmask)*8)
27 
28 /*
29 ** Trace output macros
30 */
31 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
32 int sqlite3_where_trace = 0;
33 # define WHERETRACE(X)  if(sqlite3_where_trace) sqlite3DebugPrintf X
34 #else
35 # define WHERETRACE(X)
36 #endif
37 
38 /* Forward reference
39 */
40 typedef struct WhereClause WhereClause;
41 typedef struct ExprMaskSet ExprMaskSet;
42 
43 /*
44 ** The query generator uses an array of instances of this structure to
45 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
46 ** clause subexpression is separated from the others by an AND operator.
47 **
48 ** All WhereTerms are collected into a single WhereClause structure.
49 ** The following identity holds:
50 **
51 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
52 **
53 ** When a term is of the form:
54 **
55 **              X <op> <expr>
56 **
57 ** where X is a column name and <op> is one of certain operators,
58 ** then WhereTerm.leftCursor and WhereTerm.leftColumn record the
59 ** cursor number and column number for X.  WhereTerm.operator records
60 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
61 ** use of a bitmask encoding for the operator allows us to search
62 ** quickly for terms that match any of several different operators.
63 **
64 ** prereqRight and prereqAll record sets of cursor numbers,
65 ** but they do so indirectly.  A single ExprMaskSet structure translates
66 ** cursor number into bits and the translated bit is stored in the prereq
67 ** fields.  The translation is used in order to maximize the number of
68 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
69 ** spread out over the non-negative integers.  For example, the cursor
70 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The ExprMaskSet
71 ** translates these sparse cursor numbers into consecutive integers
72 ** beginning with 0 in order to make the best possible use of the available
73 ** bits in the Bitmask.  So, in the example above, the cursor numbers
74 ** would be mapped into integers 0 through 7.
75 */
76 typedef struct WhereTerm WhereTerm;
77 struct WhereTerm {
78   Expr *pExpr;            /* Pointer to the subexpression */
79   i16 iParent;            /* Disable pWC->a[iParent] when this term disabled */
80   i16 leftCursor;         /* Cursor number of X in "X <op> <expr>" */
81   i16 leftColumn;         /* Column number of X in "X <op> <expr>" */
82   u16 eOperator;          /* A WO_xx value describing <op> */
83   u8 flags;               /* Bit flags.  See below */
84   u8 nChild;              /* Number of children that must disable us */
85   WhereClause *pWC;       /* The clause this term is part of */
86   Bitmask prereqRight;    /* Bitmask of tables used by pRight */
87   Bitmask prereqAll;      /* Bitmask of tables referenced by p */
88 };
89 
90 /*
91 ** Allowed values of WhereTerm.flags
92 */
93 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(pExpr) */
94 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
95 #define TERM_CODED      0x04   /* This term is already coded */
96 #define TERM_COPIED     0x08   /* Has a child */
97 #define TERM_OR_OK      0x10   /* Used during OR-clause processing */
98 
99 /*
100 ** An instance of the following structure holds all information about a
101 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
102 */
103 struct WhereClause {
104   Parse *pParse;           /* The parser context */
105   ExprMaskSet *pMaskSet;   /* Mapping of table indices to bitmasks */
106   int nTerm;               /* Number of terms */
107   int nSlot;               /* Number of entries in a[] */
108   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
109   WhereTerm aStatic[10];   /* Initial static space for a[] */
110 };
111 
112 /*
113 ** An instance of the following structure keeps track of a mapping
114 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
115 **
116 ** The VDBE cursor numbers are small integers contained in
117 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
118 ** clause, the cursor numbers might not begin with 0 and they might
119 ** contain gaps in the numbering sequence.  But we want to make maximum
120 ** use of the bits in our bitmasks.  This structure provides a mapping
121 ** from the sparse cursor numbers into consecutive integers beginning
122 ** with 0.
123 **
124 ** If ExprMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
125 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
126 **
127 ** For example, if the WHERE clause expression used these VDBE
128 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  ExprMaskSet structure
129 ** would map those cursor numbers into bits 0 through 5.
130 **
131 ** Note that the mapping is not necessarily ordered.  In the example
132 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
133 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
134 ** does not really matter.  What is important is that sparse cursor
135 ** numbers all get mapped into bit numbers that begin with 0 and contain
136 ** no gaps.
137 */
138 struct ExprMaskSet {
139   int n;                        /* Number of assigned cursor values */
140   int ix[sizeof(Bitmask)*8];    /* Cursor assigned to each bit */
141 };
142 
143 
144 /*
145 ** Bitmasks for the operators that indices are able to exploit.  An
146 ** OR-ed combination of these values can be used when searching for
147 ** terms in the where clause.
148 */
149 #define WO_IN     1
150 #define WO_EQ     2
151 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
152 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
153 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
154 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
155 #define WO_MATCH  64
156 #define WO_ISNULL 128
157 
158 /*
159 ** Value for flags returned by bestIndex().
160 **
161 ** The least significant byte is reserved as a mask for WO_ values above.
162 ** The WhereLevel.flags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
163 ** But if the table is the right table of a left join, WhereLevel.flags
164 ** is set to WO_IN|WO_EQ.  The WhereLevel.flags field can then be used as
165 ** the "op" parameter to findTerm when we are resolving equality constraints.
166 ** ISNULL constraints will then not be used on the right table of a left
167 ** join.  Tickets #2177 and #2189.
168 */
169 #define WHERE_ROWID_EQ     0x000100   /* rowid=EXPR or rowid IN (...) */
170 #define WHERE_ROWID_RANGE  0x000200   /* rowid<EXPR and/or rowid>EXPR */
171 #define WHERE_COLUMN_EQ    0x001000   /* x=EXPR or x IN (...) */
172 #define WHERE_COLUMN_RANGE 0x002000   /* x<EXPR and/or x>EXPR */
173 #define WHERE_COLUMN_IN    0x004000   /* x IN (...) */
174 #define WHERE_TOP_LIMIT    0x010000   /* x<EXPR or x<=EXPR constraint */
175 #define WHERE_BTM_LIMIT    0x020000   /* x>EXPR or x>=EXPR constraint */
176 #define WHERE_IDX_ONLY     0x080000   /* Use index only - omit table */
177 #define WHERE_ORDERBY      0x100000   /* Output will appear in correct order */
178 #define WHERE_REVERSE      0x200000   /* Scan in reverse order */
179 #define WHERE_UNIQUE       0x400000   /* Selects no more than one row */
180 #define WHERE_VIRTUALTABLE 0x800000   /* Use virtual-table processing */
181 
182 /*
183 ** Initialize a preallocated WhereClause structure.
184 */
185 static void whereClauseInit(
186   WhereClause *pWC,        /* The WhereClause to be initialized */
187   Parse *pParse,           /* The parsing context */
188   ExprMaskSet *pMaskSet    /* Mapping from table indices to bitmasks */
189 ){
190   pWC->pParse = pParse;
191   pWC->pMaskSet = pMaskSet;
192   pWC->nTerm = 0;
193   pWC->nSlot = ArraySize(pWC->aStatic);
194   pWC->a = pWC->aStatic;
195 }
196 
197 /*
198 ** Deallocate a WhereClause structure.  The WhereClause structure
199 ** itself is not freed.  This routine is the inverse of whereClauseInit().
200 */
201 static void whereClauseClear(WhereClause *pWC){
202   int i;
203   WhereTerm *a;
204   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
205     if( a->flags & TERM_DYNAMIC ){
206       sqlite3ExprDelete(a->pExpr);
207     }
208   }
209   if( pWC->a!=pWC->aStatic ){
210     sqliteFree(pWC->a);
211   }
212 }
213 
214 /*
215 ** Add a new entries to the WhereClause structure.  Increase the allocated
216 ** space as necessary.
217 **
218 ** If the flags argument includes TERM_DYNAMIC, then responsibility
219 ** for freeing the expression p is assumed by the WhereClause object.
220 **
221 ** WARNING:  This routine might reallocate the space used to store
222 ** WhereTerms.  All pointers to WhereTerms should be invalided after
223 ** calling this routine.  Such pointers may be reinitialized by referencing
224 ** the pWC->a[] array.
225 */
226 static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){
227   WhereTerm *pTerm;
228   int idx;
229   if( pWC->nTerm>=pWC->nSlot ){
230     WhereTerm *pOld = pWC->a;
231     pWC->a = sqliteMalloc( sizeof(pWC->a[0])*pWC->nSlot*2 );
232     if( pWC->a==0 ){
233       if( flags & TERM_DYNAMIC ){
234         sqlite3ExprDelete(p);
235       }
236       return 0;
237     }
238     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
239     if( pOld!=pWC->aStatic ){
240       sqliteFree(pOld);
241     }
242     pWC->nSlot *= 2;
243   }
244   pTerm = &pWC->a[idx = pWC->nTerm];
245   pWC->nTerm++;
246   pTerm->pExpr = p;
247   pTerm->flags = flags;
248   pTerm->pWC = pWC;
249   pTerm->iParent = -1;
250   return idx;
251 }
252 
253 /*
254 ** This routine identifies subexpressions in the WHERE clause where
255 ** each subexpression is separated by the AND operator or some other
256 ** operator specified in the op parameter.  The WhereClause structure
257 ** is filled with pointers to subexpressions.  For example:
258 **
259 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
260 **           \________/     \_______________/     \________________/
261 **            slot[0]            slot[1]               slot[2]
262 **
263 ** The original WHERE clause in pExpr is unaltered.  All this routine
264 ** does is make slot[] entries point to substructure within pExpr.
265 **
266 ** In the previous sentence and in the diagram, "slot[]" refers to
267 ** the WhereClause.a[] array.  This array grows as needed to contain
268 ** all terms of the WHERE clause.
269 */
270 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
271   if( pExpr==0 ) return;
272   if( pExpr->op!=op ){
273     whereClauseInsert(pWC, pExpr, 0);
274   }else{
275     whereSplit(pWC, pExpr->pLeft, op);
276     whereSplit(pWC, pExpr->pRight, op);
277   }
278 }
279 
280 /*
281 ** Initialize an expression mask set
282 */
283 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
284 
285 /*
286 ** Return the bitmask for the given cursor number.  Return 0 if
287 ** iCursor is not in the set.
288 */
289 static Bitmask getMask(ExprMaskSet *pMaskSet, int iCursor){
290   int i;
291   for(i=0; i<pMaskSet->n; i++){
292     if( pMaskSet->ix[i]==iCursor ){
293       return ((Bitmask)1)<<i;
294     }
295   }
296   return 0;
297 }
298 
299 /*
300 ** Create a new mask for cursor iCursor.
301 **
302 ** There is one cursor per table in the FROM clause.  The number of
303 ** tables in the FROM clause is limited by a test early in the
304 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
305 ** array will never overflow.
306 */
307 static void createMask(ExprMaskSet *pMaskSet, int iCursor){
308   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
309   pMaskSet->ix[pMaskSet->n++] = iCursor;
310 }
311 
312 /*
313 ** This routine walks (recursively) an expression tree and generates
314 ** a bitmask indicating which tables are used in that expression
315 ** tree.
316 **
317 ** In order for this routine to work, the calling function must have
318 ** previously invoked sqlite3ExprResolveNames() on the expression.  See
319 ** the header comment on that routine for additional information.
320 ** The sqlite3ExprResolveNames() routines looks for column names and
321 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
322 ** the VDBE cursor number of the table.  This routine just has to
323 ** translate the cursor numbers into bitmask values and OR all
324 ** the bitmasks together.
325 */
326 static Bitmask exprListTableUsage(ExprMaskSet*, ExprList*);
327 static Bitmask exprSelectTableUsage(ExprMaskSet*, Select*);
328 static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
329   Bitmask mask = 0;
330   if( p==0 ) return 0;
331   if( p->op==TK_COLUMN ){
332     mask = getMask(pMaskSet, p->iTable);
333     return mask;
334   }
335   mask = exprTableUsage(pMaskSet, p->pRight);
336   mask |= exprTableUsage(pMaskSet, p->pLeft);
337   mask |= exprListTableUsage(pMaskSet, p->pList);
338   mask |= exprSelectTableUsage(pMaskSet, p->pSelect);
339   return mask;
340 }
341 static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
342   int i;
343   Bitmask mask = 0;
344   if( pList ){
345     for(i=0; i<pList->nExpr; i++){
346       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
347     }
348   }
349   return mask;
350 }
351 static Bitmask exprSelectTableUsage(ExprMaskSet *pMaskSet, Select *pS){
352   Bitmask mask;
353   if( pS==0 ){
354     mask = 0;
355   }else{
356     mask = exprListTableUsage(pMaskSet, pS->pEList);
357     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
358     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
359     mask |= exprTableUsage(pMaskSet, pS->pWhere);
360     mask |= exprTableUsage(pMaskSet, pS->pHaving);
361   }
362   return mask;
363 }
364 
365 /*
366 ** Return TRUE if the given operator is one of the operators that is
367 ** allowed for an indexable WHERE clause term.  The allowed operators are
368 ** "=", "<", ">", "<=", ">=", and "IN".
369 */
370 static int allowedOp(int op){
371   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
372   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
373   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
374   assert( TK_GE==TK_EQ+4 );
375   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
376 }
377 
378 /*
379 ** Swap two objects of type T.
380 */
381 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
382 
383 /*
384 ** Commute a comparision operator.  Expressions of the form "X op Y"
385 ** are converted into "Y op X".
386 */
387 static void exprCommute(Expr *pExpr){
388   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
389   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
390   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
391   if( pExpr->op>=TK_GT ){
392     assert( TK_LT==TK_GT+2 );
393     assert( TK_GE==TK_LE+2 );
394     assert( TK_GT>TK_EQ );
395     assert( TK_GT<TK_LE );
396     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
397     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
398   }
399 }
400 
401 /*
402 ** Translate from TK_xx operator to WO_xx bitmask.
403 */
404 static int operatorMask(int op){
405   int c;
406   assert( allowedOp(op) );
407   if( op==TK_IN ){
408     c = WO_IN;
409   }else if( op==TK_ISNULL ){
410     c = WO_ISNULL;
411   }else{
412     c = WO_EQ<<(op-TK_EQ);
413   }
414   assert( op!=TK_ISNULL || c==WO_ISNULL );
415   assert( op!=TK_IN || c==WO_IN );
416   assert( op!=TK_EQ || c==WO_EQ );
417   assert( op!=TK_LT || c==WO_LT );
418   assert( op!=TK_LE || c==WO_LE );
419   assert( op!=TK_GT || c==WO_GT );
420   assert( op!=TK_GE || c==WO_GE );
421   return c;
422 }
423 
424 /*
425 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
426 ** where X is a reference to the iColumn of table iCur and <op> is one of
427 ** the WO_xx operator codes specified by the op parameter.
428 ** Return a pointer to the term.  Return 0 if not found.
429 */
430 static WhereTerm *findTerm(
431   WhereClause *pWC,     /* The WHERE clause to be searched */
432   int iCur,             /* Cursor number of LHS */
433   int iColumn,          /* Column number of LHS */
434   Bitmask notReady,     /* RHS must not overlap with this mask */
435   u16 op,               /* Mask of WO_xx values describing operator */
436   Index *pIdx           /* Must be compatible with this index, if not NULL */
437 ){
438   WhereTerm *pTerm;
439   int k;
440   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
441     if( pTerm->leftCursor==iCur
442        && (pTerm->prereqRight & notReady)==0
443        && pTerm->leftColumn==iColumn
444        && (pTerm->eOperator & op)!=0
445     ){
446       if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
447         Expr *pX = pTerm->pExpr;
448         CollSeq *pColl;
449         char idxaff;
450         int j;
451         Parse *pParse = pWC->pParse;
452 
453         idxaff = pIdx->pTable->aCol[iColumn].affinity;
454         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
455 
456         /* Figure out the collation sequence required from an index for
457         ** it to be useful for optimising expression pX. Store this
458         ** value in variable pColl.
459         */
460         assert(pX->pLeft);
461         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
462         if( !pColl ){
463           pColl = pParse->db->pDfltColl;
464         }
465 
466         for(j=0; j<pIdx->nColumn && pIdx->aiColumn[j]!=iColumn; j++){}
467         assert( j<pIdx->nColumn );
468         if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
469       }
470       return pTerm;
471     }
472   }
473   return 0;
474 }
475 
476 /* Forward reference */
477 static void exprAnalyze(SrcList*, WhereClause*, int);
478 
479 /*
480 ** Call exprAnalyze on all terms in a WHERE clause.
481 **
482 **
483 */
484 static void exprAnalyzeAll(
485   SrcList *pTabList,       /* the FROM clause */
486   WhereClause *pWC         /* the WHERE clause to be analyzed */
487 ){
488   int i;
489   for(i=pWC->nTerm-1; i>=0; i--){
490     exprAnalyze(pTabList, pWC, i);
491   }
492 }
493 
494 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
495 /*
496 ** Check to see if the given expression is a LIKE or GLOB operator that
497 ** can be optimized using inequality constraints.  Return TRUE if it is
498 ** so and false if not.
499 **
500 ** In order for the operator to be optimizible, the RHS must be a string
501 ** literal that does not begin with a wildcard.
502 */
503 static int isLikeOrGlob(
504   sqlite3 *db,      /* The database */
505   Expr *pExpr,      /* Test this expression */
506   int *pnPattern,   /* Number of non-wildcard prefix characters */
507   int *pisComplete  /* True if the only wildcard is % in the last character */
508 ){
509   const char *z;
510   Expr *pRight, *pLeft;
511   ExprList *pList;
512   int c, cnt;
513   int noCase;
514   char wc[3];
515   CollSeq *pColl;
516 
517   if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){
518     return 0;
519   }
520   pList = pExpr->pList;
521   pRight = pList->a[0].pExpr;
522   if( pRight->op!=TK_STRING ){
523     return 0;
524   }
525   pLeft = pList->a[1].pExpr;
526   if( pLeft->op!=TK_COLUMN ){
527     return 0;
528   }
529   pColl = pLeft->pColl;
530   if( pColl==0 ){
531     /* TODO: Coverage testing doesn't get this case. Is it actually possible
532     ** for an expression of type TK_COLUMN to not have an assigned collation
533     ** sequence at this point?
534     */
535     pColl = db->pDfltColl;
536   }
537   if( (pColl->type!=SQLITE_COLL_BINARY || noCase) &&
538       (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){
539     return 0;
540   }
541   sqlite3DequoteExpr(pRight);
542   z = (char *)pRight->token.z;
543   for(cnt=0; (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2]; cnt++){}
544   if( cnt==0 || 255==(u8)z[cnt] ){
545     return 0;
546   }
547   *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
548   *pnPattern = cnt;
549   return 1;
550 }
551 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
552 
553 
554 #ifndef SQLITE_OMIT_VIRTUALTABLE
555 /*
556 ** Check to see if the given expression is of the form
557 **
558 **         column MATCH expr
559 **
560 ** If it is then return TRUE.  If not, return FALSE.
561 */
562 static int isMatchOfColumn(
563   Expr *pExpr      /* Test this expression */
564 ){
565   ExprList *pList;
566 
567   if( pExpr->op!=TK_FUNCTION ){
568     return 0;
569   }
570   if( pExpr->token.n!=5 ||
571        sqlite3StrNICmp((const char*)pExpr->token.z,"match",5)!=0 ){
572     return 0;
573   }
574   pList = pExpr->pList;
575   if( pList->nExpr!=2 ){
576     return 0;
577   }
578   if( pList->a[1].pExpr->op != TK_COLUMN ){
579     return 0;
580   }
581   return 1;
582 }
583 #endif /* SQLITE_OMIT_VIRTUALTABLE */
584 
585 /*
586 ** If the pBase expression originated in the ON or USING clause of
587 ** a join, then transfer the appropriate markings over to derived.
588 */
589 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
590   pDerived->flags |= pBase->flags & EP_FromJoin;
591   pDerived->iRightJoinTable = pBase->iRightJoinTable;
592 }
593 
594 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
595 /*
596 ** Return TRUE if the given term of an OR clause can be converted
597 ** into an IN clause.  The iCursor and iColumn define the left-hand
598 ** side of the IN clause.
599 **
600 ** The context is that we have multiple OR-connected equality terms
601 ** like this:
602 **
603 **           a=<expr1> OR  a=<expr2> OR b=<expr3>  OR ...
604 **
605 ** The pOrTerm input to this routine corresponds to a single term of
606 ** this OR clause.  In order for the term to be a condidate for
607 ** conversion to an IN operator, the following must be true:
608 **
609 **     *  The left-hand side of the term must be the column which
610 **        is identified by iCursor and iColumn.
611 **
612 **     *  If the right-hand side is also a column, then the affinities
613 **        of both right and left sides must be such that no type
614 **        conversions are required on the right.  (Ticket #2249)
615 **
616 ** If both of these conditions are true, then return true.  Otherwise
617 ** return false.
618 */
619 static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){
620   int affLeft, affRight;
621   assert( pOrTerm->eOperator==WO_EQ );
622   if( pOrTerm->leftCursor!=iCursor ){
623     return 0;
624   }
625   if( pOrTerm->leftColumn!=iColumn ){
626     return 0;
627   }
628   affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
629   if( affRight==0 ){
630     return 1;
631   }
632   affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
633   if( affRight!=affLeft ){
634     return 0;
635   }
636   return 1;
637 }
638 
639 /*
640 ** Return true if the given term of an OR clause can be ignored during
641 ** a check to make sure all OR terms are candidates for optimization.
642 ** In other words, return true if a call to the orTermIsOptCandidate()
643 ** above returned false but it is not necessary to disqualify the
644 ** optimization.
645 **
646 ** Suppose the original OR phrase was this:
647 **
648 **           a=4  OR  a=11  OR  a=b
649 **
650 ** During analysis, the third term gets flipped around and duplicate
651 ** so that we are left with this:
652 **
653 **           a=4  OR  a=11  OR  a=b  OR  b=a
654 **
655 ** Since the last two terms are duplicates, only one of them
656 ** has to qualify in order for the whole phrase to qualify.  When
657 ** this routine is called, we know that pOrTerm did not qualify.
658 ** This routine merely checks to see if pOrTerm has a duplicate that
659 ** might qualify.  If there is a duplicate that has not yet been
660 ** disqualified, then return true.  If there are no duplicates, or
661 ** the duplicate has also been disqualifed, return false.
662 */
663 static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){
664   if( pOrTerm->flags & TERM_COPIED ){
665     /* This is the original term.  The duplicate is to the left had
666     ** has not yet been analyzed and thus has not yet been disqualified. */
667     return 1;
668   }
669   if( (pOrTerm->flags & TERM_VIRTUAL)!=0
670      && (pOr->a[pOrTerm->iParent].flags & TERM_OR_OK)!=0 ){
671     /* This is a duplicate term.  The original qualified so this one
672     ** does not have to. */
673     return 1;
674   }
675   /* This is either a singleton term or else it is a duplicate for
676   ** which the original did not qualify.  Either way we are done for. */
677   return 0;
678 }
679 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
680 
681 /*
682 ** The input to this routine is an WhereTerm structure with only the
683 ** "pExpr" field filled in.  The job of this routine is to analyze the
684 ** subexpression and populate all the other fields of the WhereTerm
685 ** structure.
686 **
687 ** If the expression is of the form "<expr> <op> X" it gets commuted
688 ** to the standard form of "X <op> <expr>".  If the expression is of
689 ** the form "X <op> Y" where both X and Y are columns, then the original
690 ** expression is unchanged and a new virtual expression of the form
691 ** "Y <op> X" is added to the WHERE clause and analyzed separately.
692 */
693 static void exprAnalyze(
694   SrcList *pSrc,            /* the FROM clause */
695   WhereClause *pWC,         /* the WHERE clause */
696   int idxTerm               /* Index of the term to be analyzed */
697 ){
698   WhereTerm *pTerm = &pWC->a[idxTerm];
699   ExprMaskSet *pMaskSet = pWC->pMaskSet;
700   Expr *pExpr = pTerm->pExpr;
701   Bitmask prereqLeft;
702   Bitmask prereqAll;
703   int nPattern;
704   int isComplete;
705   int op;
706 
707   if( sqlite3MallocFailed() ) return;
708   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
709   op = pExpr->op;
710   if( op==TK_IN ){
711     assert( pExpr->pRight==0 );
712     pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList)
713                           | exprSelectTableUsage(pMaskSet, pExpr->pSelect);
714   }else if( op==TK_ISNULL ){
715     pTerm->prereqRight = 0;
716   }else{
717     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
718   }
719   prereqAll = exprTableUsage(pMaskSet, pExpr);
720   if( ExprHasProperty(pExpr, EP_FromJoin) ){
721     prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable);
722   }
723   pTerm->prereqAll = prereqAll;
724   pTerm->leftCursor = -1;
725   pTerm->iParent = -1;
726   pTerm->eOperator = 0;
727   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
728     Expr *pLeft = pExpr->pLeft;
729     Expr *pRight = pExpr->pRight;
730     if( pLeft->op==TK_COLUMN ){
731       pTerm->leftCursor = pLeft->iTable;
732       pTerm->leftColumn = pLeft->iColumn;
733       pTerm->eOperator = operatorMask(op);
734     }
735     if( pRight && pRight->op==TK_COLUMN ){
736       WhereTerm *pNew;
737       Expr *pDup;
738       if( pTerm->leftCursor>=0 ){
739         int idxNew;
740         pDup = sqlite3ExprDup(pExpr);
741         if( sqlite3MallocFailed() ){
742           sqlite3ExprDelete(pDup);
743           return;
744         }
745         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
746         if( idxNew==0 ) return;
747         pNew = &pWC->a[idxNew];
748         pNew->iParent = idxTerm;
749         pTerm = &pWC->a[idxTerm];
750         pTerm->nChild = 1;
751         pTerm->flags |= TERM_COPIED;
752       }else{
753         pDup = pExpr;
754         pNew = pTerm;
755       }
756       exprCommute(pDup);
757       pLeft = pDup->pLeft;
758       pNew->leftCursor = pLeft->iTable;
759       pNew->leftColumn = pLeft->iColumn;
760       pNew->prereqRight = prereqLeft;
761       pNew->prereqAll = prereqAll;
762       pNew->eOperator = operatorMask(pDup->op);
763     }
764   }
765 
766 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
767   /* If a term is the BETWEEN operator, create two new virtual terms
768   ** that define the range that the BETWEEN implements.
769   */
770   else if( pExpr->op==TK_BETWEEN ){
771     ExprList *pList = pExpr->pList;
772     int i;
773     static const u8 ops[] = {TK_GE, TK_LE};
774     assert( pList!=0 );
775     assert( pList->nExpr==2 );
776     for(i=0; i<2; i++){
777       Expr *pNewExpr;
778       int idxNew;
779       pNewExpr = sqlite3Expr(ops[i], sqlite3ExprDup(pExpr->pLeft),
780                              sqlite3ExprDup(pList->a[i].pExpr), 0);
781       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
782       exprAnalyze(pSrc, pWC, idxNew);
783       pTerm = &pWC->a[idxTerm];
784       pWC->a[idxNew].iParent = idxTerm;
785     }
786     pTerm->nChild = 2;
787   }
788 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
789 
790 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
791   /* Attempt to convert OR-connected terms into an IN operator so that
792   ** they can make use of indices.  Example:
793   **
794   **      x = expr1  OR  expr2 = x  OR  x = expr3
795   **
796   ** is converted into
797   **
798   **      x IN (expr1,expr2,expr3)
799   **
800   ** This optimization must be omitted if OMIT_SUBQUERY is defined because
801   ** the compiler for the the IN operator is part of sub-queries.
802   */
803   else if( pExpr->op==TK_OR ){
804     int ok;
805     int i, j;
806     int iColumn, iCursor;
807     WhereClause sOr;
808     WhereTerm *pOrTerm;
809 
810     assert( (pTerm->flags & TERM_DYNAMIC)==0 );
811     whereClauseInit(&sOr, pWC->pParse, pMaskSet);
812     whereSplit(&sOr, pExpr, TK_OR);
813     exprAnalyzeAll(pSrc, &sOr);
814     assert( sOr.nTerm>=2 );
815     j = 0;
816     do{
817       assert( j<sOr.nTerm );
818       iColumn = sOr.a[j].leftColumn;
819       iCursor = sOr.a[j].leftCursor;
820       ok = iCursor>=0;
821       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
822         if( pOrTerm->eOperator!=WO_EQ ){
823           goto or_not_possible;
824         }
825         if( orTermIsOptCandidate(pOrTerm, iCursor, iColumn) ){
826           pOrTerm->flags |= TERM_OR_OK;
827         }else if( orTermHasOkDuplicate(&sOr, pOrTerm) ){
828           pOrTerm->flags &= ~TERM_OR_OK;
829         }else{
830           ok = 0;
831         }
832       }
833     }while( !ok && (sOr.a[j++].flags & TERM_COPIED)!=0 && j<2 );
834     if( ok ){
835       ExprList *pList = 0;
836       Expr *pNew, *pDup;
837       Expr *pLeft = 0;
838       for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){
839         if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue;
840         pDup = sqlite3ExprDup(pOrTerm->pExpr->pRight);
841         pList = sqlite3ExprListAppend(pList, pDup, 0);
842         pLeft = pOrTerm->pExpr->pLeft;
843       }
844       assert( pLeft!=0 );
845       pDup = sqlite3ExprDup(pLeft);
846       pNew = sqlite3Expr(TK_IN, pDup, 0, 0);
847       if( pNew ){
848         int idxNew;
849         transferJoinMarkings(pNew, pExpr);
850         pNew->pList = pList;
851         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
852         exprAnalyze(pSrc, pWC, idxNew);
853         pTerm = &pWC->a[idxTerm];
854         pWC->a[idxNew].iParent = idxTerm;
855         pTerm->nChild = 1;
856       }else{
857         sqlite3ExprListDelete(pList);
858       }
859     }
860 or_not_possible:
861     whereClauseClear(&sOr);
862   }
863 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
864 
865 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
866   /* Add constraints to reduce the search space on a LIKE or GLOB
867   ** operator.
868   */
869   if( isLikeOrGlob(pWC->pParse->db, pExpr, &nPattern, &isComplete) ){
870     Expr *pLeft, *pRight;
871     Expr *pStr1, *pStr2;
872     Expr *pNewExpr1, *pNewExpr2;
873     int idxNew1, idxNew2;
874 
875     pLeft = pExpr->pList->a[1].pExpr;
876     pRight = pExpr->pList->a[0].pExpr;
877     pStr1 = sqlite3Expr(TK_STRING, 0, 0, 0);
878     if( pStr1 ){
879       sqlite3TokenCopy(&pStr1->token, &pRight->token);
880       pStr1->token.n = nPattern;
881       pStr1->flags = EP_Dequoted;
882     }
883     pStr2 = sqlite3ExprDup(pStr1);
884     if( pStr2 ){
885       assert( pStr2->token.dyn );
886       ++*(u8*)&pStr2->token.z[nPattern-1];
887     }
888     pNewExpr1 = sqlite3Expr(TK_GE, sqlite3ExprDup(pLeft), pStr1, 0);
889     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
890     exprAnalyze(pSrc, pWC, idxNew1);
891     pNewExpr2 = sqlite3Expr(TK_LT, sqlite3ExprDup(pLeft), pStr2, 0);
892     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
893     exprAnalyze(pSrc, pWC, idxNew2);
894     pTerm = &pWC->a[idxTerm];
895     if( isComplete ){
896       pWC->a[idxNew1].iParent = idxTerm;
897       pWC->a[idxNew2].iParent = idxTerm;
898       pTerm->nChild = 2;
899     }
900   }
901 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
902 
903 #ifndef SQLITE_OMIT_VIRTUALTABLE
904   /* Add a WO_MATCH auxiliary term to the constraint set if the
905   ** current expression is of the form:  column MATCH expr.
906   ** This information is used by the xBestIndex methods of
907   ** virtual tables.  The native query optimizer does not attempt
908   ** to do anything with MATCH functions.
909   */
910   if( isMatchOfColumn(pExpr) ){
911     int idxNew;
912     Expr *pRight, *pLeft;
913     WhereTerm *pNewTerm;
914     Bitmask prereqColumn, prereqExpr;
915 
916     pRight = pExpr->pList->a[0].pExpr;
917     pLeft = pExpr->pList->a[1].pExpr;
918     prereqExpr = exprTableUsage(pMaskSet, pRight);
919     prereqColumn = exprTableUsage(pMaskSet, pLeft);
920     if( (prereqExpr & prereqColumn)==0 ){
921       Expr *pNewExpr;
922       pNewExpr = sqlite3Expr(TK_MATCH, 0, sqlite3ExprDup(pRight), 0);
923       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
924       pNewTerm = &pWC->a[idxNew];
925       pNewTerm->prereqRight = prereqExpr;
926       pNewTerm->leftCursor = pLeft->iTable;
927       pNewTerm->leftColumn = pLeft->iColumn;
928       pNewTerm->eOperator = WO_MATCH;
929       pNewTerm->iParent = idxTerm;
930       pTerm = &pWC->a[idxTerm];
931       pTerm->nChild = 1;
932       pTerm->flags |= TERM_COPIED;
933       pNewTerm->prereqAll = pTerm->prereqAll;
934     }
935   }
936 #endif /* SQLITE_OMIT_VIRTUALTABLE */
937 }
938 
939 /*
940 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
941 ** a reference to any table other than the iBase table.
942 */
943 static int referencesOtherTables(
944   ExprList *pList,          /* Search expressions in ths list */
945   ExprMaskSet *pMaskSet,    /* Mapping from tables to bitmaps */
946   int iFirst,               /* Be searching with the iFirst-th expression */
947   int iBase                 /* Ignore references to this table */
948 ){
949   Bitmask allowed = ~getMask(pMaskSet, iBase);
950   while( iFirst<pList->nExpr ){
951     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
952       return 1;
953     }
954   }
955   return 0;
956 }
957 
958 
959 /*
960 ** This routine decides if pIdx can be used to satisfy the ORDER BY
961 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
962 ** ORDER BY clause, this routine returns 0.
963 **
964 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
965 ** left-most table in the FROM clause of that same SELECT statement and
966 ** the table has a cursor number of "base".  pIdx is an index on pTab.
967 **
968 ** nEqCol is the number of columns of pIdx that are used as equality
969 ** constraints.  Any of these columns may be missing from the ORDER BY
970 ** clause and the match can still be a success.
971 **
972 ** All terms of the ORDER BY that match against the index must be either
973 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
974 ** index do not need to satisfy this constraint.)  The *pbRev value is
975 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
976 ** the ORDER BY clause is all ASC.
977 */
978 static int isSortingIndex(
979   Parse *pParse,          /* Parsing context */
980   ExprMaskSet *pMaskSet,  /* Mapping from table indices to bitmaps */
981   Index *pIdx,            /* The index we are testing */
982   int base,               /* Cursor number for the table to be sorted */
983   ExprList *pOrderBy,     /* The ORDER BY clause */
984   int nEqCol,             /* Number of index columns with == constraints */
985   int *pbRev              /* Set to 1 if ORDER BY is DESC */
986 ){
987   int i, j;                       /* Loop counters */
988   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
989   int nTerm;                      /* Number of ORDER BY terms */
990   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
991   sqlite3 *db = pParse->db;
992 
993   assert( pOrderBy!=0 );
994   nTerm = pOrderBy->nExpr;
995   assert( nTerm>0 );
996 
997   /* Match terms of the ORDER BY clause against columns of
998   ** the index.
999   **
1000   ** Note that indices have pIdx->nColumn regular columns plus
1001   ** one additional column containing the rowid.  The rowid column
1002   ** of the index is also allowed to match against the ORDER BY
1003   ** clause.
1004   */
1005   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
1006     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
1007     CollSeq *pColl;    /* The collating sequence of pExpr */
1008     int termSortOrder; /* Sort order for this term */
1009     int iColumn;       /* The i-th column of the index.  -1 for rowid */
1010     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
1011     const char *zColl; /* Name of the collating sequence for i-th index term */
1012 
1013     pExpr = pTerm->pExpr;
1014     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
1015       /* Can not use an index sort on anything that is not a column in the
1016       ** left-most table of the FROM clause */
1017       break;
1018     }
1019     pColl = sqlite3ExprCollSeq(pParse, pExpr);
1020     if( !pColl ){
1021       pColl = db->pDfltColl;
1022     }
1023     if( i<pIdx->nColumn ){
1024       iColumn = pIdx->aiColumn[i];
1025       if( iColumn==pIdx->pTable->iPKey ){
1026         iColumn = -1;
1027       }
1028       iSortOrder = pIdx->aSortOrder[i];
1029       zColl = pIdx->azColl[i];
1030     }else{
1031       iColumn = -1;
1032       iSortOrder = 0;
1033       zColl = pColl->zName;
1034     }
1035     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
1036       /* Term j of the ORDER BY clause does not match column i of the index */
1037       if( i<nEqCol ){
1038         /* If an index column that is constrained by == fails to match an
1039         ** ORDER BY term, that is OK.  Just ignore that column of the index
1040         */
1041         continue;
1042       }else{
1043         /* If an index column fails to match and is not constrained by ==
1044         ** then the index cannot satisfy the ORDER BY constraint.
1045         */
1046         return 0;
1047       }
1048     }
1049     assert( pIdx->aSortOrder!=0 );
1050     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
1051     assert( iSortOrder==0 || iSortOrder==1 );
1052     termSortOrder = iSortOrder ^ pTerm->sortOrder;
1053     if( i>nEqCol ){
1054       if( termSortOrder!=sortOrder ){
1055         /* Indices can only be used if all ORDER BY terms past the
1056         ** equality constraints are all either DESC or ASC. */
1057         return 0;
1058       }
1059     }else{
1060       sortOrder = termSortOrder;
1061     }
1062     j++;
1063     pTerm++;
1064     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
1065       /* If the indexed column is the primary key and everything matches
1066       ** so far and none of the ORDER BY terms to the right reference other
1067       ** tables in the join, then we are assured that the index can be used
1068       ** to sort because the primary key is unique and so none of the other
1069       ** columns will make any difference
1070       */
1071       j = nTerm;
1072     }
1073   }
1074 
1075   *pbRev = sortOrder!=0;
1076   if( j>=nTerm ){
1077     /* All terms of the ORDER BY clause are covered by this index so
1078     ** this index can be used for sorting. */
1079     return 1;
1080   }
1081   if( pIdx->onError!=OE_None && i==pIdx->nColumn
1082       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
1083     /* All terms of this index match some prefix of the ORDER BY clause
1084     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
1085     ** clause reference other tables in a join.  If this is all true then
1086     ** the order by clause is superfluous. */
1087     return 1;
1088   }
1089   return 0;
1090 }
1091 
1092 /*
1093 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
1094 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
1095 ** true for reverse ROWID and false for forward ROWID order.
1096 */
1097 static int sortableByRowid(
1098   int base,               /* Cursor number for table to be sorted */
1099   ExprList *pOrderBy,     /* The ORDER BY clause */
1100   ExprMaskSet *pMaskSet,  /* Mapping from tables to bitmaps */
1101   int *pbRev              /* Set to 1 if ORDER BY is DESC */
1102 ){
1103   Expr *p;
1104 
1105   assert( pOrderBy!=0 );
1106   assert( pOrderBy->nExpr>0 );
1107   p = pOrderBy->a[0].pExpr;
1108   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
1109     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
1110     *pbRev = pOrderBy->a[0].sortOrder;
1111     return 1;
1112   }
1113   return 0;
1114 }
1115 
1116 /*
1117 ** Prepare a crude estimate of the logarithm of the input value.
1118 ** The results need not be exact.  This is only used for estimating
1119 ** the total cost of performing operatings with O(logN) or O(NlogN)
1120 ** complexity.  Because N is just a guess, it is no great tragedy if
1121 ** logN is a little off.
1122 */
1123 static double estLog(double N){
1124   double logN = 1;
1125   double x = 10;
1126   while( N>x ){
1127     logN += 1;
1128     x *= 10;
1129   }
1130   return logN;
1131 }
1132 
1133 /*
1134 ** Two routines for printing the content of an sqlite3_index_info
1135 ** structure.  Used for testing and debugging only.  If neither
1136 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1137 ** are no-ops.
1138 */
1139 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
1140 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1141   int i;
1142   if( !sqlite3_where_trace ) return;
1143   for(i=0; i<p->nConstraint; i++){
1144     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1145        i,
1146        p->aConstraint[i].iColumn,
1147        p->aConstraint[i].iTermOffset,
1148        p->aConstraint[i].op,
1149        p->aConstraint[i].usable);
1150   }
1151   for(i=0; i<p->nOrderBy; i++){
1152     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
1153        i,
1154        p->aOrderBy[i].iColumn,
1155        p->aOrderBy[i].desc);
1156   }
1157 }
1158 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1159   int i;
1160   if( !sqlite3_where_trace ) return;
1161   for(i=0; i<p->nConstraint; i++){
1162     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
1163        i,
1164        p->aConstraintUsage[i].argvIndex,
1165        p->aConstraintUsage[i].omit);
1166   }
1167   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
1168   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
1169   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
1170   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
1171 }
1172 #else
1173 #define TRACE_IDX_INPUTS(A)
1174 #define TRACE_IDX_OUTPUTS(A)
1175 #endif
1176 
1177 #ifndef SQLITE_OMIT_VIRTUALTABLE
1178 /*
1179 ** Compute the best index for a virtual table.
1180 **
1181 ** The best index is computed by the xBestIndex method of the virtual
1182 ** table module.  This routine is really just a wrapper that sets up
1183 ** the sqlite3_index_info structure that is used to communicate with
1184 ** xBestIndex.
1185 **
1186 ** In a join, this routine might be called multiple times for the
1187 ** same virtual table.  The sqlite3_index_info structure is created
1188 ** and initialized on the first invocation and reused on all subsequent
1189 ** invocations.  The sqlite3_index_info structure is also used when
1190 ** code is generated to access the virtual table.  The whereInfoDelete()
1191 ** routine takes care of freeing the sqlite3_index_info structure after
1192 ** everybody has finished with it.
1193 */
1194 static double bestVirtualIndex(
1195   Parse *pParse,                 /* The parsing context */
1196   WhereClause *pWC,              /* The WHERE clause */
1197   struct SrcList_item *pSrc,     /* The FROM clause term to search */
1198   Bitmask notReady,              /* Mask of cursors that are not available */
1199   ExprList *pOrderBy,            /* The order by clause */
1200   int orderByUsable,             /* True if we can potential sort */
1201   sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
1202 ){
1203   Table *pTab = pSrc->pTab;
1204   sqlite3_index_info *pIdxInfo;
1205   struct sqlite3_index_constraint *pIdxCons;
1206   struct sqlite3_index_orderby *pIdxOrderBy;
1207   struct sqlite3_index_constraint_usage *pUsage;
1208   WhereTerm *pTerm;
1209   int i, j;
1210   int nOrderBy;
1211   int rc;
1212 
1213   /* If the sqlite3_index_info structure has not been previously
1214   ** allocated and initialized for this virtual table, then allocate
1215   ** and initialize it now
1216   */
1217   pIdxInfo = *ppIdxInfo;
1218   if( pIdxInfo==0 ){
1219     WhereTerm *pTerm;
1220     int nTerm;
1221     WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
1222 
1223     /* Count the number of possible WHERE clause constraints referring
1224     ** to this virtual table */
1225     for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1226       if( pTerm->leftCursor != pSrc->iCursor ) continue;
1227       if( pTerm->eOperator==WO_IN ) continue;
1228       nTerm++;
1229     }
1230 
1231     /* If the ORDER BY clause contains only columns in the current
1232     ** virtual table then allocate space for the aOrderBy part of
1233     ** the sqlite3_index_info structure.
1234     */
1235     nOrderBy = 0;
1236     if( pOrderBy ){
1237       for(i=0; i<pOrderBy->nExpr; i++){
1238         Expr *pExpr = pOrderBy->a[i].pExpr;
1239         if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1240       }
1241       if( i==pOrderBy->nExpr ){
1242         nOrderBy = pOrderBy->nExpr;
1243       }
1244     }
1245 
1246     /* Allocate the sqlite3_index_info structure
1247     */
1248     pIdxInfo = sqliteMalloc( sizeof(*pIdxInfo)
1249                              + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1250                              + sizeof(*pIdxOrderBy)*nOrderBy );
1251     if( pIdxInfo==0 ){
1252       sqlite3ErrorMsg(pParse, "out of memory");
1253       return 0.0;
1254     }
1255     *ppIdxInfo = pIdxInfo;
1256 
1257     /* Initialize the structure.  The sqlite3_index_info structure contains
1258     ** many fields that are declared "const" to prevent xBestIndex from
1259     ** changing them.  We have to do some funky casting in order to
1260     ** initialize those fields.
1261     */
1262     pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1263     pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1264     pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1265     *(int*)&pIdxInfo->nConstraint = nTerm;
1266     *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1267     *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1268     *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1269     *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1270                                                                      pUsage;
1271 
1272     for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1273       if( pTerm->leftCursor != pSrc->iCursor ) continue;
1274       if( pTerm->eOperator==WO_IN ) continue;
1275       pIdxCons[j].iColumn = pTerm->leftColumn;
1276       pIdxCons[j].iTermOffset = i;
1277       pIdxCons[j].op = pTerm->eOperator;
1278       /* The direct assignment in the previous line is possible only because
1279       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
1280       ** following asserts verify this fact. */
1281       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1282       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1283       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1284       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1285       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1286       assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
1287       assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
1288       j++;
1289     }
1290     for(i=0; i<nOrderBy; i++){
1291       Expr *pExpr = pOrderBy->a[i].pExpr;
1292       pIdxOrderBy[i].iColumn = pExpr->iColumn;
1293       pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1294     }
1295   }
1296 
1297   /* At this point, the sqlite3_index_info structure that pIdxInfo points
1298   ** to will have been initialized, either during the current invocation or
1299   ** during some prior invocation.  Now we just have to customize the
1300   ** details of pIdxInfo for the current invocation and pass it to
1301   ** xBestIndex.
1302   */
1303 
1304   /* The module name must be defined. Also, by this point there must
1305   ** be a pointer to an sqlite3_vtab structure. Otherwise
1306   ** sqlite3ViewGetColumnNames() would have picked up the error.
1307   */
1308   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
1309   assert( pTab->pVtab );
1310 #if 0
1311   if( pTab->pVtab==0 ){
1312     sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
1313         pTab->azModuleArg[0], pTab->zName);
1314     return 0.0;
1315   }
1316 #endif
1317 
1318   /* Set the aConstraint[].usable fields and initialize all
1319   ** output variables to zero.
1320   **
1321   ** aConstraint[].usable is true for constraints where the right-hand
1322   ** side contains only references to tables to the left of the current
1323   ** table.  In other words, if the constraint is of the form:
1324   **
1325   **           column = expr
1326   **
1327   ** and we are evaluating a join, then the constraint on column is
1328   ** only valid if all tables referenced in expr occur to the left
1329   ** of the table containing column.
1330   **
1331   ** The aConstraints[] array contains entries for all constraints
1332   ** on the current table.  That way we only have to compute it once
1333   ** even though we might try to pick the best index multiple times.
1334   ** For each attempt at picking an index, the order of tables in the
1335   ** join might be different so we have to recompute the usable flag
1336   ** each time.
1337   */
1338   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
1339   pUsage = pIdxInfo->aConstraintUsage;
1340   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
1341     j = pIdxCons->iTermOffset;
1342     pTerm = &pWC->a[j];
1343     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0;
1344   }
1345   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
1346   if( pIdxInfo->needToFreeIdxStr ){
1347     sqlite3_free(pIdxInfo->idxStr);
1348   }
1349   pIdxInfo->idxStr = 0;
1350   pIdxInfo->idxNum = 0;
1351   pIdxInfo->needToFreeIdxStr = 0;
1352   pIdxInfo->orderByConsumed = 0;
1353   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / 2.0;
1354   nOrderBy = pIdxInfo->nOrderBy;
1355   if( pIdxInfo->nOrderBy && !orderByUsable ){
1356     *(int*)&pIdxInfo->nOrderBy = 0;
1357   }
1358 
1359   sqlite3SafetyOff(pParse->db);
1360   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
1361   TRACE_IDX_INPUTS(pIdxInfo);
1362   rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo);
1363   TRACE_IDX_OUTPUTS(pIdxInfo);
1364   if( rc!=SQLITE_OK ){
1365     if( rc==SQLITE_NOMEM ){
1366       sqlite3FailedMalloc();
1367     }else {
1368       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1369     }
1370     sqlite3SafetyOn(pParse->db);
1371   }else{
1372     rc = sqlite3SafetyOn(pParse->db);
1373   }
1374   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1375 
1376   return pIdxInfo->estimatedCost;
1377 }
1378 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1379 
1380 /*
1381 ** Find the best index for accessing a particular table.  Return a pointer
1382 ** to the index, flags that describe how the index should be used, the
1383 ** number of equality constraints, and the "cost" for this index.
1384 **
1385 ** The lowest cost index wins.  The cost is an estimate of the amount of
1386 ** CPU and disk I/O need to process the request using the selected index.
1387 ** Factors that influence cost include:
1388 **
1389 **    *  The estimated number of rows that will be retrieved.  (The
1390 **       fewer the better.)
1391 **
1392 **    *  Whether or not sorting must occur.
1393 **
1394 **    *  Whether or not there must be separate lookups in the
1395 **       index and in the main table.
1396 **
1397 */
1398 static double bestIndex(
1399   Parse *pParse,              /* The parsing context */
1400   WhereClause *pWC,           /* The WHERE clause */
1401   struct SrcList_item *pSrc,  /* The FROM clause term to search */
1402   Bitmask notReady,           /* Mask of cursors that are not available */
1403   ExprList *pOrderBy,         /* The order by clause */
1404   Index **ppIndex,            /* Make *ppIndex point to the best index */
1405   int *pFlags,                /* Put flags describing this choice in *pFlags */
1406   int *pnEq                   /* Put the number of == or IN constraints here */
1407 ){
1408   WhereTerm *pTerm;
1409   Index *bestIdx = 0;         /* Index that gives the lowest cost */
1410   double lowestCost;          /* The cost of using bestIdx */
1411   int bestFlags = 0;          /* Flags associated with bestIdx */
1412   int bestNEq = 0;            /* Best value for nEq */
1413   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
1414   Index *pProbe;              /* An index we are evaluating */
1415   int rev;                    /* True to scan in reverse order */
1416   int flags;                  /* Flags associated with pProbe */
1417   int nEq;                    /* Number of == or IN constraints */
1418   int eqTermMask;             /* Mask of valid equality operators */
1419   double cost;                /* Cost of using pProbe */
1420 
1421   WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady));
1422   lowestCost = SQLITE_BIG_DBL;
1423   pProbe = pSrc->pTab->pIndex;
1424 
1425   /* If the table has no indices and there are no terms in the where
1426   ** clause that refer to the ROWID, then we will never be able to do
1427   ** anything other than a full table scan on this table.  We might as
1428   ** well put it first in the join order.  That way, perhaps it can be
1429   ** referenced by other tables in the join.
1430   */
1431   if( pProbe==0 &&
1432      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
1433      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
1434     *pFlags = 0;
1435     *ppIndex = 0;
1436     *pnEq = 0;
1437     return 0.0;
1438   }
1439 
1440   /* Check for a rowid=EXPR or rowid IN (...) constraints
1441   */
1442   pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1443   if( pTerm ){
1444     Expr *pExpr;
1445     *ppIndex = 0;
1446     bestFlags = WHERE_ROWID_EQ;
1447     if( pTerm->eOperator & WO_EQ ){
1448       /* Rowid== is always the best pick.  Look no further.  Because only
1449       ** a single row is generated, output is always in sorted order */
1450       *pFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
1451       *pnEq = 1;
1452       WHERETRACE(("... best is rowid\n"));
1453       return 0.0;
1454     }else if( (pExpr = pTerm->pExpr)->pList!=0 ){
1455       /* Rowid IN (LIST): cost is NlogN where N is the number of list
1456       ** elements.  */
1457       lowestCost = pExpr->pList->nExpr;
1458       lowestCost *= estLog(lowestCost);
1459     }else{
1460       /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
1461       ** in the result of the inner select.  We have no way to estimate
1462       ** that value so make a wild guess. */
1463       lowestCost = 200;
1464     }
1465     WHERETRACE(("... rowid IN cost: %.9g\n", lowestCost));
1466   }
1467 
1468   /* Estimate the cost of a table scan.  If we do not know how many
1469   ** entries are in the table, use 1 million as a guess.
1470   */
1471   cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
1472   WHERETRACE(("... table scan base cost: %.9g\n", cost));
1473   flags = WHERE_ROWID_RANGE;
1474 
1475   /* Check for constraints on a range of rowids in a table scan.
1476   */
1477   pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
1478   if( pTerm ){
1479     if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
1480       flags |= WHERE_TOP_LIMIT;
1481       cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds or rows */
1482     }
1483     if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
1484       flags |= WHERE_BTM_LIMIT;
1485       cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
1486     }
1487     WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
1488   }else{
1489     flags = 0;
1490   }
1491 
1492   /* If the table scan does not satisfy the ORDER BY clause, increase
1493   ** the cost by NlogN to cover the expense of sorting. */
1494   if( pOrderBy ){
1495     if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
1496       flags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
1497       if( rev ){
1498         flags |= WHERE_REVERSE;
1499       }
1500     }else{
1501       cost += cost*estLog(cost);
1502       WHERETRACE(("... sorting increases cost to %.9g\n", cost));
1503     }
1504   }
1505   if( cost<lowestCost ){
1506     lowestCost = cost;
1507     bestFlags = flags;
1508   }
1509 
1510   /* If the pSrc table is the right table of a LEFT JOIN then we may not
1511   ** use an index to satisfy IS NULL constraints on that table.  This is
1512   ** because columns might end up being NULL if the table does not match -
1513   ** a circumstance which the index cannot help us discover.  Ticket #2177.
1514   */
1515   if( (pSrc->jointype & JT_LEFT)!=0 ){
1516     eqTermMask = WO_EQ|WO_IN;
1517   }else{
1518     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
1519   }
1520 
1521   /* Look at each index.
1522   */
1523   for(; pProbe; pProbe=pProbe->pNext){
1524     int i;                       /* Loop counter */
1525     double inMultiplier = 1;
1526 
1527     WHERETRACE(("... index %s:\n", pProbe->zName));
1528 
1529     /* Count the number of columns in the index that are satisfied
1530     ** by x=EXPR constraints or x IN (...) constraints.
1531     */
1532     flags = 0;
1533     for(i=0; i<pProbe->nColumn; i++){
1534       int j = pProbe->aiColumn[i];
1535       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
1536       if( pTerm==0 ) break;
1537       flags |= WHERE_COLUMN_EQ;
1538       if( pTerm->eOperator & WO_IN ){
1539         Expr *pExpr = pTerm->pExpr;
1540         flags |= WHERE_COLUMN_IN;
1541         if( pExpr->pSelect!=0 ){
1542           inMultiplier *= 25;
1543         }else if( pExpr->pList!=0 ){
1544           inMultiplier *= pExpr->pList->nExpr + 1;
1545         }
1546       }
1547     }
1548     cost = pProbe->aiRowEst[i] * inMultiplier * estLog(inMultiplier);
1549     nEq = i;
1550     if( pProbe->onError!=OE_None && (flags & WHERE_COLUMN_IN)==0
1551          && nEq==pProbe->nColumn ){
1552       flags |= WHERE_UNIQUE;
1553     }
1554     WHERETRACE(("...... nEq=%d inMult=%.9g cost=%.9g\n", nEq, inMultiplier, cost));
1555 
1556     /* Look for range constraints
1557     */
1558     if( nEq<pProbe->nColumn ){
1559       int j = pProbe->aiColumn[nEq];
1560       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
1561       if( pTerm ){
1562         flags |= WHERE_COLUMN_RANGE;
1563         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
1564           flags |= WHERE_TOP_LIMIT;
1565           cost /= 3;
1566         }
1567         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
1568           flags |= WHERE_BTM_LIMIT;
1569           cost /= 3;
1570         }
1571         WHERETRACE(("...... range reduces cost to %.9g\n", cost));
1572       }
1573     }
1574 
1575     /* Add the additional cost of sorting if that is a factor.
1576     */
1577     if( pOrderBy ){
1578       if( (flags & WHERE_COLUMN_IN)==0 &&
1579            isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
1580         if( flags==0 ){
1581           flags = WHERE_COLUMN_RANGE;
1582         }
1583         flags |= WHERE_ORDERBY;
1584         if( rev ){
1585           flags |= WHERE_REVERSE;
1586         }
1587       }else{
1588         cost += cost*estLog(cost);
1589         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
1590       }
1591     }
1592 
1593     /* Check to see if we can get away with using just the index without
1594     ** ever reading the table.  If that is the case, then halve the
1595     ** cost of this index.
1596     */
1597     if( flags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
1598       Bitmask m = pSrc->colUsed;
1599       int j;
1600       for(j=0; j<pProbe->nColumn; j++){
1601         int x = pProbe->aiColumn[j];
1602         if( x<BMS-1 ){
1603           m &= ~(((Bitmask)1)<<x);
1604         }
1605       }
1606       if( m==0 ){
1607         flags |= WHERE_IDX_ONLY;
1608         cost /= 2;
1609         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
1610       }
1611     }
1612 
1613     /* If this index has achieved the lowest cost so far, then use it.
1614     */
1615     if( cost < lowestCost ){
1616       bestIdx = pProbe;
1617       lowestCost = cost;
1618       assert( flags!=0 );
1619       bestFlags = flags;
1620       bestNEq = nEq;
1621     }
1622   }
1623 
1624   /* Report the best result
1625   */
1626   *ppIndex = bestIdx;
1627   WHERETRACE(("best index is %s, cost=%.9g, flags=%x, nEq=%d\n",
1628         bestIdx ? bestIdx->zName : "(none)", lowestCost, bestFlags, bestNEq));
1629   *pFlags = bestFlags | eqTermMask;
1630   *pnEq = bestNEq;
1631   return lowestCost;
1632 }
1633 
1634 
1635 /*
1636 ** Disable a term in the WHERE clause.  Except, do not disable the term
1637 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
1638 ** or USING clause of that join.
1639 **
1640 ** Consider the term t2.z='ok' in the following queries:
1641 **
1642 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
1643 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
1644 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
1645 **
1646 ** The t2.z='ok' is disabled in the in (2) because it originates
1647 ** in the ON clause.  The term is disabled in (3) because it is not part
1648 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
1649 **
1650 ** Disabling a term causes that term to not be tested in the inner loop
1651 ** of the join.  Disabling is an optimization.  When terms are satisfied
1652 ** by indices, we disable them to prevent redundant tests in the inner
1653 ** loop.  We would get the correct results if nothing were ever disabled,
1654 ** but joins might run a little slower.  The trick is to disable as much
1655 ** as we can without disabling too much.  If we disabled in (1), we'd get
1656 ** the wrong answer.  See ticket #813.
1657 */
1658 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
1659   if( pTerm
1660       && (pTerm->flags & TERM_CODED)==0
1661       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
1662   ){
1663     pTerm->flags |= TERM_CODED;
1664     if( pTerm->iParent>=0 ){
1665       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
1666       if( (--pOther->nChild)==0 ){
1667         disableTerm(pLevel, pOther);
1668       }
1669     }
1670   }
1671 }
1672 
1673 /*
1674 ** Generate code that builds a probe for an index.
1675 **
1676 ** There should be nColumn values on the stack.  The index
1677 ** to be probed is pIdx.  Pop the values from the stack and
1678 ** replace them all with a single record that is the index
1679 ** problem.
1680 */
1681 static void buildIndexProbe(
1682   Vdbe *v,        /* Generate code into this VM */
1683   int nColumn,    /* The number of columns to check for NULL */
1684   Index *pIdx     /* Index that we will be searching */
1685 ){
1686   sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
1687   sqlite3IndexAffinityStr(v, pIdx);
1688 }
1689 
1690 
1691 /*
1692 ** Generate code for a single equality term of the WHERE clause.  An equality
1693 ** term can be either X=expr or X IN (...).   pTerm is the term to be
1694 ** coded.
1695 **
1696 ** The current value for the constraint is left on the top of the stack.
1697 **
1698 ** For a constraint of the form X=expr, the expression is evaluated and its
1699 ** result is left on the stack.  For constraints of the form X IN (...)
1700 ** this routine sets up a loop that will iterate over all values of X.
1701 */
1702 static void codeEqualityTerm(
1703   Parse *pParse,      /* The parsing context */
1704   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
1705   WhereLevel *pLevel  /* When level of the FROM clause we are working on */
1706 ){
1707   Expr *pX = pTerm->pExpr;
1708   Vdbe *v = pParse->pVdbe;
1709   if( pX->op==TK_EQ ){
1710     sqlite3ExprCode(pParse, pX->pRight);
1711   }else if( pX->op==TK_ISNULL ){
1712     sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1713 #ifndef SQLITE_OMIT_SUBQUERY
1714   }else{
1715     int iTab;
1716     struct InLoop *pIn;
1717 
1718     assert( pX->op==TK_IN );
1719     sqlite3CodeSubselect(pParse, pX);
1720     iTab = pX->iTable;
1721     sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
1722     VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
1723     if( pLevel->nIn==0 ){
1724       pLevel->nxt = sqlite3VdbeMakeLabel(v);
1725     }
1726     pLevel->nIn++;
1727     pLevel->aInLoop = sqliteReallocOrFree(pLevel->aInLoop,
1728                                     sizeof(pLevel->aInLoop[0])*pLevel->nIn);
1729     pIn = pLevel->aInLoop;
1730     if( pIn ){
1731       pIn += pLevel->nIn - 1;
1732       pIn->iCur = iTab;
1733       pIn->topAddr = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
1734       sqlite3VdbeAddOp(v, OP_IsNull, -1, 0);
1735     }else{
1736       pLevel->nIn = 0;
1737     }
1738 #endif
1739   }
1740   disableTerm(pLevel, pTerm);
1741 }
1742 
1743 /*
1744 ** Generate code that will evaluate all == and IN constraints for an
1745 ** index.  The values for all constraints are left on the stack.
1746 **
1747 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
1748 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
1749 ** The index has as many as three equality constraints, but in this
1750 ** example, the third "c" value is an inequality.  So only two
1751 ** constraints are coded.  This routine will generate code to evaluate
1752 ** a==5 and b IN (1,2,3).  The current values for a and b will be left
1753 ** on the stack - a is the deepest and b the shallowest.
1754 **
1755 ** In the example above nEq==2.  But this subroutine works for any value
1756 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
1757 ** The only thing it does is allocate the pLevel->iMem memory cell.
1758 **
1759 ** This routine always allocates at least one memory cell and puts
1760 ** the address of that memory cell in pLevel->iMem.  The code that
1761 ** calls this routine will use pLevel->iMem to store the termination
1762 ** key value of the loop.  If one or more IN operators appear, then
1763 ** this routine allocates an additional nEq memory cells for internal
1764 ** use.
1765 */
1766 static void codeAllEqualityTerms(
1767   Parse *pParse,        /* Parsing context */
1768   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
1769   WhereClause *pWC,     /* The WHERE clause */
1770   Bitmask notReady      /* Which parts of FROM have not yet been coded */
1771 ){
1772   int nEq = pLevel->nEq;        /* The number of == or IN constraints to code */
1773   int termsInMem = 0;           /* If true, store value in mem[] cells */
1774   Vdbe *v = pParse->pVdbe;      /* The virtual machine under construction */
1775   Index *pIdx = pLevel->pIdx;   /* The index being used for this loop */
1776   int iCur = pLevel->iTabCur;   /* The cursor of the table */
1777   WhereTerm *pTerm;             /* A single constraint term */
1778   int j;                        /* Loop counter */
1779 
1780   /* Figure out how many memory cells we will need then allocate them.
1781   ** We always need at least one used to store the loop terminator
1782   ** value.  If there are IN operators we'll need one for each == or
1783   ** IN constraint.
1784   */
1785   pLevel->iMem = pParse->nMem++;
1786   if( pLevel->flags & WHERE_COLUMN_IN ){
1787     pParse->nMem += pLevel->nEq;
1788     termsInMem = 1;
1789   }
1790 
1791   /* Evaluate the equality constraints
1792   */
1793   assert( pIdx->nColumn>=nEq );
1794   for(j=0; j<nEq; j++){
1795     int k = pIdx->aiColumn[j];
1796     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx);
1797     if( pTerm==0 ) break;
1798     assert( (pTerm->flags & TERM_CODED)==0 );
1799     codeEqualityTerm(pParse, pTerm, pLevel);
1800     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
1801       sqlite3VdbeAddOp(v, OP_IsNull, termsInMem ? -1 : -(j+1), pLevel->brk);
1802     }
1803     if( termsInMem ){
1804       sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1);
1805     }
1806   }
1807 
1808   /* Make sure all the constraint values are on the top of the stack
1809   */
1810   if( termsInMem ){
1811     for(j=0; j<nEq; j++){
1812       sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0);
1813     }
1814   }
1815 }
1816 
1817 #if defined(SQLITE_TEST)
1818 /*
1819 ** The following variable holds a text description of query plan generated
1820 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
1821 ** overwrites the previous.  This information is used for testing and
1822 ** analysis only.
1823 */
1824 char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
1825 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
1826 
1827 #endif /* SQLITE_TEST */
1828 
1829 
1830 /*
1831 ** Free a WhereInfo structure
1832 */
1833 static void whereInfoFree(WhereInfo *pWInfo){
1834   if( pWInfo ){
1835     int i;
1836     for(i=0; i<pWInfo->nLevel; i++){
1837       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
1838       if( pInfo ){
1839         if( pInfo->needToFreeIdxStr ){
1840           /* Coverage: Don't think this can be reached. By the time this
1841           ** function is called, the index-strings have been passed
1842           ** to the vdbe layer for deletion.
1843           */
1844           sqlite3_free(pInfo->idxStr);
1845         }
1846         sqliteFree(pInfo);
1847       }
1848     }
1849     sqliteFree(pWInfo);
1850   }
1851 }
1852 
1853 
1854 /*
1855 ** Generate the beginning of the loop used for WHERE clause processing.
1856 ** The return value is a pointer to an opaque structure that contains
1857 ** information needed to terminate the loop.  Later, the calling routine
1858 ** should invoke sqlite3WhereEnd() with the return value of this function
1859 ** in order to complete the WHERE clause processing.
1860 **
1861 ** If an error occurs, this routine returns NULL.
1862 **
1863 ** The basic idea is to do a nested loop, one loop for each table in
1864 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
1865 ** same as a SELECT with only a single table in the FROM clause.)  For
1866 ** example, if the SQL is this:
1867 **
1868 **       SELECT * FROM t1, t2, t3 WHERE ...;
1869 **
1870 ** Then the code generated is conceptually like the following:
1871 **
1872 **      foreach row1 in t1 do       \    Code generated
1873 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
1874 **          foreach row3 in t3 do   /
1875 **            ...
1876 **          end                     \    Code generated
1877 **        end                        |-- by sqlite3WhereEnd()
1878 **      end                         /
1879 **
1880 ** Note that the loops might not be nested in the order in which they
1881 ** appear in the FROM clause if a different order is better able to make
1882 ** use of indices.  Note also that when the IN operator appears in
1883 ** the WHERE clause, it might result in additional nested loops for
1884 ** scanning through all values on the right-hand side of the IN.
1885 **
1886 ** There are Btree cursors associated with each table.  t1 uses cursor
1887 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
1888 ** And so forth.  This routine generates code to open those VDBE cursors
1889 ** and sqlite3WhereEnd() generates the code to close them.
1890 **
1891 ** The code that sqlite3WhereBegin() generates leaves the cursors named
1892 ** in pTabList pointing at their appropriate entries.  The [...] code
1893 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
1894 ** data from the various tables of the loop.
1895 **
1896 ** If the WHERE clause is empty, the foreach loops must each scan their
1897 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
1898 ** the tables have indices and there are terms in the WHERE clause that
1899 ** refer to those indices, a complete table scan can be avoided and the
1900 ** code will run much faster.  Most of the work of this routine is checking
1901 ** to see if there are indices that can be used to speed up the loop.
1902 **
1903 ** Terms of the WHERE clause are also used to limit which rows actually
1904 ** make it to the "..." in the middle of the loop.  After each "foreach",
1905 ** terms of the WHERE clause that use only terms in that loop and outer
1906 ** loops are evaluated and if false a jump is made around all subsequent
1907 ** inner loops (or around the "..." if the test occurs within the inner-
1908 ** most loop)
1909 **
1910 ** OUTER JOINS
1911 **
1912 ** An outer join of tables t1 and t2 is conceptally coded as follows:
1913 **
1914 **    foreach row1 in t1 do
1915 **      flag = 0
1916 **      foreach row2 in t2 do
1917 **        start:
1918 **          ...
1919 **          flag = 1
1920 **      end
1921 **      if flag==0 then
1922 **        move the row2 cursor to a null row
1923 **        goto start
1924 **      fi
1925 **    end
1926 **
1927 ** ORDER BY CLAUSE PROCESSING
1928 **
1929 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
1930 ** if there is one.  If there is no ORDER BY clause or if this routine
1931 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
1932 **
1933 ** If an index can be used so that the natural output order of the table
1934 ** scan is correct for the ORDER BY clause, then that index is used and
1935 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
1936 ** unnecessary sort of the result set if an index appropriate for the
1937 ** ORDER BY clause already exists.
1938 **
1939 ** If the where clause loops cannot be arranged to provide the correct
1940 ** output order, then the *ppOrderBy is unchanged.
1941 */
1942 WhereInfo *sqlite3WhereBegin(
1943   Parse *pParse,        /* The parser context */
1944   SrcList *pTabList,    /* A list of all tables to be scanned */
1945   Expr *pWhere,         /* The WHERE clause */
1946   ExprList **ppOrderBy  /* An ORDER BY clause, or NULL */
1947 ){
1948   int i;                     /* Loop counter */
1949   WhereInfo *pWInfo;         /* Will become the return value of this function */
1950   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
1951   int brk, cont = 0;         /* Addresses used during code generation */
1952   Bitmask notReady;          /* Cursors that are not yet positioned */
1953   WhereTerm *pTerm;          /* A single term in the WHERE clause */
1954   ExprMaskSet maskSet;       /* The expression mask set */
1955   WhereClause wc;            /* The WHERE clause is divided into these terms */
1956   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
1957   WhereLevel *pLevel;             /* A single level in the pWInfo list */
1958   int iFrom;                      /* First unused FROM clause element */
1959   int andFlags;              /* AND-ed combination of all wc.a[].flags */
1960 
1961   /* The number of tables in the FROM clause is limited by the number of
1962   ** bits in a Bitmask
1963   */
1964   if( pTabList->nSrc>BMS ){
1965     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
1966     return 0;
1967   }
1968 
1969   /* Split the WHERE clause into separate subexpressions where each
1970   ** subexpression is separated by an AND operator.
1971   */
1972   initMaskSet(&maskSet);
1973   whereClauseInit(&wc, pParse, &maskSet);
1974   whereSplit(&wc, pWhere, TK_AND);
1975 
1976   /* Allocate and initialize the WhereInfo structure that will become the
1977   ** return value.
1978   */
1979   pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
1980   if( sqlite3MallocFailed() ){
1981     goto whereBeginNoMem;
1982   }
1983   pWInfo->nLevel = pTabList->nSrc;
1984   pWInfo->pParse = pParse;
1985   pWInfo->pTabList = pTabList;
1986   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
1987 
1988   /* Special case: a WHERE clause that is constant.  Evaluate the
1989   ** expression and either jump over all of the code or fall thru.
1990   */
1991   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
1992     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
1993     pWhere = 0;
1994   }
1995 
1996   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
1997   ** add new virtual terms onto the end of the WHERE clause.  We do not
1998   ** want to analyze these virtual terms, so start analyzing at the end
1999   ** and work forward so that the added virtual terms are never processed.
2000   */
2001   for(i=0; i<pTabList->nSrc; i++){
2002     createMask(&maskSet, pTabList->a[i].iCursor);
2003   }
2004   exprAnalyzeAll(pTabList, &wc);
2005   if( sqlite3MallocFailed() ){
2006     goto whereBeginNoMem;
2007   }
2008 
2009   /* Chose the best index to use for each table in the FROM clause.
2010   **
2011   ** This loop fills in the following fields:
2012   **
2013   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
2014   **   pWInfo->a[].flags     WHERE_xxx flags associated with pIdx
2015   **   pWInfo->a[].nEq       The number of == and IN constraints
2016   **   pWInfo->a[].iFrom     When term of the FROM clause is being coded
2017   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
2018   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
2019   **
2020   ** This loop also figures out the nesting order of tables in the FROM
2021   ** clause.
2022   */
2023   notReady = ~(Bitmask)0;
2024   pTabItem = pTabList->a;
2025   pLevel = pWInfo->a;
2026   andFlags = ~0;
2027   WHERETRACE(("*** Optimizer Start ***\n"));
2028   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
2029     Index *pIdx;                /* Index for FROM table at pTabItem */
2030     int flags;                  /* Flags asssociated with pIdx */
2031     int nEq;                    /* Number of == or IN constraints */
2032     double cost;                /* The cost for pIdx */
2033     int j;                      /* For looping over FROM tables */
2034     Index *pBest = 0;           /* The best index seen so far */
2035     int bestFlags = 0;          /* Flags associated with pBest */
2036     int bestNEq = 0;            /* nEq associated with pBest */
2037     double lowestCost;          /* Cost of the pBest */
2038     int bestJ = 0;              /* The value of j */
2039     Bitmask m;                  /* Bitmask value for j or bestJ */
2040     int once = 0;               /* True when first table is seen */
2041     sqlite3_index_info *pIndex; /* Current virtual index */
2042 
2043     lowestCost = SQLITE_BIG_DBL;
2044     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
2045       int doNotReorder;  /* True if this table should not be reordered */
2046 
2047       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
2048       if( once && doNotReorder ) break;
2049       m = getMask(&maskSet, pTabItem->iCursor);
2050       if( (m & notReady)==0 ){
2051         if( j==iFrom ) iFrom++;
2052         continue;
2053       }
2054       assert( pTabItem->pTab );
2055 #ifndef SQLITE_OMIT_VIRTUALTABLE
2056       if( IsVirtual(pTabItem->pTab) ){
2057         sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
2058         cost = bestVirtualIndex(pParse, &wc, pTabItem, notReady,
2059                                 ppOrderBy ? *ppOrderBy : 0, i==0,
2060                                 ppIdxInfo);
2061         flags = WHERE_VIRTUALTABLE;
2062         pIndex = *ppIdxInfo;
2063         if( pIndex && pIndex->orderByConsumed ){
2064           flags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
2065         }
2066         pIdx = 0;
2067         nEq = 0;
2068         if( (SQLITE_BIG_DBL/2.0)<cost ){
2069           /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
2070           ** inital value of lowestCost in this loop. If it is, then
2071           ** the (cost<lowestCost) test below will never be true and
2072           ** pLevel->pBestIdx never set.
2073           */
2074           cost = (SQLITE_BIG_DBL/2.0);
2075         }
2076       }else
2077 #endif
2078       {
2079         cost = bestIndex(pParse, &wc, pTabItem, notReady,
2080                          (i==0 && ppOrderBy) ? *ppOrderBy : 0,
2081                          &pIdx, &flags, &nEq);
2082         pIndex = 0;
2083       }
2084       if( cost<lowestCost ){
2085         once = 1;
2086         lowestCost = cost;
2087         pBest = pIdx;
2088         bestFlags = flags;
2089         bestNEq = nEq;
2090         bestJ = j;
2091         pLevel->pBestIdx = pIndex;
2092       }
2093       if( doNotReorder ) break;
2094     }
2095     WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ,
2096            pLevel-pWInfo->a));
2097     if( (bestFlags & WHERE_ORDERBY)!=0 ){
2098       *ppOrderBy = 0;
2099     }
2100     andFlags &= bestFlags;
2101     pLevel->flags = bestFlags;
2102     pLevel->pIdx = pBest;
2103     pLevel->nEq = bestNEq;
2104     pLevel->aInLoop = 0;
2105     pLevel->nIn = 0;
2106     if( pBest ){
2107       pLevel->iIdxCur = pParse->nTab++;
2108     }else{
2109       pLevel->iIdxCur = -1;
2110     }
2111     notReady &= ~getMask(&maskSet, pTabList->a[bestJ].iCursor);
2112     pLevel->iFrom = bestJ;
2113   }
2114   WHERETRACE(("*** Optimizer Finished ***\n"));
2115 
2116   /* If the total query only selects a single row, then the ORDER BY
2117   ** clause is irrelevant.
2118   */
2119   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
2120     *ppOrderBy = 0;
2121   }
2122 
2123   /* Open all tables in the pTabList and any indices selected for
2124   ** searching those tables.
2125   */
2126   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
2127   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
2128     Table *pTab;     /* Table to open */
2129     Index *pIx;      /* Index used to access pTab (if any) */
2130     int iDb;         /* Index of database containing table/index */
2131     int iIdxCur = pLevel->iIdxCur;
2132 
2133 #ifndef SQLITE_OMIT_EXPLAIN
2134     if( pParse->explain==2 ){
2135       char *zMsg;
2136       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
2137       zMsg = sqlite3MPrintf("TABLE %s", pItem->zName);
2138       if( pItem->zAlias ){
2139         zMsg = sqlite3MPrintf("%z AS %s", zMsg, pItem->zAlias);
2140       }
2141       if( (pIx = pLevel->pIdx)!=0 ){
2142         zMsg = sqlite3MPrintf("%z WITH INDEX %s", zMsg, pIx->zName);
2143       }else if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
2144         zMsg = sqlite3MPrintf("%z USING PRIMARY KEY", zMsg);
2145       }
2146 #ifndef SQLITE_OMIT_VIRTUALTABLE
2147       else if( pLevel->pBestIdx ){
2148         sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
2149         zMsg = sqlite3MPrintf("%z VIRTUAL TABLE INDEX %d:%s", zMsg,
2150                     pBestIdx->idxNum, pBestIdx->idxStr);
2151       }
2152 #endif
2153       if( pLevel->flags & WHERE_ORDERBY ){
2154         zMsg = sqlite3MPrintf("%z ORDER BY", zMsg);
2155       }
2156       sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC);
2157     }
2158 #endif /* SQLITE_OMIT_EXPLAIN */
2159     pTabItem = &pTabList->a[pLevel->iFrom];
2160     pTab = pTabItem->pTab;
2161     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2162     if( pTab->isEphem || pTab->pSelect ) continue;
2163 #ifndef SQLITE_OMIT_VIRTUALTABLE
2164     if( pLevel->pBestIdx ){
2165       int iCur = pTabItem->iCursor;
2166       sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB);
2167     }else
2168 #endif
2169     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
2170       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead);
2171       if( pTab->nCol<(sizeof(Bitmask)*8) ){
2172         Bitmask b = pTabItem->colUsed;
2173         int n = 0;
2174         for(; b; b=b>>1, n++){}
2175         sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n);
2176         assert( n<=pTab->nCol );
2177       }
2178     }else{
2179       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2180     }
2181     pLevel->iTabCur = pTabItem->iCursor;
2182     if( (pIx = pLevel->pIdx)!=0 ){
2183       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
2184       assert( pIx->pSchema==pTab->pSchema );
2185       sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
2186       VdbeComment((v, "# %s", pIx->zName));
2187       sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum,
2188                      (char*)pKey, P3_KEYINFO_HANDOFF);
2189     }
2190     if( (pLevel->flags & (WHERE_IDX_ONLY|WHERE_COLUMN_RANGE))!=0 ){
2191       /* Only call OP_SetNumColumns on the index if we might later use
2192       ** OP_Column on the index. */
2193       sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1);
2194     }
2195     sqlite3CodeVerifySchema(pParse, iDb);
2196   }
2197   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
2198 
2199   /* Generate the code to do the search.  Each iteration of the for
2200   ** loop below generates code for a single nested loop of the VM
2201   ** program.
2202   */
2203   notReady = ~(Bitmask)0;
2204   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
2205     int j;
2206     int iCur = pTabItem->iCursor;  /* The VDBE cursor for the table */
2207     Index *pIdx;       /* The index we will be using */
2208     int nxt;           /* Where to jump to continue with the next IN case */
2209     int iIdxCur;       /* The VDBE cursor for the index */
2210     int omitTable;     /* True if we use the index only */
2211     int bRev;          /* True if we need to scan in reverse order */
2212 
2213     pTabItem = &pTabList->a[pLevel->iFrom];
2214     iCur = pTabItem->iCursor;
2215     pIdx = pLevel->pIdx;
2216     iIdxCur = pLevel->iIdxCur;
2217     bRev = (pLevel->flags & WHERE_REVERSE)!=0;
2218     omitTable = (pLevel->flags & WHERE_IDX_ONLY)!=0;
2219 
2220     /* Create labels for the "break" and "continue" instructions
2221     ** for the current loop.  Jump to brk to break out of a loop.
2222     ** Jump to cont to go immediately to the next iteration of the
2223     ** loop.
2224     **
2225     ** When there is an IN operator, we also have a "nxt" label that
2226     ** means to continue with the next IN value combination.  When
2227     ** there are no IN operators in the constraints, the "nxt" label
2228     ** is the same as "brk".
2229     */
2230     brk = pLevel->brk = pLevel->nxt = sqlite3VdbeMakeLabel(v);
2231     cont = pLevel->cont = sqlite3VdbeMakeLabel(v);
2232 
2233     /* If this is the right table of a LEFT OUTER JOIN, allocate and
2234     ** initialize a memory cell that records if this table matches any
2235     ** row of the left table of the join.
2236     */
2237     if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
2238       if( !pParse->nMem ) pParse->nMem++;
2239       pLevel->iLeftJoin = pParse->nMem++;
2240       sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin);
2241       VdbeComment((v, "# init LEFT JOIN no-match flag"));
2242     }
2243 
2244 #ifndef SQLITE_OMIT_VIRTUALTABLE
2245     if( pLevel->pBestIdx ){
2246       /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
2247       **          to access the data.
2248       */
2249       int j;
2250       sqlite3_index_info *pBestIdx = pLevel->pBestIdx;
2251       int nConstraint = pBestIdx->nConstraint;
2252       struct sqlite3_index_constraint_usage *aUsage =
2253                                                   pBestIdx->aConstraintUsage;
2254       const struct sqlite3_index_constraint *aConstraint =
2255                                                   pBestIdx->aConstraint;
2256 
2257       for(j=1; j<=nConstraint; j++){
2258         int k;
2259         for(k=0; k<nConstraint; k++){
2260           if( aUsage[k].argvIndex==j ){
2261             int iTerm = aConstraint[k].iTermOffset;
2262             sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight);
2263             break;
2264           }
2265         }
2266         if( k==nConstraint ) break;
2267       }
2268       sqlite3VdbeAddOp(v, OP_Integer, j-1, 0);
2269       sqlite3VdbeAddOp(v, OP_Integer, pBestIdx->idxNum, 0);
2270       sqlite3VdbeOp3(v, OP_VFilter, iCur, brk, pBestIdx->idxStr,
2271                       pBestIdx->needToFreeIdxStr ? P3_MPRINTF : P3_STATIC);
2272       pBestIdx->needToFreeIdxStr = 0;
2273       for(j=0; j<pBestIdx->nConstraint; j++){
2274         if( aUsage[j].omit ){
2275           int iTerm = aConstraint[j].iTermOffset;
2276           disableTerm(pLevel, &wc.a[iTerm]);
2277         }
2278       }
2279       pLevel->op = OP_VNext;
2280       pLevel->p1 = iCur;
2281       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2282     }else
2283 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2284 
2285     if( pLevel->flags & WHERE_ROWID_EQ ){
2286       /* Case 1:  We can directly reference a single row using an
2287       **          equality comparison against the ROWID field.  Or
2288       **          we reference multiple rows using a "rowid IN (...)"
2289       **          construct.
2290       */
2291       pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0);
2292       assert( pTerm!=0 );
2293       assert( pTerm->pExpr!=0 );
2294       assert( pTerm->leftCursor==iCur );
2295       assert( omitTable==0 );
2296       codeEqualityTerm(pParse, pTerm, pLevel);
2297       nxt = pLevel->nxt;
2298       sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt);
2299       sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt);
2300       VdbeComment((v, "pk"));
2301       pLevel->op = OP_Noop;
2302     }else if( pLevel->flags & WHERE_ROWID_RANGE ){
2303       /* Case 2:  We have an inequality comparison against the ROWID field.
2304       */
2305       int testOp = OP_Noop;
2306       int start;
2307       WhereTerm *pStart, *pEnd;
2308 
2309       assert( omitTable==0 );
2310       pStart = findTerm(&wc, iCur, -1, notReady, WO_GT|WO_GE, 0);
2311       pEnd = findTerm(&wc, iCur, -1, notReady, WO_LT|WO_LE, 0);
2312       if( bRev ){
2313         pTerm = pStart;
2314         pStart = pEnd;
2315         pEnd = pTerm;
2316       }
2317       if( pStart ){
2318         Expr *pX;
2319         pX = pStart->pExpr;
2320         assert( pX!=0 );
2321         assert( pStart->leftCursor==iCur );
2322         sqlite3ExprCode(pParse, pX->pRight);
2323         sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk);
2324         sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk);
2325         VdbeComment((v, "pk"));
2326         disableTerm(pLevel, pStart);
2327       }else{
2328         sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk);
2329       }
2330       if( pEnd ){
2331         Expr *pX;
2332         pX = pEnd->pExpr;
2333         assert( pX!=0 );
2334         assert( pEnd->leftCursor==iCur );
2335         sqlite3ExprCode(pParse, pX->pRight);
2336         pLevel->iMem = pParse->nMem++;
2337         sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
2338         if( pX->op==TK_LT || pX->op==TK_GT ){
2339           testOp = bRev ? OP_Le : OP_Ge;
2340         }else{
2341           testOp = bRev ? OP_Lt : OP_Gt;
2342         }
2343         disableTerm(pLevel, pEnd);
2344       }
2345       start = sqlite3VdbeCurrentAddr(v);
2346       pLevel->op = bRev ? OP_Prev : OP_Next;
2347       pLevel->p1 = iCur;
2348       pLevel->p2 = start;
2349       if( testOp!=OP_Noop ){
2350         sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0);
2351         sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
2352         sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk);
2353       }
2354     }else if( pLevel->flags & WHERE_COLUMN_RANGE ){
2355       /* Case 3: The WHERE clause term that refers to the right-most
2356       **         column of the index is an inequality.  For example, if
2357       **         the index is on (x,y,z) and the WHERE clause is of the
2358       **         form "x=5 AND y<10" then this case is used.  Only the
2359       **         right-most column can be an inequality - the rest must
2360       **         use the "==" and "IN" operators.
2361       **
2362       **         This case is also used when there are no WHERE clause
2363       **         constraints but an index is selected anyway, in order
2364       **         to force the output order to conform to an ORDER BY.
2365       */
2366       int start;
2367       int nEq = pLevel->nEq;
2368       int topEq=0;        /* True if top limit uses ==. False is strictly < */
2369       int btmEq=0;        /* True if btm limit uses ==. False if strictly > */
2370       int topOp, btmOp;   /* Operators for the top and bottom search bounds */
2371       int testOp;
2372       int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0;
2373       int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0;
2374 
2375       /* Generate code to evaluate all constraint terms using == or IN
2376       ** and level the values of those terms on the stack.
2377       */
2378       codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
2379 
2380       /* Duplicate the equality term values because they will all be
2381       ** used twice: once to make the termination key and once to make the
2382       ** start key.
2383       */
2384       for(j=0; j<nEq; j++){
2385         sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0);
2386       }
2387 
2388       /* Figure out what comparison operators to use for top and bottom
2389       ** search bounds. For an ascending index, the bottom bound is a > or >=
2390       ** operator and the top bound is a < or <= operator.  For a descending
2391       ** index the operators are reversed.
2392       */
2393       if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){
2394         topOp = WO_LT|WO_LE;
2395         btmOp = WO_GT|WO_GE;
2396       }else{
2397         topOp = WO_GT|WO_GE;
2398         btmOp = WO_LT|WO_LE;
2399         SWAP(int, topLimit, btmLimit);
2400       }
2401 
2402       /* Generate the termination key.  This is the key value that
2403       ** will end the search.  There is no termination key if there
2404       ** are no equality terms and no "X<..." term.
2405       **
2406       ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
2407       ** key computed here really ends up being the start key.
2408       */
2409       nxt = pLevel->nxt;
2410       if( topLimit ){
2411         Expr *pX;
2412         int k = pIdx->aiColumn[j];
2413         pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx);
2414         assert( pTerm!=0 );
2415         pX = pTerm->pExpr;
2416         assert( (pTerm->flags & TERM_CODED)==0 );
2417         sqlite3ExprCode(pParse, pX->pRight);
2418         sqlite3VdbeAddOp(v, OP_IsNull, -(nEq*2+1), nxt);
2419         topEq = pTerm->eOperator & (WO_LE|WO_GE);
2420         disableTerm(pLevel, pTerm);
2421         testOp = OP_IdxGE;
2422       }else{
2423         testOp = nEq>0 ? OP_IdxGE : OP_Noop;
2424         topEq = 1;
2425       }
2426       if( testOp!=OP_Noop ){
2427         int nCol = nEq + topLimit;
2428         pLevel->iMem = pParse->nMem++;
2429         buildIndexProbe(v, nCol, pIdx);
2430         if( bRev ){
2431           int op = topEq ? OP_MoveLe : OP_MoveLt;
2432           sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
2433         }else{
2434           sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
2435         }
2436       }else if( bRev ){
2437         sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk);
2438       }
2439 
2440       /* Generate the start key.  This is the key that defines the lower
2441       ** bound on the search.  There is no start key if there are no
2442       ** equality terms and if there is no "X>..." term.  In
2443       ** that case, generate a "Rewind" instruction in place of the
2444       ** start key search.
2445       **
2446       ** 2002-Dec-04: In the case of a reverse-order search, the so-called
2447       ** "start" key really ends up being used as the termination key.
2448       */
2449       if( btmLimit ){
2450         Expr *pX;
2451         int k = pIdx->aiColumn[j];
2452         pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx);
2453         assert( pTerm!=0 );
2454         pX = pTerm->pExpr;
2455         assert( (pTerm->flags & TERM_CODED)==0 );
2456         sqlite3ExprCode(pParse, pX->pRight);
2457         sqlite3VdbeAddOp(v, OP_IsNull, -(nEq+1), nxt);
2458         btmEq = pTerm->eOperator & (WO_LE|WO_GE);
2459         disableTerm(pLevel, pTerm);
2460       }else{
2461         btmEq = 1;
2462       }
2463       if( nEq>0 || btmLimit ){
2464         int nCol = nEq + btmLimit;
2465         buildIndexProbe(v, nCol, pIdx);
2466         if( bRev ){
2467           pLevel->iMem = pParse->nMem++;
2468           sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
2469           testOp = OP_IdxLT;
2470         }else{
2471           int op = btmEq ? OP_MoveGe : OP_MoveGt;
2472           sqlite3VdbeAddOp(v, op, iIdxCur, nxt);
2473         }
2474       }else if( bRev ){
2475         testOp = OP_Noop;
2476       }else{
2477         sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk);
2478       }
2479 
2480       /* Generate the the top of the loop.  If there is a termination
2481       ** key we have to test for that key and abort at the top of the
2482       ** loop.
2483       */
2484       start = sqlite3VdbeCurrentAddr(v);
2485       if( testOp!=OP_Noop ){
2486         sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
2487         sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt);
2488         if( (topEq && !bRev) || (!btmEq && bRev) ){
2489           sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC);
2490         }
2491       }
2492       if( topLimit | btmLimit ){
2493         sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq);
2494         sqlite3VdbeAddOp(v, OP_IsNull, 1, cont);
2495       }
2496       if( !omitTable ){
2497         sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
2498         sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
2499       }
2500 
2501       /* Record the instruction used to terminate the loop.
2502       */
2503       pLevel->op = bRev ? OP_Prev : OP_Next;
2504       pLevel->p1 = iIdxCur;
2505       pLevel->p2 = start;
2506     }else if( pLevel->flags & WHERE_COLUMN_EQ ){
2507       /* Case 4:  There is an index and all terms of the WHERE clause that
2508       **          refer to the index using the "==" or "IN" operators.
2509       */
2510       int start;
2511       int nEq = pLevel->nEq;
2512 
2513       /* Generate code to evaluate all constraint terms using == or IN
2514       ** and leave the values of those terms on the stack.
2515       */
2516       codeAllEqualityTerms(pParse, pLevel, &wc, notReady);
2517       nxt = pLevel->nxt;
2518 
2519       /* Generate a single key that will be used to both start and terminate
2520       ** the search
2521       */
2522       buildIndexProbe(v, nEq, pIdx);
2523       sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
2524 
2525       /* Generate code (1) to move to the first matching element of the table.
2526       ** Then generate code (2) that jumps to "nxt" after the cursor is past
2527       ** the last matching element of the table.  The code (1) is executed
2528       ** once to initialize the search, the code (2) is executed before each
2529       ** iteration of the scan to see if the scan has finished. */
2530       if( bRev ){
2531         /* Scan in reverse order */
2532         sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, nxt);
2533         start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
2534         sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, nxt);
2535         pLevel->op = OP_Prev;
2536       }else{
2537         /* Scan in the forward order */
2538         sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, nxt);
2539         start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
2540         sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, nxt, "+", P3_STATIC);
2541         pLevel->op = OP_Next;
2542       }
2543       if( !omitTable ){
2544         sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0);
2545         sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0);
2546       }
2547       pLevel->p1 = iIdxCur;
2548       pLevel->p2 = start;
2549     }else{
2550       /* Case 5:  There is no usable index.  We must do a complete
2551       **          scan of the entire table.
2552       */
2553       assert( omitTable==0 );
2554       assert( bRev==0 );
2555       pLevel->op = OP_Next;
2556       pLevel->p1 = iCur;
2557       pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk);
2558     }
2559     notReady &= ~getMask(&maskSet, iCur);
2560 
2561     /* Insert code to test every subexpression that can be completely
2562     ** computed using the current set of tables.
2563     */
2564     for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){
2565       Expr *pE;
2566       if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
2567       if( (pTerm->prereqAll & notReady)!=0 ) continue;
2568       pE = pTerm->pExpr;
2569       assert( pE!=0 );
2570       if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
2571         continue;
2572       }
2573       sqlite3ExprIfFalse(pParse, pE, cont, 1);
2574       pTerm->flags |= TERM_CODED;
2575     }
2576 
2577     /* For a LEFT OUTER JOIN, generate code that will record the fact that
2578     ** at least one row of the right table has matched the left table.
2579     */
2580     if( pLevel->iLeftJoin ){
2581       pLevel->top = sqlite3VdbeCurrentAddr(v);
2582       sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin);
2583       VdbeComment((v, "# record LEFT JOIN hit"));
2584       for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){
2585         if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue;
2586         if( (pTerm->prereqAll & notReady)!=0 ) continue;
2587         assert( pTerm->pExpr );
2588         sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1);
2589         pTerm->flags |= TERM_CODED;
2590       }
2591     }
2592   }
2593 
2594 #ifdef SQLITE_TEST  /* For testing and debugging use only */
2595   /* Record in the query plan information about the current table
2596   ** and the index used to access it (if any).  If the table itself
2597   ** is not used, its name is just '{}'.  If no index is used
2598   ** the index is listed as "{}".  If the primary key is used the
2599   ** index name is '*'.
2600   */
2601   for(i=0; i<pTabList->nSrc; i++){
2602     char *z;
2603     int n;
2604     pLevel = &pWInfo->a[i];
2605     pTabItem = &pTabList->a[pLevel->iFrom];
2606     z = pTabItem->zAlias;
2607     if( z==0 ) z = pTabItem->pTab->zName;
2608     n = strlen(z);
2609     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
2610       if( pLevel->flags & WHERE_IDX_ONLY ){
2611         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
2612         nQPlan += 2;
2613       }else{
2614         memcpy(&sqlite3_query_plan[nQPlan], z, n);
2615         nQPlan += n;
2616       }
2617       sqlite3_query_plan[nQPlan++] = ' ';
2618     }
2619     if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
2620       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
2621       nQPlan += 2;
2622     }else if( pLevel->pIdx==0 ){
2623       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
2624       nQPlan += 3;
2625     }else{
2626       n = strlen(pLevel->pIdx->zName);
2627       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
2628         memcpy(&sqlite3_query_plan[nQPlan], pLevel->pIdx->zName, n);
2629         nQPlan += n;
2630         sqlite3_query_plan[nQPlan++] = ' ';
2631       }
2632     }
2633   }
2634   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
2635     sqlite3_query_plan[--nQPlan] = 0;
2636   }
2637   sqlite3_query_plan[nQPlan] = 0;
2638   nQPlan = 0;
2639 #endif /* SQLITE_TEST // Testing and debugging use only */
2640 
2641   /* Record the continuation address in the WhereInfo structure.  Then
2642   ** clean up and return.
2643   */
2644   pWInfo->iContinue = cont;
2645   whereClauseClear(&wc);
2646   return pWInfo;
2647 
2648   /* Jump here if malloc fails */
2649 whereBeginNoMem:
2650   whereClauseClear(&wc);
2651   whereInfoFree(pWInfo);
2652   return 0;
2653 }
2654 
2655 /*
2656 ** Generate the end of the WHERE loop.  See comments on
2657 ** sqlite3WhereBegin() for additional information.
2658 */
2659 void sqlite3WhereEnd(WhereInfo *pWInfo){
2660   Vdbe *v = pWInfo->pParse->pVdbe;
2661   int i;
2662   WhereLevel *pLevel;
2663   SrcList *pTabList = pWInfo->pTabList;
2664 
2665   /* Generate loop termination code.
2666   */
2667   for(i=pTabList->nSrc-1; i>=0; i--){
2668     pLevel = &pWInfo->a[i];
2669     sqlite3VdbeResolveLabel(v, pLevel->cont);
2670     if( pLevel->op!=OP_Noop ){
2671       sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
2672     }
2673     if( pLevel->nIn ){
2674       struct InLoop *pIn;
2675       int j;
2676       sqlite3VdbeResolveLabel(v, pLevel->nxt);
2677       for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){
2678         sqlite3VdbeJumpHere(v, pIn->topAddr+1);
2679         sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr);
2680         sqlite3VdbeJumpHere(v, pIn->topAddr-1);
2681       }
2682       sqliteFree(pLevel->aInLoop);
2683     }
2684     sqlite3VdbeResolveLabel(v, pLevel->brk);
2685     if( pLevel->iLeftJoin ){
2686       int addr;
2687       addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0);
2688       sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
2689       if( pLevel->iIdxCur>=0 ){
2690         sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0);
2691       }
2692       sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top);
2693       sqlite3VdbeJumpHere(v, addr);
2694     }
2695   }
2696 
2697   /* The "break" point is here, just past the end of the outer loop.
2698   ** Set it.
2699   */
2700   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
2701 
2702   /* Close all of the cursors that were opened by sqlite3WhereBegin.
2703   */
2704   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
2705     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
2706     Table *pTab = pTabItem->pTab;
2707     assert( pTab!=0 );
2708     if( pTab->isEphem || pTab->pSelect ) continue;
2709     if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){
2710       sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0);
2711     }
2712     if( pLevel->pIdx!=0 ){
2713       sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0);
2714     }
2715 
2716     /* Make cursor substitutions for cases where we want to use
2717     ** just the index and never reference the table.
2718     **
2719     ** Calls to the code generator in between sqlite3WhereBegin and
2720     ** sqlite3WhereEnd will have created code that references the table
2721     ** directly.  This loop scans all that code looking for opcodes
2722     ** that reference the table and converts them into opcodes that
2723     ** reference the index.
2724     */
2725     if( pLevel->flags & WHERE_IDX_ONLY ){
2726       int k, j, last;
2727       VdbeOp *pOp;
2728       Index *pIdx = pLevel->pIdx;
2729 
2730       assert( pIdx!=0 );
2731       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
2732       last = sqlite3VdbeCurrentAddr(v);
2733       for(k=pWInfo->iTop; k<last; k++, pOp++){
2734         if( pOp->p1!=pLevel->iTabCur ) continue;
2735         if( pOp->opcode==OP_Column ){
2736           pOp->p1 = pLevel->iIdxCur;
2737           for(j=0; j<pIdx->nColumn; j++){
2738             if( pOp->p2==pIdx->aiColumn[j] ){
2739               pOp->p2 = j;
2740               break;
2741             }
2742           }
2743         }else if( pOp->opcode==OP_Rowid ){
2744           pOp->p1 = pLevel->iIdxCur;
2745           pOp->opcode = OP_IdxRowid;
2746         }else if( pOp->opcode==OP_NullRow ){
2747           pOp->opcode = OP_Noop;
2748         }
2749       }
2750     }
2751   }
2752 
2753   /* Final cleanup
2754   */
2755   whereInfoFree(pWInfo);
2756   return;
2757 }
2758