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