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