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