xref: /sqlite-3.40.0/src/where.c (revision 5368f29a)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This module contains C code that generates VDBE code used to process
13 ** the WHERE clause of SQL statements.  This module is responsible for
14 ** generating the code that loops through a table looking for applicable
15 ** rows.  Indices are selected and used to speed the search when doing
16 ** so is applicable.  Because this module is responsible for selecting
17 ** indices, you might also think of this module as the "query optimizer".
18 **
19 ** $Id: where.c,v 1.408 2009/06/16 14:15:22 shane Exp $
20 */
21 #include "sqliteInt.h"
22 
23 /*
24 ** Trace output macros
25 */
26 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
27 int sqlite3WhereTrace = 0;
28 #endif
29 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
30 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
31 #else
32 # define WHERETRACE(X)
33 #endif
34 
35 /* Forward reference
36 */
37 typedef struct WhereClause WhereClause;
38 typedef struct WhereMaskSet WhereMaskSet;
39 typedef struct WhereOrInfo WhereOrInfo;
40 typedef struct WhereAndInfo WhereAndInfo;
41 typedef struct WhereCost WhereCost;
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 AND operators,
47 ** usually, or sometimes subexpressions separated by OR.
48 **
49 ** All WhereTerms are collected into a single WhereClause structure.
50 ** The following identity holds:
51 **
52 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
53 **
54 ** When a term is of the form:
55 **
56 **              X <op> <expr>
57 **
58 ** where X is a column name and <op> is one of certain operators,
59 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
60 ** cursor number and column number for X.  WhereTerm.eOperator records
61 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
62 ** use of a bitmask encoding for the operator allows us to search
63 ** quickly for terms that match any of several different operators.
64 **
65 ** A WhereTerm might also be two or more subterms connected by OR:
66 **
67 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
68 **
69 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
70 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
71 ** is collected about the
72 **
73 ** If a term in the WHERE clause does not match either of the two previous
74 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
75 ** to the original subexpression content and wtFlags is set up appropriately
76 ** but no other fields in the WhereTerm object are meaningful.
77 **
78 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
79 ** but they do so indirectly.  A single WhereMaskSet structure translates
80 ** cursor number into bits and the translated bit is stored in the prereq
81 ** fields.  The translation is used in order to maximize the number of
82 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
83 ** spread out over the non-negative integers.  For example, the cursor
84 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
85 ** translates these sparse cursor numbers into consecutive integers
86 ** beginning with 0 in order to make the best possible use of the available
87 ** bits in the Bitmask.  So, in the example above, the cursor numbers
88 ** would be mapped into integers 0 through 7.
89 **
90 ** The number of terms in a join is limited by the number of bits
91 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
92 ** is only able to process joins with 64 or fewer tables.
93 */
94 typedef struct WhereTerm WhereTerm;
95 struct WhereTerm {
96   Expr *pExpr;            /* Pointer to the subexpression that is this term */
97   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
98   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
99   union {
100     int leftColumn;         /* Column number of X in "X <op> <expr>" */
101     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
102     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
103   } u;
104   u16 eOperator;          /* A WO_xx value describing <op> */
105   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
106   u8 nChild;              /* Number of children that must disable us */
107   WhereClause *pWC;       /* The clause this term is part of */
108   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
109   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
110 };
111 
112 /*
113 ** Allowed values of WhereTerm.wtFlags
114 */
115 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
116 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
117 #define TERM_CODED      0x04   /* This term is already coded */
118 #define TERM_COPIED     0x08   /* Has a child */
119 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
120 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
121 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
122 
123 /*
124 ** An instance of the following structure holds all information about a
125 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
126 */
127 struct WhereClause {
128   Parse *pParse;           /* The parser context */
129   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
130   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
131   u8 op;                   /* Split operator.  TK_AND or TK_OR */
132   int nTerm;               /* Number of terms */
133   int nSlot;               /* Number of entries in a[] */
134   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
135 #if defined(SQLITE_SMALL_STACK)
136   WhereTerm aStatic[1];    /* Initial static space for a[] */
137 #else
138   WhereTerm aStatic[8];    /* Initial static space for a[] */
139 #endif
140 };
141 
142 /*
143 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
144 ** a dynamically allocated instance of the following structure.
145 */
146 struct WhereOrInfo {
147   WhereClause wc;          /* Decomposition into subterms */
148   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
149 };
150 
151 /*
152 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
153 ** a dynamically allocated instance of the following structure.
154 */
155 struct WhereAndInfo {
156   WhereClause wc;          /* The subexpression broken out */
157 };
158 
159 /*
160 ** An instance of the following structure keeps track of a mapping
161 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
162 **
163 ** The VDBE cursor numbers are small integers contained in
164 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
165 ** clause, the cursor numbers might not begin with 0 and they might
166 ** contain gaps in the numbering sequence.  But we want to make maximum
167 ** use of the bits in our bitmasks.  This structure provides a mapping
168 ** from the sparse cursor numbers into consecutive integers beginning
169 ** with 0.
170 **
171 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
172 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
173 **
174 ** For example, if the WHERE clause expression used these VDBE
175 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
176 ** would map those cursor numbers into bits 0 through 5.
177 **
178 ** Note that the mapping is not necessarily ordered.  In the example
179 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
180 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
181 ** does not really matter.  What is important is that sparse cursor
182 ** numbers all get mapped into bit numbers that begin with 0 and contain
183 ** no gaps.
184 */
185 struct WhereMaskSet {
186   int n;                        /* Number of assigned cursor values */
187   int ix[BMS];                  /* Cursor assigned to each bit */
188 };
189 
190 /*
191 ** A WhereCost object records a lookup strategy and the estimated
192 ** cost of pursuing that strategy.
193 */
194 struct WhereCost {
195   WherePlan plan;    /* The lookup strategy */
196   double rCost;      /* Overall cost of pursuing this search strategy */
197   double nRow;       /* Estimated number of output rows */
198 };
199 
200 /*
201 ** Bitmasks for the operators that indices are able to exploit.  An
202 ** OR-ed combination of these values can be used when searching for
203 ** terms in the where clause.
204 */
205 #define WO_IN     0x001
206 #define WO_EQ     0x002
207 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
208 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
209 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
210 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
211 #define WO_MATCH  0x040
212 #define WO_ISNULL 0x080
213 #define WO_OR     0x100       /* Two or more OR-connected terms */
214 #define WO_AND    0x200       /* Two or more AND-connected terms */
215 
216 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
217 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
218 
219 /*
220 ** Value for wsFlags returned by bestIndex() and stored in
221 ** WhereLevel.wsFlags.  These flags determine which search
222 ** strategies are appropriate.
223 **
224 ** The least significant 12 bits is reserved as a mask for WO_ values above.
225 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
226 ** But if the table is the right table of a left join, WhereLevel.wsFlags
227 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
228 ** the "op" parameter to findTerm when we are resolving equality constraints.
229 ** ISNULL constraints will then not be used on the right table of a left
230 ** join.  Tickets #2177 and #2189.
231 */
232 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
233 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
234 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
235 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
236 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
237 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
238 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
239 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
240 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
241 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
242 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
243 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
244 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
245 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
246 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
247 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
248 
249 /*
250 ** Initialize a preallocated WhereClause structure.
251 */
252 static void whereClauseInit(
253   WhereClause *pWC,        /* The WhereClause to be initialized */
254   Parse *pParse,           /* The parsing context */
255   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
256 ){
257   pWC->pParse = pParse;
258   pWC->pMaskSet = pMaskSet;
259   pWC->nTerm = 0;
260   pWC->nSlot = ArraySize(pWC->aStatic);
261   pWC->a = pWC->aStatic;
262   pWC->vmask = 0;
263 }
264 
265 /* Forward reference */
266 static void whereClauseClear(WhereClause*);
267 
268 /*
269 ** Deallocate all memory associated with a WhereOrInfo object.
270 */
271 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
272   whereClauseClear(&p->wc);
273   sqlite3DbFree(db, p);
274 }
275 
276 /*
277 ** Deallocate all memory associated with a WhereAndInfo object.
278 */
279 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
280   whereClauseClear(&p->wc);
281   sqlite3DbFree(db, p);
282 }
283 
284 /*
285 ** Deallocate a WhereClause structure.  The WhereClause structure
286 ** itself is not freed.  This routine is the inverse of whereClauseInit().
287 */
288 static void whereClauseClear(WhereClause *pWC){
289   int i;
290   WhereTerm *a;
291   sqlite3 *db = pWC->pParse->db;
292   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
293     if( a->wtFlags & TERM_DYNAMIC ){
294       sqlite3ExprDelete(db, a->pExpr);
295     }
296     if( a->wtFlags & TERM_ORINFO ){
297       whereOrInfoDelete(db, a->u.pOrInfo);
298     }else if( a->wtFlags & TERM_ANDINFO ){
299       whereAndInfoDelete(db, a->u.pAndInfo);
300     }
301   }
302   if( pWC->a!=pWC->aStatic ){
303     sqlite3DbFree(db, pWC->a);
304   }
305 }
306 
307 /*
308 ** Add a single new WhereTerm entry to the WhereClause object pWC.
309 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
310 ** The index in pWC->a[] of the new WhereTerm is returned on success.
311 ** 0 is returned if the new WhereTerm could not be added due to a memory
312 ** allocation error.  The memory allocation failure will be recorded in
313 ** the db->mallocFailed flag so that higher-level functions can detect it.
314 **
315 ** This routine will increase the size of the pWC->a[] array as necessary.
316 **
317 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
318 ** for freeing the expression p is assumed by the WhereClause object pWC.
319 ** This is true even if this routine fails to allocate a new WhereTerm.
320 **
321 ** WARNING:  This routine might reallocate the space used to store
322 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
323 ** calling this routine.  Such pointers may be reinitialized by referencing
324 ** the pWC->a[] array.
325 */
326 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
327   WhereTerm *pTerm;
328   int idx;
329   if( pWC->nTerm>=pWC->nSlot ){
330     WhereTerm *pOld = pWC->a;
331     sqlite3 *db = pWC->pParse->db;
332     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
333     if( pWC->a==0 ){
334       if( wtFlags & TERM_DYNAMIC ){
335         sqlite3ExprDelete(db, p);
336       }
337       pWC->a = pOld;
338       return 0;
339     }
340     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
341     if( pOld!=pWC->aStatic ){
342       sqlite3DbFree(db, pOld);
343     }
344     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
345   }
346   pTerm = &pWC->a[idx = pWC->nTerm++];
347   pTerm->pExpr = p;
348   pTerm->wtFlags = wtFlags;
349   pTerm->pWC = pWC;
350   pTerm->iParent = -1;
351   return idx;
352 }
353 
354 /*
355 ** This routine identifies subexpressions in the WHERE clause where
356 ** each subexpression is separated by the AND operator or some other
357 ** operator specified in the op parameter.  The WhereClause structure
358 ** is filled with pointers to subexpressions.  For example:
359 **
360 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
361 **           \________/     \_______________/     \________________/
362 **            slot[0]            slot[1]               slot[2]
363 **
364 ** The original WHERE clause in pExpr is unaltered.  All this routine
365 ** does is make slot[] entries point to substructure within pExpr.
366 **
367 ** In the previous sentence and in the diagram, "slot[]" refers to
368 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
369 ** all terms of the WHERE clause.
370 */
371 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
372   pWC->op = (u8)op;
373   if( pExpr==0 ) return;
374   if( pExpr->op!=op ){
375     whereClauseInsert(pWC, pExpr, 0);
376   }else{
377     whereSplit(pWC, pExpr->pLeft, op);
378     whereSplit(pWC, pExpr->pRight, op);
379   }
380 }
381 
382 /*
383 ** Initialize an expression mask set (a WhereMaskSet object)
384 */
385 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
386 
387 /*
388 ** Return the bitmask for the given cursor number.  Return 0 if
389 ** iCursor is not in the set.
390 */
391 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
392   int i;
393   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
394   for(i=0; i<pMaskSet->n; i++){
395     if( pMaskSet->ix[i]==iCursor ){
396       return ((Bitmask)1)<<i;
397     }
398   }
399   return 0;
400 }
401 
402 /*
403 ** Create a new mask for cursor iCursor.
404 **
405 ** There is one cursor per table in the FROM clause.  The number of
406 ** tables in the FROM clause is limited by a test early in the
407 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
408 ** array will never overflow.
409 */
410 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
411   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
412   pMaskSet->ix[pMaskSet->n++] = iCursor;
413 }
414 
415 /*
416 ** This routine walks (recursively) an expression tree and generates
417 ** a bitmask indicating which tables are used in that expression
418 ** tree.
419 **
420 ** In order for this routine to work, the calling function must have
421 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
422 ** the header comment on that routine for additional information.
423 ** The sqlite3ResolveExprNames() routines looks for column names and
424 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
425 ** the VDBE cursor number of the table.  This routine just has to
426 ** translate the cursor numbers into bitmask values and OR all
427 ** the bitmasks together.
428 */
429 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
430 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
431 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
432   Bitmask mask = 0;
433   if( p==0 ) return 0;
434   if( p->op==TK_COLUMN ){
435     mask = getMask(pMaskSet, p->iTable);
436     return mask;
437   }
438   mask = exprTableUsage(pMaskSet, p->pRight);
439   mask |= exprTableUsage(pMaskSet, p->pLeft);
440   if( ExprHasProperty(p, EP_xIsSelect) ){
441     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
442   }else{
443     mask |= exprListTableUsage(pMaskSet, p->x.pList);
444   }
445   return mask;
446 }
447 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
448   int i;
449   Bitmask mask = 0;
450   if( pList ){
451     for(i=0; i<pList->nExpr; i++){
452       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
453     }
454   }
455   return mask;
456 }
457 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
458   Bitmask mask = 0;
459   while( pS ){
460     mask |= exprListTableUsage(pMaskSet, pS->pEList);
461     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
462     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
463     mask |= exprTableUsage(pMaskSet, pS->pWhere);
464     mask |= exprTableUsage(pMaskSet, pS->pHaving);
465     pS = pS->pPrior;
466   }
467   return mask;
468 }
469 
470 /*
471 ** Return TRUE if the given operator is one of the operators that is
472 ** allowed for an indexable WHERE clause term.  The allowed operators are
473 ** "=", "<", ">", "<=", ">=", and "IN".
474 */
475 static int allowedOp(int op){
476   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
477   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
478   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
479   assert( TK_GE==TK_EQ+4 );
480   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
481 }
482 
483 /*
484 ** Swap two objects of type TYPE.
485 */
486 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
487 
488 /*
489 ** Commute a comparison operator.  Expressions of the form "X op Y"
490 ** are converted into "Y op X".
491 **
492 ** If a collation sequence is associated with either the left or right
493 ** side of the comparison, it remains associated with the same side after
494 ** the commutation. So "Y collate NOCASE op X" becomes
495 ** "X collate NOCASE op Y". This is because any collation sequence on
496 ** the left hand side of a comparison overrides any collation sequence
497 ** attached to the right. For the same reason the EP_ExpCollate flag
498 ** is not commuted.
499 */
500 static void exprCommute(Parse *pParse, Expr *pExpr){
501   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
502   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
503   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
504   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
505   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
506   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
507   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
508   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
509   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
510   if( pExpr->op>=TK_GT ){
511     assert( TK_LT==TK_GT+2 );
512     assert( TK_GE==TK_LE+2 );
513     assert( TK_GT>TK_EQ );
514     assert( TK_GT<TK_LE );
515     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
516     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
517   }
518 }
519 
520 /*
521 ** Translate from TK_xx operator to WO_xx bitmask.
522 */
523 static u16 operatorMask(int op){
524   u16 c;
525   assert( allowedOp(op) );
526   if( op==TK_IN ){
527     c = WO_IN;
528   }else if( op==TK_ISNULL ){
529     c = WO_ISNULL;
530   }else{
531     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
532     c = (u16)(WO_EQ<<(op-TK_EQ));
533   }
534   assert( op!=TK_ISNULL || c==WO_ISNULL );
535   assert( op!=TK_IN || c==WO_IN );
536   assert( op!=TK_EQ || c==WO_EQ );
537   assert( op!=TK_LT || c==WO_LT );
538   assert( op!=TK_LE || c==WO_LE );
539   assert( op!=TK_GT || c==WO_GT );
540   assert( op!=TK_GE || c==WO_GE );
541   return c;
542 }
543 
544 /*
545 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
546 ** where X is a reference to the iColumn of table iCur and <op> is one of
547 ** the WO_xx operator codes specified by the op parameter.
548 ** Return a pointer to the term.  Return 0 if not found.
549 */
550 static WhereTerm *findTerm(
551   WhereClause *pWC,     /* The WHERE clause to be searched */
552   int iCur,             /* Cursor number of LHS */
553   int iColumn,          /* Column number of LHS */
554   Bitmask notReady,     /* RHS must not overlap with this mask */
555   u32 op,               /* Mask of WO_xx values describing operator */
556   Index *pIdx           /* Must be compatible with this index, if not NULL */
557 ){
558   WhereTerm *pTerm;
559   int k;
560   assert( iCur>=0 );
561   op &= WO_ALL;
562   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
563     if( pTerm->leftCursor==iCur
564        && (pTerm->prereqRight & notReady)==0
565        && pTerm->u.leftColumn==iColumn
566        && (pTerm->eOperator & op)!=0
567     ){
568       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
569         Expr *pX = pTerm->pExpr;
570         CollSeq *pColl;
571         char idxaff;
572         int j;
573         Parse *pParse = pWC->pParse;
574 
575         idxaff = pIdx->pTable->aCol[iColumn].affinity;
576         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
577 
578         /* Figure out the collation sequence required from an index for
579         ** it to be useful for optimising expression pX. Store this
580         ** value in variable pColl.
581         */
582         assert(pX->pLeft);
583         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
584         assert(pColl || pParse->nErr);
585 
586         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
587           if( NEVER(j>=pIdx->nColumn) ) return 0;
588         }
589         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
590       }
591       return pTerm;
592     }
593   }
594   return 0;
595 }
596 
597 /* Forward reference */
598 static void exprAnalyze(SrcList*, WhereClause*, int);
599 
600 /*
601 ** Call exprAnalyze on all terms in a WHERE clause.
602 **
603 **
604 */
605 static void exprAnalyzeAll(
606   SrcList *pTabList,       /* the FROM clause */
607   WhereClause *pWC         /* the WHERE clause to be analyzed */
608 ){
609   int i;
610   for(i=pWC->nTerm-1; i>=0; i--){
611     exprAnalyze(pTabList, pWC, i);
612   }
613 }
614 
615 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
616 /*
617 ** Check to see if the given expression is a LIKE or GLOB operator that
618 ** can be optimized using inequality constraints.  Return TRUE if it is
619 ** so and false if not.
620 **
621 ** In order for the operator to be optimizible, the RHS must be a string
622 ** literal that does not begin with a wildcard.
623 */
624 static int isLikeOrGlob(
625   Parse *pParse,    /* Parsing and code generating context */
626   Expr *pExpr,      /* Test this expression */
627   int *pnPattern,   /* Number of non-wildcard prefix characters */
628   int *pisComplete, /* True if the only wildcard is % in the last character */
629   int *pnoCase      /* True if uppercase is equivalent to lowercase */
630 ){
631   const char *z;             /* String on RHS of LIKE operator */
632   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
633   ExprList *pList;           /* List of operands to the LIKE operator */
634   int c;                     /* One character in z[] */
635   int cnt;                   /* Number of non-wildcard prefix characters */
636   char wc[3];                /* Wildcard characters */
637   CollSeq *pColl;            /* Collating sequence for LHS */
638   sqlite3 *db = pParse->db;  /* Database connection */
639 
640   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
641     return 0;
642   }
643 #ifdef SQLITE_EBCDIC
644   if( *pnoCase ) return 0;
645 #endif
646   pList = pExpr->x.pList;
647   pRight = pList->a[0].pExpr;
648   if( pRight->op!=TK_STRING ){
649     return 0;
650   }
651   pLeft = pList->a[1].pExpr;
652   if( pLeft->op!=TK_COLUMN ){
653     return 0;
654   }
655   pColl = sqlite3ExprCollSeq(pParse, pLeft);
656   assert( pColl!=0 || pLeft->iColumn==-1 );
657   if( pColl==0 ) return 0;
658   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
659       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
660     return 0;
661   }
662   if( sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ) return 0;
663   z = pRight->u.zToken;
664   if( ALWAYS(z) ){
665     cnt = 0;
666     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
667       cnt++;
668     }
669     if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
670       *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
671       *pnPattern = cnt;
672       return 1;
673     }
674   }
675   return 0;
676 }
677 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
678 
679 
680 #ifndef SQLITE_OMIT_VIRTUALTABLE
681 /*
682 ** Check to see if the given expression is of the form
683 **
684 **         column MATCH expr
685 **
686 ** If it is then return TRUE.  If not, return FALSE.
687 */
688 static int isMatchOfColumn(
689   Expr *pExpr      /* Test this expression */
690 ){
691   ExprList *pList;
692 
693   if( pExpr->op!=TK_FUNCTION ){
694     return 0;
695   }
696   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
697     return 0;
698   }
699   pList = pExpr->x.pList;
700   if( pList->nExpr!=2 ){
701     return 0;
702   }
703   if( pList->a[1].pExpr->op != TK_COLUMN ){
704     return 0;
705   }
706   return 1;
707 }
708 #endif /* SQLITE_OMIT_VIRTUALTABLE */
709 
710 /*
711 ** If the pBase expression originated in the ON or USING clause of
712 ** a join, then transfer the appropriate markings over to derived.
713 */
714 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
715   pDerived->flags |= pBase->flags & EP_FromJoin;
716   pDerived->iRightJoinTable = pBase->iRightJoinTable;
717 }
718 
719 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
720 /*
721 ** Analyze a term that consists of two or more OR-connected
722 ** subterms.  So in:
723 **
724 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
725 **                          ^^^^^^^^^^^^^^^^^^^^
726 **
727 ** This routine analyzes terms such as the middle term in the above example.
728 ** A WhereOrTerm object is computed and attached to the term under
729 ** analysis, regardless of the outcome of the analysis.  Hence:
730 **
731 **     WhereTerm.wtFlags   |=  TERM_ORINFO
732 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
733 **
734 ** The term being analyzed must have two or more of OR-connected subterms.
735 ** A single subterm might be a set of AND-connected sub-subterms.
736 ** Examples of terms under analysis:
737 **
738 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
739 **     (B)     x=expr1 OR expr2=x OR x=expr3
740 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
741 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
742 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
743 **
744 ** CASE 1:
745 **
746 ** If all subterms are of the form T.C=expr for some single column of C
747 ** a single table T (as shown in example B above) then create a new virtual
748 ** term that is an equivalent IN expression.  In other words, if the term
749 ** being analyzed is:
750 **
751 **      x = expr1  OR  expr2 = x  OR  x = expr3
752 **
753 ** then create a new virtual term like this:
754 **
755 **      x IN (expr1,expr2,expr3)
756 **
757 ** CASE 2:
758 **
759 ** If all subterms are indexable by a single table T, then set
760 **
761 **     WhereTerm.eOperator              =  WO_OR
762 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
763 **
764 ** A subterm is "indexable" if it is of the form
765 ** "T.C <op> <expr>" where C is any column of table T and
766 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
767 ** A subterm is also indexable if it is an AND of two or more
768 ** subsubterms at least one of which is indexable.  Indexable AND
769 ** subterms have their eOperator set to WO_AND and they have
770 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
771 **
772 ** From another point of view, "indexable" means that the subterm could
773 ** potentially be used with an index if an appropriate index exists.
774 ** This analysis does not consider whether or not the index exists; that
775 ** is something the bestIndex() routine will determine.  This analysis
776 ** only looks at whether subterms appropriate for indexing exist.
777 **
778 ** All examples A through E above all satisfy case 2.  But if a term
779 ** also statisfies case 1 (such as B) we know that the optimizer will
780 ** always prefer case 1, so in that case we pretend that case 2 is not
781 ** satisfied.
782 **
783 ** It might be the case that multiple tables are indexable.  For example,
784 ** (E) above is indexable on tables P, Q, and R.
785 **
786 ** Terms that satisfy case 2 are candidates for lookup by using
787 ** separate indices to find rowids for each subterm and composing
788 ** the union of all rowids using a RowSet object.  This is similar
789 ** to "bitmap indices" in other database engines.
790 **
791 ** OTHERWISE:
792 **
793 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
794 ** zero.  This term is not useful for search.
795 */
796 static void exprAnalyzeOrTerm(
797   SrcList *pSrc,            /* the FROM clause */
798   WhereClause *pWC,         /* the complete WHERE clause */
799   int idxTerm               /* Index of the OR-term to be analyzed */
800 ){
801   Parse *pParse = pWC->pParse;            /* Parser context */
802   sqlite3 *db = pParse->db;               /* Database connection */
803   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
804   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
805   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
806   int i;                                  /* Loop counters */
807   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
808   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
809   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
810   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
811   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
812 
813   /*
814   ** Break the OR clause into its separate subterms.  The subterms are
815   ** stored in a WhereClause structure containing within the WhereOrInfo
816   ** object that is attached to the original OR clause term.
817   */
818   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
819   assert( pExpr->op==TK_OR );
820   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
821   if( pOrInfo==0 ) return;
822   pTerm->wtFlags |= TERM_ORINFO;
823   pOrWc = &pOrInfo->wc;
824   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
825   whereSplit(pOrWc, pExpr, TK_OR);
826   exprAnalyzeAll(pSrc, pOrWc);
827   if( db->mallocFailed ) return;
828   assert( pOrWc->nTerm>=2 );
829 
830   /*
831   ** Compute the set of tables that might satisfy cases 1 or 2.
832   */
833   indexable = ~(Bitmask)0;
834   chngToIN = ~(pWC->vmask);
835   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
836     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
837       WhereAndInfo *pAndInfo;
838       assert( pOrTerm->eOperator==0 );
839       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
840       chngToIN = 0;
841       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
842       if( pAndInfo ){
843         WhereClause *pAndWC;
844         WhereTerm *pAndTerm;
845         int j;
846         Bitmask b = 0;
847         pOrTerm->u.pAndInfo = pAndInfo;
848         pOrTerm->wtFlags |= TERM_ANDINFO;
849         pOrTerm->eOperator = WO_AND;
850         pAndWC = &pAndInfo->wc;
851         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
852         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
853         exprAnalyzeAll(pSrc, pAndWC);
854         testcase( db->mallocFailed );
855         if( !db->mallocFailed ){
856           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
857             assert( pAndTerm->pExpr );
858             if( allowedOp(pAndTerm->pExpr->op) ){
859               b |= getMask(pMaskSet, pAndTerm->leftCursor);
860             }
861           }
862         }
863         indexable &= b;
864       }
865     }else if( pOrTerm->wtFlags & TERM_COPIED ){
866       /* Skip this term for now.  We revisit it when we process the
867       ** corresponding TERM_VIRTUAL term */
868     }else{
869       Bitmask b;
870       b = getMask(pMaskSet, pOrTerm->leftCursor);
871       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
872         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
873         b |= getMask(pMaskSet, pOther->leftCursor);
874       }
875       indexable &= b;
876       if( pOrTerm->eOperator!=WO_EQ ){
877         chngToIN = 0;
878       }else{
879         chngToIN &= b;
880       }
881     }
882   }
883 
884   /*
885   ** Record the set of tables that satisfy case 2.  The set might be
886   ** empty.
887   */
888   pOrInfo->indexable = indexable;
889   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
890 
891   /*
892   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
893   ** we have to do some additional checking to see if case 1 really
894   ** is satisfied.
895   **
896   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
897   ** that there is no possibility of transforming the OR clause into an
898   ** IN operator because one or more terms in the OR clause contain
899   ** something other than == on a column in the single table.  The 1-bit
900   ** case means that every term of the OR clause is of the form
901   ** "table.column=expr" for some single table.  The one bit that is set
902   ** will correspond to the common table.  We still need to check to make
903   ** sure the same column is used on all terms.  The 2-bit case is when
904   ** the all terms are of the form "table1.column=table2.column".  It
905   ** might be possible to form an IN operator with either table1.column
906   ** or table2.column as the LHS if either is common to every term of
907   ** the OR clause.
908   **
909   ** Note that terms of the form "table.column1=table.column2" (the
910   ** same table on both sizes of the ==) cannot be optimized.
911   */
912   if( chngToIN ){
913     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
914     int iColumn = -1;         /* Column index on lhs of IN operator */
915     int iCursor = -1;         /* Table cursor common to all terms */
916     int j = 0;                /* Loop counter */
917 
918     /* Search for a table and column that appears on one side or the
919     ** other of the == operator in every subterm.  That table and column
920     ** will be recorded in iCursor and iColumn.  There might not be any
921     ** such table and column.  Set okToChngToIN if an appropriate table
922     ** and column is found but leave okToChngToIN false if not found.
923     */
924     for(j=0; j<2 && !okToChngToIN; j++){
925       pOrTerm = pOrWc->a;
926       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
927         assert( pOrTerm->eOperator==WO_EQ );
928         pOrTerm->wtFlags &= ~TERM_OR_OK;
929         if( pOrTerm->leftCursor==iCursor ){
930           /* This is the 2-bit case and we are on the second iteration and
931           ** current term is from the first iteration.  So skip this term. */
932           assert( j==1 );
933           continue;
934         }
935         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
936           /* This term must be of the form t1.a==t2.b where t2 is in the
937           ** chngToIN set but t1 is not.  This term will be either preceeded
938           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
939           ** and use its inversion. */
940           testcase( pOrTerm->wtFlags & TERM_COPIED );
941           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
942           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
943           continue;
944         }
945         iColumn = pOrTerm->u.leftColumn;
946         iCursor = pOrTerm->leftCursor;
947         break;
948       }
949       if( i<0 ){
950         /* No candidate table+column was found.  This can only occur
951         ** on the second iteration */
952         assert( j==1 );
953         assert( (chngToIN&(chngToIN-1))==0 );
954         assert( chngToIN==getMask(pMaskSet, iCursor) );
955         break;
956       }
957       testcase( j==1 );
958 
959       /* We have found a candidate table and column.  Check to see if that
960       ** table and column is common to every term in the OR clause */
961       okToChngToIN = 1;
962       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
963         assert( pOrTerm->eOperator==WO_EQ );
964         if( pOrTerm->leftCursor!=iCursor ){
965           pOrTerm->wtFlags &= ~TERM_OR_OK;
966         }else if( pOrTerm->u.leftColumn!=iColumn ){
967           okToChngToIN = 0;
968         }else{
969           int affLeft, affRight;
970           /* If the right-hand side is also a column, then the affinities
971           ** of both right and left sides must be such that no type
972           ** conversions are required on the right.  (Ticket #2249)
973           */
974           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
975           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
976           if( affRight!=0 && affRight!=affLeft ){
977             okToChngToIN = 0;
978           }else{
979             pOrTerm->wtFlags |= TERM_OR_OK;
980           }
981         }
982       }
983     }
984 
985     /* At this point, okToChngToIN is true if original pTerm satisfies
986     ** case 1.  In that case, construct a new virtual term that is
987     ** pTerm converted into an IN operator.
988     */
989     if( okToChngToIN ){
990       Expr *pDup;            /* A transient duplicate expression */
991       ExprList *pList = 0;   /* The RHS of the IN operator */
992       Expr *pLeft = 0;       /* The LHS of the IN operator */
993       Expr *pNew;            /* The complete IN operator */
994 
995       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
996         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
997         assert( pOrTerm->eOperator==WO_EQ );
998         assert( pOrTerm->leftCursor==iCursor );
999         assert( pOrTerm->u.leftColumn==iColumn );
1000         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
1001         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
1002         pLeft = pOrTerm->pExpr->pLeft;
1003       }
1004       assert( pLeft!=0 );
1005       pDup = sqlite3ExprDup(db, pLeft, 0);
1006       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
1007       if( pNew ){
1008         int idxNew;
1009         transferJoinMarkings(pNew, pExpr);
1010         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1011         pNew->x.pList = pList;
1012         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1013         testcase( idxNew==0 );
1014         exprAnalyze(pSrc, pWC, idxNew);
1015         pTerm = &pWC->a[idxTerm];
1016         pWC->a[idxNew].iParent = idxTerm;
1017         pTerm->nChild = 1;
1018       }else{
1019         sqlite3ExprListDelete(db, pList);
1020       }
1021       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
1022     }
1023   }
1024 }
1025 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
1026 
1027 
1028 /*
1029 ** The input to this routine is an WhereTerm structure with only the
1030 ** "pExpr" field filled in.  The job of this routine is to analyze the
1031 ** subexpression and populate all the other fields of the WhereTerm
1032 ** structure.
1033 **
1034 ** If the expression is of the form "<expr> <op> X" it gets commuted
1035 ** to the standard form of "X <op> <expr>".
1036 **
1037 ** If the expression is of the form "X <op> Y" where both X and Y are
1038 ** columns, then the original expression is unchanged and a new virtual
1039 ** term of the form "Y <op> X" is added to the WHERE clause and
1040 ** analyzed separately.  The original term is marked with TERM_COPIED
1041 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1042 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1043 ** is a commuted copy of a prior term.)  The original term has nChild=1
1044 ** and the copy has idxParent set to the index of the original term.
1045 */
1046 static void exprAnalyze(
1047   SrcList *pSrc,            /* the FROM clause */
1048   WhereClause *pWC,         /* the WHERE clause */
1049   int idxTerm               /* Index of the term to be analyzed */
1050 ){
1051   WhereTerm *pTerm;                /* The term to be analyzed */
1052   WhereMaskSet *pMaskSet;          /* Set of table index masks */
1053   Expr *pExpr;                     /* The expression to be analyzed */
1054   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
1055   Bitmask prereqAll;               /* Prerequesites of pExpr */
1056   Bitmask extraRight = 0;
1057   int nPattern;
1058   int isComplete;
1059   int noCase;
1060   int op;                          /* Top-level operator.  pExpr->op */
1061   Parse *pParse = pWC->pParse;     /* Parsing context */
1062   sqlite3 *db = pParse->db;        /* Database connection */
1063 
1064   if( db->mallocFailed ){
1065     return;
1066   }
1067   pTerm = &pWC->a[idxTerm];
1068   pMaskSet = pWC->pMaskSet;
1069   pExpr = pTerm->pExpr;
1070   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
1071   op = pExpr->op;
1072   if( op==TK_IN ){
1073     assert( pExpr->pRight==0 );
1074     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1075       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1076     }else{
1077       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1078     }
1079   }else if( op==TK_ISNULL ){
1080     pTerm->prereqRight = 0;
1081   }else{
1082     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1083   }
1084   prereqAll = exprTableUsage(pMaskSet, pExpr);
1085   if( ExprHasProperty(pExpr, EP_FromJoin) ){
1086     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1087     prereqAll |= x;
1088     extraRight = x-1;  /* ON clause terms may not be used with an index
1089                        ** on left table of a LEFT JOIN.  Ticket #3015 */
1090   }
1091   pTerm->prereqAll = prereqAll;
1092   pTerm->leftCursor = -1;
1093   pTerm->iParent = -1;
1094   pTerm->eOperator = 0;
1095   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
1096     Expr *pLeft = pExpr->pLeft;
1097     Expr *pRight = pExpr->pRight;
1098     if( pLeft->op==TK_COLUMN ){
1099       pTerm->leftCursor = pLeft->iTable;
1100       pTerm->u.leftColumn = pLeft->iColumn;
1101       pTerm->eOperator = operatorMask(op);
1102     }
1103     if( pRight && pRight->op==TK_COLUMN ){
1104       WhereTerm *pNew;
1105       Expr *pDup;
1106       if( pTerm->leftCursor>=0 ){
1107         int idxNew;
1108         pDup = sqlite3ExprDup(db, pExpr, 0);
1109         if( db->mallocFailed ){
1110           sqlite3ExprDelete(db, pDup);
1111           return;
1112         }
1113         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1114         if( idxNew==0 ) return;
1115         pNew = &pWC->a[idxNew];
1116         pNew->iParent = idxTerm;
1117         pTerm = &pWC->a[idxTerm];
1118         pTerm->nChild = 1;
1119         pTerm->wtFlags |= TERM_COPIED;
1120       }else{
1121         pDup = pExpr;
1122         pNew = pTerm;
1123       }
1124       exprCommute(pParse, pDup);
1125       pLeft = pDup->pLeft;
1126       pNew->leftCursor = pLeft->iTable;
1127       pNew->u.leftColumn = pLeft->iColumn;
1128       pNew->prereqRight = prereqLeft;
1129       pNew->prereqAll = prereqAll;
1130       pNew->eOperator = operatorMask(pDup->op);
1131     }
1132   }
1133 
1134 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1135   /* If a term is the BETWEEN operator, create two new virtual terms
1136   ** that define the range that the BETWEEN implements.  For example:
1137   **
1138   **      a BETWEEN b AND c
1139   **
1140   ** is converted into:
1141   **
1142   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1143   **
1144   ** The two new terms are added onto the end of the WhereClause object.
1145   ** The new terms are "dynamic" and are children of the original BETWEEN
1146   ** term.  That means that if the BETWEEN term is coded, the children are
1147   ** skipped.  Or, if the children are satisfied by an index, the original
1148   ** BETWEEN term is skipped.
1149   */
1150   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1151     ExprList *pList = pExpr->x.pList;
1152     int i;
1153     static const u8 ops[] = {TK_GE, TK_LE};
1154     assert( pList!=0 );
1155     assert( pList->nExpr==2 );
1156     for(i=0; i<2; i++){
1157       Expr *pNewExpr;
1158       int idxNew;
1159       pNewExpr = sqlite3PExpr(pParse, ops[i],
1160                              sqlite3ExprDup(db, pExpr->pLeft, 0),
1161                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
1162       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1163       testcase( idxNew==0 );
1164       exprAnalyze(pSrc, pWC, idxNew);
1165       pTerm = &pWC->a[idxTerm];
1166       pWC->a[idxNew].iParent = idxTerm;
1167     }
1168     pTerm->nChild = 2;
1169   }
1170 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1171 
1172 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1173   /* Analyze a term that is composed of two or more subterms connected by
1174   ** an OR operator.
1175   */
1176   else if( pExpr->op==TK_OR ){
1177     assert( pWC->op==TK_AND );
1178     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1179   }
1180 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1181 
1182 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1183   /* Add constraints to reduce the search space on a LIKE or GLOB
1184   ** operator.
1185   **
1186   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1187   **
1188   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
1189   **
1190   ** The last character of the prefix "abc" is incremented to form the
1191   ** termination condition "abd".
1192   */
1193   if( isLikeOrGlob(pParse, pExpr, &nPattern, &isComplete, &noCase)
1194          && pWC->op==TK_AND ){
1195     Expr *pLeft, *pRight;
1196     Expr *pStr1, *pStr2;
1197     Expr *pNewExpr1, *pNewExpr2;
1198     int idxNew1, idxNew2;
1199 
1200     pLeft = pExpr->x.pList->a[1].pExpr;
1201     pRight = pExpr->x.pList->a[0].pExpr;
1202     pStr1 = sqlite3Expr(db, TK_STRING, pRight->u.zToken);
1203     if( pStr1 ) pStr1->u.zToken[nPattern] = 0;
1204     pStr2 = sqlite3ExprDup(db, pStr1, 0);
1205     if( !db->mallocFailed ){
1206       u8 c, *pC;       /* Last character before the first wildcard */
1207       pC = (u8*)&pStr2->u.zToken[nPattern-1];
1208       c = *pC;
1209       if( noCase ){
1210         /* The point is to increment the last character before the first
1211         ** wildcard.  But if we increment '@', that will push it into the
1212         ** alphabetic range where case conversions will mess up the
1213         ** inequality.  To avoid this, make sure to also run the full
1214         ** LIKE on all candidate expressions by clearing the isComplete flag
1215         */
1216         if( c=='A'-1 ) isComplete = 0;
1217 
1218         c = sqlite3UpperToLower[c];
1219       }
1220       *pC = c + 1;
1221     }
1222     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
1223     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
1224     testcase( idxNew1==0 );
1225     exprAnalyze(pSrc, pWC, idxNew1);
1226     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
1227     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
1228     testcase( idxNew2==0 );
1229     exprAnalyze(pSrc, pWC, idxNew2);
1230     pTerm = &pWC->a[idxTerm];
1231     if( isComplete ){
1232       pWC->a[idxNew1].iParent = idxTerm;
1233       pWC->a[idxNew2].iParent = idxTerm;
1234       pTerm->nChild = 2;
1235     }
1236   }
1237 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1238 
1239 #ifndef SQLITE_OMIT_VIRTUALTABLE
1240   /* Add a WO_MATCH auxiliary term to the constraint set if the
1241   ** current expression is of the form:  column MATCH expr.
1242   ** This information is used by the xBestIndex methods of
1243   ** virtual tables.  The native query optimizer does not attempt
1244   ** to do anything with MATCH functions.
1245   */
1246   if( isMatchOfColumn(pExpr) ){
1247     int idxNew;
1248     Expr *pRight, *pLeft;
1249     WhereTerm *pNewTerm;
1250     Bitmask prereqColumn, prereqExpr;
1251 
1252     pRight = pExpr->x.pList->a[0].pExpr;
1253     pLeft = pExpr->x.pList->a[1].pExpr;
1254     prereqExpr = exprTableUsage(pMaskSet, pRight);
1255     prereqColumn = exprTableUsage(pMaskSet, pLeft);
1256     if( (prereqExpr & prereqColumn)==0 ){
1257       Expr *pNewExpr;
1258       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1259                               0, sqlite3ExprDup(db, pRight, 0), 0);
1260       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1261       testcase( idxNew==0 );
1262       pNewTerm = &pWC->a[idxNew];
1263       pNewTerm->prereqRight = prereqExpr;
1264       pNewTerm->leftCursor = pLeft->iTable;
1265       pNewTerm->u.leftColumn = pLeft->iColumn;
1266       pNewTerm->eOperator = WO_MATCH;
1267       pNewTerm->iParent = idxTerm;
1268       pTerm = &pWC->a[idxTerm];
1269       pTerm->nChild = 1;
1270       pTerm->wtFlags |= TERM_COPIED;
1271       pNewTerm->prereqAll = pTerm->prereqAll;
1272     }
1273   }
1274 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1275 
1276   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1277   ** an index for tables to the left of the join.
1278   */
1279   pTerm->prereqRight |= extraRight;
1280 }
1281 
1282 /*
1283 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
1284 ** a reference to any table other than the iBase table.
1285 */
1286 static int referencesOtherTables(
1287   ExprList *pList,          /* Search expressions in ths list */
1288   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
1289   int iFirst,               /* Be searching with the iFirst-th expression */
1290   int iBase                 /* Ignore references to this table */
1291 ){
1292   Bitmask allowed = ~getMask(pMaskSet, iBase);
1293   while( iFirst<pList->nExpr ){
1294     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
1295       return 1;
1296     }
1297   }
1298   return 0;
1299 }
1300 
1301 
1302 /*
1303 ** This routine decides if pIdx can be used to satisfy the ORDER BY
1304 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
1305 ** ORDER BY clause, this routine returns 0.
1306 **
1307 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
1308 ** left-most table in the FROM clause of that same SELECT statement and
1309 ** the table has a cursor number of "base".  pIdx is an index on pTab.
1310 **
1311 ** nEqCol is the number of columns of pIdx that are used as equality
1312 ** constraints.  Any of these columns may be missing from the ORDER BY
1313 ** clause and the match can still be a success.
1314 **
1315 ** All terms of the ORDER BY that match against the index must be either
1316 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
1317 ** index do not need to satisfy this constraint.)  The *pbRev value is
1318 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
1319 ** the ORDER BY clause is all ASC.
1320 */
1321 static int isSortingIndex(
1322   Parse *pParse,          /* Parsing context */
1323   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
1324   Index *pIdx,            /* The index we are testing */
1325   int base,               /* Cursor number for the table to be sorted */
1326   ExprList *pOrderBy,     /* The ORDER BY clause */
1327   int nEqCol,             /* Number of index columns with == constraints */
1328   int *pbRev              /* Set to 1 if ORDER BY is DESC */
1329 ){
1330   int i, j;                       /* Loop counters */
1331   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
1332   int nTerm;                      /* Number of ORDER BY terms */
1333   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
1334   sqlite3 *db = pParse->db;
1335 
1336   assert( pOrderBy!=0 );
1337   nTerm = pOrderBy->nExpr;
1338   assert( nTerm>0 );
1339 
1340   /* Match terms of the ORDER BY clause against columns of
1341   ** the index.
1342   **
1343   ** Note that indices have pIdx->nColumn regular columns plus
1344   ** one additional column containing the rowid.  The rowid column
1345   ** of the index is also allowed to match against the ORDER BY
1346   ** clause.
1347   */
1348   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
1349     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
1350     CollSeq *pColl;    /* The collating sequence of pExpr */
1351     int termSortOrder; /* Sort order for this term */
1352     int iColumn;       /* The i-th column of the index.  -1 for rowid */
1353     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
1354     const char *zColl; /* Name of the collating sequence for i-th index term */
1355 
1356     pExpr = pTerm->pExpr;
1357     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
1358       /* Can not use an index sort on anything that is not a column in the
1359       ** left-most table of the FROM clause */
1360       break;
1361     }
1362     pColl = sqlite3ExprCollSeq(pParse, pExpr);
1363     if( !pColl ){
1364       pColl = db->pDfltColl;
1365     }
1366     if( i<pIdx->nColumn ){
1367       iColumn = pIdx->aiColumn[i];
1368       if( iColumn==pIdx->pTable->iPKey ){
1369         iColumn = -1;
1370       }
1371       iSortOrder = pIdx->aSortOrder[i];
1372       zColl = pIdx->azColl[i];
1373     }else{
1374       iColumn = -1;
1375       iSortOrder = 0;
1376       zColl = pColl->zName;
1377     }
1378     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
1379       /* Term j of the ORDER BY clause does not match column i of the index */
1380       if( i<nEqCol ){
1381         /* If an index column that is constrained by == fails to match an
1382         ** ORDER BY term, that is OK.  Just ignore that column of the index
1383         */
1384         continue;
1385       }else if( i==pIdx->nColumn ){
1386         /* Index column i is the rowid.  All other terms match. */
1387         break;
1388       }else{
1389         /* If an index column fails to match and is not constrained by ==
1390         ** then the index cannot satisfy the ORDER BY constraint.
1391         */
1392         return 0;
1393       }
1394     }
1395     assert( pIdx->aSortOrder!=0 );
1396     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
1397     assert( iSortOrder==0 || iSortOrder==1 );
1398     termSortOrder = iSortOrder ^ pTerm->sortOrder;
1399     if( i>nEqCol ){
1400       if( termSortOrder!=sortOrder ){
1401         /* Indices can only be used if all ORDER BY terms past the
1402         ** equality constraints are all either DESC or ASC. */
1403         return 0;
1404       }
1405     }else{
1406       sortOrder = termSortOrder;
1407     }
1408     j++;
1409     pTerm++;
1410     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
1411       /* If the indexed column is the primary key and everything matches
1412       ** so far and none of the ORDER BY terms to the right reference other
1413       ** tables in the join, then we are assured that the index can be used
1414       ** to sort because the primary key is unique and so none of the other
1415       ** columns will make any difference
1416       */
1417       j = nTerm;
1418     }
1419   }
1420 
1421   *pbRev = sortOrder!=0;
1422   if( j>=nTerm ){
1423     /* All terms of the ORDER BY clause are covered by this index so
1424     ** this index can be used for sorting. */
1425     return 1;
1426   }
1427   if( pIdx->onError!=OE_None && i==pIdx->nColumn
1428       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
1429     /* All terms of this index match some prefix of the ORDER BY clause
1430     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
1431     ** clause reference other tables in a join.  If this is all true then
1432     ** the order by clause is superfluous. */
1433     return 1;
1434   }
1435   return 0;
1436 }
1437 
1438 /*
1439 ** Check table to see if the ORDER BY clause in pOrderBy can be satisfied
1440 ** by sorting in order of ROWID.  Return true if so and set *pbRev to be
1441 ** true for reverse ROWID and false for forward ROWID order.
1442 */
1443 static int sortableByRowid(
1444   int base,               /* Cursor number for table to be sorted */
1445   ExprList *pOrderBy,     /* The ORDER BY clause */
1446   WhereMaskSet *pMaskSet, /* Mapping from table cursors to bitmaps */
1447   int *pbRev              /* Set to 1 if ORDER BY is DESC */
1448 ){
1449   Expr *p;
1450 
1451   assert( pOrderBy!=0 );
1452   assert( pOrderBy->nExpr>0 );
1453   p = pOrderBy->a[0].pExpr;
1454   if( p->op==TK_COLUMN && p->iTable==base && p->iColumn==-1
1455     && !referencesOtherTables(pOrderBy, pMaskSet, 1, base) ){
1456     *pbRev = pOrderBy->a[0].sortOrder;
1457     return 1;
1458   }
1459   return 0;
1460 }
1461 
1462 /*
1463 ** Prepare a crude estimate of the logarithm of the input value.
1464 ** The results need not be exact.  This is only used for estimating
1465 ** the total cost of performing operations with O(logN) or O(NlogN)
1466 ** complexity.  Because N is just a guess, it is no great tragedy if
1467 ** logN is a little off.
1468 */
1469 static double estLog(double N){
1470   double logN = 1;
1471   double x = 10;
1472   while( N>x ){
1473     logN += 1;
1474     x *= 10;
1475   }
1476   return logN;
1477 }
1478 
1479 /*
1480 ** Two routines for printing the content of an sqlite3_index_info
1481 ** structure.  Used for testing and debugging only.  If neither
1482 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1483 ** are no-ops.
1484 */
1485 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
1486 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1487   int i;
1488   if( !sqlite3WhereTrace ) return;
1489   for(i=0; i<p->nConstraint; i++){
1490     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1491        i,
1492        p->aConstraint[i].iColumn,
1493        p->aConstraint[i].iTermOffset,
1494        p->aConstraint[i].op,
1495        p->aConstraint[i].usable);
1496   }
1497   for(i=0; i<p->nOrderBy; i++){
1498     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
1499        i,
1500        p->aOrderBy[i].iColumn,
1501        p->aOrderBy[i].desc);
1502   }
1503 }
1504 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1505   int i;
1506   if( !sqlite3WhereTrace ) return;
1507   for(i=0; i<p->nConstraint; i++){
1508     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
1509        i,
1510        p->aConstraintUsage[i].argvIndex,
1511        p->aConstraintUsage[i].omit);
1512   }
1513   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
1514   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
1515   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
1516   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
1517 }
1518 #else
1519 #define TRACE_IDX_INPUTS(A)
1520 #define TRACE_IDX_OUTPUTS(A)
1521 #endif
1522 
1523 /*
1524 ** Required because bestIndex() is called by bestOrClauseIndex()
1525 */
1526 static void bestIndex(
1527     Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
1528 
1529 /*
1530 ** This routine attempts to find an scanning strategy that can be used
1531 ** to optimize an 'OR' expression that is part of a WHERE clause.
1532 **
1533 ** The table associated with FROM clause term pSrc may be either a
1534 ** regular B-Tree table or a virtual table.
1535 */
1536 static void bestOrClauseIndex(
1537   Parse *pParse,              /* The parsing context */
1538   WhereClause *pWC,           /* The WHERE clause */
1539   struct SrcList_item *pSrc,  /* The FROM clause term to search */
1540   Bitmask notReady,           /* Mask of cursors that are not available */
1541   ExprList *pOrderBy,         /* The ORDER BY clause */
1542   WhereCost *pCost            /* Lowest cost query plan */
1543 ){
1544 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
1545   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
1546   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
1547   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
1548   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
1549 
1550   /* Search the WHERE clause terms for a usable WO_OR term. */
1551   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1552     if( pTerm->eOperator==WO_OR
1553      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
1554      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
1555     ){
1556       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
1557       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
1558       WhereTerm *pOrTerm;
1559       int flags = WHERE_MULTI_OR;
1560       double rTotal = 0;
1561       double nRow = 0;
1562 
1563       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
1564         WhereCost sTermCost;
1565         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
1566           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
1567         ));
1568         if( pOrTerm->eOperator==WO_AND ){
1569           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
1570           bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
1571         }else if( pOrTerm->leftCursor==iCur ){
1572           WhereClause tempWC;
1573           tempWC.pParse = pWC->pParse;
1574           tempWC.pMaskSet = pWC->pMaskSet;
1575           tempWC.op = TK_AND;
1576           tempWC.a = pOrTerm;
1577           tempWC.nTerm = 1;
1578           bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
1579         }else{
1580           continue;
1581         }
1582         rTotal += sTermCost.rCost;
1583         nRow += sTermCost.nRow;
1584         if( rTotal>=pCost->rCost ) break;
1585       }
1586 
1587       /* If there is an ORDER BY clause, increase the scan cost to account
1588       ** for the cost of the sort. */
1589       if( pOrderBy!=0 ){
1590         rTotal += nRow*estLog(nRow);
1591         WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
1592       }
1593 
1594       /* If the cost of scanning using this OR term for optimization is
1595       ** less than the current cost stored in pCost, replace the contents
1596       ** of pCost. */
1597       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
1598       if( rTotal<pCost->rCost ){
1599         pCost->rCost = rTotal;
1600         pCost->nRow = nRow;
1601         pCost->plan.wsFlags = flags;
1602         pCost->plan.u.pTerm = pTerm;
1603       }
1604     }
1605   }
1606 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1607 }
1608 
1609 #ifndef SQLITE_OMIT_VIRTUALTABLE
1610 /*
1611 ** Allocate and populate an sqlite3_index_info structure. It is the
1612 ** responsibility of the caller to eventually release the structure
1613 ** by passing the pointer returned by this function to sqlite3_free().
1614 */
1615 static sqlite3_index_info *allocateIndexInfo(
1616   Parse *pParse,
1617   WhereClause *pWC,
1618   struct SrcList_item *pSrc,
1619   ExprList *pOrderBy
1620 ){
1621   int i, j;
1622   int nTerm;
1623   struct sqlite3_index_constraint *pIdxCons;
1624   struct sqlite3_index_orderby *pIdxOrderBy;
1625   struct sqlite3_index_constraint_usage *pUsage;
1626   WhereTerm *pTerm;
1627   int nOrderBy;
1628   sqlite3_index_info *pIdxInfo;
1629 
1630   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
1631 
1632   /* Count the number of possible WHERE clause constraints referring
1633   ** to this virtual table */
1634   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1635     if( pTerm->leftCursor != pSrc->iCursor ) continue;
1636     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
1637     testcase( pTerm->eOperator==WO_IN );
1638     testcase( pTerm->eOperator==WO_ISNULL );
1639     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
1640     nTerm++;
1641   }
1642 
1643   /* If the ORDER BY clause contains only columns in the current
1644   ** virtual table then allocate space for the aOrderBy part of
1645   ** the sqlite3_index_info structure.
1646   */
1647   nOrderBy = 0;
1648   if( pOrderBy ){
1649     for(i=0; i<pOrderBy->nExpr; i++){
1650       Expr *pExpr = pOrderBy->a[i].pExpr;
1651       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1652     }
1653     if( i==pOrderBy->nExpr ){
1654       nOrderBy = pOrderBy->nExpr;
1655     }
1656   }
1657 
1658   /* Allocate the sqlite3_index_info structure
1659   */
1660   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1661                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1662                            + sizeof(*pIdxOrderBy)*nOrderBy );
1663   if( pIdxInfo==0 ){
1664     sqlite3ErrorMsg(pParse, "out of memory");
1665     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1666     return 0;
1667   }
1668 
1669   /* Initialize the structure.  The sqlite3_index_info structure contains
1670   ** many fields that are declared "const" to prevent xBestIndex from
1671   ** changing them.  We have to do some funky casting in order to
1672   ** initialize those fields.
1673   */
1674   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1675   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1676   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1677   *(int*)&pIdxInfo->nConstraint = nTerm;
1678   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1679   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1680   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1681   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1682                                                                    pUsage;
1683 
1684   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1685     if( pTerm->leftCursor != pSrc->iCursor ) continue;
1686     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
1687     testcase( pTerm->eOperator==WO_IN );
1688     testcase( pTerm->eOperator==WO_ISNULL );
1689     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
1690     pIdxCons[j].iColumn = pTerm->u.leftColumn;
1691     pIdxCons[j].iTermOffset = i;
1692     pIdxCons[j].op = (u8)pTerm->eOperator;
1693     /* The direct assignment in the previous line is possible only because
1694     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
1695     ** following asserts verify this fact. */
1696     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1697     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1698     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1699     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1700     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1701     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
1702     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
1703     j++;
1704   }
1705   for(i=0; i<nOrderBy; i++){
1706     Expr *pExpr = pOrderBy->a[i].pExpr;
1707     pIdxOrderBy[i].iColumn = pExpr->iColumn;
1708     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1709   }
1710 
1711   return pIdxInfo;
1712 }
1713 
1714 /*
1715 ** The table object reference passed as the second argument to this function
1716 ** must represent a virtual table. This function invokes the xBestIndex()
1717 ** method of the virtual table with the sqlite3_index_info pointer passed
1718 ** as the argument.
1719 **
1720 ** If an error occurs, pParse is populated with an error message and a
1721 ** non-zero value is returned. Otherwise, 0 is returned and the output
1722 ** part of the sqlite3_index_info structure is left populated.
1723 **
1724 ** Whether or not an error is returned, it is the responsibility of the
1725 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1726 ** that this is required.
1727 */
1728 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
1729   sqlite3_vtab *pVtab = pTab->pVtab;
1730   int i;
1731   int rc;
1732 
1733   (void)sqlite3SafetyOff(pParse->db);
1734   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
1735   TRACE_IDX_INPUTS(p);
1736   rc = pVtab->pModule->xBestIndex(pVtab, p);
1737   TRACE_IDX_OUTPUTS(p);
1738   (void)sqlite3SafetyOn(pParse->db);
1739 
1740   if( rc!=SQLITE_OK ){
1741     if( rc==SQLITE_NOMEM ){
1742       pParse->db->mallocFailed = 1;
1743     }else if( !pVtab->zErrMsg ){
1744       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1745     }else{
1746       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1747     }
1748   }
1749   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
1750   pVtab->zErrMsg = 0;
1751 
1752   for(i=0; i<p->nConstraint; i++){
1753     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
1754       sqlite3ErrorMsg(pParse,
1755           "table %s: xBestIndex returned an invalid plan", pTab->zName);
1756     }
1757   }
1758 
1759   return pParse->nErr;
1760 }
1761 
1762 
1763 /*
1764 ** Compute the best index for a virtual table.
1765 **
1766 ** The best index is computed by the xBestIndex method of the virtual
1767 ** table module.  This routine is really just a wrapper that sets up
1768 ** the sqlite3_index_info structure that is used to communicate with
1769 ** xBestIndex.
1770 **
1771 ** In a join, this routine might be called multiple times for the
1772 ** same virtual table.  The sqlite3_index_info structure is created
1773 ** and initialized on the first invocation and reused on all subsequent
1774 ** invocations.  The sqlite3_index_info structure is also used when
1775 ** code is generated to access the virtual table.  The whereInfoDelete()
1776 ** routine takes care of freeing the sqlite3_index_info structure after
1777 ** everybody has finished with it.
1778 */
1779 static void bestVirtualIndex(
1780   Parse *pParse,                  /* The parsing context */
1781   WhereClause *pWC,               /* The WHERE clause */
1782   struct SrcList_item *pSrc,      /* The FROM clause term to search */
1783   Bitmask notReady,               /* Mask of cursors that are not available */
1784   ExprList *pOrderBy,             /* The order by clause */
1785   WhereCost *pCost,               /* Lowest cost query plan */
1786   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
1787 ){
1788   Table *pTab = pSrc->pTab;
1789   sqlite3_index_info *pIdxInfo;
1790   struct sqlite3_index_constraint *pIdxCons;
1791   struct sqlite3_index_constraint_usage *pUsage;
1792   WhereTerm *pTerm;
1793   int i, j;
1794   int nOrderBy;
1795 
1796   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
1797   ** malloc in allocateIndexInfo() fails and this function returns leaving
1798   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
1799   */
1800   memset(pCost, 0, sizeof(*pCost));
1801   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
1802 
1803   /* If the sqlite3_index_info structure has not been previously
1804   ** allocated and initialized, then allocate and initialize it now.
1805   */
1806   pIdxInfo = *ppIdxInfo;
1807   if( pIdxInfo==0 ){
1808     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
1809   }
1810   if( pIdxInfo==0 ){
1811     return;
1812   }
1813 
1814   /* At this point, the sqlite3_index_info structure that pIdxInfo points
1815   ** to will have been initialized, either during the current invocation or
1816   ** during some prior invocation.  Now we just have to customize the
1817   ** details of pIdxInfo for the current invocation and pass it to
1818   ** xBestIndex.
1819   */
1820 
1821   /* The module name must be defined. Also, by this point there must
1822   ** be a pointer to an sqlite3_vtab structure. Otherwise
1823   ** sqlite3ViewGetColumnNames() would have picked up the error.
1824   */
1825   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
1826   assert( pTab->pVtab );
1827 
1828   /* Set the aConstraint[].usable fields and initialize all
1829   ** output variables to zero.
1830   **
1831   ** aConstraint[].usable is true for constraints where the right-hand
1832   ** side contains only references to tables to the left of the current
1833   ** table.  In other words, if the constraint is of the form:
1834   **
1835   **           column = expr
1836   **
1837   ** and we are evaluating a join, then the constraint on column is
1838   ** only valid if all tables referenced in expr occur to the left
1839   ** of the table containing column.
1840   **
1841   ** The aConstraints[] array contains entries for all constraints
1842   ** on the current table.  That way we only have to compute it once
1843   ** even though we might try to pick the best index multiple times.
1844   ** For each attempt at picking an index, the order of tables in the
1845   ** join might be different so we have to recompute the usable flag
1846   ** each time.
1847   */
1848   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
1849   pUsage = pIdxInfo->aConstraintUsage;
1850   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
1851     j = pIdxCons->iTermOffset;
1852     pTerm = &pWC->a[j];
1853     pIdxCons->usable =  (pTerm->prereqRight & notReady)==0 ?1:0;
1854   }
1855   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
1856   if( pIdxInfo->needToFreeIdxStr ){
1857     sqlite3_free(pIdxInfo->idxStr);
1858   }
1859   pIdxInfo->idxStr = 0;
1860   pIdxInfo->idxNum = 0;
1861   pIdxInfo->needToFreeIdxStr = 0;
1862   pIdxInfo->orderByConsumed = 0;
1863   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
1864   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
1865   nOrderBy = pIdxInfo->nOrderBy;
1866   if( !pOrderBy ){
1867     pIdxInfo->nOrderBy = 0;
1868   }
1869 
1870   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
1871     return;
1872   }
1873 
1874   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
1875   ** inital value of lowestCost in this loop. If it is, then the
1876   ** (cost<lowestCost) test below will never be true.
1877   **
1878   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
1879   ** is defined.
1880   */
1881   if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
1882     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
1883   }else{
1884     pCost->rCost = pIdxInfo->estimatedCost;
1885   }
1886   pCost->plan.u.pVtabIdx = pIdxInfo;
1887   if( pIdxInfo->orderByConsumed ){
1888     pCost->plan.wsFlags |= WHERE_ORDERBY;
1889   }
1890   pCost->plan.nEq = 0;
1891   pIdxInfo->nOrderBy = nOrderBy;
1892 
1893   /* Try to find a more efficient access pattern by using multiple indexes
1894   ** to optimize an OR expression within the WHERE clause.
1895   */
1896   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
1897 }
1898 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1899 
1900 /*
1901 ** Find the query plan for accessing a particular table.  Write the
1902 ** best query plan and its cost into the WhereCost object supplied as the
1903 ** last parameter.
1904 **
1905 ** The lowest cost plan wins.  The cost is an estimate of the amount of
1906 ** CPU and disk I/O need to process the request using the selected plan.
1907 ** Factors that influence cost include:
1908 **
1909 **    *  The estimated number of rows that will be retrieved.  (The
1910 **       fewer the better.)
1911 **
1912 **    *  Whether or not sorting must occur.
1913 **
1914 **    *  Whether or not there must be separate lookups in the
1915 **       index and in the main table.
1916 **
1917 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
1918 ** the SQL statement, then this function only considers plans using the
1919 ** named index. If no such plan is found, then the returned cost is
1920 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
1921 ** then the cost is calculated in the usual way.
1922 **
1923 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
1924 ** in the SELECT statement, then no indexes are considered. However, the
1925 ** selected plan may still take advantage of the tables built-in rowid
1926 ** index.
1927 */
1928 static void bestBtreeIndex(
1929   Parse *pParse,              /* The parsing context */
1930   WhereClause *pWC,           /* The WHERE clause */
1931   struct SrcList_item *pSrc,  /* The FROM clause term to search */
1932   Bitmask notReady,           /* Mask of cursors that are not available */
1933   ExprList *pOrderBy,         /* The ORDER BY clause */
1934   WhereCost *pCost            /* Lowest cost query plan */
1935 ){
1936   WhereTerm *pTerm;           /* A single term of the WHERE clause */
1937   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
1938   Index *pProbe;              /* An index we are evaluating */
1939   int rev;                    /* True to scan in reverse order */
1940   int wsFlags;                /* Flags associated with pProbe */
1941   int nEq;                    /* Number of == or IN constraints */
1942   int eqTermMask;             /* Mask of valid equality operators */
1943   double cost;                /* Cost of using pProbe */
1944   double nRow;                /* Estimated number of rows in result set */
1945   int i;                      /* Loop counter */
1946 
1947   WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
1948   pProbe = pSrc->pTab->pIndex;
1949   if( pSrc->notIndexed ){
1950     pProbe = 0;
1951   }
1952 
1953   /* If the table has no indices and there are no terms in the where
1954   ** clause that refer to the ROWID, then we will never be able to do
1955   ** anything other than a full table scan on this table.  We might as
1956   ** well put it first in the join order.  That way, perhaps it can be
1957   ** referenced by other tables in the join.
1958   */
1959   memset(pCost, 0, sizeof(*pCost));
1960   if( pProbe==0 &&
1961      findTerm(pWC, iCur, -1, 0, WO_EQ|WO_IN|WO_LT|WO_LE|WO_GT|WO_GE,0)==0 &&
1962      (pOrderBy==0 || !sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev)) ){
1963      if( pParse->db->flags & SQLITE_ReverseOrder ){
1964       /* For application testing, randomly reverse the output order for
1965       ** SELECT statements that omit the ORDER BY clause.  This will help
1966       ** to find cases where
1967       */
1968       pCost->plan.wsFlags |= WHERE_REVERSE;
1969     }
1970     return;
1971   }
1972   pCost->rCost = SQLITE_BIG_DBL;
1973 
1974   /* Check for a rowid=EXPR or rowid IN (...) constraints. If there was
1975   ** an INDEXED BY clause attached to this table, skip this step.
1976   */
1977   if( !pSrc->pIndex ){
1978     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
1979     if( pTerm ){
1980       Expr *pExpr;
1981       pCost->plan.wsFlags = WHERE_ROWID_EQ;
1982       if( pTerm->eOperator & WO_EQ ){
1983         /* Rowid== is always the best pick.  Look no further.  Because only
1984         ** a single row is generated, output is always in sorted order */
1985         pCost->plan.wsFlags = WHERE_ROWID_EQ | WHERE_UNIQUE;
1986         pCost->plan.nEq = 1;
1987         WHERETRACE(("... best is rowid\n"));
1988         pCost->rCost = 0;
1989         pCost->nRow = 1;
1990         return;
1991       }else if( !ExprHasProperty((pExpr = pTerm->pExpr), EP_xIsSelect)
1992              && pExpr->x.pList
1993       ){
1994         /* Rowid IN (LIST): cost is NlogN where N is the number of list
1995         ** elements.  */
1996         pCost->rCost = pCost->nRow = pExpr->x.pList->nExpr;
1997         pCost->rCost *= estLog(pCost->rCost);
1998       }else{
1999         /* Rowid IN (SELECT): cost is NlogN where N is the number of rows
2000         ** in the result of the inner select.  We have no way to estimate
2001         ** that value so make a wild guess. */
2002         pCost->nRow = 100;
2003         pCost->rCost = 200;
2004       }
2005       WHERETRACE(("... rowid IN cost: %.9g\n", pCost->rCost));
2006     }
2007 
2008     /* Estimate the cost of a table scan.  If we do not know how many
2009     ** entries are in the table, use 1 million as a guess.
2010     */
2011     cost = pProbe ? pProbe->aiRowEst[0] : 1000000;
2012     WHERETRACE(("... table scan base cost: %.9g\n", cost));
2013     wsFlags = WHERE_ROWID_RANGE;
2014 
2015     /* Check for constraints on a range of rowids in a table scan.
2016     */
2017     pTerm = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE|WO_GT|WO_GE, 0);
2018     if( pTerm ){
2019       if( findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0) ){
2020         wsFlags |= WHERE_TOP_LIMIT;
2021         cost /= 3;  /* Guess that rowid<EXPR eliminates two-thirds of rows */
2022       }
2023       if( findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0) ){
2024         wsFlags |= WHERE_BTM_LIMIT;
2025         cost /= 3;  /* Guess that rowid>EXPR eliminates two-thirds of rows */
2026       }
2027       WHERETRACE(("... rowid range reduces cost to %.9g\n", cost));
2028     }else{
2029       wsFlags = 0;
2030     }
2031     nRow = cost;
2032 
2033     /* If the table scan does not satisfy the ORDER BY clause, increase
2034     ** the cost by NlogN to cover the expense of sorting. */
2035     if( pOrderBy ){
2036       if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) ){
2037         wsFlags |= WHERE_ORDERBY|WHERE_ROWID_RANGE;
2038         if( rev ){
2039           wsFlags |= WHERE_REVERSE;
2040         }
2041       }else{
2042         cost += cost*estLog(cost);
2043         WHERETRACE(("... sorting increases cost to %.9g\n", cost));
2044       }
2045     }else if( pParse->db->flags & SQLITE_ReverseOrder ){
2046       /* For application testing, randomly reverse the output order for
2047       ** SELECT statements that omit the ORDER BY clause.  This will help
2048       ** to find cases where
2049       */
2050       wsFlags |= WHERE_REVERSE;
2051     }
2052 
2053     /* Remember this case if it is the best so far */
2054     if( cost<pCost->rCost ){
2055       pCost->rCost = cost;
2056       pCost->nRow = nRow;
2057       pCost->plan.wsFlags = wsFlags;
2058     }
2059   }
2060 
2061   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
2062 
2063   /* If the pSrc table is the right table of a LEFT JOIN then we may not
2064   ** use an index to satisfy IS NULL constraints on that table.  This is
2065   ** because columns might end up being NULL if the table does not match -
2066   ** a circumstance which the index cannot help us discover.  Ticket #2177.
2067   */
2068   if( (pSrc->jointype & JT_LEFT)!=0 ){
2069     eqTermMask = WO_EQ|WO_IN;
2070   }else{
2071     eqTermMask = WO_EQ|WO_IN|WO_ISNULL;
2072   }
2073 
2074   /* Look at each index.
2075   */
2076   if( pSrc->pIndex ){
2077     pProbe = pSrc->pIndex;
2078   }
2079   for(; pProbe; pProbe=(pSrc->pIndex ? 0 : pProbe->pNext)){
2080     double inMultiplier = 1;  /* Number of equality look-ups needed */
2081     int inMultIsEst = 0;      /* True if inMultiplier is an estimate */
2082 
2083     WHERETRACE(("... index %s:\n", pProbe->zName));
2084 
2085     /* Count the number of columns in the index that are satisfied
2086     ** by x=EXPR or x IS NULL constraints or x IN (...) constraints.
2087     ** For a term of the form x=EXPR or x IS NULL we only have to do
2088     ** a single binary search.  But for x IN (...) we have to do a
2089     ** number of binary searched
2090     ** equal to the number of entries on the RHS of the IN operator.
2091     ** The inMultipler variable with try to estimate the number of
2092     ** binary searches needed.
2093     */
2094     wsFlags = 0;
2095     for(i=0; i<pProbe->nColumn; i++){
2096       int j = pProbe->aiColumn[i];
2097       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pProbe);
2098       if( pTerm==0 ) break;
2099       wsFlags |= WHERE_COLUMN_EQ;
2100       if( pTerm->eOperator & WO_IN ){
2101         Expr *pExpr = pTerm->pExpr;
2102         wsFlags |= WHERE_COLUMN_IN;
2103         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2104           inMultiplier *= 25;
2105           inMultIsEst = 1;
2106         }else if( pExpr->x.pList ){
2107           inMultiplier *= pExpr->x.pList->nExpr + 1;
2108         }
2109       }else if( pTerm->eOperator & WO_ISNULL ){
2110         wsFlags |= WHERE_COLUMN_NULL;
2111       }
2112     }
2113     nRow = pProbe->aiRowEst[i] * inMultiplier;
2114     /* If inMultiplier is an estimate and that estimate results in an
2115     ** nRow it that is more than half number of rows in the table,
2116     ** then reduce inMultipler */
2117     if( inMultIsEst && nRow*2 > pProbe->aiRowEst[0] ){
2118       nRow = pProbe->aiRowEst[0]/2;
2119       inMultiplier = nRow/pProbe->aiRowEst[i];
2120     }
2121     cost = nRow + inMultiplier*estLog(pProbe->aiRowEst[0]);
2122     nEq = i;
2123     if( pProbe->onError!=OE_None && nEq==pProbe->nColumn ){
2124       testcase( wsFlags & WHERE_COLUMN_IN );
2125       testcase( wsFlags & WHERE_COLUMN_NULL );
2126       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
2127         wsFlags |= WHERE_UNIQUE;
2128       }
2129     }
2130     WHERETRACE(("...... nEq=%d inMult=%.9g nRow=%.9g cost=%.9g\n",
2131                 nEq, inMultiplier, nRow, cost));
2132 
2133     /* Look for range constraints.  Assume that each range constraint
2134     ** makes the search space 1/3rd smaller.
2135     */
2136     if( nEq<pProbe->nColumn ){
2137       int j = pProbe->aiColumn[nEq];
2138       pTerm = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pProbe);
2139       if( pTerm ){
2140         wsFlags |= WHERE_COLUMN_RANGE;
2141         if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pProbe) ){
2142           wsFlags |= WHERE_TOP_LIMIT;
2143           cost /= 3;
2144           nRow /= 3;
2145         }
2146         if( findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pProbe) ){
2147           wsFlags |= WHERE_BTM_LIMIT;
2148           cost /= 3;
2149           nRow /= 3;
2150         }
2151         WHERETRACE(("...... range reduces nRow to %.9g and cost to %.9g\n",
2152                     nRow, cost));
2153       }
2154     }
2155 
2156     /* Add the additional cost of sorting if that is a factor.
2157     */
2158     if( pOrderBy ){
2159       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
2160        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
2161       ){
2162         if( wsFlags==0 ){
2163           wsFlags = WHERE_COLUMN_RANGE;
2164         }
2165         wsFlags |= WHERE_ORDERBY;
2166         if( rev ){
2167           wsFlags |= WHERE_REVERSE;
2168         }
2169       }else{
2170         cost += cost*estLog(cost);
2171         WHERETRACE(("...... orderby increases cost to %.9g\n", cost));
2172       }
2173     }else if( wsFlags!=0 && (pParse->db->flags & SQLITE_ReverseOrder)!=0 ){
2174       /* For application testing, randomly reverse the output order for
2175       ** SELECT statements that omit the ORDER BY clause.  This will help
2176       ** to find cases where
2177       */
2178       wsFlags |= WHERE_REVERSE;
2179     }
2180 
2181     /* Check to see if we can get away with using just the index without
2182     ** ever reading the table.  If that is the case, then halve the
2183     ** cost of this index.
2184     */
2185     if( wsFlags && pSrc->colUsed < (((Bitmask)1)<<(BMS-1)) ){
2186       Bitmask m = pSrc->colUsed;
2187       int j;
2188       for(j=0; j<pProbe->nColumn; j++){
2189         int x = pProbe->aiColumn[j];
2190         if( x<BMS-1 ){
2191           m &= ~(((Bitmask)1)<<x);
2192         }
2193       }
2194       if( m==0 ){
2195         wsFlags |= WHERE_IDX_ONLY;
2196         cost /= 2;
2197         WHERETRACE(("...... idx-only reduces cost to %.9g\n", cost));
2198       }
2199     }
2200 
2201     /* If this index has achieved the lowest cost so far, then use it.
2202     */
2203     if( wsFlags!=0 && cost < pCost->rCost ){
2204       pCost->rCost = cost;
2205       pCost->nRow = nRow;
2206       pCost->plan.wsFlags = wsFlags;
2207       pCost->plan.nEq = nEq;
2208       assert( pCost->plan.wsFlags & WHERE_INDEXED );
2209       pCost->plan.u.pIdx = pProbe;
2210     }
2211   }
2212 
2213   /* Report the best result
2214   */
2215   pCost->plan.wsFlags |= eqTermMask;
2216   WHERETRACE(("best index is %s, cost=%.9g, nrow=%.9g, wsFlags=%x, nEq=%d\n",
2217         (pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
2218              pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
2219         pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
2220 }
2221 
2222 /*
2223 ** Find the query plan for accessing table pSrc->pTab. Write the
2224 ** best query plan and its cost into the WhereCost object supplied
2225 ** as the last parameter. This function may calculate the cost of
2226 ** both real and virtual table scans.
2227 */
2228 static void bestIndex(
2229   Parse *pParse,              /* The parsing context */
2230   WhereClause *pWC,           /* The WHERE clause */
2231   struct SrcList_item *pSrc,  /* The FROM clause term to search */
2232   Bitmask notReady,           /* Mask of cursors that are not available */
2233   ExprList *pOrderBy,         /* The ORDER BY clause */
2234   WhereCost *pCost            /* Lowest cost query plan */
2235 ){
2236 #ifndef SQLITE_OMIT_VIRTUALTABLE
2237   if( IsVirtual(pSrc->pTab) ){
2238     sqlite3_index_info *p = 0;
2239     bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
2240     if( p->needToFreeIdxStr ){
2241       sqlite3_free(p->idxStr);
2242     }
2243     sqlite3DbFree(pParse->db, p);
2244   }else
2245 #endif
2246   {
2247     bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
2248   }
2249 }
2250 
2251 /*
2252 ** Disable a term in the WHERE clause.  Except, do not disable the term
2253 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2254 ** or USING clause of that join.
2255 **
2256 ** Consider the term t2.z='ok' in the following queries:
2257 **
2258 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2259 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2260 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2261 **
2262 ** The t2.z='ok' is disabled in the in (2) because it originates
2263 ** in the ON clause.  The term is disabled in (3) because it is not part
2264 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
2265 **
2266 ** Disabling a term causes that term to not be tested in the inner loop
2267 ** of the join.  Disabling is an optimization.  When terms are satisfied
2268 ** by indices, we disable them to prevent redundant tests in the inner
2269 ** loop.  We would get the correct results if nothing were ever disabled,
2270 ** but joins might run a little slower.  The trick is to disable as much
2271 ** as we can without disabling too much.  If we disabled in (1), we'd get
2272 ** the wrong answer.  See ticket #813.
2273 */
2274 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2275   if( pTerm
2276       && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
2277       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
2278   ){
2279     pTerm->wtFlags |= TERM_CODED;
2280     if( pTerm->iParent>=0 ){
2281       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2282       if( (--pOther->nChild)==0 ){
2283         disableTerm(pLevel, pOther);
2284       }
2285     }
2286   }
2287 }
2288 
2289 /*
2290 ** Apply the affinities associated with the first n columns of index
2291 ** pIdx to the values in the n registers starting at base.
2292 */
2293 static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){
2294   if( n>0 ){
2295     Vdbe *v = pParse->pVdbe;
2296     assert( v!=0 );
2297     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2298     sqlite3IndexAffinityStr(v, pIdx);
2299     sqlite3ExprCacheAffinityChange(pParse, base, n);
2300   }
2301 }
2302 
2303 
2304 /*
2305 ** Generate code for a single equality term of the WHERE clause.  An equality
2306 ** term can be either X=expr or X IN (...).   pTerm is the term to be
2307 ** coded.
2308 **
2309 ** The current value for the constraint is left in register iReg.
2310 **
2311 ** For a constraint of the form X=expr, the expression is evaluated and its
2312 ** result is left on the stack.  For constraints of the form X IN (...)
2313 ** this routine sets up a loop that will iterate over all values of X.
2314 */
2315 static int codeEqualityTerm(
2316   Parse *pParse,      /* The parsing context */
2317   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
2318   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
2319   int iTarget         /* Attempt to leave results in this register */
2320 ){
2321   Expr *pX = pTerm->pExpr;
2322   Vdbe *v = pParse->pVdbe;
2323   int iReg;                  /* Register holding results */
2324 
2325   assert( iTarget>0 );
2326   if( pX->op==TK_EQ ){
2327     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
2328   }else if( pX->op==TK_ISNULL ){
2329     iReg = iTarget;
2330     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
2331 #ifndef SQLITE_OMIT_SUBQUERY
2332   }else{
2333     int eType;
2334     int iTab;
2335     struct InLoop *pIn;
2336 
2337     assert( pX->op==TK_IN );
2338     iReg = iTarget;
2339     eType = sqlite3FindInIndex(pParse, pX, 0);
2340     iTab = pX->iTable;
2341     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
2342     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
2343     if( pLevel->u.in.nIn==0 ){
2344       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
2345     }
2346     pLevel->u.in.nIn++;
2347     pLevel->u.in.aInLoop =
2348        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2349                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2350     pIn = pLevel->u.in.aInLoop;
2351     if( pIn ){
2352       pIn += pLevel->u.in.nIn - 1;
2353       pIn->iCur = iTab;
2354       if( eType==IN_INDEX_ROWID ){
2355         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
2356       }else{
2357         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
2358       }
2359       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
2360     }else{
2361       pLevel->u.in.nIn = 0;
2362     }
2363 #endif
2364   }
2365   disableTerm(pLevel, pTerm);
2366   return iReg;
2367 }
2368 
2369 /*
2370 ** Generate code that will evaluate all == and IN constraints for an
2371 ** index.  The values for all constraints are left on the stack.
2372 **
2373 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2374 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
2375 ** The index has as many as three equality constraints, but in this
2376 ** example, the third "c" value is an inequality.  So only two
2377 ** constraints are coded.  This routine will generate code to evaluate
2378 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
2379 ** in consecutive registers and the index of the first register is returned.
2380 **
2381 ** In the example above nEq==2.  But this subroutine works for any value
2382 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
2383 ** The only thing it does is allocate the pLevel->iMem memory cell.
2384 **
2385 ** This routine always allocates at least one memory cell and returns
2386 ** the index of that memory cell. The code that
2387 ** calls this routine will use that memory cell to store the termination
2388 ** key value of the loop.  If one or more IN operators appear, then
2389 ** this routine allocates an additional nEq memory cells for internal
2390 ** use.
2391 */
2392 static int codeAllEqualityTerms(
2393   Parse *pParse,        /* Parsing context */
2394   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
2395   WhereClause *pWC,     /* The WHERE clause */
2396   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
2397   int nExtraReg         /* Number of extra registers to allocate */
2398 ){
2399   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
2400   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
2401   Index *pIdx;                  /* The index being used for this loop */
2402   int iCur = pLevel->iTabCur;   /* The cursor of the table */
2403   WhereTerm *pTerm;             /* A single constraint term */
2404   int j;                        /* Loop counter */
2405   int regBase;                  /* Base register */
2406   int nReg;                     /* Number of registers to allocate */
2407 
2408   /* This module is only called on query plans that use an index. */
2409   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
2410   pIdx = pLevel->plan.u.pIdx;
2411 
2412   /* Figure out how many memory cells we will need then allocate them.
2413   */
2414   regBase = pParse->nMem + 1;
2415   nReg = pLevel->plan.nEq + nExtraReg;
2416   pParse->nMem += nReg;
2417 
2418   /* Evaluate the equality constraints
2419   */
2420   assert( pIdx->nColumn>=nEq );
2421   for(j=0; j<nEq; j++){
2422     int r1;
2423     int k = pIdx->aiColumn[j];
2424     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
2425     if( NEVER(pTerm==0) ) break;
2426     assert( (pTerm->wtFlags & TERM_CODED)==0 );
2427     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
2428     if( r1!=regBase+j ){
2429       if( nReg==1 ){
2430         sqlite3ReleaseTempReg(pParse, regBase);
2431         regBase = r1;
2432       }else{
2433         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
2434       }
2435     }
2436     testcase( pTerm->eOperator & WO_ISNULL );
2437     testcase( pTerm->eOperator & WO_IN );
2438     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
2439       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
2440     }
2441   }
2442   return regBase;
2443 }
2444 
2445 /*
2446 ** Generate code for the start of the iLevel-th loop in the WHERE clause
2447 ** implementation described by pWInfo.
2448 */
2449 static Bitmask codeOneLoopStart(
2450   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
2451   int iLevel,          /* Which level of pWInfo->a[] should be coded */
2452   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
2453   Bitmask notReady     /* Which tables are currently available */
2454 ){
2455   int j, k;            /* Loop counters */
2456   int iCur;            /* The VDBE cursor for the table */
2457   int addrNxt;         /* Where to jump to continue with the next IN case */
2458   int omitTable;       /* True if we use the index only */
2459   int bRev;            /* True if we need to scan in reverse order */
2460   WhereLevel *pLevel;  /* The where level to be coded */
2461   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
2462   WhereTerm *pTerm;               /* A WHERE clause term */
2463   Parse *pParse;                  /* Parsing context */
2464   Vdbe *v;                        /* The prepared stmt under constructions */
2465   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
2466   int addrBrk;                    /* Jump here to break out of the loop */
2467   int addrCont;                   /* Jump here to continue with next cycle */
2468   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
2469   int iReleaseReg = 0;      /* Temp register to free before returning */
2470 
2471   pParse = pWInfo->pParse;
2472   v = pParse->pVdbe;
2473   pWC = pWInfo->pWC;
2474   pLevel = &pWInfo->a[iLevel];
2475   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
2476   iCur = pTabItem->iCursor;
2477   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
2478   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
2479            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
2480 
2481   /* Create labels for the "break" and "continue" instructions
2482   ** for the current loop.  Jump to addrBrk to break out of a loop.
2483   ** Jump to cont to go immediately to the next iteration of the
2484   ** loop.
2485   **
2486   ** When there is an IN operator, we also have a "addrNxt" label that
2487   ** means to continue with the next IN value combination.  When
2488   ** there are no IN operators in the constraints, the "addrNxt" label
2489   ** is the same as "addrBrk".
2490   */
2491   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
2492   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
2493 
2494   /* If this is the right table of a LEFT OUTER JOIN, allocate and
2495   ** initialize a memory cell that records if this table matches any
2496   ** row of the left table of the join.
2497   */
2498   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
2499     pLevel->iLeftJoin = ++pParse->nMem;
2500     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
2501     VdbeComment((v, "init LEFT JOIN no-match flag"));
2502   }
2503 
2504 #ifndef SQLITE_OMIT_VIRTUALTABLE
2505   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
2506     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
2507     **          to access the data.
2508     */
2509     int iReg;   /* P3 Value for OP_VFilter */
2510     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
2511     int nConstraint = pVtabIdx->nConstraint;
2512     struct sqlite3_index_constraint_usage *aUsage =
2513                                                 pVtabIdx->aConstraintUsage;
2514     const struct sqlite3_index_constraint *aConstraint =
2515                                                 pVtabIdx->aConstraint;
2516 
2517     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
2518     for(j=1; j<=nConstraint; j++){
2519       for(k=0; k<nConstraint; k++){
2520         if( aUsage[k].argvIndex==j ){
2521           int iTerm = aConstraint[k].iTermOffset;
2522           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
2523           break;
2524         }
2525       }
2526       if( k==nConstraint ) break;
2527     }
2528     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
2529     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
2530     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
2531                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
2532     pVtabIdx->needToFreeIdxStr = 0;
2533     for(j=0; j<nConstraint; j++){
2534       if( aUsage[j].omit ){
2535         int iTerm = aConstraint[j].iTermOffset;
2536         disableTerm(pLevel, &pWC->a[iTerm]);
2537       }
2538     }
2539     pLevel->op = OP_VNext;
2540     pLevel->p1 = iCur;
2541     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2542     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
2543   }else
2544 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2545 
2546   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
2547     /* Case 1:  We can directly reference a single row using an
2548     **          equality comparison against the ROWID field.  Or
2549     **          we reference multiple rows using a "rowid IN (...)"
2550     **          construct.
2551     */
2552     iReleaseReg = sqlite3GetTempReg(pParse);
2553     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
2554     assert( pTerm!=0 );
2555     assert( pTerm->pExpr!=0 );
2556     assert( pTerm->leftCursor==iCur );
2557     assert( omitTable==0 );
2558     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
2559     addrNxt = pLevel->addrNxt;
2560     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
2561     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
2562     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
2563     VdbeComment((v, "pk"));
2564     pLevel->op = OP_Noop;
2565   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
2566     /* Case 2:  We have an inequality comparison against the ROWID field.
2567     */
2568     int testOp = OP_Noop;
2569     int start;
2570     int memEndValue = 0;
2571     WhereTerm *pStart, *pEnd;
2572 
2573     assert( omitTable==0 );
2574     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
2575     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
2576     if( bRev ){
2577       pTerm = pStart;
2578       pStart = pEnd;
2579       pEnd = pTerm;
2580     }
2581     if( pStart ){
2582       Expr *pX;             /* The expression that defines the start bound */
2583       int r1, rTemp;        /* Registers for holding the start boundary */
2584 
2585       /* The following constant maps TK_xx codes into corresponding
2586       ** seek opcodes.  It depends on a particular ordering of TK_xx
2587       */
2588       const u8 aMoveOp[] = {
2589            /* TK_GT */  OP_SeekGt,
2590            /* TK_LE */  OP_SeekLe,
2591            /* TK_LT */  OP_SeekLt,
2592            /* TK_GE */  OP_SeekGe
2593       };
2594       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
2595       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
2596       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
2597 
2598       pX = pStart->pExpr;
2599       assert( pX!=0 );
2600       assert( pStart->leftCursor==iCur );
2601       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
2602       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
2603       VdbeComment((v, "pk"));
2604       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
2605       sqlite3ReleaseTempReg(pParse, rTemp);
2606       disableTerm(pLevel, pStart);
2607     }else{
2608       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
2609     }
2610     if( pEnd ){
2611       Expr *pX;
2612       pX = pEnd->pExpr;
2613       assert( pX!=0 );
2614       assert( pEnd->leftCursor==iCur );
2615       memEndValue = ++pParse->nMem;
2616       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
2617       if( pX->op==TK_LT || pX->op==TK_GT ){
2618         testOp = bRev ? OP_Le : OP_Ge;
2619       }else{
2620         testOp = bRev ? OP_Lt : OP_Gt;
2621       }
2622       disableTerm(pLevel, pEnd);
2623     }
2624     start = sqlite3VdbeCurrentAddr(v);
2625     pLevel->op = bRev ? OP_Prev : OP_Next;
2626     pLevel->p1 = iCur;
2627     pLevel->p2 = start;
2628     pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
2629     if( testOp!=OP_Noop ){
2630       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
2631       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
2632       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
2633       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
2634       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
2635     }
2636   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
2637     /* Case 3: A scan using an index.
2638     **
2639     **         The WHERE clause may contain zero or more equality
2640     **         terms ("==" or "IN" operators) that refer to the N
2641     **         left-most columns of the index. It may also contain
2642     **         inequality constraints (>, <, >= or <=) on the indexed
2643     **         column that immediately follows the N equalities. Only
2644     **         the right-most column can be an inequality - the rest must
2645     **         use the "==" and "IN" operators. For example, if the
2646     **         index is on (x,y,z), then the following clauses are all
2647     **         optimized:
2648     **
2649     **            x=5
2650     **            x=5 AND y=10
2651     **            x=5 AND y<10
2652     **            x=5 AND y>5 AND y<10
2653     **            x=5 AND y=5 AND z<=10
2654     **
2655     **         The z<10 term of the following cannot be used, only
2656     **         the x=5 term:
2657     **
2658     **            x=5 AND z<10
2659     **
2660     **         N may be zero if there are inequality constraints.
2661     **         If there are no inequality constraints, then N is at
2662     **         least one.
2663     **
2664     **         This case is also used when there are no WHERE clause
2665     **         constraints but an index is selected anyway, in order
2666     **         to force the output order to conform to an ORDER BY.
2667     */
2668     int aStartOp[] = {
2669       0,
2670       0,
2671       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
2672       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
2673       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
2674       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
2675       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
2676       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
2677     };
2678     int aEndOp[] = {
2679       OP_Noop,             /* 0: (!end_constraints) */
2680       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
2681       OP_IdxLT             /* 2: (end_constraints && bRev) */
2682     };
2683     int nEq = pLevel->plan.nEq;
2684     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
2685     int regBase;                 /* Base register holding constraint values */
2686     int r1;                      /* Temp register */
2687     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
2688     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
2689     int startEq;                 /* True if range start uses ==, >= or <= */
2690     int endEq;                   /* True if range end uses ==, >= or <= */
2691     int start_constraints;       /* Start of range is constrained */
2692     int nConstraint;             /* Number of constraint terms */
2693     Index *pIdx;         /* The index we will be using */
2694     int iIdxCur;         /* The VDBE cursor for the index */
2695     int nExtraReg = 0;   /* Number of extra registers needed */
2696     int op;              /* Instruction opcode */
2697 
2698     pIdx = pLevel->plan.u.pIdx;
2699     iIdxCur = pLevel->iIdxCur;
2700     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
2701 
2702     /* If this loop satisfies a sort order (pOrderBy) request that
2703     ** was passed to this function to implement a "SELECT min(x) ..."
2704     ** query, then the caller will only allow the loop to run for
2705     ** a single iteration. This means that the first row returned
2706     ** should not have a NULL value stored in 'x'. If column 'x' is
2707     ** the first one after the nEq equality constraints in the index,
2708     ** this requires some special handling.
2709     */
2710     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
2711      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
2712      && (pIdx->nColumn>nEq)
2713     ){
2714       /* assert( pOrderBy->nExpr==1 ); */
2715       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
2716       isMinQuery = 1;
2717       nExtraReg = 1;
2718     }
2719 
2720     /* Find any inequality constraint terms for the start and end
2721     ** of the range.
2722     */
2723     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
2724       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
2725       nExtraReg = 1;
2726     }
2727     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
2728       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
2729       nExtraReg = 1;
2730     }
2731 
2732     /* Generate code to evaluate all constraint terms using == or IN
2733     ** and store the values of those terms in an array of registers
2734     ** starting at regBase.
2735     */
2736     regBase = codeAllEqualityTerms(pParse, pLevel, pWC, notReady, nExtraReg);
2737     addrNxt = pLevel->addrNxt;
2738 
2739 
2740     /* If we are doing a reverse order scan on an ascending index, or
2741     ** a forward order scan on a descending index, interchange the
2742     ** start and end terms (pRangeStart and pRangeEnd).
2743     */
2744     if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
2745       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
2746     }
2747 
2748     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
2749     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
2750     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
2751     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
2752     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
2753     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
2754     start_constraints = pRangeStart || nEq>0;
2755 
2756     /* Seek the index cursor to the start of the range. */
2757     nConstraint = nEq;
2758     if( pRangeStart ){
2759       sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
2760       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
2761       nConstraint++;
2762     }else if( isMinQuery ){
2763       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
2764       nConstraint++;
2765       startEq = 0;
2766       start_constraints = 1;
2767     }
2768     codeApplyAffinity(pParse, regBase, nConstraint, pIdx);
2769     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
2770     assert( op!=0 );
2771     testcase( op==OP_Rewind );
2772     testcase( op==OP_Last );
2773     testcase( op==OP_SeekGt );
2774     testcase( op==OP_SeekGe );
2775     testcase( op==OP_SeekLe );
2776     testcase( op==OP_SeekLt );
2777     sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
2778                       SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
2779 
2780     /* Load the value for the inequality constraint at the end of the
2781     ** range (if any).
2782     */
2783     nConstraint = nEq;
2784     if( pRangeEnd ){
2785       sqlite3ExprCacheRemove(pParse, regBase+nEq);
2786       sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
2787       sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
2788       codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
2789       nConstraint++;
2790     }
2791 
2792     /* Top of the loop body */
2793     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2794 
2795     /* Check if the index cursor is past the end of the range. */
2796     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
2797     testcase( op==OP_Noop );
2798     testcase( op==OP_IdxGE );
2799     testcase( op==OP_IdxLT );
2800     if( op!=OP_Noop ){
2801       sqlite3VdbeAddOp4(v, op, iIdxCur, addrNxt, regBase,
2802                         SQLITE_INT_TO_PTR(nConstraint), P4_INT32);
2803       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
2804     }
2805 
2806     /* If there are inequality constraints, check that the value
2807     ** of the table column that the inequality contrains is not NULL.
2808     ** If it is, jump to the next iteration of the loop.
2809     */
2810     r1 = sqlite3GetTempReg(pParse);
2811     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
2812     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
2813     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
2814       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
2815       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
2816     }
2817     sqlite3ReleaseTempReg(pParse, r1);
2818 
2819     /* Seek the table cursor, if required */
2820     disableTerm(pLevel, pRangeStart);
2821     disableTerm(pLevel, pRangeEnd);
2822     if( !omitTable ){
2823       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
2824       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
2825       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
2826       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
2827     }
2828 
2829     /* Record the instruction used to terminate the loop. Disable
2830     ** WHERE clause terms made redundant by the index range scan.
2831     */
2832     pLevel->op = bRev ? OP_Prev : OP_Next;
2833     pLevel->p1 = iIdxCur;
2834   }else
2835 
2836 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
2837   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
2838     /* Case 4:  Two or more separately indexed terms connected by OR
2839     **
2840     ** Example:
2841     **
2842     **   CREATE TABLE t1(a,b,c,d);
2843     **   CREATE INDEX i1 ON t1(a);
2844     **   CREATE INDEX i2 ON t1(b);
2845     **   CREATE INDEX i3 ON t1(c);
2846     **
2847     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
2848     **
2849     ** In the example, there are three indexed terms connected by OR.
2850     ** The top of the loop looks like this:
2851     **
2852     **          Null       1                # Zero the rowset in reg 1
2853     **
2854     ** Then, for each indexed term, the following. The arguments to
2855     ** RowSetTest are such that the rowid of the current row is inserted
2856     ** into the RowSet. If it is already present, control skips the
2857     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
2858     **
2859     **        sqlite3WhereBegin(<term>)
2860     **          RowSetTest                  # Insert rowid into rowset
2861     **          Gosub      2 A
2862     **        sqlite3WhereEnd()
2863     **
2864     ** Following the above, code to terminate the loop. Label A, the target
2865     ** of the Gosub above, jumps to the instruction right after the Goto.
2866     **
2867     **          Null       1                # Zero the rowset in reg 1
2868     **          Goto       B                # The loop is finished.
2869     **
2870     **       A: <loop body>                 # Return data, whatever.
2871     **
2872     **          Return     2                # Jump back to the Gosub
2873     **
2874     **       B: <after the loop>
2875     **
2876     */
2877     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
2878     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
2879     SrcList oneTab;        /* Shortened table list */
2880 
2881     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
2882     int regRowset = 0;                        /* Register for RowSet object */
2883     int regRowid = 0;                         /* Register holding rowid */
2884     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
2885     int iRetInit;                             /* Address of regReturn init */
2886     int ii;
2887 
2888     pTerm = pLevel->plan.u.pTerm;
2889     assert( pTerm!=0 );
2890     assert( pTerm->eOperator==WO_OR );
2891     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
2892     pOrWc = &pTerm->u.pOrInfo->wc;
2893     pFinal = &pOrWc->a[pOrWc->nTerm-1];
2894 
2895     /* Set up a SrcList containing just the table being scanned by this loop. */
2896     oneTab.nSrc = 1;
2897     oneTab.nAlloc = 1;
2898     oneTab.a[0] = *pTabItem;
2899 
2900     /* Initialize the rowset register to contain NULL. An SQL NULL is
2901     ** equivalent to an empty rowset.
2902     **
2903     ** Also initialize regReturn to contain the address of the instruction
2904     ** immediately following the OP_Return at the bottom of the loop. This
2905     ** is required in a few obscure LEFT JOIN cases where control jumps
2906     ** over the top of the loop into the body of it. In this case the
2907     ** correct response for the end-of-loop code (the OP_Return) is to
2908     ** fall through to the next instruction, just as an OP_Next does if
2909     ** called on an uninitialized cursor.
2910     */
2911     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
2912       regRowset = ++pParse->nMem;
2913       regRowid = ++pParse->nMem;
2914       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
2915     }
2916     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
2917 
2918     for(ii=0; ii<pOrWc->nTerm; ii++){
2919       WhereTerm *pOrTerm = &pOrWc->a[ii];
2920       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
2921         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
2922         /* Loop through table entries that match term pOrTerm. */
2923         pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
2924                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE | WHERE_FORCE_TABLE);
2925         if( pSubWInfo ){
2926           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
2927             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
2928             int r;
2929             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
2930                                          regRowid, 0);
2931             sqlite3VdbeAddOp4(v, OP_RowSetTest, regRowset,
2932                               sqlite3VdbeCurrentAddr(v)+2,
2933                               r, SQLITE_INT_TO_PTR(iSet), P4_INT32);
2934           }
2935           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
2936 
2937           /* Finish the loop through table entries that match term pOrTerm. */
2938           sqlite3WhereEnd(pSubWInfo);
2939         }
2940       }
2941     }
2942     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
2943     /* sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); */
2944     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
2945     sqlite3VdbeResolveLabel(v, iLoopBody);
2946 
2947     pLevel->op = OP_Return;
2948     pLevel->p1 = regReturn;
2949     disableTerm(pLevel, pTerm);
2950   }else
2951 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
2952 
2953   {
2954     /* Case 5:  There is no usable index.  We must do a complete
2955     **          scan of the entire table.
2956     */
2957     static const u8 aStep[] = { OP_Next, OP_Prev };
2958     static const u8 aStart[] = { OP_Rewind, OP_Last };
2959     assert( bRev==0 || bRev==1 );
2960     assert( omitTable==0 );
2961     pLevel->op = aStep[bRev];
2962     pLevel->p1 = iCur;
2963     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
2964     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
2965   }
2966   notReady &= ~getMask(pWC->pMaskSet, iCur);
2967 
2968   /* Insert code to test every subexpression that can be completely
2969   ** computed using the current set of tables.
2970   */
2971   k = 0;
2972   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
2973     Expr *pE;
2974     testcase( pTerm->wtFlags & TERM_VIRTUAL );
2975     testcase( pTerm->wtFlags & TERM_CODED );
2976     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
2977     if( (pTerm->prereqAll & notReady)!=0 ) continue;
2978     pE = pTerm->pExpr;
2979     assert( pE!=0 );
2980     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
2981       continue;
2982     }
2983     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
2984     k = 1;
2985     pTerm->wtFlags |= TERM_CODED;
2986   }
2987 
2988   /* For a LEFT OUTER JOIN, generate code that will record the fact that
2989   ** at least one row of the right table has matched the left table.
2990   */
2991   if( pLevel->iLeftJoin ){
2992     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
2993     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
2994     VdbeComment((v, "record LEFT JOIN hit"));
2995     sqlite3ExprCacheClear(pParse);
2996     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
2997       testcase( pTerm->wtFlags & TERM_VIRTUAL );
2998       testcase( pTerm->wtFlags & TERM_CODED );
2999       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3000       if( (pTerm->prereqAll & notReady)!=0 ) continue;
3001       assert( pTerm->pExpr );
3002       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3003       pTerm->wtFlags |= TERM_CODED;
3004     }
3005   }
3006   sqlite3ReleaseTempReg(pParse, iReleaseReg);
3007 
3008   return notReady;
3009 }
3010 
3011 #if defined(SQLITE_TEST)
3012 /*
3013 ** The following variable holds a text description of query plan generated
3014 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
3015 ** overwrites the previous.  This information is used for testing and
3016 ** analysis only.
3017 */
3018 char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
3019 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
3020 
3021 #endif /* SQLITE_TEST */
3022 
3023 
3024 /*
3025 ** Free a WhereInfo structure
3026 */
3027 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
3028   if( pWInfo ){
3029     int i;
3030     for(i=0; i<pWInfo->nLevel; i++){
3031       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
3032       if( pInfo ){
3033         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
3034         if( pInfo->needToFreeIdxStr ){
3035           sqlite3_free(pInfo->idxStr);
3036         }
3037         sqlite3DbFree(db, pInfo);
3038       }
3039     }
3040     whereClauseClear(pWInfo->pWC);
3041     sqlite3DbFree(db, pWInfo);
3042   }
3043 }
3044 
3045 
3046 /*
3047 ** Generate the beginning of the loop used for WHERE clause processing.
3048 ** The return value is a pointer to an opaque structure that contains
3049 ** information needed to terminate the loop.  Later, the calling routine
3050 ** should invoke sqlite3WhereEnd() with the return value of this function
3051 ** in order to complete the WHERE clause processing.
3052 **
3053 ** If an error occurs, this routine returns NULL.
3054 **
3055 ** The basic idea is to do a nested loop, one loop for each table in
3056 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
3057 ** same as a SELECT with only a single table in the FROM clause.)  For
3058 ** example, if the SQL is this:
3059 **
3060 **       SELECT * FROM t1, t2, t3 WHERE ...;
3061 **
3062 ** Then the code generated is conceptually like the following:
3063 **
3064 **      foreach row1 in t1 do       \    Code generated
3065 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
3066 **          foreach row3 in t3 do   /
3067 **            ...
3068 **          end                     \    Code generated
3069 **        end                        |-- by sqlite3WhereEnd()
3070 **      end                         /
3071 **
3072 ** Note that the loops might not be nested in the order in which they
3073 ** appear in the FROM clause if a different order is better able to make
3074 ** use of indices.  Note also that when the IN operator appears in
3075 ** the WHERE clause, it might result in additional nested loops for
3076 ** scanning through all values on the right-hand side of the IN.
3077 **
3078 ** There are Btree cursors associated with each table.  t1 uses cursor
3079 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
3080 ** And so forth.  This routine generates code to open those VDBE cursors
3081 ** and sqlite3WhereEnd() generates the code to close them.
3082 **
3083 ** The code that sqlite3WhereBegin() generates leaves the cursors named
3084 ** in pTabList pointing at their appropriate entries.  The [...] code
3085 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
3086 ** data from the various tables of the loop.
3087 **
3088 ** If the WHERE clause is empty, the foreach loops must each scan their
3089 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
3090 ** the tables have indices and there are terms in the WHERE clause that
3091 ** refer to those indices, a complete table scan can be avoided and the
3092 ** code will run much faster.  Most of the work of this routine is checking
3093 ** to see if there are indices that can be used to speed up the loop.
3094 **
3095 ** Terms of the WHERE clause are also used to limit which rows actually
3096 ** make it to the "..." in the middle of the loop.  After each "foreach",
3097 ** terms of the WHERE clause that use only terms in that loop and outer
3098 ** loops are evaluated and if false a jump is made around all subsequent
3099 ** inner loops (or around the "..." if the test occurs within the inner-
3100 ** most loop)
3101 **
3102 ** OUTER JOINS
3103 **
3104 ** An outer join of tables t1 and t2 is conceptally coded as follows:
3105 **
3106 **    foreach row1 in t1 do
3107 **      flag = 0
3108 **      foreach row2 in t2 do
3109 **        start:
3110 **          ...
3111 **          flag = 1
3112 **      end
3113 **      if flag==0 then
3114 **        move the row2 cursor to a null row
3115 **        goto start
3116 **      fi
3117 **    end
3118 **
3119 ** ORDER BY CLAUSE PROCESSING
3120 **
3121 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
3122 ** if there is one.  If there is no ORDER BY clause or if this routine
3123 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
3124 **
3125 ** If an index can be used so that the natural output order of the table
3126 ** scan is correct for the ORDER BY clause, then that index is used and
3127 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
3128 ** unnecessary sort of the result set if an index appropriate for the
3129 ** ORDER BY clause already exists.
3130 **
3131 ** If the where clause loops cannot be arranged to provide the correct
3132 ** output order, then the *ppOrderBy is unchanged.
3133 */
3134 WhereInfo *sqlite3WhereBegin(
3135   Parse *pParse,        /* The parser context */
3136   SrcList *pTabList,    /* A list of all tables to be scanned */
3137   Expr *pWhere,         /* The WHERE clause */
3138   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
3139   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
3140 ){
3141   int i;                     /* Loop counter */
3142   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
3143   WhereInfo *pWInfo;         /* Will become the return value of this function */
3144   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
3145   Bitmask notReady;          /* Cursors that are not yet positioned */
3146   WhereMaskSet *pMaskSet;    /* The expression mask set */
3147   WhereClause *pWC;               /* Decomposition of the WHERE clause */
3148   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
3149   WhereLevel *pLevel;             /* A single level in the pWInfo list */
3150   int iFrom;                      /* First unused FROM clause element */
3151   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
3152   sqlite3 *db;               /* Database connection */
3153 
3154   /* The number of tables in the FROM clause is limited by the number of
3155   ** bits in a Bitmask
3156   */
3157   if( pTabList->nSrc>BMS ){
3158     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
3159     return 0;
3160   }
3161 
3162   /* Allocate and initialize the WhereInfo structure that will become the
3163   ** return value. A single allocation is used to store the WhereInfo
3164   ** struct, the contents of WhereInfo.a[], the WhereClause structure
3165   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
3166   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
3167   ** some architectures. Hence the ROUND8() below.
3168   */
3169   db = pParse->db;
3170   nByteWInfo = ROUND8(sizeof(WhereInfo)+(pTabList->nSrc-1)*sizeof(WhereLevel));
3171   pWInfo = sqlite3DbMallocZero(db,
3172       nByteWInfo +
3173       sizeof(WhereClause) +
3174       sizeof(WhereMaskSet)
3175   );
3176   if( db->mallocFailed ){
3177     goto whereBeginError;
3178   }
3179   pWInfo->nLevel = pTabList->nSrc;
3180   pWInfo->pParse = pParse;
3181   pWInfo->pTabList = pTabList;
3182   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
3183   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
3184   pWInfo->wctrlFlags = wctrlFlags;
3185   pMaskSet = (WhereMaskSet*)&pWC[1];
3186 
3187   /* Split the WHERE clause into separate subexpressions where each
3188   ** subexpression is separated by an AND operator.
3189   */
3190   initMaskSet(pMaskSet);
3191   whereClauseInit(pWC, pParse, pMaskSet);
3192   sqlite3ExprCodeConstants(pParse, pWhere);
3193   whereSplit(pWC, pWhere, TK_AND);
3194 
3195   /* Special case: a WHERE clause that is constant.  Evaluate the
3196   ** expression and either jump over all of the code or fall thru.
3197   */
3198   if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
3199     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
3200     pWhere = 0;
3201   }
3202 
3203   /* Assign a bit from the bitmask to every term in the FROM clause.
3204   **
3205   ** When assigning bitmask values to FROM clause cursors, it must be
3206   ** the case that if X is the bitmask for the N-th FROM clause term then
3207   ** the bitmask for all FROM clause terms to the left of the N-th term
3208   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
3209   ** its Expr.iRightJoinTable value to find the bitmask of the right table
3210   ** of the join.  Subtracting one from the right table bitmask gives a
3211   ** bitmask for all tables to the left of the join.  Knowing the bitmask
3212   ** for all tables to the left of a left join is important.  Ticket #3015.
3213   **
3214   ** Configure the WhereClause.vmask variable so that bits that correspond
3215   ** to virtual table cursors are set. This is used to selectively disable
3216   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
3217   ** with virtual tables.
3218   */
3219   assert( pWC->vmask==0 && pMaskSet->n==0 );
3220   for(i=0; i<pTabList->nSrc; i++){
3221     createMask(pMaskSet, pTabList->a[i].iCursor);
3222 #ifndef SQLITE_OMIT_VIRTUALTABLE
3223     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
3224       pWC->vmask |= ((Bitmask)1 << i);
3225     }
3226 #endif
3227   }
3228 #ifndef NDEBUG
3229   {
3230     Bitmask toTheLeft = 0;
3231     for(i=0; i<pTabList->nSrc; i++){
3232       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
3233       assert( (m-1)==toTheLeft );
3234       toTheLeft |= m;
3235     }
3236   }
3237 #endif
3238 
3239   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
3240   ** add new virtual terms onto the end of the WHERE clause.  We do not
3241   ** want to analyze these virtual terms, so start analyzing at the end
3242   ** and work forward so that the added virtual terms are never processed.
3243   */
3244   exprAnalyzeAll(pTabList, pWC);
3245   if( db->mallocFailed ){
3246     goto whereBeginError;
3247   }
3248 
3249   /* Chose the best index to use for each table in the FROM clause.
3250   **
3251   ** This loop fills in the following fields:
3252   **
3253   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
3254   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
3255   **   pWInfo->a[].nEq       The number of == and IN constraints
3256   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
3257   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
3258   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
3259   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
3260   **
3261   ** This loop also figures out the nesting order of tables in the FROM
3262   ** clause.
3263   */
3264   notReady = ~(Bitmask)0;
3265   pTabItem = pTabList->a;
3266   pLevel = pWInfo->a;
3267   andFlags = ~0;
3268   WHERETRACE(("*** Optimizer Start ***\n"));
3269   for(i=iFrom=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
3270     WhereCost bestPlan;         /* Most efficient plan seen so far */
3271     Index *pIdx;                /* Index for FROM table at pTabItem */
3272     int j;                      /* For looping over FROM tables */
3273     int bestJ = 0;              /* The value of j */
3274     Bitmask m;                  /* Bitmask value for j or bestJ */
3275     int once = 0;               /* True when first table is seen */
3276 
3277     memset(&bestPlan, 0, sizeof(bestPlan));
3278     bestPlan.rCost = SQLITE_BIG_DBL;
3279     for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
3280       int doNotReorder;    /* True if this table should not be reordered */
3281       WhereCost sCost;     /* Cost information from best[Virtual]Index() */
3282       ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
3283 
3284       doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
3285       if( once && doNotReorder ) break;
3286       m = getMask(pMaskSet, pTabItem->iCursor);
3287       if( (m & notReady)==0 ){
3288         if( j==iFrom ) iFrom++;
3289         continue;
3290       }
3291       pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
3292 
3293       assert( pTabItem->pTab );
3294 #ifndef SQLITE_OMIT_VIRTUALTABLE
3295       if( IsVirtual(pTabItem->pTab) ){
3296         sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
3297         bestVirtualIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost, pp);
3298       }else
3299 #endif
3300       {
3301         bestBtreeIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost);
3302       }
3303       if( once==0 || sCost.rCost<bestPlan.rCost ){
3304         once = 1;
3305         bestPlan = sCost;
3306         bestJ = j;
3307       }
3308       if( doNotReorder ) break;
3309     }
3310     assert( once );
3311     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
3312     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
3313            pLevel-pWInfo->a));
3314     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
3315       *ppOrderBy = 0;
3316     }
3317     andFlags &= bestPlan.plan.wsFlags;
3318     pLevel->plan = bestPlan.plan;
3319     if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
3320       pLevel->iIdxCur = pParse->nTab++;
3321     }else{
3322       pLevel->iIdxCur = -1;
3323     }
3324     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
3325     pLevel->iFrom = (u8)bestJ;
3326 
3327     /* Check that if the table scanned by this loop iteration had an
3328     ** INDEXED BY clause attached to it, that the named index is being
3329     ** used for the scan. If not, then query compilation has failed.
3330     ** Return an error.
3331     */
3332     pIdx = pTabList->a[bestJ].pIndex;
3333     if( pIdx ){
3334       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
3335         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
3336         goto whereBeginError;
3337       }else{
3338         /* If an INDEXED BY clause is used, the bestIndex() function is
3339         ** guaranteed to find the index specified in the INDEXED BY clause
3340         ** if it find an index at all. */
3341         assert( bestPlan.plan.u.pIdx==pIdx );
3342       }
3343     }
3344   }
3345   WHERETRACE(("*** Optimizer Finished ***\n"));
3346   if( pParse->nErr || db->mallocFailed ){
3347     goto whereBeginError;
3348   }
3349 
3350   /* If the total query only selects a single row, then the ORDER BY
3351   ** clause is irrelevant.
3352   */
3353   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
3354     *ppOrderBy = 0;
3355   }
3356 
3357   /* If the caller is an UPDATE or DELETE statement that is requesting
3358   ** to use a one-pass algorithm, determine if this is appropriate.
3359   ** The one-pass algorithm only works if the WHERE clause constraints
3360   ** the statement to update a single row.
3361   */
3362   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
3363   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
3364     pWInfo->okOnePass = 1;
3365     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
3366   }
3367 
3368   /* Open all tables in the pTabList and any indices selected for
3369   ** searching those tables.
3370   */
3371   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
3372   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
3373     Table *pTab;     /* Table to open */
3374     int iDb;         /* Index of database containing table/index */
3375 
3376 #ifndef SQLITE_OMIT_EXPLAIN
3377     if( pParse->explain==2 ){
3378       char *zMsg;
3379       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
3380       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
3381       if( pItem->zAlias ){
3382         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
3383       }
3384       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
3385         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
3386            zMsg, pLevel->plan.u.pIdx->zName);
3387       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
3388         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
3389       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
3390         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
3391       }
3392 #ifndef SQLITE_OMIT_VIRTUALTABLE
3393       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3394         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
3395         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
3396                     pVtabIdx->idxNum, pVtabIdx->idxStr);
3397       }
3398 #endif
3399       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
3400         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
3401       }
3402       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
3403     }
3404 #endif /* SQLITE_OMIT_EXPLAIN */
3405     pTabItem = &pTabList->a[pLevel->iFrom];
3406     pTab = pTabItem->pTab;
3407     iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3408     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
3409 #ifndef SQLITE_OMIT_VIRTUALTABLE
3410     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3411       int iCur = pTabItem->iCursor;
3412       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0,
3413                         (const char*)pTab->pVtab, P4_VTAB);
3414     }else
3415 #endif
3416     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
3417          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
3418       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
3419       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
3420       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
3421         Bitmask b = pTabItem->colUsed;
3422         int n = 0;
3423         for(; b; b=b>>1, n++){}
3424         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, SQLITE_INT_TO_PTR(n), P4_INT32);
3425         assert( n<=pTab->nCol );
3426       }
3427     }else{
3428       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
3429     }
3430     pLevel->iTabCur = pTabItem->iCursor;
3431     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
3432       Index *pIx = pLevel->plan.u.pIdx;
3433       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
3434       int iIdxCur = pLevel->iIdxCur;
3435       assert( pIx->pSchema==pTab->pSchema );
3436       assert( iIdxCur>=0 );
3437       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
3438                         (char*)pKey, P4_KEYINFO_HANDOFF);
3439       VdbeComment((v, "%s", pIx->zName));
3440     }
3441     sqlite3CodeVerifySchema(pParse, iDb);
3442   }
3443   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
3444 
3445   /* Generate the code to do the search.  Each iteration of the for
3446   ** loop below generates code for a single nested loop of the VM
3447   ** program.
3448   */
3449   notReady = ~(Bitmask)0;
3450   for(i=0; i<pTabList->nSrc; i++){
3451     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
3452     pWInfo->iContinue = pWInfo->a[i].addrCont;
3453   }
3454 
3455 #ifdef SQLITE_TEST  /* For testing and debugging use only */
3456   /* Record in the query plan information about the current table
3457   ** and the index used to access it (if any).  If the table itself
3458   ** is not used, its name is just '{}'.  If no index is used
3459   ** the index is listed as "{}".  If the primary key is used the
3460   ** index name is '*'.
3461   */
3462   for(i=0; i<pTabList->nSrc; i++){
3463     char *z;
3464     int n;
3465     pLevel = &pWInfo->a[i];
3466     pTabItem = &pTabList->a[pLevel->iFrom];
3467     z = pTabItem->zAlias;
3468     if( z==0 ) z = pTabItem->pTab->zName;
3469     n = sqlite3Strlen30(z);
3470     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
3471       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
3472         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
3473         nQPlan += 2;
3474       }else{
3475         memcpy(&sqlite3_query_plan[nQPlan], z, n);
3476         nQPlan += n;
3477       }
3478       sqlite3_query_plan[nQPlan++] = ' ';
3479     }
3480     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
3481     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
3482     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
3483       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
3484       nQPlan += 2;
3485     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
3486       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
3487       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
3488         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
3489         nQPlan += n;
3490         sqlite3_query_plan[nQPlan++] = ' ';
3491       }
3492     }else{
3493       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
3494       nQPlan += 3;
3495     }
3496   }
3497   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
3498     sqlite3_query_plan[--nQPlan] = 0;
3499   }
3500   sqlite3_query_plan[nQPlan] = 0;
3501   nQPlan = 0;
3502 #endif /* SQLITE_TEST // Testing and debugging use only */
3503 
3504   /* Record the continuation address in the WhereInfo structure.  Then
3505   ** clean up and return.
3506   */
3507   return pWInfo;
3508 
3509   /* Jump here if malloc fails */
3510 whereBeginError:
3511   whereInfoFree(db, pWInfo);
3512   return 0;
3513 }
3514 
3515 /*
3516 ** Generate the end of the WHERE loop.  See comments on
3517 ** sqlite3WhereBegin() for additional information.
3518 */
3519 void sqlite3WhereEnd(WhereInfo *pWInfo){
3520   Parse *pParse = pWInfo->pParse;
3521   Vdbe *v = pParse->pVdbe;
3522   int i;
3523   WhereLevel *pLevel;
3524   SrcList *pTabList = pWInfo->pTabList;
3525   sqlite3 *db = pParse->db;
3526 
3527   /* Generate loop termination code.
3528   */
3529   sqlite3ExprCacheClear(pParse);
3530   for(i=pTabList->nSrc-1; i>=0; i--){
3531     pLevel = &pWInfo->a[i];
3532     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
3533     if( pLevel->op!=OP_Noop ){
3534       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
3535       sqlite3VdbeChangeP5(v, pLevel->p5);
3536     }
3537     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
3538       struct InLoop *pIn;
3539       int j;
3540       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
3541       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
3542         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
3543         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
3544         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
3545       }
3546       sqlite3DbFree(db, pLevel->u.in.aInLoop);
3547     }
3548     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
3549     if( pLevel->iLeftJoin ){
3550       int addr;
3551       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
3552       sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
3553       if( pLevel->iIdxCur>=0 ){
3554         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
3555       }
3556       if( pLevel->op==OP_Return ){
3557         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
3558       }else{
3559         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
3560       }
3561       sqlite3VdbeJumpHere(v, addr);
3562     }
3563   }
3564 
3565   /* The "break" point is here, just past the end of the outer loop.
3566   ** Set it.
3567   */
3568   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
3569 
3570   /* Close all of the cursors that were opened by sqlite3WhereBegin.
3571   */
3572   for(i=0, pLevel=pWInfo->a; i<pTabList->nSrc; i++, pLevel++){
3573     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
3574     Table *pTab = pTabItem->pTab;
3575     assert( pTab!=0 );
3576     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
3577     if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
3578       if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
3579         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
3580       }
3581       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
3582         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
3583       }
3584     }
3585 
3586     /* If this scan uses an index, make code substitutions to read data
3587     ** from the index in preference to the table. Sometimes, this means
3588     ** the table need never be read from. This is a performance boost,
3589     ** as the vdbe level waits until the table is read before actually
3590     ** seeking the table cursor to the record corresponding to the current
3591     ** position in the index.
3592     **
3593     ** Calls to the code generator in between sqlite3WhereBegin and
3594     ** sqlite3WhereEnd will have created code that references the table
3595     ** directly.  This loop scans all that code looking for opcodes
3596     ** that reference the table and converts them into opcodes that
3597     ** reference the index.
3598     */
3599     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
3600       int k, j, last;
3601       VdbeOp *pOp;
3602       Index *pIdx = pLevel->plan.u.pIdx;
3603       int useIndexOnly = pLevel->plan.wsFlags & WHERE_IDX_ONLY;
3604 
3605       assert( pIdx!=0 );
3606       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
3607       last = sqlite3VdbeCurrentAddr(v);
3608       for(k=pWInfo->iTop; k<last; k++, pOp++){
3609         if( pOp->p1!=pLevel->iTabCur ) continue;
3610         if( pOp->opcode==OP_Column ){
3611           for(j=0; j<pIdx->nColumn; j++){
3612             if( pOp->p2==pIdx->aiColumn[j] ){
3613               pOp->p2 = j;
3614               pOp->p1 = pLevel->iIdxCur;
3615               break;
3616             }
3617           }
3618           assert(!useIndexOnly || j<pIdx->nColumn);
3619         }else if( pOp->opcode==OP_Rowid ){
3620           pOp->p1 = pLevel->iIdxCur;
3621           pOp->opcode = OP_IdxRowid;
3622         }else if( pOp->opcode==OP_NullRow && useIndexOnly ){
3623           pOp->opcode = OP_Noop;
3624         }
3625       }
3626     }
3627   }
3628 
3629   /* Final cleanup
3630   */
3631   whereInfoFree(db, pWInfo);
3632   return;
3633 }
3634