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