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