xref: /sqlite-3.40.0/src/where.c (revision 48864df9)
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 #include "sqliteInt.h"
20 
21 
22 /*
23 ** Trace output macros
24 */
25 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
26 /***/ int sqlite3WhereTrace = 0;
27 #endif
28 #if defined(SQLITE_DEBUG) \
29     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
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)!=0 */
102     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
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 #ifdef SQLITE_ENABLE_STAT3
123 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
124 #else
125 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
126 #endif
127 
128 /*
129 ** An instance of the following structure holds all information about a
130 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
131 **
132 ** Explanation of pOuter:  For a WHERE clause of the form
133 **
134 **           a AND ((b AND c) OR (d AND e)) AND f
135 **
136 ** There are separate WhereClause objects for the whole clause and for
137 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
138 ** subclauses points to the WhereClause object for the whole clause.
139 */
140 struct WhereClause {
141   Parse *pParse;           /* The parser context */
142   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
143   WhereClause *pOuter;     /* Outer conjunction */
144   u8 op;                   /* Split operator.  TK_AND or TK_OR */
145   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
146   int nTerm;               /* Number of terms */
147   int nSlot;               /* Number of entries in a[] */
148   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
149 #if defined(SQLITE_SMALL_STACK)
150   WhereTerm aStatic[1];    /* Initial static space for a[] */
151 #else
152   WhereTerm aStatic[8];    /* Initial static space for a[] */
153 #endif
154 };
155 
156 /*
157 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
158 ** a dynamically allocated instance of the following structure.
159 */
160 struct WhereOrInfo {
161   WhereClause wc;          /* Decomposition into subterms */
162   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
163 };
164 
165 /*
166 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
167 ** a dynamically allocated instance of the following structure.
168 */
169 struct WhereAndInfo {
170   WhereClause wc;          /* The subexpression broken out */
171 };
172 
173 /*
174 ** An instance of the following structure keeps track of a mapping
175 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
176 **
177 ** The VDBE cursor numbers are small integers contained in
178 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
179 ** clause, the cursor numbers might not begin with 0 and they might
180 ** contain gaps in the numbering sequence.  But we want to make maximum
181 ** use of the bits in our bitmasks.  This structure provides a mapping
182 ** from the sparse cursor numbers into consecutive integers beginning
183 ** with 0.
184 **
185 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
186 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
187 **
188 ** For example, if the WHERE clause expression used these VDBE
189 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
190 ** would map those cursor numbers into bits 0 through 5.
191 **
192 ** Note that the mapping is not necessarily ordered.  In the example
193 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
194 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
195 ** does not really matter.  What is important is that sparse cursor
196 ** numbers all get mapped into bit numbers that begin with 0 and contain
197 ** no gaps.
198 */
199 struct WhereMaskSet {
200   int n;                        /* Number of assigned cursor values */
201   int ix[BMS];                  /* Cursor assigned to each bit */
202 };
203 
204 /*
205 ** A WhereCost object records a lookup strategy and the estimated
206 ** cost of pursuing that strategy.
207 */
208 struct WhereCost {
209   WherePlan plan;    /* The lookup strategy */
210   double rCost;      /* Overall cost of pursuing this search strategy */
211   Bitmask used;      /* Bitmask of cursors used by this plan */
212 };
213 
214 /*
215 ** Bitmasks for the operators that indices are able to exploit.  An
216 ** OR-ed combination of these values can be used when searching for
217 ** terms in the where clause.
218 */
219 #define WO_IN     0x001
220 #define WO_EQ     0x002
221 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
222 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
223 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
224 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
225 #define WO_MATCH  0x040
226 #define WO_ISNULL 0x080
227 #define WO_OR     0x100       /* Two or more OR-connected terms */
228 #define WO_AND    0x200       /* Two or more AND-connected terms */
229 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
230 #define WO_NOOP   0x800       /* This term does not restrict search space */
231 
232 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
233 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
234 
235 /*
236 ** Value for wsFlags returned by bestIndex() and stored in
237 ** WhereLevel.wsFlags.  These flags determine which search
238 ** strategies are appropriate.
239 **
240 ** The least significant 12 bits is reserved as a mask for WO_ values above.
241 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
242 ** But if the table is the right table of a left join, WhereLevel.wsFlags
243 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
244 ** the "op" parameter to findTerm when we are resolving equality constraints.
245 ** ISNULL constraints will then not be used on the right table of a left
246 ** join.  Tickets #2177 and #2189.
247 */
248 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
249 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
250 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
251 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
252 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
253 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
254 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
255 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
256 #define WHERE_IN_ABLE      0x080f1000  /* Able to support an IN operator */
257 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
258 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
259 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
260 #define WHERE_IDX_ONLY     0x00400000  /* Use index only - omit table */
261 #define WHERE_ORDERED      0x00800000  /* Output will appear in correct order */
262 #define WHERE_REVERSE      0x01000000  /* Scan in reverse order */
263 #define WHERE_UNIQUE       0x02000000  /* Selects no more than one row */
264 #define WHERE_ALL_UNIQUE   0x04000000  /* This and all prior have one row */
265 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
266 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
267 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
268 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
269 #define WHERE_COVER_SCAN   0x80000000  /* Full scan of a covering index */
270 
271 /*
272 ** This module contains many separate subroutines that work together to
273 ** find the best indices to use for accessing a particular table in a query.
274 ** An instance of the following structure holds context information about the
275 ** index search so that it can be more easily passed between the various
276 ** routines.
277 */
278 typedef struct WhereBestIdx WhereBestIdx;
279 struct WhereBestIdx {
280   Parse *pParse;                  /* Parser context */
281   WhereClause *pWC;               /* The WHERE clause */
282   struct SrcList_item *pSrc;      /* The FROM clause term to search */
283   Bitmask notReady;               /* Mask of cursors not available */
284   Bitmask notValid;               /* Cursors not available for any purpose */
285   ExprList *pOrderBy;             /* The ORDER BY clause */
286   ExprList *pDistinct;            /* The select-list if query is DISTINCT */
287   sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
288   int i, n;                       /* Which loop is being coded; # of loops */
289   WhereLevel *aLevel;             /* Info about outer loops */
290   WhereCost cost;                 /* Lowest cost query plan */
291 };
292 
293 /*
294 ** Return TRUE if the probe cost is less than the baseline cost
295 */
296 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
297   if( pProbe->rCost<pBaseline->rCost ) return 1;
298   if( pProbe->rCost>pBaseline->rCost ) return 0;
299   if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
300   if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
301   return 0;
302 }
303 
304 /*
305 ** Initialize a preallocated WhereClause structure.
306 */
307 static void whereClauseInit(
308   WhereClause *pWC,        /* The WhereClause to be initialized */
309   Parse *pParse,           /* The parsing context */
310   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
311   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
312 ){
313   pWC->pParse = pParse;
314   pWC->pMaskSet = pMaskSet;
315   pWC->pOuter = 0;
316   pWC->nTerm = 0;
317   pWC->nSlot = ArraySize(pWC->aStatic);
318   pWC->a = pWC->aStatic;
319   pWC->wctrlFlags = wctrlFlags;
320 }
321 
322 /* Forward reference */
323 static void whereClauseClear(WhereClause*);
324 
325 /*
326 ** Deallocate all memory associated with a WhereOrInfo object.
327 */
328 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
329   whereClauseClear(&p->wc);
330   sqlite3DbFree(db, p);
331 }
332 
333 /*
334 ** Deallocate all memory associated with a WhereAndInfo object.
335 */
336 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
337   whereClauseClear(&p->wc);
338   sqlite3DbFree(db, p);
339 }
340 
341 /*
342 ** Deallocate a WhereClause structure.  The WhereClause structure
343 ** itself is not freed.  This routine is the inverse of whereClauseInit().
344 */
345 static void whereClauseClear(WhereClause *pWC){
346   int i;
347   WhereTerm *a;
348   sqlite3 *db = pWC->pParse->db;
349   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
350     if( a->wtFlags & TERM_DYNAMIC ){
351       sqlite3ExprDelete(db, a->pExpr);
352     }
353     if( a->wtFlags & TERM_ORINFO ){
354       whereOrInfoDelete(db, a->u.pOrInfo);
355     }else if( a->wtFlags & TERM_ANDINFO ){
356       whereAndInfoDelete(db, a->u.pAndInfo);
357     }
358   }
359   if( pWC->a!=pWC->aStatic ){
360     sqlite3DbFree(db, pWC->a);
361   }
362 }
363 
364 /*
365 ** Add a single new WhereTerm entry to the WhereClause object pWC.
366 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
367 ** The index in pWC->a[] of the new WhereTerm is returned on success.
368 ** 0 is returned if the new WhereTerm could not be added due to a memory
369 ** allocation error.  The memory allocation failure will be recorded in
370 ** the db->mallocFailed flag so that higher-level functions can detect it.
371 **
372 ** This routine will increase the size of the pWC->a[] array as necessary.
373 **
374 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
375 ** for freeing the expression p is assumed by the WhereClause object pWC.
376 ** This is true even if this routine fails to allocate a new WhereTerm.
377 **
378 ** WARNING:  This routine might reallocate the space used to store
379 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
380 ** calling this routine.  Such pointers may be reinitialized by referencing
381 ** the pWC->a[] array.
382 */
383 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
384   WhereTerm *pTerm;
385   int idx;
386   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
387   if( pWC->nTerm>=pWC->nSlot ){
388     WhereTerm *pOld = pWC->a;
389     sqlite3 *db = pWC->pParse->db;
390     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
391     if( pWC->a==0 ){
392       if( wtFlags & TERM_DYNAMIC ){
393         sqlite3ExprDelete(db, p);
394       }
395       pWC->a = pOld;
396       return 0;
397     }
398     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
399     if( pOld!=pWC->aStatic ){
400       sqlite3DbFree(db, pOld);
401     }
402     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
403   }
404   pTerm = &pWC->a[idx = pWC->nTerm++];
405   pTerm->pExpr = sqlite3ExprSkipCollate(p);
406   pTerm->wtFlags = wtFlags;
407   pTerm->pWC = pWC;
408   pTerm->iParent = -1;
409   return idx;
410 }
411 
412 /*
413 ** This routine identifies subexpressions in the WHERE clause where
414 ** each subexpression is separated by the AND operator or some other
415 ** operator specified in the op parameter.  The WhereClause structure
416 ** is filled with pointers to subexpressions.  For example:
417 **
418 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
419 **           \________/     \_______________/     \________________/
420 **            slot[0]            slot[1]               slot[2]
421 **
422 ** The original WHERE clause in pExpr is unaltered.  All this routine
423 ** does is make slot[] entries point to substructure within pExpr.
424 **
425 ** In the previous sentence and in the diagram, "slot[]" refers to
426 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
427 ** all terms of the WHERE clause.
428 */
429 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
430   pWC->op = (u8)op;
431   if( pExpr==0 ) return;
432   if( pExpr->op!=op ){
433     whereClauseInsert(pWC, pExpr, 0);
434   }else{
435     whereSplit(pWC, pExpr->pLeft, op);
436     whereSplit(pWC, pExpr->pRight, op);
437   }
438 }
439 
440 /*
441 ** Initialize an expression mask set (a WhereMaskSet object)
442 */
443 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
444 
445 /*
446 ** Return the bitmask for the given cursor number.  Return 0 if
447 ** iCursor is not in the set.
448 */
449 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
450   int i;
451   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
452   for(i=0; i<pMaskSet->n; i++){
453     if( pMaskSet->ix[i]==iCursor ){
454       return ((Bitmask)1)<<i;
455     }
456   }
457   return 0;
458 }
459 
460 /*
461 ** Create a new mask for cursor iCursor.
462 **
463 ** There is one cursor per table in the FROM clause.  The number of
464 ** tables in the FROM clause is limited by a test early in the
465 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
466 ** array will never overflow.
467 */
468 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
469   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
470   pMaskSet->ix[pMaskSet->n++] = iCursor;
471 }
472 
473 /*
474 ** This routine walks (recursively) an expression tree and generates
475 ** a bitmask indicating which tables are used in that expression
476 ** tree.
477 **
478 ** In order for this routine to work, the calling function must have
479 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
480 ** the header comment on that routine for additional information.
481 ** The sqlite3ResolveExprNames() routines looks for column names and
482 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
483 ** the VDBE cursor number of the table.  This routine just has to
484 ** translate the cursor numbers into bitmask values and OR all
485 ** the bitmasks together.
486 */
487 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
488 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
489 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
490   Bitmask mask = 0;
491   if( p==0 ) return 0;
492   if( p->op==TK_COLUMN ){
493     mask = getMask(pMaskSet, p->iTable);
494     return mask;
495   }
496   mask = exprTableUsage(pMaskSet, p->pRight);
497   mask |= exprTableUsage(pMaskSet, p->pLeft);
498   if( ExprHasProperty(p, EP_xIsSelect) ){
499     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
500   }else{
501     mask |= exprListTableUsage(pMaskSet, p->x.pList);
502   }
503   return mask;
504 }
505 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
506   int i;
507   Bitmask mask = 0;
508   if( pList ){
509     for(i=0; i<pList->nExpr; i++){
510       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
511     }
512   }
513   return mask;
514 }
515 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
516   Bitmask mask = 0;
517   while( pS ){
518     SrcList *pSrc = pS->pSrc;
519     mask |= exprListTableUsage(pMaskSet, pS->pEList);
520     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
521     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
522     mask |= exprTableUsage(pMaskSet, pS->pWhere);
523     mask |= exprTableUsage(pMaskSet, pS->pHaving);
524     if( ALWAYS(pSrc!=0) ){
525       int i;
526       for(i=0; i<pSrc->nSrc; i++){
527         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
528         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
529       }
530     }
531     pS = pS->pPrior;
532   }
533   return mask;
534 }
535 
536 /*
537 ** Return TRUE if the given operator is one of the operators that is
538 ** allowed for an indexable WHERE clause term.  The allowed operators are
539 ** "=", "<", ">", "<=", ">=", and "IN".
540 **
541 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
542 ** of one of the following forms: column = expression column > expression
543 ** column >= expression column < expression column <= expression
544 ** expression = column expression > column expression >= column
545 ** expression < column expression <= column column IN
546 ** (expression-list) column IN (subquery) column IS NULL
547 */
548 static int allowedOp(int op){
549   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
550   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
551   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
552   assert( TK_GE==TK_EQ+4 );
553   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
554 }
555 
556 /*
557 ** Swap two objects of type TYPE.
558 */
559 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
560 
561 /*
562 ** Commute a comparison operator.  Expressions of the form "X op Y"
563 ** are converted into "Y op X".
564 **
565 ** If left/right precedence rules come into play when determining the
566 ** collating
567 ** side of the comparison, it remains associated with the same side after
568 ** the commutation. So "Y collate NOCASE op X" becomes
569 ** "X op Y". This is because any collation sequence on
570 ** the left hand side of a comparison overrides any collation sequence
571 ** attached to the right. For the same reason the EP_Collate flag
572 ** is not commuted.
573 */
574 static void exprCommute(Parse *pParse, Expr *pExpr){
575   u16 expRight = (pExpr->pRight->flags & EP_Collate);
576   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
577   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
578   if( expRight==expLeft ){
579     /* Either X and Y both have COLLATE operator or neither do */
580     if( expRight ){
581       /* Both X and Y have COLLATE operators.  Make sure X is always
582       ** used by clearing the EP_Collate flag from Y. */
583       pExpr->pRight->flags &= ~EP_Collate;
584     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
585       /* Neither X nor Y have COLLATE operators, but X has a non-default
586       ** collating sequence.  So add the EP_Collate marker on X to cause
587       ** it to be searched first. */
588       pExpr->pLeft->flags |= EP_Collate;
589     }
590   }
591   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
592   if( pExpr->op>=TK_GT ){
593     assert( TK_LT==TK_GT+2 );
594     assert( TK_GE==TK_LE+2 );
595     assert( TK_GT>TK_EQ );
596     assert( TK_GT<TK_LE );
597     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
598     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
599   }
600 }
601 
602 /*
603 ** Translate from TK_xx operator to WO_xx bitmask.
604 */
605 static u16 operatorMask(int op){
606   u16 c;
607   assert( allowedOp(op) );
608   if( op==TK_IN ){
609     c = WO_IN;
610   }else if( op==TK_ISNULL ){
611     c = WO_ISNULL;
612   }else{
613     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
614     c = (u16)(WO_EQ<<(op-TK_EQ));
615   }
616   assert( op!=TK_ISNULL || c==WO_ISNULL );
617   assert( op!=TK_IN || c==WO_IN );
618   assert( op!=TK_EQ || c==WO_EQ );
619   assert( op!=TK_LT || c==WO_LT );
620   assert( op!=TK_LE || c==WO_LE );
621   assert( op!=TK_GT || c==WO_GT );
622   assert( op!=TK_GE || c==WO_GE );
623   return c;
624 }
625 
626 /*
627 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
628 ** where X is a reference to the iColumn of table iCur and <op> is one of
629 ** the WO_xx operator codes specified by the op parameter.
630 ** Return a pointer to the term.  Return 0 if not found.
631 **
632 ** The term returned might by Y=<expr> if there is another constraint in
633 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
634 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
635 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
636 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
637 ** and the second is for the column number.  There are 22 slots in aEquiv[]
638 ** so that means we can look for X plus up to 10 other equivalent values.
639 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
640 ** and ... and A9=A10 and A10=<expr>.
641 **
642 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
643 ** then try for the one with no dependencies on <expr> - in other words where
644 ** <expr> is a constant expression of some kind.  Only return entries of
645 ** the form "X <op> Y" where Y is a column in another table if no terms of
646 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
647 ** exist, try to return a term that does not use WO_EQUIV.
648 */
649 static WhereTerm *findTerm(
650   WhereClause *pWC,     /* The WHERE clause to be searched */
651   int iCur,             /* Cursor number of LHS */
652   int iColumn,          /* Column number of LHS */
653   Bitmask notReady,     /* RHS must not overlap with this mask */
654   u32 op,               /* Mask of WO_xx values describing operator */
655   Index *pIdx           /* Must be compatible with this index, if not NULL */
656 ){
657   WhereTerm *pTerm;            /* Term being examined as possible result */
658   WhereTerm *pResult = 0;      /* The answer to return */
659   WhereClause *pWCOrig = pWC;  /* Original pWC value */
660   int j, k;                    /* Loop counters */
661   Expr *pX;                /* Pointer to an expression */
662   Parse *pParse;           /* Parsing context */
663   int iOrigCol = iColumn;  /* Original value of iColumn */
664   int nEquiv = 2;          /* Number of entires in aEquiv[] */
665   int iEquiv = 2;          /* Number of entries of aEquiv[] processed so far */
666   int aEquiv[22];          /* iCur,iColumn and up to 10 other equivalents */
667 
668   assert( iCur>=0 );
669   aEquiv[0] = iCur;
670   aEquiv[1] = iColumn;
671   for(;;){
672     for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
673       for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
674         if( pTerm->leftCursor==iCur
675           && pTerm->u.leftColumn==iColumn
676         ){
677           if( (pTerm->prereqRight & notReady)==0
678            && (pTerm->eOperator & op & WO_ALL)!=0
679           ){
680             if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
681               CollSeq *pColl;
682               char idxaff;
683 
684               pX = pTerm->pExpr;
685               pParse = pWC->pParse;
686               idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
687               if( !sqlite3IndexAffinityOk(pX, idxaff) ){
688                 continue;
689               }
690 
691               /* Figure out the collation sequence required from an index for
692               ** it to be useful for optimising expression pX. Store this
693               ** value in variable pColl.
694               */
695               assert(pX->pLeft);
696               pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
697               if( pColl==0 ) pColl = pParse->db->pDfltColl;
698 
699               for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
700                 if( NEVER(j>=pIdx->nColumn) ) return 0;
701               }
702               if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
703                 continue;
704               }
705             }
706             if( pTerm->prereqRight==0 ){
707               pResult = pTerm;
708               goto findTerm_success;
709             }else if( pResult==0 ){
710               pResult = pTerm;
711             }
712           }
713           if( (pTerm->eOperator & WO_EQUIV)!=0
714            && nEquiv<ArraySize(aEquiv)
715           ){
716             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
717             assert( pX->op==TK_COLUMN );
718             for(j=0; j<nEquiv; j+=2){
719               if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
720             }
721             if( j==nEquiv ){
722               aEquiv[j] = pX->iTable;
723               aEquiv[j+1] = pX->iColumn;
724               nEquiv += 2;
725             }
726           }
727         }
728       }
729     }
730     if( iEquiv>=nEquiv ) break;
731     iCur = aEquiv[iEquiv++];
732     iColumn = aEquiv[iEquiv++];
733   }
734 findTerm_success:
735   return pResult;
736 }
737 
738 /* Forward reference */
739 static void exprAnalyze(SrcList*, WhereClause*, int);
740 
741 /*
742 ** Call exprAnalyze on all terms in a WHERE clause.
743 **
744 **
745 */
746 static void exprAnalyzeAll(
747   SrcList *pTabList,       /* the FROM clause */
748   WhereClause *pWC         /* the WHERE clause to be analyzed */
749 ){
750   int i;
751   for(i=pWC->nTerm-1; i>=0; i--){
752     exprAnalyze(pTabList, pWC, i);
753   }
754 }
755 
756 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
757 /*
758 ** Check to see if the given expression is a LIKE or GLOB operator that
759 ** can be optimized using inequality constraints.  Return TRUE if it is
760 ** so and false if not.
761 **
762 ** In order for the operator to be optimizible, the RHS must be a string
763 ** literal that does not begin with a wildcard.
764 */
765 static int isLikeOrGlob(
766   Parse *pParse,    /* Parsing and code generating context */
767   Expr *pExpr,      /* Test this expression */
768   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
769   int *pisComplete, /* True if the only wildcard is % in the last character */
770   int *pnoCase      /* True if uppercase is equivalent to lowercase */
771 ){
772   const char *z = 0;         /* String on RHS of LIKE operator */
773   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
774   ExprList *pList;           /* List of operands to the LIKE operator */
775   int c;                     /* One character in z[] */
776   int cnt;                   /* Number of non-wildcard prefix characters */
777   char wc[3];                /* Wildcard characters */
778   sqlite3 *db = pParse->db;  /* Database connection */
779   sqlite3_value *pVal = 0;
780   int op;                    /* Opcode of pRight */
781 
782   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
783     return 0;
784   }
785 #ifdef SQLITE_EBCDIC
786   if( *pnoCase ) return 0;
787 #endif
788   pList = pExpr->x.pList;
789   pLeft = pList->a[1].pExpr;
790   if( pLeft->op!=TK_COLUMN
791    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
792    || IsVirtual(pLeft->pTab)
793   ){
794     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
795     ** be the name of an indexed column with TEXT affinity. */
796     return 0;
797   }
798   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
799 
800   pRight = pList->a[0].pExpr;
801   op = pRight->op;
802   if( op==TK_REGISTER ){
803     op = pRight->op2;
804   }
805   if( op==TK_VARIABLE ){
806     Vdbe *pReprepare = pParse->pReprepare;
807     int iCol = pRight->iColumn;
808     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
809     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
810       z = (char *)sqlite3_value_text(pVal);
811     }
812     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
813     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
814   }else if( op==TK_STRING ){
815     z = pRight->u.zToken;
816   }
817   if( z ){
818     cnt = 0;
819     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
820       cnt++;
821     }
822     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
823       Expr *pPrefix;
824       *pisComplete = c==wc[0] && z[cnt+1]==0;
825       pPrefix = sqlite3Expr(db, TK_STRING, z);
826       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
827       *ppPrefix = pPrefix;
828       if( op==TK_VARIABLE ){
829         Vdbe *v = pParse->pVdbe;
830         sqlite3VdbeSetVarmask(v, pRight->iColumn);
831         if( *pisComplete && pRight->u.zToken[1] ){
832           /* If the rhs of the LIKE expression is a variable, and the current
833           ** value of the variable means there is no need to invoke the LIKE
834           ** function, then no OP_Variable will be added to the program.
835           ** This causes problems for the sqlite3_bind_parameter_name()
836           ** API. To workaround them, add a dummy OP_Variable here.
837           */
838           int r1 = sqlite3GetTempReg(pParse);
839           sqlite3ExprCodeTarget(pParse, pRight, r1);
840           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
841           sqlite3ReleaseTempReg(pParse, r1);
842         }
843       }
844     }else{
845       z = 0;
846     }
847   }
848 
849   sqlite3ValueFree(pVal);
850   return (z!=0);
851 }
852 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
853 
854 
855 #ifndef SQLITE_OMIT_VIRTUALTABLE
856 /*
857 ** Check to see if the given expression is of the form
858 **
859 **         column MATCH expr
860 **
861 ** If it is then return TRUE.  If not, return FALSE.
862 */
863 static int isMatchOfColumn(
864   Expr *pExpr      /* Test this expression */
865 ){
866   ExprList *pList;
867 
868   if( pExpr->op!=TK_FUNCTION ){
869     return 0;
870   }
871   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
872     return 0;
873   }
874   pList = pExpr->x.pList;
875   if( pList->nExpr!=2 ){
876     return 0;
877   }
878   if( pList->a[1].pExpr->op != TK_COLUMN ){
879     return 0;
880   }
881   return 1;
882 }
883 #endif /* SQLITE_OMIT_VIRTUALTABLE */
884 
885 /*
886 ** If the pBase expression originated in the ON or USING clause of
887 ** a join, then transfer the appropriate markings over to derived.
888 */
889 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
890   pDerived->flags |= pBase->flags & EP_FromJoin;
891   pDerived->iRightJoinTable = pBase->iRightJoinTable;
892 }
893 
894 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
895 /*
896 ** Analyze a term that consists of two or more OR-connected
897 ** subterms.  So in:
898 **
899 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
900 **                          ^^^^^^^^^^^^^^^^^^^^
901 **
902 ** This routine analyzes terms such as the middle term in the above example.
903 ** A WhereOrTerm object is computed and attached to the term under
904 ** analysis, regardless of the outcome of the analysis.  Hence:
905 **
906 **     WhereTerm.wtFlags   |=  TERM_ORINFO
907 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
908 **
909 ** The term being analyzed must have two or more of OR-connected subterms.
910 ** A single subterm might be a set of AND-connected sub-subterms.
911 ** Examples of terms under analysis:
912 **
913 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
914 **     (B)     x=expr1 OR expr2=x OR x=expr3
915 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
916 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
917 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
918 **
919 ** CASE 1:
920 **
921 ** If all subterms are of the form T.C=expr for some single column of C and
922 ** a single table T (as shown in example B above) then create a new virtual
923 ** term that is an equivalent IN expression.  In other words, if the term
924 ** being analyzed is:
925 **
926 **      x = expr1  OR  expr2 = x  OR  x = expr3
927 **
928 ** then create a new virtual term like this:
929 **
930 **      x IN (expr1,expr2,expr3)
931 **
932 ** CASE 2:
933 **
934 ** If all subterms are indexable by a single table T, then set
935 **
936 **     WhereTerm.eOperator              =  WO_OR
937 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
938 **
939 ** A subterm is "indexable" if it is of the form
940 ** "T.C <op> <expr>" where C is any column of table T and
941 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
942 ** A subterm is also indexable if it is an AND of two or more
943 ** subsubterms at least one of which is indexable.  Indexable AND
944 ** subterms have their eOperator set to WO_AND and they have
945 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
946 **
947 ** From another point of view, "indexable" means that the subterm could
948 ** potentially be used with an index if an appropriate index exists.
949 ** This analysis does not consider whether or not the index exists; that
950 ** is something the bestIndex() routine will determine.  This analysis
951 ** only looks at whether subterms appropriate for indexing exist.
952 **
953 ** All examples A through E above all satisfy case 2.  But if a term
954 ** also statisfies case 1 (such as B) we know that the optimizer will
955 ** always prefer case 1, so in that case we pretend that case 2 is not
956 ** satisfied.
957 **
958 ** It might be the case that multiple tables are indexable.  For example,
959 ** (E) above is indexable on tables P, Q, and R.
960 **
961 ** Terms that satisfy case 2 are candidates for lookup by using
962 ** separate indices to find rowids for each subterm and composing
963 ** the union of all rowids using a RowSet object.  This is similar
964 ** to "bitmap indices" in other database engines.
965 **
966 ** OTHERWISE:
967 **
968 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
969 ** zero.  This term is not useful for search.
970 */
971 static void exprAnalyzeOrTerm(
972   SrcList *pSrc,            /* the FROM clause */
973   WhereClause *pWC,         /* the complete WHERE clause */
974   int idxTerm               /* Index of the OR-term to be analyzed */
975 ){
976   Parse *pParse = pWC->pParse;            /* Parser context */
977   sqlite3 *db = pParse->db;               /* Database connection */
978   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
979   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
980   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
981   int i;                                  /* Loop counters */
982   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
983   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
984   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
985   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
986   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
987 
988   /*
989   ** Break the OR clause into its separate subterms.  The subterms are
990   ** stored in a WhereClause structure containing within the WhereOrInfo
991   ** object that is attached to the original OR clause term.
992   */
993   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
994   assert( pExpr->op==TK_OR );
995   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
996   if( pOrInfo==0 ) return;
997   pTerm->wtFlags |= TERM_ORINFO;
998   pOrWc = &pOrInfo->wc;
999   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
1000   whereSplit(pOrWc, pExpr, TK_OR);
1001   exprAnalyzeAll(pSrc, pOrWc);
1002   if( db->mallocFailed ) return;
1003   assert( pOrWc->nTerm>=2 );
1004 
1005   /*
1006   ** Compute the set of tables that might satisfy cases 1 or 2.
1007   */
1008   indexable = ~(Bitmask)0;
1009   chngToIN = ~(Bitmask)0;
1010   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1011     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
1012       WhereAndInfo *pAndInfo;
1013       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
1014       chngToIN = 0;
1015       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1016       if( pAndInfo ){
1017         WhereClause *pAndWC;
1018         WhereTerm *pAndTerm;
1019         int j;
1020         Bitmask b = 0;
1021         pOrTerm->u.pAndInfo = pAndInfo;
1022         pOrTerm->wtFlags |= TERM_ANDINFO;
1023         pOrTerm->eOperator = WO_AND;
1024         pAndWC = &pAndInfo->wc;
1025         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
1026         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1027         exprAnalyzeAll(pSrc, pAndWC);
1028         pAndWC->pOuter = pWC;
1029         testcase( db->mallocFailed );
1030         if( !db->mallocFailed ){
1031           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1032             assert( pAndTerm->pExpr );
1033             if( allowedOp(pAndTerm->pExpr->op) ){
1034               b |= getMask(pMaskSet, pAndTerm->leftCursor);
1035             }
1036           }
1037         }
1038         indexable &= b;
1039       }
1040     }else if( pOrTerm->wtFlags & TERM_COPIED ){
1041       /* Skip this term for now.  We revisit it when we process the
1042       ** corresponding TERM_VIRTUAL term */
1043     }else{
1044       Bitmask b;
1045       b = getMask(pMaskSet, pOrTerm->leftCursor);
1046       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1047         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
1048         b |= getMask(pMaskSet, pOther->leftCursor);
1049       }
1050       indexable &= b;
1051       if( (pOrTerm->eOperator & WO_EQ)==0 ){
1052         chngToIN = 0;
1053       }else{
1054         chngToIN &= b;
1055       }
1056     }
1057   }
1058 
1059   /*
1060   ** Record the set of tables that satisfy case 2.  The set might be
1061   ** empty.
1062   */
1063   pOrInfo->indexable = indexable;
1064   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
1065 
1066   /*
1067   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
1068   ** we have to do some additional checking to see if case 1 really
1069   ** is satisfied.
1070   **
1071   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
1072   ** that there is no possibility of transforming the OR clause into an
1073   ** IN operator because one or more terms in the OR clause contain
1074   ** something other than == on a column in the single table.  The 1-bit
1075   ** case means that every term of the OR clause is of the form
1076   ** "table.column=expr" for some single table.  The one bit that is set
1077   ** will correspond to the common table.  We still need to check to make
1078   ** sure the same column is used on all terms.  The 2-bit case is when
1079   ** the all terms are of the form "table1.column=table2.column".  It
1080   ** might be possible to form an IN operator with either table1.column
1081   ** or table2.column as the LHS if either is common to every term of
1082   ** the OR clause.
1083   **
1084   ** Note that terms of the form "table.column1=table.column2" (the
1085   ** same table on both sizes of the ==) cannot be optimized.
1086   */
1087   if( chngToIN ){
1088     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
1089     int iColumn = -1;         /* Column index on lhs of IN operator */
1090     int iCursor = -1;         /* Table cursor common to all terms */
1091     int j = 0;                /* Loop counter */
1092 
1093     /* Search for a table and column that appears on one side or the
1094     ** other of the == operator in every subterm.  That table and column
1095     ** will be recorded in iCursor and iColumn.  There might not be any
1096     ** such table and column.  Set okToChngToIN if an appropriate table
1097     ** and column is found but leave okToChngToIN false if not found.
1098     */
1099     for(j=0; j<2 && !okToChngToIN; j++){
1100       pOrTerm = pOrWc->a;
1101       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
1102         assert( pOrTerm->eOperator & WO_EQ );
1103         pOrTerm->wtFlags &= ~TERM_OR_OK;
1104         if( pOrTerm->leftCursor==iCursor ){
1105           /* This is the 2-bit case and we are on the second iteration and
1106           ** current term is from the first iteration.  So skip this term. */
1107           assert( j==1 );
1108           continue;
1109         }
1110         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
1111           /* This term must be of the form t1.a==t2.b where t2 is in the
1112           ** chngToIN set but t1 is not.  This term will be either preceeded
1113           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
1114           ** and use its inversion. */
1115           testcase( pOrTerm->wtFlags & TERM_COPIED );
1116           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1117           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1118           continue;
1119         }
1120         iColumn = pOrTerm->u.leftColumn;
1121         iCursor = pOrTerm->leftCursor;
1122         break;
1123       }
1124       if( i<0 ){
1125         /* No candidate table+column was found.  This can only occur
1126         ** on the second iteration */
1127         assert( j==1 );
1128         assert( IsPowerOfTwo(chngToIN) );
1129         assert( chngToIN==getMask(pMaskSet, iCursor) );
1130         break;
1131       }
1132       testcase( j==1 );
1133 
1134       /* We have found a candidate table and column.  Check to see if that
1135       ** table and column is common to every term in the OR clause */
1136       okToChngToIN = 1;
1137       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
1138         assert( pOrTerm->eOperator & WO_EQ );
1139         if( pOrTerm->leftCursor!=iCursor ){
1140           pOrTerm->wtFlags &= ~TERM_OR_OK;
1141         }else if( pOrTerm->u.leftColumn!=iColumn ){
1142           okToChngToIN = 0;
1143         }else{
1144           int affLeft, affRight;
1145           /* If the right-hand side is also a column, then the affinities
1146           ** of both right and left sides must be such that no type
1147           ** conversions are required on the right.  (Ticket #2249)
1148           */
1149           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1150           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1151           if( affRight!=0 && affRight!=affLeft ){
1152             okToChngToIN = 0;
1153           }else{
1154             pOrTerm->wtFlags |= TERM_OR_OK;
1155           }
1156         }
1157       }
1158     }
1159 
1160     /* At this point, okToChngToIN is true if original pTerm satisfies
1161     ** case 1.  In that case, construct a new virtual term that is
1162     ** pTerm converted into an IN operator.
1163     **
1164     ** EV: R-00211-15100
1165     */
1166     if( okToChngToIN ){
1167       Expr *pDup;            /* A transient duplicate expression */
1168       ExprList *pList = 0;   /* The RHS of the IN operator */
1169       Expr *pLeft = 0;       /* The LHS of the IN operator */
1170       Expr *pNew;            /* The complete IN operator */
1171 
1172       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1173         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
1174         assert( pOrTerm->eOperator & WO_EQ );
1175         assert( pOrTerm->leftCursor==iCursor );
1176         assert( pOrTerm->u.leftColumn==iColumn );
1177         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
1178         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
1179         pLeft = pOrTerm->pExpr->pLeft;
1180       }
1181       assert( pLeft!=0 );
1182       pDup = sqlite3ExprDup(db, pLeft, 0);
1183       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
1184       if( pNew ){
1185         int idxNew;
1186         transferJoinMarkings(pNew, pExpr);
1187         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1188         pNew->x.pList = pList;
1189         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1190         testcase( idxNew==0 );
1191         exprAnalyze(pSrc, pWC, idxNew);
1192         pTerm = &pWC->a[idxTerm];
1193         pWC->a[idxNew].iParent = idxTerm;
1194         pTerm->nChild = 1;
1195       }else{
1196         sqlite3ExprListDelete(db, pList);
1197       }
1198       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
1199     }
1200   }
1201 }
1202 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
1203 
1204 /*
1205 ** The input to this routine is an WhereTerm structure with only the
1206 ** "pExpr" field filled in.  The job of this routine is to analyze the
1207 ** subexpression and populate all the other fields of the WhereTerm
1208 ** structure.
1209 **
1210 ** If the expression is of the form "<expr> <op> X" it gets commuted
1211 ** to the standard form of "X <op> <expr>".
1212 **
1213 ** If the expression is of the form "X <op> Y" where both X and Y are
1214 ** columns, then the original expression is unchanged and a new virtual
1215 ** term of the form "Y <op> X" is added to the WHERE clause and
1216 ** analyzed separately.  The original term is marked with TERM_COPIED
1217 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1218 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1219 ** is a commuted copy of a prior term.)  The original term has nChild=1
1220 ** and the copy has idxParent set to the index of the original term.
1221 */
1222 static void exprAnalyze(
1223   SrcList *pSrc,            /* the FROM clause */
1224   WhereClause *pWC,         /* the WHERE clause */
1225   int idxTerm               /* Index of the term to be analyzed */
1226 ){
1227   WhereTerm *pTerm;                /* The term to be analyzed */
1228   WhereMaskSet *pMaskSet;          /* Set of table index masks */
1229   Expr *pExpr;                     /* The expression to be analyzed */
1230   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
1231   Bitmask prereqAll;               /* Prerequesites of pExpr */
1232   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
1233   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
1234   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
1235   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
1236   int op;                          /* Top-level operator.  pExpr->op */
1237   Parse *pParse = pWC->pParse;     /* Parsing context */
1238   sqlite3 *db = pParse->db;        /* Database connection */
1239 
1240   if( db->mallocFailed ){
1241     return;
1242   }
1243   pTerm = &pWC->a[idxTerm];
1244   pMaskSet = pWC->pMaskSet;
1245   pExpr = pTerm->pExpr;
1246   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1247   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
1248   op = pExpr->op;
1249   if( op==TK_IN ){
1250     assert( pExpr->pRight==0 );
1251     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1252       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1253     }else{
1254       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1255     }
1256   }else if( op==TK_ISNULL ){
1257     pTerm->prereqRight = 0;
1258   }else{
1259     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1260   }
1261   prereqAll = exprTableUsage(pMaskSet, pExpr);
1262   if( ExprHasProperty(pExpr, EP_FromJoin) ){
1263     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1264     prereqAll |= x;
1265     extraRight = x-1;  /* ON clause terms may not be used with an index
1266                        ** on left table of a LEFT JOIN.  Ticket #3015 */
1267   }
1268   pTerm->prereqAll = prereqAll;
1269   pTerm->leftCursor = -1;
1270   pTerm->iParent = -1;
1271   pTerm->eOperator = 0;
1272   if( allowedOp(op) ){
1273     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1274     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1275     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
1276     if( pLeft->op==TK_COLUMN ){
1277       pTerm->leftCursor = pLeft->iTable;
1278       pTerm->u.leftColumn = pLeft->iColumn;
1279       pTerm->eOperator = operatorMask(op) & opMask;
1280     }
1281     if( pRight && pRight->op==TK_COLUMN ){
1282       WhereTerm *pNew;
1283       Expr *pDup;
1284       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
1285       if( pTerm->leftCursor>=0 ){
1286         int idxNew;
1287         pDup = sqlite3ExprDup(db, pExpr, 0);
1288         if( db->mallocFailed ){
1289           sqlite3ExprDelete(db, pDup);
1290           return;
1291         }
1292         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1293         if( idxNew==0 ) return;
1294         pNew = &pWC->a[idxNew];
1295         pNew->iParent = idxTerm;
1296         pTerm = &pWC->a[idxTerm];
1297         pTerm->nChild = 1;
1298         pTerm->wtFlags |= TERM_COPIED;
1299         if( pExpr->op==TK_EQ
1300          && !ExprHasProperty(pExpr, EP_FromJoin)
1301          && OptimizationEnabled(db, SQLITE_Transitive)
1302         ){
1303           pTerm->eOperator |= WO_EQUIV;
1304           eExtraOp = WO_EQUIV;
1305         }
1306       }else{
1307         pDup = pExpr;
1308         pNew = pTerm;
1309       }
1310       exprCommute(pParse, pDup);
1311       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
1312       pNew->leftCursor = pLeft->iTable;
1313       pNew->u.leftColumn = pLeft->iColumn;
1314       testcase( (prereqLeft | extraRight) != prereqLeft );
1315       pNew->prereqRight = prereqLeft | extraRight;
1316       pNew->prereqAll = prereqAll;
1317       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1318     }
1319   }
1320 
1321 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1322   /* If a term is the BETWEEN operator, create two new virtual terms
1323   ** that define the range that the BETWEEN implements.  For example:
1324   **
1325   **      a BETWEEN b AND c
1326   **
1327   ** is converted into:
1328   **
1329   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1330   **
1331   ** The two new terms are added onto the end of the WhereClause object.
1332   ** The new terms are "dynamic" and are children of the original BETWEEN
1333   ** term.  That means that if the BETWEEN term is coded, the children are
1334   ** skipped.  Or, if the children are satisfied by an index, the original
1335   ** BETWEEN term is skipped.
1336   */
1337   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1338     ExprList *pList = pExpr->x.pList;
1339     int i;
1340     static const u8 ops[] = {TK_GE, TK_LE};
1341     assert( pList!=0 );
1342     assert( pList->nExpr==2 );
1343     for(i=0; i<2; i++){
1344       Expr *pNewExpr;
1345       int idxNew;
1346       pNewExpr = sqlite3PExpr(pParse, ops[i],
1347                              sqlite3ExprDup(db, pExpr->pLeft, 0),
1348                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
1349       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1350       testcase( idxNew==0 );
1351       exprAnalyze(pSrc, pWC, idxNew);
1352       pTerm = &pWC->a[idxTerm];
1353       pWC->a[idxNew].iParent = idxTerm;
1354     }
1355     pTerm->nChild = 2;
1356   }
1357 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1358 
1359 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1360   /* Analyze a term that is composed of two or more subterms connected by
1361   ** an OR operator.
1362   */
1363   else if( pExpr->op==TK_OR ){
1364     assert( pWC->op==TK_AND );
1365     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1366     pTerm = &pWC->a[idxTerm];
1367   }
1368 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1369 
1370 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1371   /* Add constraints to reduce the search space on a LIKE or GLOB
1372   ** operator.
1373   **
1374   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1375   **
1376   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
1377   **
1378   ** The last character of the prefix "abc" is incremented to form the
1379   ** termination condition "abd".
1380   */
1381   if( pWC->op==TK_AND
1382    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1383   ){
1384     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
1385     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1386     Expr *pNewExpr1;
1387     Expr *pNewExpr2;
1388     int idxNew1;
1389     int idxNew2;
1390     Token sCollSeqName;  /* Name of collating sequence */
1391 
1392     pLeft = pExpr->x.pList->a[1].pExpr;
1393     pStr2 = sqlite3ExprDup(db, pStr1, 0);
1394     if( !db->mallocFailed ){
1395       u8 c, *pC;       /* Last character before the first wildcard */
1396       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1397       c = *pC;
1398       if( noCase ){
1399         /* The point is to increment the last character before the first
1400         ** wildcard.  But if we increment '@', that will push it into the
1401         ** alphabetic range where case conversions will mess up the
1402         ** inequality.  To avoid this, make sure to also run the full
1403         ** LIKE on all candidate expressions by clearing the isComplete flag
1404         */
1405         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
1406 
1407 
1408         c = sqlite3UpperToLower[c];
1409       }
1410       *pC = c + 1;
1411     }
1412     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1413     sCollSeqName.n = 6;
1414     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1415     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1416            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
1417            pStr1, 0);
1418     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
1419     testcase( idxNew1==0 );
1420     exprAnalyze(pSrc, pWC, idxNew1);
1421     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1422     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1423            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
1424            pStr2, 0);
1425     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
1426     testcase( idxNew2==0 );
1427     exprAnalyze(pSrc, pWC, idxNew2);
1428     pTerm = &pWC->a[idxTerm];
1429     if( isComplete ){
1430       pWC->a[idxNew1].iParent = idxTerm;
1431       pWC->a[idxNew2].iParent = idxTerm;
1432       pTerm->nChild = 2;
1433     }
1434   }
1435 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1436 
1437 #ifndef SQLITE_OMIT_VIRTUALTABLE
1438   /* Add a WO_MATCH auxiliary term to the constraint set if the
1439   ** current expression is of the form:  column MATCH expr.
1440   ** This information is used by the xBestIndex methods of
1441   ** virtual tables.  The native query optimizer does not attempt
1442   ** to do anything with MATCH functions.
1443   */
1444   if( isMatchOfColumn(pExpr) ){
1445     int idxNew;
1446     Expr *pRight, *pLeft;
1447     WhereTerm *pNewTerm;
1448     Bitmask prereqColumn, prereqExpr;
1449 
1450     pRight = pExpr->x.pList->a[0].pExpr;
1451     pLeft = pExpr->x.pList->a[1].pExpr;
1452     prereqExpr = exprTableUsage(pMaskSet, pRight);
1453     prereqColumn = exprTableUsage(pMaskSet, pLeft);
1454     if( (prereqExpr & prereqColumn)==0 ){
1455       Expr *pNewExpr;
1456       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1457                               0, sqlite3ExprDup(db, pRight, 0), 0);
1458       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1459       testcase( idxNew==0 );
1460       pNewTerm = &pWC->a[idxNew];
1461       pNewTerm->prereqRight = prereqExpr;
1462       pNewTerm->leftCursor = pLeft->iTable;
1463       pNewTerm->u.leftColumn = pLeft->iColumn;
1464       pNewTerm->eOperator = WO_MATCH;
1465       pNewTerm->iParent = idxTerm;
1466       pTerm = &pWC->a[idxTerm];
1467       pTerm->nChild = 1;
1468       pTerm->wtFlags |= TERM_COPIED;
1469       pNewTerm->prereqAll = pTerm->prereqAll;
1470     }
1471   }
1472 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1473 
1474 #ifdef SQLITE_ENABLE_STAT3
1475   /* When sqlite_stat3 histogram data is available an operator of the
1476   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1477   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
1478   ** virtual term of that form.
1479   **
1480   ** Note that the virtual term must be tagged with TERM_VNULL.  This
1481   ** TERM_VNULL tag will suppress the not-null check at the beginning
1482   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
1483   ** the start of the loop will prevent any results from being returned.
1484   */
1485   if( pExpr->op==TK_NOTNULL
1486    && pExpr->pLeft->op==TK_COLUMN
1487    && pExpr->pLeft->iColumn>=0
1488   ){
1489     Expr *pNewExpr;
1490     Expr *pLeft = pExpr->pLeft;
1491     int idxNew;
1492     WhereTerm *pNewTerm;
1493 
1494     pNewExpr = sqlite3PExpr(pParse, TK_GT,
1495                             sqlite3ExprDup(db, pLeft, 0),
1496                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1497 
1498     idxNew = whereClauseInsert(pWC, pNewExpr,
1499                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1500     if( idxNew ){
1501       pNewTerm = &pWC->a[idxNew];
1502       pNewTerm->prereqRight = 0;
1503       pNewTerm->leftCursor = pLeft->iTable;
1504       pNewTerm->u.leftColumn = pLeft->iColumn;
1505       pNewTerm->eOperator = WO_GT;
1506       pNewTerm->iParent = idxTerm;
1507       pTerm = &pWC->a[idxTerm];
1508       pTerm->nChild = 1;
1509       pTerm->wtFlags |= TERM_COPIED;
1510       pNewTerm->prereqAll = pTerm->prereqAll;
1511     }
1512   }
1513 #endif /* SQLITE_ENABLE_STAT */
1514 
1515   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1516   ** an index for tables to the left of the join.
1517   */
1518   pTerm->prereqRight |= extraRight;
1519 }
1520 
1521 /*
1522 ** This function searches the expression list passed as the second argument
1523 ** for an expression of type TK_COLUMN that refers to the same column and
1524 ** uses the same collation sequence as the iCol'th column of index pIdx.
1525 ** Argument iBase is the cursor number used for the table that pIdx refers
1526 ** to.
1527 **
1528 ** If such an expression is found, its index in pList->a[] is returned. If
1529 ** no expression is found, -1 is returned.
1530 */
1531 static int findIndexCol(
1532   Parse *pParse,                  /* Parse context */
1533   ExprList *pList,                /* Expression list to search */
1534   int iBase,                      /* Cursor for table associated with pIdx */
1535   Index *pIdx,                    /* Index to match column of */
1536   int iCol                        /* Column of index to match */
1537 ){
1538   int i;
1539   const char *zColl = pIdx->azColl[iCol];
1540 
1541   for(i=0; i<pList->nExpr; i++){
1542     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1543     if( p->op==TK_COLUMN
1544      && p->iColumn==pIdx->aiColumn[iCol]
1545      && p->iTable==iBase
1546     ){
1547       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1548       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
1549         return i;
1550       }
1551     }
1552   }
1553 
1554   return -1;
1555 }
1556 
1557 /*
1558 ** This routine determines if pIdx can be used to assist in processing a
1559 ** DISTINCT qualifier. In other words, it tests whether or not using this
1560 ** index for the outer loop guarantees that rows with equal values for
1561 ** all expressions in the pDistinct list are delivered grouped together.
1562 **
1563 ** For example, the query
1564 **
1565 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
1566 **
1567 ** can benefit from any index on columns "b" and "c".
1568 */
1569 static int isDistinctIndex(
1570   Parse *pParse,                  /* Parsing context */
1571   WhereClause *pWC,               /* The WHERE clause */
1572   Index *pIdx,                    /* The index being considered */
1573   int base,                       /* Cursor number for the table pIdx is on */
1574   ExprList *pDistinct,            /* The DISTINCT expressions */
1575   int nEqCol                      /* Number of index columns with == */
1576 ){
1577   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
1578   int i;                          /* Iterator variable */
1579 
1580   assert( pDistinct!=0 );
1581   if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
1582   testcase( pDistinct->nExpr==BMS-1 );
1583 
1584   /* Loop through all the expressions in the distinct list. If any of them
1585   ** are not simple column references, return early. Otherwise, test if the
1586   ** WHERE clause contains a "col=X" clause. If it does, the expression
1587   ** can be ignored. If it does not, and the column does not belong to the
1588   ** same table as index pIdx, return early. Finally, if there is no
1589   ** matching "col=X" expression and the column is on the same table as pIdx,
1590   ** set the corresponding bit in variable mask.
1591   */
1592   for(i=0; i<pDistinct->nExpr; i++){
1593     WhereTerm *pTerm;
1594     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
1595     if( p->op!=TK_COLUMN ) return 0;
1596     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
1597     if( pTerm ){
1598       Expr *pX = pTerm->pExpr;
1599       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
1600       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
1601       if( p1==p2 ) continue;
1602     }
1603     if( p->iTable!=base ) return 0;
1604     mask |= (((Bitmask)1) << i);
1605   }
1606 
1607   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
1608     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
1609     if( iExpr<0 ) break;
1610     mask &= ~(((Bitmask)1) << iExpr);
1611   }
1612 
1613   return (mask==0);
1614 }
1615 
1616 
1617 /*
1618 ** Return true if the DISTINCT expression-list passed as the third argument
1619 ** is redundant. A DISTINCT list is redundant if the database contains a
1620 ** UNIQUE index that guarantees that the result of the query will be distinct
1621 ** anyway.
1622 */
1623 static int isDistinctRedundant(
1624   Parse *pParse,
1625   SrcList *pTabList,
1626   WhereClause *pWC,
1627   ExprList *pDistinct
1628 ){
1629   Table *pTab;
1630   Index *pIdx;
1631   int i;
1632   int iBase;
1633 
1634   /* If there is more than one table or sub-select in the FROM clause of
1635   ** this query, then it will not be possible to show that the DISTINCT
1636   ** clause is redundant. */
1637   if( pTabList->nSrc!=1 ) return 0;
1638   iBase = pTabList->a[0].iCursor;
1639   pTab = pTabList->a[0].pTab;
1640 
1641   /* If any of the expressions is an IPK column on table iBase, then return
1642   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1643   ** current SELECT is a correlated sub-query.
1644   */
1645   for(i=0; i<pDistinct->nExpr; i++){
1646     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
1647     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
1648   }
1649 
1650   /* Loop through all indices on the table, checking each to see if it makes
1651   ** the DISTINCT qualifier redundant. It does so if:
1652   **
1653   **   1. The index is itself UNIQUE, and
1654   **
1655   **   2. All of the columns in the index are either part of the pDistinct
1656   **      list, or else the WHERE clause contains a term of the form "col=X",
1657   **      where X is a constant value. The collation sequences of the
1658   **      comparison and select-list expressions must match those of the index.
1659   **
1660   **   3. All of those index columns for which the WHERE clause does not
1661   **      contain a "col=X" term are subject to a NOT NULL constraint.
1662   */
1663   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1664     if( pIdx->onError==OE_None ) continue;
1665     for(i=0; i<pIdx->nColumn; i++){
1666       int iCol = pIdx->aiColumn[i];
1667       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1668         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
1669         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
1670           break;
1671         }
1672       }
1673     }
1674     if( i==pIdx->nColumn ){
1675       /* This index implies that the DISTINCT qualifier is redundant. */
1676       return 1;
1677     }
1678   }
1679 
1680   return 0;
1681 }
1682 
1683 /*
1684 ** Prepare a crude estimate of the logarithm of the input value.
1685 ** The results need not be exact.  This is only used for estimating
1686 ** the total cost of performing operations with O(logN) or O(NlogN)
1687 ** complexity.  Because N is just a guess, it is no great tragedy if
1688 ** logN is a little off.
1689 */
1690 static double estLog(double N){
1691   double logN = 1;
1692   double x = 10;
1693   while( N>x ){
1694     logN += 1;
1695     x *= 10;
1696   }
1697   return logN;
1698 }
1699 
1700 /*
1701 ** Two routines for printing the content of an sqlite3_index_info
1702 ** structure.  Used for testing and debugging only.  If neither
1703 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1704 ** are no-ops.
1705 */
1706 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
1707 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1708   int i;
1709   if( !sqlite3WhereTrace ) return;
1710   for(i=0; i<p->nConstraint; i++){
1711     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1712        i,
1713        p->aConstraint[i].iColumn,
1714        p->aConstraint[i].iTermOffset,
1715        p->aConstraint[i].op,
1716        p->aConstraint[i].usable);
1717   }
1718   for(i=0; i<p->nOrderBy; i++){
1719     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
1720        i,
1721        p->aOrderBy[i].iColumn,
1722        p->aOrderBy[i].desc);
1723   }
1724 }
1725 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1726   int i;
1727   if( !sqlite3WhereTrace ) return;
1728   for(i=0; i<p->nConstraint; i++){
1729     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
1730        i,
1731        p->aConstraintUsage[i].argvIndex,
1732        p->aConstraintUsage[i].omit);
1733   }
1734   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
1735   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
1736   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
1737   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
1738 }
1739 #else
1740 #define TRACE_IDX_INPUTS(A)
1741 #define TRACE_IDX_OUTPUTS(A)
1742 #endif
1743 
1744 /*
1745 ** Required because bestIndex() is called by bestOrClauseIndex()
1746 */
1747 static void bestIndex(WhereBestIdx*);
1748 
1749 /*
1750 ** This routine attempts to find an scanning strategy that can be used
1751 ** to optimize an 'OR' expression that is part of a WHERE clause.
1752 **
1753 ** The table associated with FROM clause term pSrc may be either a
1754 ** regular B-Tree table or a virtual table.
1755 */
1756 static void bestOrClauseIndex(WhereBestIdx *p){
1757 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
1758   WhereClause *pWC = p->pWC;           /* The WHERE clause */
1759   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
1760   const int iCur = pSrc->iCursor;      /* The cursor of the table  */
1761   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
1762   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
1763   WhereTerm *pTerm;                    /* A single term of the WHERE clause */
1764 
1765   /* The OR-clause optimization is disallowed if the INDEXED BY or
1766   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
1767   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
1768     return;
1769   }
1770   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
1771     return;
1772   }
1773 
1774   /* Search the WHERE clause terms for a usable WO_OR term. */
1775   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1776     if( (pTerm->eOperator & WO_OR)!=0
1777      && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
1778      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
1779     ){
1780       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
1781       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
1782       WhereTerm *pOrTerm;
1783       int flags = WHERE_MULTI_OR;
1784       double rTotal = 0;
1785       double nRow = 0;
1786       Bitmask used = 0;
1787       WhereBestIdx sBOI;
1788 
1789       sBOI = *p;
1790       sBOI.pOrderBy = 0;
1791       sBOI.pDistinct = 0;
1792       sBOI.ppIdxInfo = 0;
1793       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
1794         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
1795           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
1796         ));
1797         if( (pOrTerm->eOperator& WO_AND)!=0 ){
1798           sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
1799           bestIndex(&sBOI);
1800         }else if( pOrTerm->leftCursor==iCur ){
1801           WhereClause tempWC;
1802           tempWC.pParse = pWC->pParse;
1803           tempWC.pMaskSet = pWC->pMaskSet;
1804           tempWC.pOuter = pWC;
1805           tempWC.op = TK_AND;
1806           tempWC.a = pOrTerm;
1807           tempWC.wctrlFlags = 0;
1808           tempWC.nTerm = 1;
1809           sBOI.pWC = &tempWC;
1810           bestIndex(&sBOI);
1811         }else{
1812           continue;
1813         }
1814         rTotal += sBOI.cost.rCost;
1815         nRow += sBOI.cost.plan.nRow;
1816         used |= sBOI.cost.used;
1817         if( rTotal>=p->cost.rCost ) break;
1818       }
1819 
1820       /* If there is an ORDER BY clause, increase the scan cost to account
1821       ** for the cost of the sort. */
1822       if( p->pOrderBy!=0 ){
1823         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
1824                     rTotal, rTotal+nRow*estLog(nRow)));
1825         rTotal += nRow*estLog(nRow);
1826       }
1827 
1828       /* If the cost of scanning using this OR term for optimization is
1829       ** less than the current cost stored in pCost, replace the contents
1830       ** of pCost. */
1831       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
1832       if( rTotal<p->cost.rCost ){
1833         p->cost.rCost = rTotal;
1834         p->cost.used = used;
1835         p->cost.plan.nRow = nRow;
1836         p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
1837         p->cost.plan.wsFlags = flags;
1838         p->cost.plan.u.pTerm = pTerm;
1839       }
1840     }
1841   }
1842 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1843 }
1844 
1845 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1846 /*
1847 ** Return TRUE if the WHERE clause term pTerm is of a form where it
1848 ** could be used with an index to access pSrc, assuming an appropriate
1849 ** index existed.
1850 */
1851 static int termCanDriveIndex(
1852   WhereTerm *pTerm,              /* WHERE clause term to check */
1853   struct SrcList_item *pSrc,     /* Table we are trying to access */
1854   Bitmask notReady               /* Tables in outer loops of the join */
1855 ){
1856   char aff;
1857   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
1858   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
1859   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
1860   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1861   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1862   return 1;
1863 }
1864 #endif
1865 
1866 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1867 /*
1868 ** If the query plan for pSrc specified in pCost is a full table scan
1869 ** and indexing is allows (if there is no NOT INDEXED clause) and it
1870 ** possible to construct a transient index that would perform better
1871 ** than a full table scan even when the cost of constructing the index
1872 ** is taken into account, then alter the query plan to use the
1873 ** transient index.
1874 */
1875 static void bestAutomaticIndex(WhereBestIdx *p){
1876   Parse *pParse = p->pParse;            /* The parsing context */
1877   WhereClause *pWC = p->pWC;            /* The WHERE clause */
1878   struct SrcList_item *pSrc = p->pSrc;  /* The FROM clause term to search */
1879   double nTableRow;                     /* Rows in the input table */
1880   double logN;                          /* log(nTableRow) */
1881   double costTempIdx;         /* per-query cost of the transient index */
1882   WhereTerm *pTerm;           /* A single term of the WHERE clause */
1883   WhereTerm *pWCEnd;          /* End of pWC->a[] */
1884   Table *pTable;              /* Table tht might be indexed */
1885 
1886   if( pParse->nQueryLoop<=(double)1 ){
1887     /* There is no point in building an automatic index for a single scan */
1888     return;
1889   }
1890   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
1891     /* Automatic indices are disabled at run-time */
1892     return;
1893   }
1894   if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
1895    && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
1896   ){
1897     /* We already have some kind of index in use for this query. */
1898     return;
1899   }
1900   if( pSrc->viaCoroutine ){
1901     /* Cannot index a co-routine */
1902     return;
1903   }
1904   if( pSrc->notIndexed ){
1905     /* The NOT INDEXED clause appears in the SQL. */
1906     return;
1907   }
1908   if( pSrc->isCorrelated ){
1909     /* The source is a correlated sub-query. No point in indexing it. */
1910     return;
1911   }
1912 
1913   assert( pParse->nQueryLoop >= (double)1 );
1914   pTable = pSrc->pTab;
1915   nTableRow = pTable->nRowEst;
1916   logN = estLog(nTableRow);
1917   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
1918   if( costTempIdx>=p->cost.rCost ){
1919     /* The cost of creating the transient table would be greater than
1920     ** doing the full table scan */
1921     return;
1922   }
1923 
1924   /* Search for any equality comparison term */
1925   pWCEnd = &pWC->a[pWC->nTerm];
1926   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1927     if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
1928       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
1929                     p->cost.rCost, costTempIdx));
1930       p->cost.rCost = costTempIdx;
1931       p->cost.plan.nRow = logN + 1;
1932       p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
1933       p->cost.used = pTerm->prereqRight;
1934       break;
1935     }
1936   }
1937 }
1938 #else
1939 # define bestAutomaticIndex(A)  /* no-op */
1940 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1941 
1942 
1943 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1944 /*
1945 ** Generate code to construct the Index object for an automatic index
1946 ** and to set up the WhereLevel object pLevel so that the code generator
1947 ** makes use of the automatic index.
1948 */
1949 static void constructAutomaticIndex(
1950   Parse *pParse,              /* The parsing context */
1951   WhereClause *pWC,           /* The WHERE clause */
1952   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
1953   Bitmask notReady,           /* Mask of cursors that are not available */
1954   WhereLevel *pLevel          /* Write new index here */
1955 ){
1956   int nColumn;                /* Number of columns in the constructed index */
1957   WhereTerm *pTerm;           /* A single term of the WHERE clause */
1958   WhereTerm *pWCEnd;          /* End of pWC->a[] */
1959   int nByte;                  /* Byte of memory needed for pIdx */
1960   Index *pIdx;                /* Object describing the transient index */
1961   Vdbe *v;                    /* Prepared statement under construction */
1962   int addrInit;               /* Address of the initialization bypass jump */
1963   Table *pTable;              /* The table being indexed */
1964   KeyInfo *pKeyinfo;          /* Key information for the index */
1965   int addrTop;                /* Top of the index fill loop */
1966   int regRecord;              /* Register holding an index record */
1967   int n;                      /* Column counter */
1968   int i;                      /* Loop counter */
1969   int mxBitCol;               /* Maximum column in pSrc->colUsed */
1970   CollSeq *pColl;             /* Collating sequence to on a column */
1971   Bitmask idxCols;            /* Bitmap of columns used for indexing */
1972   Bitmask extraCols;          /* Bitmap of additional columns */
1973 
1974   /* Generate code to skip over the creation and initialization of the
1975   ** transient index on 2nd and subsequent iterations of the loop. */
1976   v = pParse->pVdbe;
1977   assert( v!=0 );
1978   addrInit = sqlite3CodeOnce(pParse);
1979 
1980   /* Count the number of columns that will be added to the index
1981   ** and used to match WHERE clause constraints */
1982   nColumn = 0;
1983   pTable = pSrc->pTab;
1984   pWCEnd = &pWC->a[pWC->nTerm];
1985   idxCols = 0;
1986   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1987     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1988       int iCol = pTerm->u.leftColumn;
1989       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
1990       testcase( iCol==BMS );
1991       testcase( iCol==BMS-1 );
1992       if( (idxCols & cMask)==0 ){
1993         nColumn++;
1994         idxCols |= cMask;
1995       }
1996     }
1997   }
1998   assert( nColumn>0 );
1999   pLevel->plan.nEq = nColumn;
2000 
2001   /* Count the number of additional columns needed to create a
2002   ** covering index.  A "covering index" is an index that contains all
2003   ** columns that are needed by the query.  With a covering index, the
2004   ** original table never needs to be accessed.  Automatic indices must
2005   ** be a covering index because the index will not be updated if the
2006   ** original table changes and the index and table cannot both be used
2007   ** if they go out of sync.
2008   */
2009   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
2010   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
2011   testcase( pTable->nCol==BMS-1 );
2012   testcase( pTable->nCol==BMS-2 );
2013   for(i=0; i<mxBitCol; i++){
2014     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
2015   }
2016   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
2017     nColumn += pTable->nCol - BMS + 1;
2018   }
2019   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
2020 
2021   /* Construct the Index object to describe this index */
2022   nByte = sizeof(Index);
2023   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
2024   nByte += nColumn*sizeof(char*);   /* Index.azColl */
2025   nByte += nColumn;                 /* Index.aSortOrder */
2026   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
2027   if( pIdx==0 ) return;
2028   pLevel->plan.u.pIdx = pIdx;
2029   pIdx->azColl = (char**)&pIdx[1];
2030   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
2031   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
2032   pIdx->zName = "auto-index";
2033   pIdx->nColumn = nColumn;
2034   pIdx->pTable = pTable;
2035   n = 0;
2036   idxCols = 0;
2037   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
2038     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
2039       int iCol = pTerm->u.leftColumn;
2040       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
2041       if( (idxCols & cMask)==0 ){
2042         Expr *pX = pTerm->pExpr;
2043         idxCols |= cMask;
2044         pIdx->aiColumn[n] = pTerm->u.leftColumn;
2045         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
2046         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
2047         n++;
2048       }
2049     }
2050   }
2051   assert( (u32)n==pLevel->plan.nEq );
2052 
2053   /* Add additional columns needed to make the automatic index into
2054   ** a covering index */
2055   for(i=0; i<mxBitCol; i++){
2056     if( extraCols & (((Bitmask)1)<<i) ){
2057       pIdx->aiColumn[n] = i;
2058       pIdx->azColl[n] = "BINARY";
2059       n++;
2060     }
2061   }
2062   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
2063     for(i=BMS-1; i<pTable->nCol; i++){
2064       pIdx->aiColumn[n] = i;
2065       pIdx->azColl[n] = "BINARY";
2066       n++;
2067     }
2068   }
2069   assert( n==nColumn );
2070 
2071   /* Create the automatic index */
2072   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
2073   assert( pLevel->iIdxCur>=0 );
2074   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
2075                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
2076   VdbeComment((v, "for %s", pTable->zName));
2077 
2078   /* Fill the automatic index with content */
2079   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
2080   regRecord = sqlite3GetTempReg(pParse);
2081   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
2082   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
2083   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2084   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
2085   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
2086   sqlite3VdbeJumpHere(v, addrTop);
2087   sqlite3ReleaseTempReg(pParse, regRecord);
2088 
2089   /* Jump here when skipping the initialization */
2090   sqlite3VdbeJumpHere(v, addrInit);
2091 }
2092 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
2093 
2094 #ifndef SQLITE_OMIT_VIRTUALTABLE
2095 /*
2096 ** Allocate and populate an sqlite3_index_info structure. It is the
2097 ** responsibility of the caller to eventually release the structure
2098 ** by passing the pointer returned by this function to sqlite3_free().
2099 */
2100 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
2101   Parse *pParse = p->pParse;
2102   WhereClause *pWC = p->pWC;
2103   struct SrcList_item *pSrc = p->pSrc;
2104   ExprList *pOrderBy = p->pOrderBy;
2105   int i, j;
2106   int nTerm;
2107   struct sqlite3_index_constraint *pIdxCons;
2108   struct sqlite3_index_orderby *pIdxOrderBy;
2109   struct sqlite3_index_constraint_usage *pUsage;
2110   WhereTerm *pTerm;
2111   int nOrderBy;
2112   sqlite3_index_info *pIdxInfo;
2113 
2114   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
2115 
2116   /* Count the number of possible WHERE clause constraints referring
2117   ** to this virtual table */
2118   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2119     if( pTerm->leftCursor != pSrc->iCursor ) continue;
2120     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2121     testcase( pTerm->eOperator & WO_IN );
2122     testcase( pTerm->eOperator & WO_ISNULL );
2123     if( pTerm->eOperator & (WO_ISNULL) ) continue;
2124     if( pTerm->wtFlags & TERM_VNULL ) continue;
2125     nTerm++;
2126   }
2127 
2128   /* If the ORDER BY clause contains only columns in the current
2129   ** virtual table then allocate space for the aOrderBy part of
2130   ** the sqlite3_index_info structure.
2131   */
2132   nOrderBy = 0;
2133   if( pOrderBy ){
2134     int n = pOrderBy->nExpr;
2135     for(i=0; i<n; i++){
2136       Expr *pExpr = pOrderBy->a[i].pExpr;
2137       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2138     }
2139     if( i==n){
2140       nOrderBy = n;
2141     }
2142   }
2143 
2144   /* Allocate the sqlite3_index_info structure
2145   */
2146   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2147                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2148                            + sizeof(*pIdxOrderBy)*nOrderBy );
2149   if( pIdxInfo==0 ){
2150     sqlite3ErrorMsg(pParse, "out of memory");
2151     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
2152     return 0;
2153   }
2154 
2155   /* Initialize the structure.  The sqlite3_index_info structure contains
2156   ** many fields that are declared "const" to prevent xBestIndex from
2157   ** changing them.  We have to do some funky casting in order to
2158   ** initialize those fields.
2159   */
2160   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2161   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2162   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2163   *(int*)&pIdxInfo->nConstraint = nTerm;
2164   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2165   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2166   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2167   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2168                                                                    pUsage;
2169 
2170   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2171     u8 op;
2172     if( pTerm->leftCursor != pSrc->iCursor ) continue;
2173     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2174     testcase( pTerm->eOperator & WO_IN );
2175     testcase( pTerm->eOperator & WO_ISNULL );
2176     if( pTerm->eOperator & (WO_ISNULL) ) continue;
2177     if( pTerm->wtFlags & TERM_VNULL ) continue;
2178     pIdxCons[j].iColumn = pTerm->u.leftColumn;
2179     pIdxCons[j].iTermOffset = i;
2180     op = (u8)pTerm->eOperator & WO_ALL;
2181     if( op==WO_IN ) op = WO_EQ;
2182     pIdxCons[j].op = op;
2183     /* The direct assignment in the previous line is possible only because
2184     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
2185     ** following asserts verify this fact. */
2186     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2187     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2188     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2189     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2190     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2191     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
2192     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
2193     j++;
2194   }
2195   for(i=0; i<nOrderBy; i++){
2196     Expr *pExpr = pOrderBy->a[i].pExpr;
2197     pIdxOrderBy[i].iColumn = pExpr->iColumn;
2198     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2199   }
2200 
2201   return pIdxInfo;
2202 }
2203 
2204 /*
2205 ** The table object reference passed as the second argument to this function
2206 ** must represent a virtual table. This function invokes the xBestIndex()
2207 ** method of the virtual table with the sqlite3_index_info pointer passed
2208 ** as the argument.
2209 **
2210 ** If an error occurs, pParse is populated with an error message and a
2211 ** non-zero value is returned. Otherwise, 0 is returned and the output
2212 ** part of the sqlite3_index_info structure is left populated.
2213 **
2214 ** Whether or not an error is returned, it is the responsibility of the
2215 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2216 ** that this is required.
2217 */
2218 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
2219   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
2220   int i;
2221   int rc;
2222 
2223   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
2224   TRACE_IDX_INPUTS(p);
2225   rc = pVtab->pModule->xBestIndex(pVtab, p);
2226   TRACE_IDX_OUTPUTS(p);
2227 
2228   if( rc!=SQLITE_OK ){
2229     if( rc==SQLITE_NOMEM ){
2230       pParse->db->mallocFailed = 1;
2231     }else if( !pVtab->zErrMsg ){
2232       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2233     }else{
2234       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2235     }
2236   }
2237   sqlite3_free(pVtab->zErrMsg);
2238   pVtab->zErrMsg = 0;
2239 
2240   for(i=0; i<p->nConstraint; i++){
2241     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2242       sqlite3ErrorMsg(pParse,
2243           "table %s: xBestIndex returned an invalid plan", pTab->zName);
2244     }
2245   }
2246 
2247   return pParse->nErr;
2248 }
2249 
2250 
2251 /*
2252 ** Compute the best index for a virtual table.
2253 **
2254 ** The best index is computed by the xBestIndex method of the virtual
2255 ** table module.  This routine is really just a wrapper that sets up
2256 ** the sqlite3_index_info structure that is used to communicate with
2257 ** xBestIndex.
2258 **
2259 ** In a join, this routine might be called multiple times for the
2260 ** same virtual table.  The sqlite3_index_info structure is created
2261 ** and initialized on the first invocation and reused on all subsequent
2262 ** invocations.  The sqlite3_index_info structure is also used when
2263 ** code is generated to access the virtual table.  The whereInfoDelete()
2264 ** routine takes care of freeing the sqlite3_index_info structure after
2265 ** everybody has finished with it.
2266 */
2267 static void bestVirtualIndex(WhereBestIdx *p){
2268   Parse *pParse = p->pParse;      /* The parsing context */
2269   WhereClause *pWC = p->pWC;      /* The WHERE clause */
2270   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
2271   Table *pTab = pSrc->pTab;
2272   sqlite3_index_info *pIdxInfo;
2273   struct sqlite3_index_constraint *pIdxCons;
2274   struct sqlite3_index_constraint_usage *pUsage;
2275   WhereTerm *pTerm;
2276   int i, j, k;
2277   int nOrderBy;
2278   int sortOrder;                  /* Sort order for IN clauses */
2279   int bAllowIN;                   /* Allow IN optimizations */
2280   double rCost;
2281 
2282   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
2283   ** malloc in allocateIndexInfo() fails and this function returns leaving
2284   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
2285   */
2286   memset(&p->cost, 0, sizeof(p->cost));
2287   p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
2288 
2289   /* If the sqlite3_index_info structure has not been previously
2290   ** allocated and initialized, then allocate and initialize it now.
2291   */
2292   pIdxInfo = *p->ppIdxInfo;
2293   if( pIdxInfo==0 ){
2294     *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
2295   }
2296   if( pIdxInfo==0 ){
2297     return;
2298   }
2299 
2300   /* At this point, the sqlite3_index_info structure that pIdxInfo points
2301   ** to will have been initialized, either during the current invocation or
2302   ** during some prior invocation.  Now we just have to customize the
2303   ** details of pIdxInfo for the current invocation and pass it to
2304   ** xBestIndex.
2305   */
2306 
2307   /* The module name must be defined. Also, by this point there must
2308   ** be a pointer to an sqlite3_vtab structure. Otherwise
2309   ** sqlite3ViewGetColumnNames() would have picked up the error.
2310   */
2311   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
2312   assert( sqlite3GetVTable(pParse->db, pTab) );
2313 
2314   /* Try once or twice.  On the first attempt, allow IN optimizations.
2315   ** If an IN optimization is accepted by the virtual table xBestIndex
2316   ** method, but the  pInfo->aConstrainUsage.omit flag is not set, then
2317   ** the query will not work because it might allow duplicate rows in
2318   ** output.  In that case, run the xBestIndex method a second time
2319   ** without the IN constraints.  Usually this loop only runs once.
2320   ** The loop will exit using a "break" statement.
2321   */
2322   for(bAllowIN=1; 1; bAllowIN--){
2323     assert( bAllowIN==0 || bAllowIN==1 );
2324 
2325     /* Set the aConstraint[].usable fields and initialize all
2326     ** output variables to zero.
2327     **
2328     ** aConstraint[].usable is true for constraints where the right-hand
2329     ** side contains only references to tables to the left of the current
2330     ** table.  In other words, if the constraint is of the form:
2331     **
2332     **           column = expr
2333     **
2334     ** and we are evaluating a join, then the constraint on column is
2335     ** only valid if all tables referenced in expr occur to the left
2336     ** of the table containing column.
2337     **
2338     ** The aConstraints[] array contains entries for all constraints
2339     ** on the current table.  That way we only have to compute it once
2340     ** even though we might try to pick the best index multiple times.
2341     ** For each attempt at picking an index, the order of tables in the
2342     ** join might be different so we have to recompute the usable flag
2343     ** each time.
2344     */
2345     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2346     pUsage = pIdxInfo->aConstraintUsage;
2347     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
2348       j = pIdxCons->iTermOffset;
2349       pTerm = &pWC->a[j];
2350       if( (pTerm->prereqRight&p->notReady)==0
2351        && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
2352       ){
2353         pIdxCons->usable = 1;
2354       }else{
2355         pIdxCons->usable = 0;
2356       }
2357     }
2358     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
2359     if( pIdxInfo->needToFreeIdxStr ){
2360       sqlite3_free(pIdxInfo->idxStr);
2361     }
2362     pIdxInfo->idxStr = 0;
2363     pIdxInfo->idxNum = 0;
2364     pIdxInfo->needToFreeIdxStr = 0;
2365     pIdxInfo->orderByConsumed = 0;
2366     /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
2367     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
2368     nOrderBy = pIdxInfo->nOrderBy;
2369     if( !p->pOrderBy ){
2370       pIdxInfo->nOrderBy = 0;
2371     }
2372 
2373     if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
2374       return;
2375     }
2376 
2377     sortOrder = SQLITE_SO_ASC;
2378     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2379     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
2380       if( pUsage[i].argvIndex>0 ){
2381         j = pIdxCons->iTermOffset;
2382         pTerm = &pWC->a[j];
2383         p->cost.used |= pTerm->prereqRight;
2384         if( (pTerm->eOperator & WO_IN)!=0 ){
2385           if( pUsage[i].omit==0 ){
2386             /* Do not attempt to use an IN constraint if the virtual table
2387             ** says that the equivalent EQ constraint cannot be safely omitted.
2388             ** If we do attempt to use such a constraint, some rows might be
2389             ** repeated in the output. */
2390             break;
2391           }
2392           for(k=0; k<pIdxInfo->nOrderBy; k++){
2393             if( pIdxInfo->aOrderBy[k].iColumn==pIdxCons->iColumn ){
2394               sortOrder = pIdxInfo->aOrderBy[k].desc;
2395               break;
2396             }
2397           }
2398         }
2399       }
2400     }
2401     if( i>=pIdxInfo->nConstraint ) break;
2402   }
2403 
2404   /* If there is an ORDER BY clause, and the selected virtual table index
2405   ** does not satisfy it, increase the cost of the scan accordingly. This
2406   ** matches the processing for non-virtual tables in bestBtreeIndex().
2407   */
2408   rCost = pIdxInfo->estimatedCost;
2409   if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
2410     rCost += estLog(rCost)*rCost;
2411   }
2412 
2413   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
2414   ** inital value of lowestCost in this loop. If it is, then the
2415   ** (cost<lowestCost) test below will never be true.
2416   **
2417   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
2418   ** is defined.
2419   */
2420   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
2421     p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
2422   }else{
2423     p->cost.rCost = rCost;
2424   }
2425   p->cost.plan.u.pVtabIdx = pIdxInfo;
2426   if( pIdxInfo->orderByConsumed ){
2427     assert( sortOrder==0 || sortOrder==1 );
2428     p->cost.plan.wsFlags |= WHERE_ORDERED + sortOrder*WHERE_REVERSE;
2429     p->cost.plan.nOBSat = nOrderBy;
2430   }else{
2431     p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
2432   }
2433   p->cost.plan.nEq = 0;
2434   pIdxInfo->nOrderBy = nOrderBy;
2435 
2436   /* Try to find a more efficient access pattern by using multiple indexes
2437   ** to optimize an OR expression within the WHERE clause.
2438   */
2439   bestOrClauseIndex(p);
2440 }
2441 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2442 
2443 #ifdef SQLITE_ENABLE_STAT3
2444 /*
2445 ** Estimate the location of a particular key among all keys in an
2446 ** index.  Store the results in aStat as follows:
2447 **
2448 **    aStat[0]      Est. number of rows less than pVal
2449 **    aStat[1]      Est. number of rows equal to pVal
2450 **
2451 ** Return SQLITE_OK on success.
2452 */
2453 static int whereKeyStats(
2454   Parse *pParse,              /* Database connection */
2455   Index *pIdx,                /* Index to consider domain of */
2456   sqlite3_value *pVal,        /* Value to consider */
2457   int roundUp,                /* Round up if true.  Round down if false */
2458   tRowcnt *aStat              /* OUT: stats written here */
2459 ){
2460   tRowcnt n;
2461   IndexSample *aSample;
2462   int i, eType;
2463   int isEq = 0;
2464   i64 v;
2465   double r, rS;
2466 
2467   assert( roundUp==0 || roundUp==1 );
2468   assert( pIdx->nSample>0 );
2469   if( pVal==0 ) return SQLITE_ERROR;
2470   n = pIdx->aiRowEst[0];
2471   aSample = pIdx->aSample;
2472   eType = sqlite3_value_type(pVal);
2473 
2474   if( eType==SQLITE_INTEGER ){
2475     v = sqlite3_value_int64(pVal);
2476     r = (i64)v;
2477     for(i=0; i<pIdx->nSample; i++){
2478       if( aSample[i].eType==SQLITE_NULL ) continue;
2479       if( aSample[i].eType>=SQLITE_TEXT ) break;
2480       if( aSample[i].eType==SQLITE_INTEGER ){
2481         if( aSample[i].u.i>=v ){
2482           isEq = aSample[i].u.i==v;
2483           break;
2484         }
2485       }else{
2486         assert( aSample[i].eType==SQLITE_FLOAT );
2487         if( aSample[i].u.r>=r ){
2488           isEq = aSample[i].u.r==r;
2489           break;
2490         }
2491       }
2492     }
2493   }else if( eType==SQLITE_FLOAT ){
2494     r = sqlite3_value_double(pVal);
2495     for(i=0; i<pIdx->nSample; i++){
2496       if( aSample[i].eType==SQLITE_NULL ) continue;
2497       if( aSample[i].eType>=SQLITE_TEXT ) break;
2498       if( aSample[i].eType==SQLITE_FLOAT ){
2499         rS = aSample[i].u.r;
2500       }else{
2501         rS = aSample[i].u.i;
2502       }
2503       if( rS>=r ){
2504         isEq = rS==r;
2505         break;
2506       }
2507     }
2508   }else if( eType==SQLITE_NULL ){
2509     i = 0;
2510     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
2511   }else{
2512     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2513     for(i=0; i<pIdx->nSample; i++){
2514       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
2515         break;
2516       }
2517     }
2518     if( i<pIdx->nSample ){
2519       sqlite3 *db = pParse->db;
2520       CollSeq *pColl;
2521       const u8 *z;
2522       if( eType==SQLITE_BLOB ){
2523         z = (const u8 *)sqlite3_value_blob(pVal);
2524         pColl = db->pDfltColl;
2525         assert( pColl->enc==SQLITE_UTF8 );
2526       }else{
2527         pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
2528         if( pColl==0 ){
2529           return SQLITE_ERROR;
2530         }
2531         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
2532         if( !z ){
2533           return SQLITE_NOMEM;
2534         }
2535         assert( z && pColl && pColl->xCmp );
2536       }
2537       n = sqlite3ValueBytes(pVal, pColl->enc);
2538 
2539       for(; i<pIdx->nSample; i++){
2540         int c;
2541         int eSampletype = aSample[i].eType;
2542         if( eSampletype<eType ) continue;
2543         if( eSampletype!=eType ) break;
2544 #ifndef SQLITE_OMIT_UTF16
2545         if( pColl->enc!=SQLITE_UTF8 ){
2546           int nSample;
2547           char *zSample = sqlite3Utf8to16(
2548               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
2549           );
2550           if( !zSample ){
2551             assert( db->mallocFailed );
2552             return SQLITE_NOMEM;
2553           }
2554           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
2555           sqlite3DbFree(db, zSample);
2556         }else
2557 #endif
2558         {
2559           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
2560         }
2561         if( c>=0 ){
2562           if( c==0 ) isEq = 1;
2563           break;
2564         }
2565       }
2566     }
2567   }
2568 
2569   /* At this point, aSample[i] is the first sample that is greater than
2570   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
2571   ** than pVal.  If aSample[i]==pVal, then isEq==1.
2572   */
2573   if( isEq ){
2574     assert( i<pIdx->nSample );
2575     aStat[0] = aSample[i].nLt;
2576     aStat[1] = aSample[i].nEq;
2577   }else{
2578     tRowcnt iLower, iUpper, iGap;
2579     if( i==0 ){
2580       iLower = 0;
2581       iUpper = aSample[0].nLt;
2582     }else{
2583       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
2584       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
2585     }
2586     aStat[1] = pIdx->avgEq;
2587     if( iLower>=iUpper ){
2588       iGap = 0;
2589     }else{
2590       iGap = iUpper - iLower;
2591     }
2592     if( roundUp ){
2593       iGap = (iGap*2)/3;
2594     }else{
2595       iGap = iGap/3;
2596     }
2597     aStat[0] = iLower + iGap;
2598   }
2599   return SQLITE_OK;
2600 }
2601 #endif /* SQLITE_ENABLE_STAT3 */
2602 
2603 /*
2604 ** If expression pExpr represents a literal value, set *pp to point to
2605 ** an sqlite3_value structure containing the same value, with affinity
2606 ** aff applied to it, before returning. It is the responsibility of the
2607 ** caller to eventually release this structure by passing it to
2608 ** sqlite3ValueFree().
2609 **
2610 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
2611 ** is an SQL variable that currently has a non-NULL value bound to it,
2612 ** create an sqlite3_value structure containing this value, again with
2613 ** affinity aff applied to it, instead.
2614 **
2615 ** If neither of the above apply, set *pp to NULL.
2616 **
2617 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
2618 */
2619 #ifdef SQLITE_ENABLE_STAT3
2620 static int valueFromExpr(
2621   Parse *pParse,
2622   Expr *pExpr,
2623   u8 aff,
2624   sqlite3_value **pp
2625 ){
2626   if( pExpr->op==TK_VARIABLE
2627    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
2628   ){
2629     int iVar = pExpr->iColumn;
2630     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
2631     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
2632     return SQLITE_OK;
2633   }
2634   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
2635 }
2636 #endif
2637 
2638 /*
2639 ** This function is used to estimate the number of rows that will be visited
2640 ** by scanning an index for a range of values. The range may have an upper
2641 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
2642 ** and lower bounds are represented by pLower and pUpper respectively. For
2643 ** example, assuming that index p is on t1(a):
2644 **
2645 **   ... FROM t1 WHERE a > ? AND a < ? ...
2646 **                    |_____|   |_____|
2647 **                       |         |
2648 **                     pLower    pUpper
2649 **
2650 ** If either of the upper or lower bound is not present, then NULL is passed in
2651 ** place of the corresponding WhereTerm.
2652 **
2653 ** The nEq parameter is passed the index of the index column subject to the
2654 ** range constraint. Or, equivalently, the number of equality constraints
2655 ** optimized by the proposed index scan. For example, assuming index p is
2656 ** on t1(a, b), and the SQL query is:
2657 **
2658 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2659 **
2660 ** then nEq should be passed the value 1 (as the range restricted column,
2661 ** b, is the second left-most column of the index). Or, if the query is:
2662 **
2663 **   ... FROM t1 WHERE a > ? AND a < ? ...
2664 **
2665 ** then nEq should be passed 0.
2666 **
2667 ** The returned value is an integer divisor to reduce the estimated
2668 ** search space.  A return value of 1 means that range constraints are
2669 ** no help at all.  A return value of 2 means range constraints are
2670 ** expected to reduce the search space by half.  And so forth...
2671 **
2672 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
2673 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
2674 ** results in a return of 4 and a range constraint (x>? AND x<?) results
2675 ** in a return of 16.
2676 */
2677 static int whereRangeScanEst(
2678   Parse *pParse,       /* Parsing & code generating context */
2679   Index *p,            /* The index containing the range-compared column; "x" */
2680   int nEq,             /* index into p->aCol[] of the range-compared column */
2681   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
2682   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
2683   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
2684 ){
2685   int rc = SQLITE_OK;
2686 
2687 #ifdef SQLITE_ENABLE_STAT3
2688 
2689   if( nEq==0 && p->nSample ){
2690     sqlite3_value *pRangeVal;
2691     tRowcnt iLower = 0;
2692     tRowcnt iUpper = p->aiRowEst[0];
2693     tRowcnt a[2];
2694     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
2695 
2696     if( pLower ){
2697       Expr *pExpr = pLower->pExpr->pRight;
2698       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
2699       assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
2700       if( rc==SQLITE_OK
2701        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
2702       ){
2703         iLower = a[0];
2704         if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
2705       }
2706       sqlite3ValueFree(pRangeVal);
2707     }
2708     if( rc==SQLITE_OK && pUpper ){
2709       Expr *pExpr = pUpper->pExpr->pRight;
2710       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
2711       assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
2712       if( rc==SQLITE_OK
2713        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
2714       ){
2715         iUpper = a[0];
2716         if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
2717       }
2718       sqlite3ValueFree(pRangeVal);
2719     }
2720     if( rc==SQLITE_OK ){
2721       if( iUpper<=iLower ){
2722         *pRangeDiv = (double)p->aiRowEst[0];
2723       }else{
2724         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
2725       }
2726       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
2727                   (u32)iLower, (u32)iUpper, *pRangeDiv));
2728       return SQLITE_OK;
2729     }
2730   }
2731 #else
2732   UNUSED_PARAMETER(pParse);
2733   UNUSED_PARAMETER(p);
2734   UNUSED_PARAMETER(nEq);
2735 #endif
2736   assert( pLower || pUpper );
2737   *pRangeDiv = (double)1;
2738   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
2739   if( pUpper ) *pRangeDiv *= (double)4;
2740   return rc;
2741 }
2742 
2743 #ifdef SQLITE_ENABLE_STAT3
2744 /*
2745 ** Estimate the number of rows that will be returned based on
2746 ** an equality constraint x=VALUE and where that VALUE occurs in
2747 ** the histogram data.  This only works when x is the left-most
2748 ** column of an index and sqlite_stat3 histogram data is available
2749 ** for that index.  When pExpr==NULL that means the constraint is
2750 ** "x IS NULL" instead of "x=VALUE".
2751 **
2752 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2753 ** If unable to make an estimate, leave *pnRow unchanged and return
2754 ** non-zero.
2755 **
2756 ** This routine can fail if it is unable to load a collating sequence
2757 ** required for string comparison, or if unable to allocate memory
2758 ** for a UTF conversion required for comparison.  The error is stored
2759 ** in the pParse structure.
2760 */
2761 static int whereEqualScanEst(
2762   Parse *pParse,       /* Parsing & code generating context */
2763   Index *p,            /* The index whose left-most column is pTerm */
2764   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
2765   double *pnRow        /* Write the revised row estimate here */
2766 ){
2767   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
2768   u8 aff;                   /* Column affinity */
2769   int rc;                   /* Subfunction return code */
2770   tRowcnt a[2];             /* Statistics */
2771 
2772   assert( p->aSample!=0 );
2773   assert( p->nSample>0 );
2774   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
2775   if( pExpr ){
2776     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
2777     if( rc ) goto whereEqualScanEst_cancel;
2778   }else{
2779     pRhs = sqlite3ValueNew(pParse->db);
2780   }
2781   if( pRhs==0 ) return SQLITE_NOTFOUND;
2782   rc = whereKeyStats(pParse, p, pRhs, 0, a);
2783   if( rc==SQLITE_OK ){
2784     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
2785     *pnRow = a[1];
2786   }
2787 whereEqualScanEst_cancel:
2788   sqlite3ValueFree(pRhs);
2789   return rc;
2790 }
2791 #endif /* defined(SQLITE_ENABLE_STAT3) */
2792 
2793 #ifdef SQLITE_ENABLE_STAT3
2794 /*
2795 ** Estimate the number of rows that will be returned based on
2796 ** an IN constraint where the right-hand side of the IN operator
2797 ** is a list of values.  Example:
2798 **
2799 **        WHERE x IN (1,2,3,4)
2800 **
2801 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2802 ** If unable to make an estimate, leave *pnRow unchanged and return
2803 ** non-zero.
2804 **
2805 ** This routine can fail if it is unable to load a collating sequence
2806 ** required for string comparison, or if unable to allocate memory
2807 ** for a UTF conversion required for comparison.  The error is stored
2808 ** in the pParse structure.
2809 */
2810 static int whereInScanEst(
2811   Parse *pParse,       /* Parsing & code generating context */
2812   Index *p,            /* The index whose left-most column is pTerm */
2813   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
2814   double *pnRow        /* Write the revised row estimate here */
2815 ){
2816   int rc = SQLITE_OK;         /* Subfunction return code */
2817   double nEst;                /* Number of rows for a single term */
2818   double nRowEst = (double)0; /* New estimate of the number of rows */
2819   int i;                      /* Loop counter */
2820 
2821   assert( p->aSample!=0 );
2822   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2823     nEst = p->aiRowEst[0];
2824     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
2825     nRowEst += nEst;
2826   }
2827   if( rc==SQLITE_OK ){
2828     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2829     *pnRow = nRowEst;
2830     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
2831   }
2832   return rc;
2833 }
2834 #endif /* defined(SQLITE_ENABLE_STAT3) */
2835 
2836 /*
2837 ** Check to see if column iCol of the table with cursor iTab will appear
2838 ** in sorted order according to the current query plan.
2839 **
2840 ** Return values:
2841 **
2842 **    0   iCol is not ordered
2843 **    1   iCol has only a single value
2844 **    2   iCol is in ASC order
2845 **    3   iCol is in DESC order
2846 */
2847 static int isOrderedColumn(
2848   WhereBestIdx *p,
2849   int iTab,
2850   int iCol
2851 ){
2852   int i, j;
2853   WhereLevel *pLevel = &p->aLevel[p->i-1];
2854   Index *pIdx;
2855   u8 sortOrder;
2856   for(i=p->i-1; i>=0; i--, pLevel--){
2857     if( pLevel->iTabCur!=iTab ) continue;
2858     if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
2859       return 1;
2860     }
2861     assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
2862     if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
2863       if( iCol<0 ){
2864         sortOrder = 0;
2865         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
2866       }else{
2867         int n = pIdx->nColumn;
2868         for(j=0; j<n; j++){
2869           if( iCol==pIdx->aiColumn[j] ) break;
2870         }
2871         if( j>=n ) return 0;
2872         sortOrder = pIdx->aSortOrder[j];
2873         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
2874       }
2875     }else{
2876       if( iCol!=(-1) ) return 0;
2877       sortOrder = 0;
2878       testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
2879     }
2880     if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
2881       assert( sortOrder==0 || sortOrder==1 );
2882       testcase( sortOrder==1 );
2883       sortOrder = 1 - sortOrder;
2884     }
2885     return sortOrder+2;
2886   }
2887   return 0;
2888 }
2889 
2890 /*
2891 ** This routine decides if pIdx can be used to satisfy the ORDER BY
2892 ** clause, either in whole or in part.  The return value is the
2893 ** cumulative number of terms in the ORDER BY clause that are satisfied
2894 ** by the index pIdx and other indices in outer loops.
2895 **
2896 ** The table being queried has a cursor number of "base".  pIdx is the
2897 ** index that is postulated for use to access the table.
2898 **
2899 ** The *pbRev value is set to 0 order 1 depending on whether or not
2900 ** pIdx should be run in the forward order or in reverse order.
2901 */
2902 static int isSortingIndex(
2903   WhereBestIdx *p,    /* Best index search context */
2904   Index *pIdx,        /* The index we are testing */
2905   int base,           /* Cursor number for the table to be sorted */
2906   int *pbRev          /* Set to 1 for reverse-order scan of pIdx */
2907 ){
2908   int i;                        /* Number of pIdx terms used */
2909   int j;                        /* Number of ORDER BY terms satisfied */
2910   int sortOrder = 2;            /* 0: forward.  1: backward.  2: unknown */
2911   int nTerm;                    /* Number of ORDER BY terms */
2912   struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
2913   Table *pTab = pIdx->pTable;   /* Table that owns index pIdx */
2914   ExprList *pOrderBy;           /* The ORDER BY clause */
2915   Parse *pParse = p->pParse;    /* Parser context */
2916   sqlite3 *db = pParse->db;     /* Database connection */
2917   int nPriorSat;                /* ORDER BY terms satisfied by outer loops */
2918   int seenRowid = 0;            /* True if an ORDER BY rowid term is seen */
2919   int uniqueNotNull;            /* pIdx is UNIQUE with all terms are NOT NULL */
2920 
2921   if( p->i==0 ){
2922     nPriorSat = 0;
2923   }else{
2924     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
2925     if( (p->aLevel[p->i-1].plan.wsFlags & WHERE_ORDERED)==0 ){
2926       /* This loop cannot be ordered unless the next outer loop is
2927       ** also ordered */
2928       return nPriorSat;
2929     }
2930     if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
2931       /* Only look at the outer-most loop if the OrderByIdxJoin
2932       ** optimization is disabled */
2933       return nPriorSat;
2934     }
2935   }
2936   pOrderBy = p->pOrderBy;
2937   assert( pOrderBy!=0 );
2938   if( pIdx->bUnordered ){
2939     /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
2940     ** be used for sorting */
2941     return nPriorSat;
2942   }
2943   nTerm = pOrderBy->nExpr;
2944   uniqueNotNull = pIdx->onError!=OE_None;
2945   assert( nTerm>0 );
2946 
2947   /* Argument pIdx must either point to a 'real' named index structure,
2948   ** or an index structure allocated on the stack by bestBtreeIndex() to
2949   ** represent the rowid index that is part of every table.  */
2950   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
2951 
2952   /* Match terms of the ORDER BY clause against columns of
2953   ** the index.
2954   **
2955   ** Note that indices have pIdx->nColumn regular columns plus
2956   ** one additional column containing the rowid.  The rowid column
2957   ** of the index is also allowed to match against the ORDER BY
2958   ** clause.
2959   */
2960   j = nPriorSat;
2961   for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
2962     Expr *pOBExpr;          /* The expression of the ORDER BY pOBItem */
2963     CollSeq *pColl;         /* The collating sequence of pOBExpr */
2964     int termSortOrder;      /* Sort order for this term */
2965     int iColumn;            /* The i-th column of the index.  -1 for rowid */
2966     int iSortOrder;         /* 1 for DESC, 0 for ASC on the i-th index term */
2967     int isEq;               /* Subject to an == or IS NULL constraint */
2968     int isMatch;            /* ORDER BY term matches the index term */
2969     const char *zColl;      /* Name of collating sequence for i-th index term */
2970     WhereTerm *pConstraint; /* A constraint in the WHERE clause */
2971 
2972     /* If the next term of the ORDER BY clause refers to anything other than
2973     ** a column in the "base" table, then this index will not be of any
2974     ** further use in handling the ORDER BY. */
2975     pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
2976     if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
2977       break;
2978     }
2979 
2980     /* Find column number and collating sequence for the next entry
2981     ** in the index */
2982     if( pIdx->zName && i<pIdx->nColumn ){
2983       iColumn = pIdx->aiColumn[i];
2984       if( iColumn==pIdx->pTable->iPKey ){
2985         iColumn = -1;
2986       }
2987       iSortOrder = pIdx->aSortOrder[i];
2988       zColl = pIdx->azColl[i];
2989       assert( zColl!=0 );
2990     }else{
2991       iColumn = -1;
2992       iSortOrder = 0;
2993       zColl = 0;
2994     }
2995 
2996     /* Check to see if the column number and collating sequence of the
2997     ** index match the column number and collating sequence of the ORDER BY
2998     ** clause entry.  Set isMatch to 1 if they both match. */
2999     if( pOBExpr->iColumn==iColumn ){
3000       if( zColl ){
3001         pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
3002         if( !pColl ) pColl = db->pDfltColl;
3003         isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
3004       }else{
3005         isMatch = 1;
3006       }
3007     }else{
3008       isMatch = 0;
3009     }
3010 
3011     /* termSortOrder is 0 or 1 for whether or not the access loop should
3012     ** run forward or backwards (respectively) in order to satisfy this
3013     ** term of the ORDER BY clause. */
3014     assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
3015     assert( iSortOrder==0 || iSortOrder==1 );
3016     termSortOrder = iSortOrder ^ pOBItem->sortOrder;
3017 
3018     /* If X is the column in the index and ORDER BY clause, check to see
3019     ** if there are any X= or X IS NULL constraints in the WHERE clause. */
3020     pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
3021                            WO_EQ|WO_ISNULL|WO_IN, pIdx);
3022     if( pConstraint==0 ){
3023       isEq = 0;
3024     }else if( (pConstraint->eOperator & WO_IN)!=0 ){
3025       isEq = 0;
3026     }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
3027       uniqueNotNull = 0;
3028       isEq = 1;  /* "X IS NULL" means X has only a single value */
3029     }else if( pConstraint->prereqRight==0 ){
3030       isEq = 1;  /* Constraint "X=constant" means X has only a single value */
3031     }else{
3032       Expr *pRight = pConstraint->pExpr->pRight;
3033       if( pRight->op==TK_COLUMN ){
3034         WHERETRACE(("       .. isOrderedColumn(tab=%d,col=%d)",
3035                     pRight->iTable, pRight->iColumn));
3036         isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
3037         WHERETRACE((" -> isEq=%d\n", isEq));
3038 
3039         /* If the constraint is of the form X=Y where Y is an ordered value
3040         ** in an outer loop, then make sure the sort order of Y matches the
3041         ** sort order required for X. */
3042         if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
3043           testcase( isEq==2 );
3044           testcase( isEq==3 );
3045           break;
3046         }
3047       }else{
3048         isEq = 0;  /* "X=expr" places no ordering constraints on X */
3049       }
3050     }
3051     if( !isMatch ){
3052       if( isEq==0 ){
3053         break;
3054       }else{
3055         continue;
3056       }
3057     }else if( isEq!=1 ){
3058       if( sortOrder==2 ){
3059         sortOrder = termSortOrder;
3060       }else if( termSortOrder!=sortOrder ){
3061         break;
3062       }
3063     }
3064     j++;
3065     pOBItem++;
3066     if( iColumn<0 ){
3067       seenRowid = 1;
3068       break;
3069     }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
3070       testcase( isEq==0 );
3071       testcase( isEq==2 );
3072       testcase( isEq==3 );
3073       uniqueNotNull = 0;
3074     }
3075   }
3076 
3077   /* If we have not found at least one ORDER BY term that matches the
3078   ** index, then show no progress. */
3079   if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
3080 
3081   /* Return the necessary scan order back to the caller */
3082   *pbRev = sortOrder & 1;
3083 
3084   /* If there was an "ORDER BY rowid" term that matched, or it is only
3085   ** possible for a single row from this table to match, then skip over
3086   ** any additional ORDER BY terms dealing with this table.
3087   */
3088   if( seenRowid || (uniqueNotNull && i>=pIdx->nColumn) ){
3089     /* Advance j over additional ORDER BY terms associated with base */
3090     WhereMaskSet *pMS = p->pWC->pMaskSet;
3091     Bitmask m = ~getMask(pMS, base);
3092     while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
3093       j++;
3094     }
3095   }
3096   return j;
3097 }
3098 
3099 /*
3100 ** Find the best query plan for accessing a particular table.  Write the
3101 ** best query plan and its cost into the p->cost.
3102 **
3103 ** The lowest cost plan wins.  The cost is an estimate of the amount of
3104 ** CPU and disk I/O needed to process the requested result.
3105 ** Factors that influence cost include:
3106 **
3107 **    *  The estimated number of rows that will be retrieved.  (The
3108 **       fewer the better.)
3109 **
3110 **    *  Whether or not sorting must occur.
3111 **
3112 **    *  Whether or not there must be separate lookups in the
3113 **       index and in the main table.
3114 **
3115 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
3116 ** the SQL statement, then this function only considers plans using the
3117 ** named index. If no such plan is found, then the returned cost is
3118 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
3119 ** then the cost is calculated in the usual way.
3120 **
3121 ** If a NOT INDEXED clause was attached to the table
3122 ** in the SELECT statement, then no indexes are considered. However, the
3123 ** selected plan may still take advantage of the built-in rowid primary key
3124 ** index.
3125 */
3126 static void bestBtreeIndex(WhereBestIdx *p){
3127   Parse *pParse = p->pParse;  /* The parsing context */
3128   WhereClause *pWC = p->pWC;  /* The WHERE clause */
3129   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
3130   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
3131   Index *pProbe;              /* An index we are evaluating */
3132   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
3133   int eqTermMask;             /* Current mask of valid equality operators */
3134   int idxEqTermMask;          /* Index mask of valid equality operators */
3135   Index sPk;                  /* A fake index object for the primary key */
3136   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
3137   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
3138   int wsFlagMask;             /* Allowed flags in p->cost.plan.wsFlag */
3139   int nPriorSat;              /* ORDER BY terms satisfied by outer loops */
3140   int nOrderBy;               /* Number of ORDER BY terms */
3141   char bSortInit;             /* Initializer for bSort in inner loop */
3142   char bDistInit;             /* Initializer for bDist in inner loop */
3143 
3144 
3145   /* Initialize the cost to a worst-case value */
3146   memset(&p->cost, 0, sizeof(p->cost));
3147   p->cost.rCost = SQLITE_BIG_DBL;
3148 
3149   /* If the pSrc table is the right table of a LEFT JOIN then we may not
3150   ** use an index to satisfy IS NULL constraints on that table.  This is
3151   ** because columns might end up being NULL if the table does not match -
3152   ** a circumstance which the index cannot help us discover.  Ticket #2177.
3153   */
3154   if( pSrc->jointype & JT_LEFT ){
3155     idxEqTermMask = WO_EQ|WO_IN;
3156   }else{
3157     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
3158   }
3159 
3160   if( pSrc->pIndex ){
3161     /* An INDEXED BY clause specifies a particular index to use */
3162     pIdx = pProbe = pSrc->pIndex;
3163     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
3164     eqTermMask = idxEqTermMask;
3165   }else{
3166     /* There is no INDEXED BY clause.  Create a fake Index object in local
3167     ** variable sPk to represent the rowid primary key index.  Make this
3168     ** fake index the first in a chain of Index objects with all of the real
3169     ** indices to follow */
3170     Index *pFirst;                  /* First of real indices on the table */
3171     memset(&sPk, 0, sizeof(Index));
3172     sPk.nColumn = 1;
3173     sPk.aiColumn = &aiColumnPk;
3174     sPk.aiRowEst = aiRowEstPk;
3175     sPk.onError = OE_Replace;
3176     sPk.pTable = pSrc->pTab;
3177     aiRowEstPk[0] = pSrc->pTab->nRowEst;
3178     aiRowEstPk[1] = 1;
3179     pFirst = pSrc->pTab->pIndex;
3180     if( pSrc->notIndexed==0 ){
3181       /* The real indices of the table are only considered if the
3182       ** NOT INDEXED qualifier is omitted from the FROM clause */
3183       sPk.pNext = pFirst;
3184     }
3185     pProbe = &sPk;
3186     wsFlagMask = ~(
3187         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
3188     );
3189     eqTermMask = WO_EQ|WO_IN;
3190     pIdx = 0;
3191   }
3192 
3193   nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
3194   if( p->i ){
3195     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
3196     bSortInit = nPriorSat<nOrderBy;
3197     bDistInit = 0;
3198   }else{
3199     nPriorSat = 0;
3200     bSortInit = nOrderBy>0;
3201     bDistInit = p->pDistinct!=0;
3202   }
3203 
3204   /* Loop over all indices looking for the best one to use
3205   */
3206   for(; pProbe; pIdx=pProbe=pProbe->pNext){
3207     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
3208     WhereCost pc;               /* Cost of using pProbe */
3209     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
3210 
3211     /* The following variables are populated based on the properties of
3212     ** index being evaluated. They are then used to determine the expected
3213     ** cost and number of rows returned.
3214     **
3215     **  pc.plan.nEq:
3216     **    Number of equality terms that can be implemented using the index.
3217     **    In other words, the number of initial fields in the index that
3218     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
3219     **
3220     **  nInMul:
3221     **    The "in-multiplier". This is an estimate of how many seek operations
3222     **    SQLite must perform on the index in question. For example, if the
3223     **    WHERE clause is:
3224     **
3225     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
3226     **
3227     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
3228     **    set to 9. Given the same schema and either of the following WHERE
3229     **    clauses:
3230     **
3231     **      WHERE a =  1
3232     **      WHERE a >= 2
3233     **
3234     **    nInMul is set to 1.
3235     **
3236     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
3237     **    the sub-select is assumed to return 25 rows for the purposes of
3238     **    determining nInMul.
3239     **
3240     **  bInEst:
3241     **    Set to true if there was at least one "x IN (SELECT ...)" term used
3242     **    in determining the value of nInMul.  Note that the RHS of the
3243     **    IN operator must be a SELECT, not a value list, for this variable
3244     **    to be true.
3245     **
3246     **  rangeDiv:
3247     **    An estimate of a divisor by which to reduce the search space due
3248     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
3249     **    data, a single inequality reduces the search space to 1/4rd its
3250     **    original size (rangeDiv==4).  Two inequalities reduce the search
3251     **    space to 1/16th of its original size (rangeDiv==16).
3252     **
3253     **  bSort:
3254     **    Boolean. True if there is an ORDER BY clause that will require an
3255     **    external sort (i.e. scanning the index being evaluated will not
3256     **    correctly order records).
3257     **
3258     **  bDist:
3259     **    Boolean. True if there is a DISTINCT clause that will require an
3260     **    external btree.
3261     **
3262     **  bLookup:
3263     **    Boolean. True if a table lookup is required for each index entry
3264     **    visited.  In other words, true if this is not a covering index.
3265     **    This is always false for the rowid primary key index of a table.
3266     **    For other indexes, it is true unless all the columns of the table
3267     **    used by the SELECT statement are present in the index (such an
3268     **    index is sometimes described as a covering index).
3269     **    For example, given the index on (a, b), the second of the following
3270     **    two queries requires table b-tree lookups in order to find the value
3271     **    of column c, but the first does not because columns a and b are
3272     **    both available in the index.
3273     **
3274     **             SELECT a, b    FROM tbl WHERE a = 1;
3275     **             SELECT a, b, c FROM tbl WHERE a = 1;
3276     */
3277     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
3278     int nInMul = 1;               /* Number of distinct equalities to lookup */
3279     double rangeDiv = (double)1;  /* Estimated reduction in search space */
3280     int nBound = 0;               /* Number of range constraints seen */
3281     char bSort = bSortInit;       /* True if external sort required */
3282     char bDist = bDistInit;       /* True if index cannot help with DISTINCT */
3283     char bLookup = 0;             /* True if not a covering index */
3284     WhereTerm *pTerm;             /* A single term of the WHERE clause */
3285 #ifdef SQLITE_ENABLE_STAT3
3286     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
3287 #endif
3288 
3289     WHERETRACE((
3290       "   %s(%s):\n",
3291       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
3292     ));
3293     memset(&pc, 0, sizeof(pc));
3294     pc.plan.nOBSat = nPriorSat;
3295 
3296     /* Determine the values of pc.plan.nEq and nInMul */
3297     for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
3298       int j = pProbe->aiColumn[pc.plan.nEq];
3299       pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
3300       if( pTerm==0 ) break;
3301       pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
3302       testcase( pTerm->pWC!=pWC );
3303       if( pTerm->eOperator & WO_IN ){
3304         Expr *pExpr = pTerm->pExpr;
3305         pc.plan.wsFlags |= WHERE_COLUMN_IN;
3306         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3307           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
3308           nInMul *= 25;
3309           bInEst = 1;
3310         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3311           /* "x IN (value, value, ...)" */
3312           nInMul *= pExpr->x.pList->nExpr;
3313         }
3314       }else if( pTerm->eOperator & WO_ISNULL ){
3315         pc.plan.wsFlags |= WHERE_COLUMN_NULL;
3316       }
3317 #ifdef SQLITE_ENABLE_STAT3
3318       if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
3319 #endif
3320       pc.used |= pTerm->prereqRight;
3321     }
3322 
3323     /* If the index being considered is UNIQUE, and there is an equality
3324     ** constraint for all columns in the index, then this search will find
3325     ** at most a single row. In this case set the WHERE_UNIQUE flag to
3326     ** indicate this to the caller.
3327     **
3328     ** Otherwise, if the search may find more than one row, test to see if
3329     ** there is a range constraint on indexed column (pc.plan.nEq+1) that
3330     ** can be optimized using the index.
3331     */
3332     if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
3333       testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
3334       testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
3335       if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
3336         pc.plan.wsFlags |= WHERE_UNIQUE;
3337         if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
3338           pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
3339         }
3340       }
3341     }else if( pProbe->bUnordered==0 ){
3342       int j;
3343       j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
3344       if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
3345         WhereTerm *pTop, *pBtm;
3346         pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
3347         pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
3348         whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
3349         if( pTop ){
3350           nBound = 1;
3351           pc.plan.wsFlags |= WHERE_TOP_LIMIT;
3352           pc.used |= pTop->prereqRight;
3353           testcase( pTop->pWC!=pWC );
3354         }
3355         if( pBtm ){
3356           nBound++;
3357           pc.plan.wsFlags |= WHERE_BTM_LIMIT;
3358           pc.used |= pBtm->prereqRight;
3359           testcase( pBtm->pWC!=pWC );
3360         }
3361         pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
3362       }
3363     }
3364 
3365     /* If there is an ORDER BY clause and the index being considered will
3366     ** naturally scan rows in the required order, set the appropriate flags
3367     ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
3368     ** the index will scan rows in a different order, set the bSort
3369     ** variable.  */
3370     if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
3371       int bRev = 2;
3372       WHERETRACE(("      --> before isSortingIndex: nPriorSat=%d\n",nPriorSat));
3373       pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev);
3374       WHERETRACE(("      --> after  isSortingIndex: bRev=%d nOBSat=%d\n",
3375                   bRev, pc.plan.nOBSat));
3376       if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
3377         pc.plan.wsFlags |= WHERE_ORDERED;
3378       }
3379       if( nOrderBy==pc.plan.nOBSat ){
3380         bSort = 0;
3381         pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
3382       }
3383       if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
3384     }
3385 
3386     /* If there is a DISTINCT qualifier and this index will scan rows in
3387     ** order of the DISTINCT expressions, clear bDist and set the appropriate
3388     ** flags in pc.plan.wsFlags. */
3389     if( bDist
3390      && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
3391      && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
3392     ){
3393       bDist = 0;
3394       pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
3395     }
3396 
3397     /* If currently calculating the cost of using an index (not the IPK
3398     ** index), determine if all required column data may be obtained without
3399     ** using the main table (i.e. if the index is a covering
3400     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
3401     ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true.  */
3402     if( pIdx ){
3403       Bitmask m = pSrc->colUsed;
3404       int j;
3405       for(j=0; j<pIdx->nColumn; j++){
3406         int x = pIdx->aiColumn[j];
3407         if( x<BMS-1 ){
3408           m &= ~(((Bitmask)1)<<x);
3409         }
3410       }
3411       if( m==0 ){
3412         pc.plan.wsFlags |= WHERE_IDX_ONLY;
3413       }else{
3414         bLookup = 1;
3415       }
3416     }
3417 
3418     /*
3419     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
3420     ** constraint, do not let the estimate exceed half the rows in the table.
3421     */
3422     pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
3423     if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
3424       pc.plan.nRow = aiRowEst[0]/2;
3425       nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
3426     }
3427 
3428 #ifdef SQLITE_ENABLE_STAT3
3429     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
3430     ** and we do not think that values of x are unique and if histogram
3431     ** data is available for column x, then it might be possible
3432     ** to get a better estimate on the number of rows based on
3433     ** VALUE and how common that value is according to the histogram.
3434     */
3435     if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
3436      && pFirstTerm!=0 && aiRowEst[1]>1 ){
3437       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
3438       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
3439         testcase( pFirstTerm->eOperator & WO_EQ );
3440         testcase( pFirstTerm->eOperator & WO_EQUIV );
3441         testcase( pFirstTerm->eOperator & WO_ISNULL );
3442         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
3443                           &pc.plan.nRow);
3444       }else if( bInEst==0 ){
3445         assert( pFirstTerm->eOperator & WO_IN );
3446         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
3447                        &pc.plan.nRow);
3448       }
3449     }
3450 #endif /* SQLITE_ENABLE_STAT3 */
3451 
3452     /* Adjust the number of output rows and downward to reflect rows
3453     ** that are excluded by range constraints.
3454     */
3455     pc.plan.nRow = pc.plan.nRow/rangeDiv;
3456     if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
3457 
3458     /* Experiments run on real SQLite databases show that the time needed
3459     ** to do a binary search to locate a row in a table or index is roughly
3460     ** log10(N) times the time to move from one row to the next row within
3461     ** a table or index.  The actual times can vary, with the size of
3462     ** records being an important factor.  Both moves and searches are
3463     ** slower with larger records, presumably because fewer records fit
3464     ** on one page and hence more pages have to be fetched.
3465     **
3466     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
3467     ** not give us data on the relative sizes of table and index records.
3468     ** So this computation assumes table records are about twice as big
3469     ** as index records
3470     */
3471     if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED))==WHERE_IDX_ONLY
3472      && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3473      && sqlite3GlobalConfig.bUseCis
3474      && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
3475     ){
3476       /* This index is not useful for indexing, but it is a covering index.
3477       ** A full-scan of the index might be a little faster than a full-scan
3478       ** of the table, so give this case a cost slightly less than a table
3479       ** scan. */
3480       pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
3481       pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
3482     }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
3483       /* The cost of a full table scan is a number of move operations equal
3484       ** to the number of rows in the table.
3485       **
3486       ** We add an additional 4x penalty to full table scans.  This causes
3487       ** the cost function to err on the side of choosing an index over
3488       ** choosing a full scan.  This 4x full-scan penalty is an arguable
3489       ** decision and one which we expect to revisit in the future.  But
3490       ** it seems to be working well enough at the moment.
3491       */
3492       pc.rCost = aiRowEst[0]*4;
3493       pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
3494       if( pIdx ){
3495         pc.plan.wsFlags &= ~WHERE_ORDERED;
3496         pc.plan.nOBSat = nPriorSat;
3497       }
3498     }else{
3499       log10N = estLog(aiRowEst[0]);
3500       pc.rCost = pc.plan.nRow;
3501       if( pIdx ){
3502         if( bLookup ){
3503           /* For an index lookup followed by a table lookup:
3504           **    nInMul index searches to find the start of each index range
3505           **  + nRow steps through the index
3506           **  + nRow table searches to lookup the table entry using the rowid
3507           */
3508           pc.rCost += (nInMul + pc.plan.nRow)*log10N;
3509         }else{
3510           /* For a covering index:
3511           **     nInMul index searches to find the initial entry
3512           **   + nRow steps through the index
3513           */
3514           pc.rCost += nInMul*log10N;
3515         }
3516       }else{
3517         /* For a rowid primary key lookup:
3518         **    nInMult table searches to find the initial entry for each range
3519         **  + nRow steps through the table
3520         */
3521         pc.rCost += nInMul*log10N;
3522       }
3523     }
3524 
3525     /* Add in the estimated cost of sorting the result.  Actual experimental
3526     ** measurements of sorting performance in SQLite show that sorting time
3527     ** adds C*N*log10(N) to the cost, where N is the number of rows to be
3528     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
3529     ** difference and select C of 3.0.
3530     */
3531     if( bSort ){
3532       double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
3533       m *= (double)(pc.plan.nOBSat ? 2 : 3);
3534       pc.rCost += pc.plan.nRow*m;
3535     }
3536     if( bDist ){
3537       pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
3538     }
3539 
3540     /**** Cost of using this index has now been computed ****/
3541 
3542     /* If there are additional constraints on this table that cannot
3543     ** be used with the current index, but which might lower the number
3544     ** of output rows, adjust the nRow value accordingly.  This only
3545     ** matters if the current index is the least costly, so do not bother
3546     ** with this step if we already know this index will not be chosen.
3547     ** Also, never reduce the output row count below 2 using this step.
3548     **
3549     ** It is critical that the notValid mask be used here instead of
3550     ** the notReady mask.  When computing an "optimal" index, the notReady
3551     ** mask will only have one bit set - the bit for the current table.
3552     ** The notValid mask, on the other hand, always has all bits set for
3553     ** tables that are not in outer loops.  If notReady is used here instead
3554     ** of notValid, then a optimal index that depends on inner joins loops
3555     ** might be selected even when there exists an optimal index that has
3556     ** no such dependency.
3557     */
3558     if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
3559       int k;                       /* Loop counter */
3560       int nSkipEq = pc.plan.nEq;   /* Number of == constraints to skip */
3561       int nSkipRange = nBound;     /* Number of < constraints to skip */
3562       Bitmask thisTab;             /* Bitmap for pSrc */
3563 
3564       thisTab = getMask(pWC->pMaskSet, iCur);
3565       for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
3566         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
3567         if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
3568         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
3569           if( nSkipEq ){
3570             /* Ignore the first pc.plan.nEq equality matches since the index
3571             ** has already accounted for these */
3572             nSkipEq--;
3573           }else{
3574             /* Assume each additional equality match reduces the result
3575             ** set size by a factor of 10 */
3576             pc.plan.nRow /= 10;
3577           }
3578         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
3579           if( nSkipRange ){
3580             /* Ignore the first nSkipRange range constraints since the index
3581             ** has already accounted for these */
3582             nSkipRange--;
3583           }else{
3584             /* Assume each additional range constraint reduces the result
3585             ** set size by a factor of 3.  Indexed range constraints reduce
3586             ** the search space by a larger factor: 4.  We make indexed range
3587             ** more selective intentionally because of the subjective
3588             ** observation that indexed range constraints really are more
3589             ** selective in practice, on average. */
3590             pc.plan.nRow /= 3;
3591           }
3592         }else if( (pTerm->eOperator & WO_NOOP)==0 ){
3593           /* Any other expression lowers the output row count by half */
3594           pc.plan.nRow /= 2;
3595         }
3596       }
3597       if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
3598     }
3599 
3600 
3601     WHERETRACE((
3602       "      nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
3603       "      notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
3604       "      used=0x%llx nOBSat=%d\n",
3605       pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
3606       p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
3607       pc.plan.nOBSat
3608     ));
3609 
3610     /* If this index is the best we have seen so far, then record this
3611     ** index and its cost in the p->cost structure.
3612     */
3613     if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
3614       p->cost = pc;
3615       p->cost.plan.wsFlags &= wsFlagMask;
3616       p->cost.plan.u.pIdx = pIdx;
3617     }
3618 
3619     /* If there was an INDEXED BY clause, then only that one index is
3620     ** considered. */
3621     if( pSrc->pIndex ) break;
3622 
3623     /* Reset masks for the next index in the loop */
3624     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
3625     eqTermMask = idxEqTermMask;
3626   }
3627 
3628   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
3629   ** is set, then reverse the order that the index will be scanned
3630   ** in. This is used for application testing, to help find cases
3631   ** where application behavior depends on the (undefined) order that
3632   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
3633   if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
3634     p->cost.plan.wsFlags |= WHERE_REVERSE;
3635   }
3636 
3637   assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
3638   assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
3639   assert( pSrc->pIndex==0
3640        || p->cost.plan.u.pIdx==0
3641        || p->cost.plan.u.pIdx==pSrc->pIndex
3642   );
3643 
3644   WHERETRACE(("   best index is %s cost=%.1f\n",
3645          p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
3646          p->cost.rCost));
3647 
3648   bestOrClauseIndex(p);
3649   bestAutomaticIndex(p);
3650   p->cost.plan.wsFlags |= eqTermMask;
3651 }
3652 
3653 /*
3654 ** Find the query plan for accessing table pSrc->pTab. Write the
3655 ** best query plan and its cost into the WhereCost object supplied
3656 ** as the last parameter. This function may calculate the cost of
3657 ** both real and virtual table scans.
3658 **
3659 ** This function does not take ORDER BY or DISTINCT into account.  Nor
3660 ** does it remember the virtual table query plan.  All it does is compute
3661 ** the cost while determining if an OR optimization is applicable.  The
3662 ** details will be reconsidered later if the optimization is found to be
3663 ** applicable.
3664 */
3665 static void bestIndex(WhereBestIdx *p){
3666 #ifndef SQLITE_OMIT_VIRTUALTABLE
3667   if( IsVirtual(p->pSrc->pTab) ){
3668     sqlite3_index_info *pIdxInfo = 0;
3669     p->ppIdxInfo = &pIdxInfo;
3670     bestVirtualIndex(p);
3671     assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
3672     if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
3673       sqlite3_free(pIdxInfo->idxStr);
3674     }
3675     sqlite3DbFree(p->pParse->db, pIdxInfo);
3676   }else
3677 #endif
3678   {
3679     bestBtreeIndex(p);
3680   }
3681 }
3682 
3683 /*
3684 ** Disable a term in the WHERE clause.  Except, do not disable the term
3685 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
3686 ** or USING clause of that join.
3687 **
3688 ** Consider the term t2.z='ok' in the following queries:
3689 **
3690 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
3691 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
3692 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
3693 **
3694 ** The t2.z='ok' is disabled in the in (2) because it originates
3695 ** in the ON clause.  The term is disabled in (3) because it is not part
3696 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
3697 **
3698 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
3699 ** completely satisfied by indices.
3700 **
3701 ** Disabling a term causes that term to not be tested in the inner loop
3702 ** of the join.  Disabling is an optimization.  When terms are satisfied
3703 ** by indices, we disable them to prevent redundant tests in the inner
3704 ** loop.  We would get the correct results if nothing were ever disabled,
3705 ** but joins might run a little slower.  The trick is to disable as much
3706 ** as we can without disabling too much.  If we disabled in (1), we'd get
3707 ** the wrong answer.  See ticket #813.
3708 */
3709 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
3710   if( pTerm
3711       && (pTerm->wtFlags & TERM_CODED)==0
3712       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
3713   ){
3714     pTerm->wtFlags |= TERM_CODED;
3715     if( pTerm->iParent>=0 ){
3716       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
3717       if( (--pOther->nChild)==0 ){
3718         disableTerm(pLevel, pOther);
3719       }
3720     }
3721   }
3722 }
3723 
3724 /*
3725 ** Code an OP_Affinity opcode to apply the column affinity string zAff
3726 ** to the n registers starting at base.
3727 **
3728 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
3729 ** beginning and end of zAff are ignored.  If all entries in zAff are
3730 ** SQLITE_AFF_NONE, then no code gets generated.
3731 **
3732 ** This routine makes its own copy of zAff so that the caller is free
3733 ** to modify zAff after this routine returns.
3734 */
3735 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
3736   Vdbe *v = pParse->pVdbe;
3737   if( zAff==0 ){
3738     assert( pParse->db->mallocFailed );
3739     return;
3740   }
3741   assert( v!=0 );
3742 
3743   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
3744   ** and end of the affinity string.
3745   */
3746   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
3747     n--;
3748     base++;
3749     zAff++;
3750   }
3751   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
3752     n--;
3753   }
3754 
3755   /* Code the OP_Affinity opcode if there is anything left to do. */
3756   if( n>0 ){
3757     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
3758     sqlite3VdbeChangeP4(v, -1, zAff, n);
3759     sqlite3ExprCacheAffinityChange(pParse, base, n);
3760   }
3761 }
3762 
3763 
3764 /*
3765 ** Generate code for a single equality term of the WHERE clause.  An equality
3766 ** term can be either X=expr or X IN (...).   pTerm is the term to be
3767 ** coded.
3768 **
3769 ** The current value for the constraint is left in register iReg.
3770 **
3771 ** For a constraint of the form X=expr, the expression is evaluated and its
3772 ** result is left on the stack.  For constraints of the form X IN (...)
3773 ** this routine sets up a loop that will iterate over all values of X.
3774 */
3775 static int codeEqualityTerm(
3776   Parse *pParse,      /* The parsing context */
3777   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
3778   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
3779   int iEq,            /* Index of the equality term within this level */
3780   int iTarget         /* Attempt to leave results in this register */
3781 ){
3782   Expr *pX = pTerm->pExpr;
3783   Vdbe *v = pParse->pVdbe;
3784   int iReg;                  /* Register holding results */
3785 
3786   assert( iTarget>0 );
3787   if( pX->op==TK_EQ ){
3788     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
3789   }else if( pX->op==TK_ISNULL ){
3790     iReg = iTarget;
3791     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
3792 #ifndef SQLITE_OMIT_SUBQUERY
3793   }else{
3794     int eType;
3795     int iTab;
3796     struct InLoop *pIn;
3797     u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
3798 
3799     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
3800       && pLevel->plan.u.pIdx->aSortOrder[iEq]
3801     ){
3802       testcase( iEq==0 );
3803       testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
3804       testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
3805       testcase( bRev );
3806       bRev = !bRev;
3807     }
3808     assert( pX->op==TK_IN );
3809     iReg = iTarget;
3810     eType = sqlite3FindInIndex(pParse, pX, 0);
3811     if( eType==IN_INDEX_INDEX_DESC ){
3812       testcase( bRev );
3813       bRev = !bRev;
3814     }
3815     iTab = pX->iTable;
3816     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
3817     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
3818     if( pLevel->u.in.nIn==0 ){
3819       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3820     }
3821     pLevel->u.in.nIn++;
3822     pLevel->u.in.aInLoop =
3823        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
3824                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
3825     pIn = pLevel->u.in.aInLoop;
3826     if( pIn ){
3827       pIn += pLevel->u.in.nIn - 1;
3828       pIn->iCur = iTab;
3829       if( eType==IN_INDEX_ROWID ){
3830         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
3831       }else{
3832         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
3833       }
3834       pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
3835       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
3836     }else{
3837       pLevel->u.in.nIn = 0;
3838     }
3839 #endif
3840   }
3841   disableTerm(pLevel, pTerm);
3842   return iReg;
3843 }
3844 
3845 /*
3846 ** Generate code that will evaluate all == and IN constraints for an
3847 ** index.
3848 **
3849 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
3850 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
3851 ** The index has as many as three equality constraints, but in this
3852 ** example, the third "c" value is an inequality.  So only two
3853 ** constraints are coded.  This routine will generate code to evaluate
3854 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
3855 ** in consecutive registers and the index of the first register is returned.
3856 **
3857 ** In the example above nEq==2.  But this subroutine works for any value
3858 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
3859 ** The only thing it does is allocate the pLevel->iMem memory cell and
3860 ** compute the affinity string.
3861 **
3862 ** This routine always allocates at least one memory cell and returns
3863 ** the index of that memory cell. The code that
3864 ** calls this routine will use that memory cell to store the termination
3865 ** key value of the loop.  If one or more IN operators appear, then
3866 ** this routine allocates an additional nEq memory cells for internal
3867 ** use.
3868 **
3869 ** Before returning, *pzAff is set to point to a buffer containing a
3870 ** copy of the column affinity string of the index allocated using
3871 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
3872 ** with equality constraints that use NONE affinity are set to
3873 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
3874 **
3875 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
3876 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
3877 **
3878 ** In the example above, the index on t1(a) has TEXT affinity. But since
3879 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
3880 ** no conversion should be attempted before using a t2.b value as part of
3881 ** a key to search the index. Hence the first byte in the returned affinity
3882 ** string in this example would be set to SQLITE_AFF_NONE.
3883 */
3884 static int codeAllEqualityTerms(
3885   Parse *pParse,        /* Parsing context */
3886   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
3887   WhereClause *pWC,     /* The WHERE clause */
3888   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
3889   int nExtraReg,        /* Number of extra registers to allocate */
3890   char **pzAff          /* OUT: Set to point to affinity string */
3891 ){
3892   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
3893   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
3894   Index *pIdx;                  /* The index being used for this loop */
3895   int iCur = pLevel->iTabCur;   /* The cursor of the table */
3896   WhereTerm *pTerm;             /* A single constraint term */
3897   int j;                        /* Loop counter */
3898   int regBase;                  /* Base register */
3899   int nReg;                     /* Number of registers to allocate */
3900   char *zAff;                   /* Affinity string to return */
3901 
3902   /* This module is only called on query plans that use an index. */
3903   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
3904   pIdx = pLevel->plan.u.pIdx;
3905 
3906   /* Figure out how many memory cells we will need then allocate them.
3907   */
3908   regBase = pParse->nMem + 1;
3909   nReg = pLevel->plan.nEq + nExtraReg;
3910   pParse->nMem += nReg;
3911 
3912   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
3913   if( !zAff ){
3914     pParse->db->mallocFailed = 1;
3915   }
3916 
3917   /* Evaluate the equality constraints
3918   */
3919   assert( pIdx->nColumn>=nEq );
3920   for(j=0; j<nEq; j++){
3921     int r1;
3922     int k = pIdx->aiColumn[j];
3923     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
3924     if( pTerm==0 ) break;
3925     /* The following true for indices with redundant columns.
3926     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
3927     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
3928     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
3929     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
3930     if( r1!=regBase+j ){
3931       if( nReg==1 ){
3932         sqlite3ReleaseTempReg(pParse, regBase);
3933         regBase = r1;
3934       }else{
3935         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
3936       }
3937     }
3938     testcase( pTerm->eOperator & WO_ISNULL );
3939     testcase( pTerm->eOperator & WO_IN );
3940     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
3941       Expr *pRight = pTerm->pExpr->pRight;
3942       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
3943       if( zAff ){
3944         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
3945           zAff[j] = SQLITE_AFF_NONE;
3946         }
3947         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
3948           zAff[j] = SQLITE_AFF_NONE;
3949         }
3950       }
3951     }
3952   }
3953   *pzAff = zAff;
3954   return regBase;
3955 }
3956 
3957 #ifndef SQLITE_OMIT_EXPLAIN
3958 /*
3959 ** This routine is a helper for explainIndexRange() below
3960 **
3961 ** pStr holds the text of an expression that we are building up one term
3962 ** at a time.  This routine adds a new term to the end of the expression.
3963 ** Terms are separated by AND so add the "AND" text for second and subsequent
3964 ** terms only.
3965 */
3966 static void explainAppendTerm(
3967   StrAccum *pStr,             /* The text expression being built */
3968   int iTerm,                  /* Index of this term.  First is zero */
3969   const char *zColumn,        /* Name of the column */
3970   const char *zOp             /* Name of the operator */
3971 ){
3972   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
3973   sqlite3StrAccumAppend(pStr, zColumn, -1);
3974   sqlite3StrAccumAppend(pStr, zOp, 1);
3975   sqlite3StrAccumAppend(pStr, "?", 1);
3976 }
3977 
3978 /*
3979 ** Argument pLevel describes a strategy for scanning table pTab. This
3980 ** function returns a pointer to a string buffer containing a description
3981 ** of the subset of table rows scanned by the strategy in the form of an
3982 ** SQL expression. Or, if all rows are scanned, NULL is returned.
3983 **
3984 ** For example, if the query:
3985 **
3986 **   SELECT * FROM t1 WHERE a=1 AND b>2;
3987 **
3988 ** is run and there is an index on (a, b), then this function returns a
3989 ** string similar to:
3990 **
3991 **   "a=? AND b>?"
3992 **
3993 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
3994 ** It is the responsibility of the caller to free the buffer when it is
3995 ** no longer required.
3996 */
3997 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
3998   WherePlan *pPlan = &pLevel->plan;
3999   Index *pIndex = pPlan->u.pIdx;
4000   int nEq = pPlan->nEq;
4001   int i, j;
4002   Column *aCol = pTab->aCol;
4003   int *aiColumn = pIndex->aiColumn;
4004   StrAccum txt;
4005 
4006   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
4007     return 0;
4008   }
4009   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
4010   txt.db = db;
4011   sqlite3StrAccumAppend(&txt, " (", 2);
4012   for(i=0; i<nEq; i++){
4013     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
4014   }
4015 
4016   j = i;
4017   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
4018     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
4019     explainAppendTerm(&txt, i++, z, ">");
4020   }
4021   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
4022     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
4023     explainAppendTerm(&txt, i, z, "<");
4024   }
4025   sqlite3StrAccumAppend(&txt, ")", 1);
4026   return sqlite3StrAccumFinish(&txt);
4027 }
4028 
4029 /*
4030 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
4031 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
4032 ** record is added to the output to describe the table scan strategy in
4033 ** pLevel.
4034 */
4035 static void explainOneScan(
4036   Parse *pParse,                  /* Parse context */
4037   SrcList *pTabList,              /* Table list this loop refers to */
4038   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
4039   int iLevel,                     /* Value for "level" column of output */
4040   int iFrom,                      /* Value for "from" column of output */
4041   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
4042 ){
4043   if( pParse->explain==2 ){
4044     u32 flags = pLevel->plan.wsFlags;
4045     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
4046     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
4047     sqlite3 *db = pParse->db;     /* Database handle */
4048     char *zMsg;                   /* Text to add to EQP output */
4049     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
4050     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
4051     int isSearch;                 /* True for a SEARCH. False for SCAN. */
4052 
4053     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
4054 
4055     isSearch = (pLevel->plan.nEq>0)
4056              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
4057              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
4058 
4059     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
4060     if( pItem->pSelect ){
4061       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
4062     }else{
4063       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
4064     }
4065 
4066     if( pItem->zAlias ){
4067       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
4068     }
4069     if( (flags & WHERE_INDEXED)!=0 ){
4070       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
4071       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
4072           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
4073           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
4074           ((flags & WHERE_TEMP_INDEX)?"":" "),
4075           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
4076           zWhere
4077       );
4078       sqlite3DbFree(db, zWhere);
4079     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
4080       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
4081 
4082       if( flags&WHERE_ROWID_EQ ){
4083         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
4084       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
4085         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
4086       }else if( flags&WHERE_BTM_LIMIT ){
4087         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
4088       }else if( flags&WHERE_TOP_LIMIT ){
4089         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
4090       }
4091     }
4092 #ifndef SQLITE_OMIT_VIRTUALTABLE
4093     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
4094       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
4095       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
4096                   pVtabIdx->idxNum, pVtabIdx->idxStr);
4097     }
4098 #endif
4099     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
4100       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
4101       nRow = 1;
4102     }else{
4103       nRow = (sqlite3_int64)pLevel->plan.nRow;
4104     }
4105     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
4106     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
4107   }
4108 }
4109 #else
4110 # define explainOneScan(u,v,w,x,y,z)
4111 #endif /* SQLITE_OMIT_EXPLAIN */
4112 
4113 
4114 /*
4115 ** Generate code for the start of the iLevel-th loop in the WHERE clause
4116 ** implementation described by pWInfo.
4117 */
4118 static Bitmask codeOneLoopStart(
4119   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
4120   int iLevel,          /* Which level of pWInfo->a[] should be coded */
4121   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
4122   Bitmask notReady     /* Which tables are currently available */
4123 ){
4124   int j, k;            /* Loop counters */
4125   int iCur;            /* The VDBE cursor for the table */
4126   int addrNxt;         /* Where to jump to continue with the next IN case */
4127   int omitTable;       /* True if we use the index only */
4128   int bRev;            /* True if we need to scan in reverse order */
4129   WhereLevel *pLevel;  /* The where level to be coded */
4130   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
4131   WhereTerm *pTerm;               /* A WHERE clause term */
4132   Parse *pParse;                  /* Parsing context */
4133   Vdbe *v;                        /* The prepared stmt under constructions */
4134   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
4135   int addrBrk;                    /* Jump here to break out of the loop */
4136   int addrCont;                   /* Jump here to continue with next cycle */
4137   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
4138   int iReleaseReg = 0;      /* Temp register to free before returning */
4139 
4140   pParse = pWInfo->pParse;
4141   v = pParse->pVdbe;
4142   pWC = pWInfo->pWC;
4143   pLevel = &pWInfo->a[iLevel];
4144   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
4145   iCur = pTabItem->iCursor;
4146   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
4147   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
4148            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
4149 
4150   /* Create labels for the "break" and "continue" instructions
4151   ** for the current loop.  Jump to addrBrk to break out of a loop.
4152   ** Jump to cont to go immediately to the next iteration of the
4153   ** loop.
4154   **
4155   ** When there is an IN operator, we also have a "addrNxt" label that
4156   ** means to continue with the next IN value combination.  When
4157   ** there are no IN operators in the constraints, the "addrNxt" label
4158   ** is the same as "addrBrk".
4159   */
4160   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
4161   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
4162 
4163   /* If this is the right table of a LEFT OUTER JOIN, allocate and
4164   ** initialize a memory cell that records if this table matches any
4165   ** row of the left table of the join.
4166   */
4167   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
4168     pLevel->iLeftJoin = ++pParse->nMem;
4169     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
4170     VdbeComment((v, "init LEFT JOIN no-match flag"));
4171   }
4172 
4173   /* Special case of a FROM clause subquery implemented as a co-routine */
4174   if( pTabItem->viaCoroutine ){
4175     int regYield = pTabItem->regReturn;
4176     sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
4177     pLevel->p2 =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
4178     VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
4179     sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
4180     pLevel->op = OP_Goto;
4181   }else
4182 
4183 #ifndef SQLITE_OMIT_VIRTUALTABLE
4184   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
4185     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
4186     **          to access the data.
4187     */
4188     int iReg;   /* P3 Value for OP_VFilter */
4189     int addrNotFound;
4190     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
4191     int nConstraint = pVtabIdx->nConstraint;
4192     struct sqlite3_index_constraint_usage *aUsage =
4193                                                 pVtabIdx->aConstraintUsage;
4194     const struct sqlite3_index_constraint *aConstraint =
4195                                                 pVtabIdx->aConstraint;
4196 
4197     sqlite3ExprCachePush(pParse);
4198     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
4199     addrNotFound = pLevel->addrBrk;
4200     for(j=1; j<=nConstraint; j++){
4201       for(k=0; k<nConstraint; k++){
4202         if( aUsage[k].argvIndex==j ){
4203           int iTarget = iReg+j+1;
4204           pTerm = &pWC->a[aConstraint[k].iTermOffset];
4205           if( pTerm->eOperator & WO_IN ){
4206             codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
4207             addrNotFound = pLevel->addrNxt;
4208           }else{
4209             sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
4210           }
4211           break;
4212         }
4213       }
4214       if( k==nConstraint ) break;
4215     }
4216     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
4217     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
4218     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
4219                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
4220     pVtabIdx->needToFreeIdxStr = 0;
4221     for(j=0; j<nConstraint; j++){
4222       if( aUsage[j].omit ){
4223         int iTerm = aConstraint[j].iTermOffset;
4224         disableTerm(pLevel, &pWC->a[iTerm]);
4225       }
4226     }
4227     pLevel->op = OP_VNext;
4228     pLevel->p1 = iCur;
4229     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
4230     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
4231     sqlite3ExprCachePop(pParse, 1);
4232   }else
4233 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4234 
4235   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
4236     /* Case 1:  We can directly reference a single row using an
4237     **          equality comparison against the ROWID field.  Or
4238     **          we reference multiple rows using a "rowid IN (...)"
4239     **          construct.
4240     */
4241     iReleaseReg = sqlite3GetTempReg(pParse);
4242     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
4243     assert( pTerm!=0 );
4244     assert( pTerm->pExpr!=0 );
4245     assert( omitTable==0 );
4246     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4247     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
4248     addrNxt = pLevel->addrNxt;
4249     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
4250     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
4251     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
4252     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
4253     VdbeComment((v, "pk"));
4254     pLevel->op = OP_Noop;
4255   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
4256     /* Case 2:  We have an inequality comparison against the ROWID field.
4257     */
4258     int testOp = OP_Noop;
4259     int start;
4260     int memEndValue = 0;
4261     WhereTerm *pStart, *pEnd;
4262 
4263     assert( omitTable==0 );
4264     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
4265     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
4266     if( bRev ){
4267       pTerm = pStart;
4268       pStart = pEnd;
4269       pEnd = pTerm;
4270     }
4271     if( pStart ){
4272       Expr *pX;             /* The expression that defines the start bound */
4273       int r1, rTemp;        /* Registers for holding the start boundary */
4274 
4275       /* The following constant maps TK_xx codes into corresponding
4276       ** seek opcodes.  It depends on a particular ordering of TK_xx
4277       */
4278       const u8 aMoveOp[] = {
4279            /* TK_GT */  OP_SeekGt,
4280            /* TK_LE */  OP_SeekLe,
4281            /* TK_LT */  OP_SeekLt,
4282            /* TK_GE */  OP_SeekGe
4283       };
4284       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
4285       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
4286       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
4287 
4288       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4289       pX = pStart->pExpr;
4290       assert( pX!=0 );
4291       assert( pStart->leftCursor==iCur );
4292       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
4293       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
4294       VdbeComment((v, "pk"));
4295       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
4296       sqlite3ReleaseTempReg(pParse, rTemp);
4297       disableTerm(pLevel, pStart);
4298     }else{
4299       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
4300     }
4301     if( pEnd ){
4302       Expr *pX;
4303       pX = pEnd->pExpr;
4304       assert( pX!=0 );
4305       assert( pEnd->leftCursor==iCur );
4306       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4307       memEndValue = ++pParse->nMem;
4308       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
4309       if( pX->op==TK_LT || pX->op==TK_GT ){
4310         testOp = bRev ? OP_Le : OP_Ge;
4311       }else{
4312         testOp = bRev ? OP_Lt : OP_Gt;
4313       }
4314       disableTerm(pLevel, pEnd);
4315     }
4316     start = sqlite3VdbeCurrentAddr(v);
4317     pLevel->op = bRev ? OP_Prev : OP_Next;
4318     pLevel->p1 = iCur;
4319     pLevel->p2 = start;
4320     if( pStart==0 && pEnd==0 ){
4321       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4322     }else{
4323       assert( pLevel->p5==0 );
4324     }
4325     if( testOp!=OP_Noop ){
4326       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
4327       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
4328       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
4329       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
4330       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
4331     }
4332   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
4333     /* Case 3: A scan using an index.
4334     **
4335     **         The WHERE clause may contain zero or more equality
4336     **         terms ("==" or "IN" operators) that refer to the N
4337     **         left-most columns of the index. It may also contain
4338     **         inequality constraints (>, <, >= or <=) on the indexed
4339     **         column that immediately follows the N equalities. Only
4340     **         the right-most column can be an inequality - the rest must
4341     **         use the "==" and "IN" operators. For example, if the
4342     **         index is on (x,y,z), then the following clauses are all
4343     **         optimized:
4344     **
4345     **            x=5
4346     **            x=5 AND y=10
4347     **            x=5 AND y<10
4348     **            x=5 AND y>5 AND y<10
4349     **            x=5 AND y=5 AND z<=10
4350     **
4351     **         The z<10 term of the following cannot be used, only
4352     **         the x=5 term:
4353     **
4354     **            x=5 AND z<10
4355     **
4356     **         N may be zero if there are inequality constraints.
4357     **         If there are no inequality constraints, then N is at
4358     **         least one.
4359     **
4360     **         This case is also used when there are no WHERE clause
4361     **         constraints but an index is selected anyway, in order
4362     **         to force the output order to conform to an ORDER BY.
4363     */
4364     static const u8 aStartOp[] = {
4365       0,
4366       0,
4367       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
4368       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
4369       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
4370       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
4371       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
4372       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
4373     };
4374     static const u8 aEndOp[] = {
4375       OP_Noop,             /* 0: (!end_constraints) */
4376       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
4377       OP_IdxLT             /* 2: (end_constraints && bRev) */
4378     };
4379     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
4380     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
4381     int regBase;                 /* Base register holding constraint values */
4382     int r1;                      /* Temp register */
4383     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
4384     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
4385     int startEq;                 /* True if range start uses ==, >= or <= */
4386     int endEq;                   /* True if range end uses ==, >= or <= */
4387     int start_constraints;       /* Start of range is constrained */
4388     int nConstraint;             /* Number of constraint terms */
4389     Index *pIdx;                 /* The index we will be using */
4390     int iIdxCur;                 /* The VDBE cursor for the index */
4391     int nExtraReg = 0;           /* Number of extra registers needed */
4392     int op;                      /* Instruction opcode */
4393     char *zStartAff;             /* Affinity for start of range constraint */
4394     char *zEndAff;               /* Affinity for end of range constraint */
4395 
4396     pIdx = pLevel->plan.u.pIdx;
4397     iIdxCur = pLevel->iIdxCur;
4398     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
4399 
4400     /* If this loop satisfies a sort order (pOrderBy) request that
4401     ** was passed to this function to implement a "SELECT min(x) ..."
4402     ** query, then the caller will only allow the loop to run for
4403     ** a single iteration. This means that the first row returned
4404     ** should not have a NULL value stored in 'x'. If column 'x' is
4405     ** the first one after the nEq equality constraints in the index,
4406     ** this requires some special handling.
4407     */
4408     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
4409      && (pLevel->plan.wsFlags&WHERE_ORDERED)
4410      && (pIdx->nColumn>nEq)
4411     ){
4412       /* assert( pOrderBy->nExpr==1 ); */
4413       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
4414       isMinQuery = 1;
4415       nExtraReg = 1;
4416     }
4417 
4418     /* Find any inequality constraint terms for the start and end
4419     ** of the range.
4420     */
4421     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
4422       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
4423       nExtraReg = 1;
4424     }
4425     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
4426       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
4427       nExtraReg = 1;
4428     }
4429 
4430     /* Generate code to evaluate all constraint terms using == or IN
4431     ** and store the values of those terms in an array of registers
4432     ** starting at regBase.
4433     */
4434     regBase = codeAllEqualityTerms(
4435         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
4436     );
4437     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
4438     addrNxt = pLevel->addrNxt;
4439 
4440     /* If we are doing a reverse order scan on an ascending index, or
4441     ** a forward order scan on a descending index, interchange the
4442     ** start and end terms (pRangeStart and pRangeEnd).
4443     */
4444     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
4445      || (bRev && pIdx->nColumn==nEq)
4446     ){
4447       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
4448     }
4449 
4450     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
4451     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
4452     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
4453     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
4454     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
4455     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
4456     start_constraints = pRangeStart || nEq>0;
4457 
4458     /* Seek the index cursor to the start of the range. */
4459     nConstraint = nEq;
4460     if( pRangeStart ){
4461       Expr *pRight = pRangeStart->pExpr->pRight;
4462       sqlite3ExprCode(pParse, pRight, regBase+nEq);
4463       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
4464         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
4465       }
4466       if( zStartAff ){
4467         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
4468           /* Since the comparison is to be performed with no conversions
4469           ** applied to the operands, set the affinity to apply to pRight to
4470           ** SQLITE_AFF_NONE.  */
4471           zStartAff[nEq] = SQLITE_AFF_NONE;
4472         }
4473         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
4474           zStartAff[nEq] = SQLITE_AFF_NONE;
4475         }
4476       }
4477       nConstraint++;
4478       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4479     }else if( isMinQuery ){
4480       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
4481       nConstraint++;
4482       startEq = 0;
4483       start_constraints = 1;
4484     }
4485     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
4486     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
4487     assert( op!=0 );
4488     testcase( op==OP_Rewind );
4489     testcase( op==OP_Last );
4490     testcase( op==OP_SeekGt );
4491     testcase( op==OP_SeekGe );
4492     testcase( op==OP_SeekLe );
4493     testcase( op==OP_SeekLt );
4494     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
4495 
4496     /* Load the value for the inequality constraint at the end of the
4497     ** range (if any).
4498     */
4499     nConstraint = nEq;
4500     if( pRangeEnd ){
4501       Expr *pRight = pRangeEnd->pExpr->pRight;
4502       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
4503       sqlite3ExprCode(pParse, pRight, regBase+nEq);
4504       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
4505         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
4506       }
4507       if( zEndAff ){
4508         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
4509           /* Since the comparison is to be performed with no conversions
4510           ** applied to the operands, set the affinity to apply to pRight to
4511           ** SQLITE_AFF_NONE.  */
4512           zEndAff[nEq] = SQLITE_AFF_NONE;
4513         }
4514         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
4515           zEndAff[nEq] = SQLITE_AFF_NONE;
4516         }
4517       }
4518       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
4519       nConstraint++;
4520       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4521     }
4522     sqlite3DbFree(pParse->db, zStartAff);
4523     sqlite3DbFree(pParse->db, zEndAff);
4524 
4525     /* Top of the loop body */
4526     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
4527 
4528     /* Check if the index cursor is past the end of the range. */
4529     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
4530     testcase( op==OP_Noop );
4531     testcase( op==OP_IdxGE );
4532     testcase( op==OP_IdxLT );
4533     if( op!=OP_Noop ){
4534       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
4535       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
4536     }
4537 
4538     /* If there are inequality constraints, check that the value
4539     ** of the table column that the inequality contrains is not NULL.
4540     ** If it is, jump to the next iteration of the loop.
4541     */
4542     r1 = sqlite3GetTempReg(pParse);
4543     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
4544     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
4545     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
4546       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
4547       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
4548     }
4549     sqlite3ReleaseTempReg(pParse, r1);
4550 
4551     /* Seek the table cursor, if required */
4552     disableTerm(pLevel, pRangeStart);
4553     disableTerm(pLevel, pRangeEnd);
4554     if( !omitTable ){
4555       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
4556       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
4557       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
4558       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
4559     }
4560 
4561     /* Record the instruction used to terminate the loop. Disable
4562     ** WHERE clause terms made redundant by the index range scan.
4563     */
4564     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
4565       pLevel->op = OP_Noop;
4566     }else if( bRev ){
4567       pLevel->op = OP_Prev;
4568     }else{
4569       pLevel->op = OP_Next;
4570     }
4571     pLevel->p1 = iIdxCur;
4572     if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
4573       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4574     }else{
4575       assert( pLevel->p5==0 );
4576     }
4577   }else
4578 
4579 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
4580   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
4581     /* Case 4:  Two or more separately indexed terms connected by OR
4582     **
4583     ** Example:
4584     **
4585     **   CREATE TABLE t1(a,b,c,d);
4586     **   CREATE INDEX i1 ON t1(a);
4587     **   CREATE INDEX i2 ON t1(b);
4588     **   CREATE INDEX i3 ON t1(c);
4589     **
4590     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
4591     **
4592     ** In the example, there are three indexed terms connected by OR.
4593     ** The top of the loop looks like this:
4594     **
4595     **          Null       1                # Zero the rowset in reg 1
4596     **
4597     ** Then, for each indexed term, the following. The arguments to
4598     ** RowSetTest are such that the rowid of the current row is inserted
4599     ** into the RowSet. If it is already present, control skips the
4600     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
4601     **
4602     **        sqlite3WhereBegin(<term>)
4603     **          RowSetTest                  # Insert rowid into rowset
4604     **          Gosub      2 A
4605     **        sqlite3WhereEnd()
4606     **
4607     ** Following the above, code to terminate the loop. Label A, the target
4608     ** of the Gosub above, jumps to the instruction right after the Goto.
4609     **
4610     **          Null       1                # Zero the rowset in reg 1
4611     **          Goto       B                # The loop is finished.
4612     **
4613     **       A: <loop body>                 # Return data, whatever.
4614     **
4615     **          Return     2                # Jump back to the Gosub
4616     **
4617     **       B: <after the loop>
4618     **
4619     */
4620     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
4621     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
4622     Index *pCov = 0;             /* Potential covering index (or NULL) */
4623     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
4624 
4625     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
4626     int regRowset = 0;                        /* Register for RowSet object */
4627     int regRowid = 0;                         /* Register holding rowid */
4628     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
4629     int iRetInit;                             /* Address of regReturn init */
4630     int untestedTerms = 0;             /* Some terms not completely tested */
4631     int ii;                            /* Loop counter */
4632     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
4633 
4634     pTerm = pLevel->plan.u.pTerm;
4635     assert( pTerm!=0 );
4636     assert( pTerm->eOperator & WO_OR );
4637     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
4638     pOrWc = &pTerm->u.pOrInfo->wc;
4639     pLevel->op = OP_Return;
4640     pLevel->p1 = regReturn;
4641 
4642     /* Set up a new SrcList in pOrTab containing the table being scanned
4643     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
4644     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
4645     */
4646     if( pWInfo->nLevel>1 ){
4647       int nNotReady;                 /* The number of notReady tables */
4648       struct SrcList_item *origSrc;     /* Original list of tables */
4649       nNotReady = pWInfo->nLevel - iLevel - 1;
4650       pOrTab = sqlite3StackAllocRaw(pParse->db,
4651                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
4652       if( pOrTab==0 ) return notReady;
4653       pOrTab->nAlloc = (i16)(nNotReady + 1);
4654       pOrTab->nSrc = pOrTab->nAlloc;
4655       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
4656       origSrc = pWInfo->pTabList->a;
4657       for(k=1; k<=nNotReady; k++){
4658         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
4659       }
4660     }else{
4661       pOrTab = pWInfo->pTabList;
4662     }
4663 
4664     /* Initialize the rowset register to contain NULL. An SQL NULL is
4665     ** equivalent to an empty rowset.
4666     **
4667     ** Also initialize regReturn to contain the address of the instruction
4668     ** immediately following the OP_Return at the bottom of the loop. This
4669     ** is required in a few obscure LEFT JOIN cases where control jumps
4670     ** over the top of the loop into the body of it. In this case the
4671     ** correct response for the end-of-loop code (the OP_Return) is to
4672     ** fall through to the next instruction, just as an OP_Next does if
4673     ** called on an uninitialized cursor.
4674     */
4675     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
4676       regRowset = ++pParse->nMem;
4677       regRowid = ++pParse->nMem;
4678       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
4679     }
4680     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
4681 
4682     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
4683     ** Then for every term xN, evaluate as the subexpression: xN AND z
4684     ** That way, terms in y that are factored into the disjunction will
4685     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
4686     **
4687     ** Actually, each subexpression is converted to "xN AND w" where w is
4688     ** the "interesting" terms of z - terms that did not originate in the
4689     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
4690     ** indices.
4691     */
4692     if( pWC->nTerm>1 ){
4693       int iTerm;
4694       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
4695         Expr *pExpr = pWC->a[iTerm].pExpr;
4696         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
4697         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
4698         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
4699         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4700         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
4701       }
4702       if( pAndExpr ){
4703         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
4704       }
4705     }
4706 
4707     for(ii=0; ii<pOrWc->nTerm; ii++){
4708       WhereTerm *pOrTerm = &pOrWc->a[ii];
4709       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
4710         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
4711         Expr *pOrExpr = pOrTerm->pExpr;
4712         if( pAndExpr ){
4713           pAndExpr->pLeft = pOrExpr;
4714           pOrExpr = pAndExpr;
4715         }
4716         /* Loop through table entries that match term pOrTerm. */
4717         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
4718                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
4719                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
4720         assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
4721         if( pSubWInfo ){
4722           WhereLevel *pLvl;
4723           explainOneScan(
4724               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
4725           );
4726           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
4727             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
4728             int r;
4729             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
4730                                          regRowid, 0);
4731             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
4732                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
4733           }
4734           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
4735 
4736           /* The pSubWInfo->untestedTerms flag means that this OR term
4737           ** contained one or more AND term from a notReady table.  The
4738           ** terms from the notReady table could not be tested and will
4739           ** need to be tested later.
4740           */
4741           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
4742 
4743           /* If all of the OR-connected terms are optimized using the same
4744           ** index, and the index is opened using the same cursor number
4745           ** by each call to sqlite3WhereBegin() made by this loop, it may
4746           ** be possible to use that index as a covering index.
4747           **
4748           ** If the call to sqlite3WhereBegin() above resulted in a scan that
4749           ** uses an index, and this is either the first OR-connected term
4750           ** processed or the index is the same as that used by all previous
4751           ** terms, set pCov to the candidate covering index. Otherwise, set
4752           ** pCov to NULL to indicate that no candidate covering index will
4753           ** be available.
4754           */
4755           pLvl = &pSubWInfo->a[0];
4756           if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
4757            && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
4758            && (ii==0 || pLvl->plan.u.pIdx==pCov)
4759           ){
4760             assert( pLvl->iIdxCur==iCovCur );
4761             pCov = pLvl->plan.u.pIdx;
4762           }else{
4763             pCov = 0;
4764           }
4765 
4766           /* Finish the loop through table entries that match term pOrTerm. */
4767           sqlite3WhereEnd(pSubWInfo);
4768         }
4769       }
4770     }
4771     pLevel->u.pCovidx = pCov;
4772     if( pCov ) pLevel->iIdxCur = iCovCur;
4773     if( pAndExpr ){
4774       pAndExpr->pLeft = 0;
4775       sqlite3ExprDelete(pParse->db, pAndExpr);
4776     }
4777     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
4778     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
4779     sqlite3VdbeResolveLabel(v, iLoopBody);
4780 
4781     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
4782     if( !untestedTerms ) disableTerm(pLevel, pTerm);
4783   }else
4784 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
4785 
4786   {
4787     /* Case 5:  There is no usable index.  We must do a complete
4788     **          scan of the entire table.
4789     */
4790     static const u8 aStep[] = { OP_Next, OP_Prev };
4791     static const u8 aStart[] = { OP_Rewind, OP_Last };
4792     assert( bRev==0 || bRev==1 );
4793     assert( omitTable==0 );
4794     pLevel->op = aStep[bRev];
4795     pLevel->p1 = iCur;
4796     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
4797     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4798   }
4799   notReady &= ~getMask(pWC->pMaskSet, iCur);
4800 
4801   /* Insert code to test every subexpression that can be completely
4802   ** computed using the current set of tables.
4803   **
4804   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
4805   ** the use of indices become tests that are evaluated against each row of
4806   ** the relevant input tables.
4807   */
4808   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
4809     Expr *pE;
4810     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
4811     testcase( pTerm->wtFlags & TERM_CODED );
4812     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
4813     if( (pTerm->prereqAll & notReady)!=0 ){
4814       testcase( pWInfo->untestedTerms==0
4815                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
4816       pWInfo->untestedTerms = 1;
4817       continue;
4818     }
4819     pE = pTerm->pExpr;
4820     assert( pE!=0 );
4821     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
4822       continue;
4823     }
4824     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
4825     pTerm->wtFlags |= TERM_CODED;
4826   }
4827 
4828   /* For a LEFT OUTER JOIN, generate code that will record the fact that
4829   ** at least one row of the right table has matched the left table.
4830   */
4831   if( pLevel->iLeftJoin ){
4832     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
4833     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
4834     VdbeComment((v, "record LEFT JOIN hit"));
4835     sqlite3ExprCacheClear(pParse);
4836     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
4837       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
4838       testcase( pTerm->wtFlags & TERM_CODED );
4839       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
4840       if( (pTerm->prereqAll & notReady)!=0 ){
4841         assert( pWInfo->untestedTerms );
4842         continue;
4843       }
4844       assert( pTerm->pExpr );
4845       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
4846       pTerm->wtFlags |= TERM_CODED;
4847     }
4848   }
4849   sqlite3ReleaseTempReg(pParse, iReleaseReg);
4850 
4851   return notReady;
4852 }
4853 
4854 #if defined(SQLITE_TEST)
4855 /*
4856 ** The following variable holds a text description of query plan generated
4857 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
4858 ** overwrites the previous.  This information is used for testing and
4859 ** analysis only.
4860 */
4861 char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
4862 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
4863 
4864 #endif /* SQLITE_TEST */
4865 
4866 
4867 /*
4868 ** Free a WhereInfo structure
4869 */
4870 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
4871   if( ALWAYS(pWInfo) ){
4872     int i;
4873     for(i=0; i<pWInfo->nLevel; i++){
4874       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
4875       if( pInfo ){
4876         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
4877         if( pInfo->needToFreeIdxStr ){
4878           sqlite3_free(pInfo->idxStr);
4879         }
4880         sqlite3DbFree(db, pInfo);
4881       }
4882       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
4883         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
4884         if( pIdx ){
4885           sqlite3DbFree(db, pIdx->zColAff);
4886           sqlite3DbFree(db, pIdx);
4887         }
4888       }
4889     }
4890     whereClauseClear(pWInfo->pWC);
4891     sqlite3DbFree(db, pWInfo);
4892   }
4893 }
4894 
4895 
4896 /*
4897 ** Generate the beginning of the loop used for WHERE clause processing.
4898 ** The return value is a pointer to an opaque structure that contains
4899 ** information needed to terminate the loop.  Later, the calling routine
4900 ** should invoke sqlite3WhereEnd() with the return value of this function
4901 ** in order to complete the WHERE clause processing.
4902 **
4903 ** If an error occurs, this routine returns NULL.
4904 **
4905 ** The basic idea is to do a nested loop, one loop for each table in
4906 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
4907 ** same as a SELECT with only a single table in the FROM clause.)  For
4908 ** example, if the SQL is this:
4909 **
4910 **       SELECT * FROM t1, t2, t3 WHERE ...;
4911 **
4912 ** Then the code generated is conceptually like the following:
4913 **
4914 **      foreach row1 in t1 do       \    Code generated
4915 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
4916 **          foreach row3 in t3 do   /
4917 **            ...
4918 **          end                     \    Code generated
4919 **        end                        |-- by sqlite3WhereEnd()
4920 **      end                         /
4921 **
4922 ** Note that the loops might not be nested in the order in which they
4923 ** appear in the FROM clause if a different order is better able to make
4924 ** use of indices.  Note also that when the IN operator appears in
4925 ** the WHERE clause, it might result in additional nested loops for
4926 ** scanning through all values on the right-hand side of the IN.
4927 **
4928 ** There are Btree cursors associated with each table.  t1 uses cursor
4929 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
4930 ** And so forth.  This routine generates code to open those VDBE cursors
4931 ** and sqlite3WhereEnd() generates the code to close them.
4932 **
4933 ** The code that sqlite3WhereBegin() generates leaves the cursors named
4934 ** in pTabList pointing at their appropriate entries.  The [...] code
4935 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
4936 ** data from the various tables of the loop.
4937 **
4938 ** If the WHERE clause is empty, the foreach loops must each scan their
4939 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
4940 ** the tables have indices and there are terms in the WHERE clause that
4941 ** refer to those indices, a complete table scan can be avoided and the
4942 ** code will run much faster.  Most of the work of this routine is checking
4943 ** to see if there are indices that can be used to speed up the loop.
4944 **
4945 ** Terms of the WHERE clause are also used to limit which rows actually
4946 ** make it to the "..." in the middle of the loop.  After each "foreach",
4947 ** terms of the WHERE clause that use only terms in that loop and outer
4948 ** loops are evaluated and if false a jump is made around all subsequent
4949 ** inner loops (or around the "..." if the test occurs within the inner-
4950 ** most loop)
4951 **
4952 ** OUTER JOINS
4953 **
4954 ** An outer join of tables t1 and t2 is conceptally coded as follows:
4955 **
4956 **    foreach row1 in t1 do
4957 **      flag = 0
4958 **      foreach row2 in t2 do
4959 **        start:
4960 **          ...
4961 **          flag = 1
4962 **      end
4963 **      if flag==0 then
4964 **        move the row2 cursor to a null row
4965 **        goto start
4966 **      fi
4967 **    end
4968 **
4969 ** ORDER BY CLAUSE PROCESSING
4970 **
4971 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
4972 ** if there is one.  If there is no ORDER BY clause or if this routine
4973 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
4974 **
4975 ** If an index can be used so that the natural output order of the table
4976 ** scan is correct for the ORDER BY clause, then that index is used and
4977 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr.  This
4978 ** is an optimization that prevents an unnecessary sort of the result set
4979 ** if an index appropriate for the ORDER BY clause already exists.
4980 **
4981 ** If the where clause loops cannot be arranged to provide the correct
4982 ** output order, then WhereInfo.nOBSat is 0.
4983 */
4984 WhereInfo *sqlite3WhereBegin(
4985   Parse *pParse,        /* The parser context */
4986   SrcList *pTabList,    /* A list of all tables to be scanned */
4987   Expr *pWhere,         /* The WHERE clause */
4988   ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
4989   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
4990   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
4991   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
4992 ){
4993   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
4994   int nTabList;              /* Number of elements in pTabList */
4995   WhereInfo *pWInfo;         /* Will become the return value of this function */
4996   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
4997   Bitmask notReady;          /* Cursors that are not yet positioned */
4998   WhereBestIdx sWBI;         /* Best index search context */
4999   WhereMaskSet *pMaskSet;    /* The expression mask set */
5000   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
5001   int iFrom;                 /* First unused FROM clause element */
5002   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
5003   int ii;                    /* Loop counter */
5004   sqlite3 *db;               /* Database connection */
5005 
5006 
5007   /* Variable initialization */
5008   memset(&sWBI, 0, sizeof(sWBI));
5009   sWBI.pParse = pParse;
5010 
5011   /* The number of tables in the FROM clause is limited by the number of
5012   ** bits in a Bitmask
5013   */
5014   testcase( pTabList->nSrc==BMS );
5015   if( pTabList->nSrc>BMS ){
5016     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
5017     return 0;
5018   }
5019 
5020   /* This function normally generates a nested loop for all tables in
5021   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
5022   ** only generate code for the first table in pTabList and assume that
5023   ** any cursors associated with subsequent tables are uninitialized.
5024   */
5025   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5026 
5027   /* Allocate and initialize the WhereInfo structure that will become the
5028   ** return value. A single allocation is used to store the WhereInfo
5029   ** struct, the contents of WhereInfo.a[], the WhereClause structure
5030   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5031   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5032   ** some architectures. Hence the ROUND8() below.
5033   */
5034   db = pParse->db;
5035   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
5036   pWInfo = sqlite3DbMallocZero(db,
5037       nByteWInfo +
5038       sizeof(WhereClause) +
5039       sizeof(WhereMaskSet)
5040   );
5041   if( db->mallocFailed ){
5042     sqlite3DbFree(db, pWInfo);
5043     pWInfo = 0;
5044     goto whereBeginError;
5045   }
5046   pWInfo->nLevel = nTabList;
5047   pWInfo->pParse = pParse;
5048   pWInfo->pTabList = pTabList;
5049   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
5050   pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
5051   pWInfo->wctrlFlags = wctrlFlags;
5052   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
5053   pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
5054   sWBI.aLevel = pWInfo->a;
5055 
5056   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5057   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5058   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
5059 
5060   /* Split the WHERE clause into separate subexpressions where each
5061   ** subexpression is separated by an AND operator.
5062   */
5063   initMaskSet(pMaskSet);
5064   whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
5065   sqlite3ExprCodeConstants(pParse, pWhere);
5066   whereSplit(sWBI.pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
5067 
5068   /* Special case: a WHERE clause that is constant.  Evaluate the
5069   ** expression and either jump over all of the code or fall thru.
5070   */
5071   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
5072     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
5073     pWhere = 0;
5074   }
5075 
5076   /* Assign a bit from the bitmask to every term in the FROM clause.
5077   **
5078   ** When assigning bitmask values to FROM clause cursors, it must be
5079   ** the case that if X is the bitmask for the N-th FROM clause term then
5080   ** the bitmask for all FROM clause terms to the left of the N-th term
5081   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
5082   ** its Expr.iRightJoinTable value to find the bitmask of the right table
5083   ** of the join.  Subtracting one from the right table bitmask gives a
5084   ** bitmask for all tables to the left of the join.  Knowing the bitmask
5085   ** for all tables to the left of a left join is important.  Ticket #3015.
5086   **
5087   ** Note that bitmasks are created for all pTabList->nSrc tables in
5088   ** pTabList, not just the first nTabList tables.  nTabList is normally
5089   ** equal to pTabList->nSrc but might be shortened to 1 if the
5090   ** WHERE_ONETABLE_ONLY flag is set.
5091   */
5092   for(ii=0; ii<pTabList->nSrc; ii++){
5093     createMask(pMaskSet, pTabList->a[ii].iCursor);
5094   }
5095 #ifndef NDEBUG
5096   {
5097     Bitmask toTheLeft = 0;
5098     for(ii=0; ii<pTabList->nSrc; ii++){
5099       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
5100       assert( (m-1)==toTheLeft );
5101       toTheLeft |= m;
5102     }
5103   }
5104 #endif
5105 
5106   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
5107   ** add new virtual terms onto the end of the WHERE clause.  We do not
5108   ** want to analyze these virtual terms, so start analyzing at the end
5109   ** and work forward so that the added virtual terms are never processed.
5110   */
5111   exprAnalyzeAll(pTabList, sWBI.pWC);
5112   if( db->mallocFailed ){
5113     goto whereBeginError;
5114   }
5115 
5116   /* Check if the DISTINCT qualifier, if there is one, is redundant.
5117   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
5118   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
5119   */
5120   if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
5121     pDistinct = 0;
5122     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5123   }
5124 
5125   /* Chose the best index to use for each table in the FROM clause.
5126   **
5127   ** This loop fills in the following fields:
5128   **
5129   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
5130   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
5131   **   pWInfo->a[].nEq       The number of == and IN constraints
5132   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
5133   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
5134   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
5135   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
5136   **
5137   ** This loop also figures out the nesting order of tables in the FROM
5138   ** clause.
5139   */
5140   sWBI.notValid = ~(Bitmask)0;
5141   sWBI.pOrderBy = pOrderBy;
5142   sWBI.n = nTabList;
5143   sWBI.pDistinct = pDistinct;
5144   andFlags = ~0;
5145   WHERETRACE(("*** Optimizer Start ***\n"));
5146   for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
5147     WhereCost bestPlan;         /* Most efficient plan seen so far */
5148     Index *pIdx;                /* Index for FROM table at pTabItem */
5149     int j;                      /* For looping over FROM tables */
5150     int bestJ = -1;             /* The value of j */
5151     Bitmask m;                  /* Bitmask value for j or bestJ */
5152     int isOptimal;              /* Iterator for optimal/non-optimal search */
5153     int ckOptimal;              /* Do the optimal scan check */
5154     int nUnconstrained;         /* Number tables without INDEXED BY */
5155     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
5156 
5157     memset(&bestPlan, 0, sizeof(bestPlan));
5158     bestPlan.rCost = SQLITE_BIG_DBL;
5159     WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
5160 
5161     /* Loop through the remaining entries in the FROM clause to find the
5162     ** next nested loop. The loop tests all FROM clause entries
5163     ** either once or twice.
5164     **
5165     ** The first test is always performed if there are two or more entries
5166     ** remaining and never performed if there is only one FROM clause entry
5167     ** to choose from.  The first test looks for an "optimal" scan.  In
5168     ** this context an optimal scan is one that uses the same strategy
5169     ** for the given FROM clause entry as would be selected if the entry
5170     ** were used as the innermost nested loop.  In other words, a table
5171     ** is chosen such that the cost of running that table cannot be reduced
5172     ** by waiting for other tables to run first.  This "optimal" test works
5173     ** by first assuming that the FROM clause is on the inner loop and finding
5174     ** its query plan, then checking to see if that query plan uses any
5175     ** other FROM clause terms that are sWBI.notValid.  If no notValid terms
5176     ** are used then the "optimal" query plan works.
5177     **
5178     ** Note that the WhereCost.nRow parameter for an optimal scan might
5179     ** not be as small as it would be if the table really were the innermost
5180     ** join.  The nRow value can be reduced by WHERE clause constraints
5181     ** that do not use indices.  But this nRow reduction only happens if the
5182     ** table really is the innermost join.
5183     **
5184     ** The second loop iteration is only performed if no optimal scan
5185     ** strategies were found by the first iteration. This second iteration
5186     ** is used to search for the lowest cost scan overall.
5187     **
5188     ** Without the optimal scan step (the first iteration) a suboptimal
5189     ** plan might be chosen for queries like this:
5190     **
5191     **   CREATE TABLE t1(a, b);
5192     **   CREATE TABLE t2(c, d);
5193     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
5194     **
5195     ** The best strategy is to iterate through table t1 first. However it
5196     ** is not possible to determine this with a simple greedy algorithm.
5197     ** Since the cost of a linear scan through table t2 is the same
5198     ** as the cost of a linear scan through table t1, a simple greedy
5199     ** algorithm may choose to use t2 for the outer loop, which is a much
5200     ** costlier approach.
5201     */
5202     nUnconstrained = 0;
5203     notIndexed = 0;
5204 
5205     /* The optimal scan check only occurs if there are two or more tables
5206     ** available to be reordered */
5207     if( iFrom==nTabList-1 ){
5208       ckOptimal = 0;  /* Common case of just one table in the FROM clause */
5209     }else{
5210       ckOptimal = -1;
5211       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
5212         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
5213         if( (m & sWBI.notValid)==0 ){
5214           if( j==iFrom ) iFrom++;
5215           continue;
5216         }
5217         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
5218         if( ++ckOptimal ) break;
5219         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
5220       }
5221     }
5222     assert( ckOptimal==0 || ckOptimal==1 );
5223 
5224     for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
5225       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
5226         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
5227           /* This break and one like it in the ckOptimal computation loop
5228           ** above prevent table reordering across LEFT and CROSS JOINs.
5229           ** The LEFT JOIN case is necessary for correctness.  The prohibition
5230           ** against reordering across a CROSS JOIN is an SQLite feature that
5231           ** allows the developer to control table reordering */
5232           break;
5233         }
5234         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
5235         if( (m & sWBI.notValid)==0 ){
5236           assert( j>iFrom );
5237           continue;
5238         }
5239         sWBI.notReady = (isOptimal ? m : sWBI.notValid);
5240         if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
5241 
5242         WHERETRACE(("   === trying table %d (%s) with isOptimal=%d ===\n",
5243                     j, sWBI.pSrc->pTab->zName, isOptimal));
5244         assert( sWBI.pSrc->pTab );
5245 #ifndef SQLITE_OMIT_VIRTUALTABLE
5246         if( IsVirtual(sWBI.pSrc->pTab) ){
5247           sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
5248           bestVirtualIndex(&sWBI);
5249         }else
5250 #endif
5251         {
5252           bestBtreeIndex(&sWBI);
5253         }
5254         assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
5255 
5256         /* If an INDEXED BY clause is present, then the plan must use that
5257         ** index if it uses any index at all */
5258         assert( sWBI.pSrc->pIndex==0
5259                   || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
5260                   || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
5261 
5262         if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
5263           notIndexed |= m;
5264         }
5265         if( isOptimal ){
5266           pWInfo->a[j].rOptCost = sWBI.cost.rCost;
5267         }else if( ckOptimal ){
5268           /* If two or more tables have nearly the same outer loop cost, but
5269           ** very different inner loop (optimal) cost, we want to choose
5270           ** for the outer loop that table which benefits the least from
5271           ** being in the inner loop.  The following code scales the
5272           ** outer loop cost estimate to accomplish that. */
5273           WHERETRACE(("   scaling cost from %.1f to %.1f\n",
5274                       sWBI.cost.rCost,
5275                       sWBI.cost.rCost/pWInfo->a[j].rOptCost));
5276           sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
5277         }
5278 
5279         /* Conditions under which this table becomes the best so far:
5280         **
5281         **   (1) The table must not depend on other tables that have not
5282         **       yet run.  (In other words, it must not depend on tables
5283         **       in inner loops.)
5284         **
5285         **   (2) (This rule was removed on 2012-11-09.  The scaling of the
5286         **       cost using the optimal scan cost made this rule obsolete.)
5287         **
5288         **   (3) All tables have an INDEXED BY clause or this table lacks an
5289         **       INDEXED BY clause or this table uses the specific
5290         **       index specified by its INDEXED BY clause.  This rule ensures
5291         **       that a best-so-far is always selected even if an impossible
5292         **       combination of INDEXED BY clauses are given.  The error
5293         **       will be detected and relayed back to the application later.
5294         **       The NEVER() comes about because rule (2) above prevents
5295         **       An indexable full-table-scan from reaching rule (3).
5296         **
5297         **   (4) The plan cost must be lower than prior plans, where "cost"
5298         **       is defined by the compareCost() function above.
5299         */
5300         if( (sWBI.cost.used&sWBI.notValid)==0                    /* (1) */
5301             && (nUnconstrained==0 || sWBI.pSrc->pIndex==0        /* (3) */
5302                 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
5303             && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan))   /* (4) */
5304         ){
5305           WHERETRACE(("   === table %d (%s) is best so far\n"
5306                       "       cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
5307                       j, sWBI.pSrc->pTab->zName,
5308                       sWBI.cost.rCost, sWBI.cost.plan.nRow,
5309                       sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
5310           bestPlan = sWBI.cost;
5311           bestJ = j;
5312         }
5313 
5314         /* In a join like "w JOIN x LEFT JOIN y JOIN z"  make sure that
5315         ** table y (and not table z) is always the next inner loop inside
5316         ** of table x. */
5317         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
5318       }
5319     }
5320     assert( bestJ>=0 );
5321     assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
5322     assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
5323     testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
5324     testcase( bestJ>iFrom && bestJ<nTabList-1
5325                           && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
5326     WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
5327                 "    cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
5328                 bestJ, pTabList->a[bestJ].pTab->zName,
5329                 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
5330                 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
5331     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
5332       assert( pWInfo->eDistinct==0 );
5333       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5334     }
5335     andFlags &= bestPlan.plan.wsFlags;
5336     pLevel->plan = bestPlan.plan;
5337     pLevel->iTabCur = pTabList->a[bestJ].iCursor;
5338     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
5339     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
5340     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
5341       if( (wctrlFlags & WHERE_ONETABLE_ONLY)
5342        && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
5343       ){
5344         pLevel->iIdxCur = iIdxCur;
5345       }else{
5346         pLevel->iIdxCur = pParse->nTab++;
5347       }
5348     }else{
5349       pLevel->iIdxCur = -1;
5350     }
5351     sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
5352     pLevel->iFrom = (u8)bestJ;
5353     if( bestPlan.plan.nRow>=(double)1 ){
5354       pParse->nQueryLoop *= bestPlan.plan.nRow;
5355     }
5356 
5357     /* Check that if the table scanned by this loop iteration had an
5358     ** INDEXED BY clause attached to it, that the named index is being
5359     ** used for the scan. If not, then query compilation has failed.
5360     ** Return an error.
5361     */
5362     pIdx = pTabList->a[bestJ].pIndex;
5363     if( pIdx ){
5364       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
5365         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
5366         goto whereBeginError;
5367       }else{
5368         /* If an INDEXED BY clause is used, the bestIndex() function is
5369         ** guaranteed to find the index specified in the INDEXED BY clause
5370         ** if it find an index at all. */
5371         assert( bestPlan.plan.u.pIdx==pIdx );
5372       }
5373     }
5374   }
5375   WHERETRACE(("*** Optimizer Finished ***\n"));
5376   if( pParse->nErr || db->mallocFailed ){
5377     goto whereBeginError;
5378   }
5379   if( nTabList ){
5380     pLevel--;
5381     pWInfo->nOBSat = pLevel->plan.nOBSat;
5382   }else{
5383     pWInfo->nOBSat = 0;
5384   }
5385 
5386   /* If the total query only selects a single row, then the ORDER BY
5387   ** clause is irrelevant.
5388   */
5389   if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
5390     assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
5391     pWInfo->nOBSat = pOrderBy->nExpr;
5392   }
5393 
5394   /* If the caller is an UPDATE or DELETE statement that is requesting
5395   ** to use a one-pass algorithm, determine if this is appropriate.
5396   ** The one-pass algorithm only works if the WHERE clause constraints
5397   ** the statement to update a single row.
5398   */
5399   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
5400   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
5401     pWInfo->okOnePass = 1;
5402     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
5403   }
5404 
5405   /* Open all tables in the pTabList and any indices selected for
5406   ** searching those tables.
5407   */
5408   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
5409   notReady = ~(Bitmask)0;
5410   pWInfo->nRowOut = (double)1;
5411   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
5412     Table *pTab;     /* Table to open */
5413     int iDb;         /* Index of database containing table/index */
5414     struct SrcList_item *pTabItem;
5415 
5416     pTabItem = &pTabList->a[pLevel->iFrom];
5417     pTab = pTabItem->pTab;
5418     pWInfo->nRowOut *= pLevel->plan.nRow;
5419     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
5420     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
5421       /* Do nothing */
5422     }else
5423 #ifndef SQLITE_OMIT_VIRTUALTABLE
5424     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
5425       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
5426       int iCur = pTabItem->iCursor;
5427       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
5428     }else if( IsVirtual(pTab) ){
5429       /* noop */
5430     }else
5431 #endif
5432     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
5433          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
5434       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
5435       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
5436       testcase( pTab->nCol==BMS-1 );
5437       testcase( pTab->nCol==BMS );
5438       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
5439         Bitmask b = pTabItem->colUsed;
5440         int n = 0;
5441         for(; b; b=b>>1, n++){}
5442         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5443                             SQLITE_INT_TO_PTR(n), P4_INT32);
5444         assert( n<=pTab->nCol );
5445       }
5446     }else{
5447       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5448     }
5449 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
5450     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
5451       constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
5452     }else
5453 #endif
5454     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
5455       Index *pIx = pLevel->plan.u.pIdx;
5456       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
5457       int iIndexCur = pLevel->iIdxCur;
5458       assert( pIx->pSchema==pTab->pSchema );
5459       assert( iIndexCur>=0 );
5460       sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
5461                         (char*)pKey, P4_KEYINFO_HANDOFF);
5462       VdbeComment((v, "%s", pIx->zName));
5463     }
5464     sqlite3CodeVerifySchema(pParse, iDb);
5465     notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
5466   }
5467   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
5468   if( db->mallocFailed ) goto whereBeginError;
5469 
5470   /* Generate the code to do the search.  Each iteration of the for
5471   ** loop below generates code for a single nested loop of the VM
5472   ** program.
5473   */
5474   notReady = ~(Bitmask)0;
5475   for(ii=0; ii<nTabList; ii++){
5476     pLevel = &pWInfo->a[ii];
5477     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
5478     notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
5479     pWInfo->iContinue = pLevel->addrCont;
5480   }
5481 
5482 #ifdef SQLITE_TEST  /* For testing and debugging use only */
5483   /* Record in the query plan information about the current table
5484   ** and the index used to access it (if any).  If the table itself
5485   ** is not used, its name is just '{}'.  If no index is used
5486   ** the index is listed as "{}".  If the primary key is used the
5487   ** index name is '*'.
5488   */
5489   for(ii=0; ii<nTabList; ii++){
5490     char *z;
5491     int n;
5492     int w;
5493     struct SrcList_item *pTabItem;
5494 
5495     pLevel = &pWInfo->a[ii];
5496     w = pLevel->plan.wsFlags;
5497     pTabItem = &pTabList->a[pLevel->iFrom];
5498     z = pTabItem->zAlias;
5499     if( z==0 ) z = pTabItem->pTab->zName;
5500     n = sqlite3Strlen30(z);
5501     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
5502       if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
5503         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
5504         nQPlan += 2;
5505       }else{
5506         memcpy(&sqlite3_query_plan[nQPlan], z, n);
5507         nQPlan += n;
5508       }
5509       sqlite3_query_plan[nQPlan++] = ' ';
5510     }
5511     testcase( w & WHERE_ROWID_EQ );
5512     testcase( w & WHERE_ROWID_RANGE );
5513     if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
5514       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
5515       nQPlan += 2;
5516     }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
5517       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
5518       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
5519         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
5520         nQPlan += n;
5521         sqlite3_query_plan[nQPlan++] = ' ';
5522       }
5523     }else{
5524       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
5525       nQPlan += 3;
5526     }
5527   }
5528   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
5529     sqlite3_query_plan[--nQPlan] = 0;
5530   }
5531   sqlite3_query_plan[nQPlan] = 0;
5532   nQPlan = 0;
5533 #endif /* SQLITE_TEST // Testing and debugging use only */
5534 
5535   /* Record the continuation address in the WhereInfo structure.  Then
5536   ** clean up and return.
5537   */
5538   return pWInfo;
5539 
5540   /* Jump here if malloc fails */
5541 whereBeginError:
5542   if( pWInfo ){
5543     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5544     whereInfoFree(db, pWInfo);
5545   }
5546   return 0;
5547 }
5548 
5549 /*
5550 ** Generate the end of the WHERE loop.  See comments on
5551 ** sqlite3WhereBegin() for additional information.
5552 */
5553 void sqlite3WhereEnd(WhereInfo *pWInfo){
5554   Parse *pParse = pWInfo->pParse;
5555   Vdbe *v = pParse->pVdbe;
5556   int i;
5557   WhereLevel *pLevel;
5558   SrcList *pTabList = pWInfo->pTabList;
5559   sqlite3 *db = pParse->db;
5560 
5561   /* Generate loop termination code.
5562   */
5563   sqlite3ExprCacheClear(pParse);
5564   for(i=pWInfo->nLevel-1; i>=0; i--){
5565     pLevel = &pWInfo->a[i];
5566     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
5567     if( pLevel->op!=OP_Noop ){
5568       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
5569       sqlite3VdbeChangeP5(v, pLevel->p5);
5570     }
5571     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
5572       struct InLoop *pIn;
5573       int j;
5574       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
5575       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
5576         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
5577         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
5578         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
5579       }
5580       sqlite3DbFree(db, pLevel->u.in.aInLoop);
5581     }
5582     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
5583     if( pLevel->iLeftJoin ){
5584       int addr;
5585       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
5586       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
5587            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
5588       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
5589         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5590       }
5591       if( pLevel->iIdxCur>=0 ){
5592         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
5593       }
5594       if( pLevel->op==OP_Return ){
5595         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5596       }else{
5597         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5598       }
5599       sqlite3VdbeJumpHere(v, addr);
5600     }
5601   }
5602 
5603   /* The "break" point is here, just past the end of the outer loop.
5604   ** Set it.
5605   */
5606   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
5607 
5608   /* Close all of the cursors that were opened by sqlite3WhereBegin.
5609   */
5610   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
5611   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
5612     Index *pIdx = 0;
5613     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
5614     Table *pTab = pTabItem->pTab;
5615     assert( pTab!=0 );
5616     if( (pTab->tabFlags & TF_Ephemeral)==0
5617      && pTab->pSelect==0
5618      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
5619     ){
5620       int ws = pLevel->plan.wsFlags;
5621       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
5622         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5623       }
5624       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
5625         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5626       }
5627     }
5628 
5629     /* If this scan uses an index, make code substitutions to read data
5630     ** from the index in preference to the table. Sometimes, this means
5631     ** the table need never be read from. This is a performance boost,
5632     ** as the vdbe level waits until the table is read before actually
5633     ** seeking the table cursor to the record corresponding to the current
5634     ** position in the index.
5635     **
5636     ** Calls to the code generator in between sqlite3WhereBegin and
5637     ** sqlite3WhereEnd will have created code that references the table
5638     ** directly.  This loop scans all that code looking for opcodes
5639     ** that reference the table and converts them into opcodes that
5640     ** reference the index.
5641     */
5642     if( pLevel->plan.wsFlags & WHERE_INDEXED ){
5643       pIdx = pLevel->plan.u.pIdx;
5644     }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
5645       pIdx = pLevel->u.pCovidx;
5646     }
5647     if( pIdx && !db->mallocFailed){
5648       int k, j, last;
5649       VdbeOp *pOp;
5650 
5651       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
5652       last = sqlite3VdbeCurrentAddr(v);
5653       for(k=pWInfo->iTop; k<last; k++, pOp++){
5654         if( pOp->p1!=pLevel->iTabCur ) continue;
5655         if( pOp->opcode==OP_Column ){
5656           for(j=0; j<pIdx->nColumn; j++){
5657             if( pOp->p2==pIdx->aiColumn[j] ){
5658               pOp->p2 = j;
5659               pOp->p1 = pLevel->iIdxCur;
5660               break;
5661             }
5662           }
5663           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
5664                || j<pIdx->nColumn );
5665         }else if( pOp->opcode==OP_Rowid ){
5666           pOp->p1 = pLevel->iIdxCur;
5667           pOp->opcode = OP_IdxRowid;
5668         }
5669       }
5670     }
5671   }
5672 
5673   /* Final cleanup
5674   */
5675   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5676   whereInfoFree(db, pWInfo);
5677   return;
5678 }
5679