xref: /sqlite-3.40.0/src/where.c (revision 962f9669)
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     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
2789     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
2790     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
2791     pLevel->op = OP_Goto;
2792   }else
2793 
2794 #ifndef SQLITE_OMIT_VIRTUALTABLE
2795   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
2796     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
2797     **          to access the data.
2798     */
2799     int iReg;   /* P3 Value for OP_VFilter */
2800     int addrNotFound;
2801     int nConstraint = pLoop->nLTerm;
2802 
2803     sqlite3ExprCachePush(pParse);
2804     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
2805     addrNotFound = pLevel->addrBrk;
2806     for(j=0; j<nConstraint; j++){
2807       int iTarget = iReg+j+2;
2808       pTerm = pLoop->aLTerm[j];
2809       if( pTerm==0 ) continue;
2810       if( pTerm->eOperator & WO_IN ){
2811         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
2812         addrNotFound = pLevel->addrNxt;
2813       }else{
2814         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
2815       }
2816     }
2817     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
2818     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
2819     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
2820                       pLoop->u.vtab.idxStr,
2821                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
2822     pLoop->u.vtab.needFree = 0;
2823     for(j=0; j<nConstraint && j<16; j++){
2824       if( (pLoop->u.vtab.omitMask>>j)&1 ){
2825         disableTerm(pLevel, pLoop->aLTerm[j]);
2826       }
2827     }
2828     pLevel->op = OP_VNext;
2829     pLevel->p1 = iCur;
2830     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
2831     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
2832     sqlite3ExprCachePop(pParse, 1);
2833   }else
2834 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2835 
2836   if( (pLoop->wsFlags & WHERE_IPK)!=0
2837    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
2838   ){
2839     /* Case 2:  We can directly reference a single row using an
2840     **          equality comparison against the ROWID field.  Or
2841     **          we reference multiple rows using a "rowid IN (...)"
2842     **          construct.
2843     */
2844     assert( pLoop->u.btree.nEq==1 );
2845     iReleaseReg = sqlite3GetTempReg(pParse);
2846     pTerm = pLoop->aLTerm[0];
2847     assert( pTerm!=0 );
2848     assert( pTerm->pExpr!=0 );
2849     assert( omitTable==0 );
2850     testcase( pTerm->wtFlags & TERM_VIRTUAL );
2851     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
2852     addrNxt = pLevel->addrNxt;
2853     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
2854     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
2855     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
2856     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
2857     VdbeComment((v, "pk"));
2858     pLevel->op = OP_Noop;
2859   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
2860          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
2861   ){
2862     /* Case 3:  We have an inequality comparison against the ROWID field.
2863     */
2864     int testOp = OP_Noop;
2865     int start;
2866     int memEndValue = 0;
2867     WhereTerm *pStart, *pEnd;
2868 
2869     assert( omitTable==0 );
2870     j = 0;
2871     pStart = pEnd = 0;
2872     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
2873     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
2874     assert( pStart!=0 || pEnd!=0 );
2875     if( bRev ){
2876       pTerm = pStart;
2877       pStart = pEnd;
2878       pEnd = pTerm;
2879     }
2880     if( pStart ){
2881       Expr *pX;             /* The expression that defines the start bound */
2882       int r1, rTemp;        /* Registers for holding the start boundary */
2883 
2884       /* The following constant maps TK_xx codes into corresponding
2885       ** seek opcodes.  It depends on a particular ordering of TK_xx
2886       */
2887       const u8 aMoveOp[] = {
2888            /* TK_GT */  OP_SeekGt,
2889            /* TK_LE */  OP_SeekLe,
2890            /* TK_LT */  OP_SeekLt,
2891            /* TK_GE */  OP_SeekGe
2892       };
2893       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
2894       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
2895       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
2896 
2897       assert( (pStart->wtFlags & TERM_VNULL)==0 );
2898       testcase( pStart->wtFlags & TERM_VIRTUAL );
2899       pX = pStart->pExpr;
2900       assert( pX!=0 );
2901       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
2902       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
2903       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
2904       VdbeComment((v, "pk"));
2905       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
2906       sqlite3ReleaseTempReg(pParse, rTemp);
2907       disableTerm(pLevel, pStart);
2908     }else{
2909       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
2910     }
2911     if( pEnd ){
2912       Expr *pX;
2913       pX = pEnd->pExpr;
2914       assert( pX!=0 );
2915       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
2916       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
2917       testcase( pEnd->wtFlags & TERM_VIRTUAL );
2918       memEndValue = ++pParse->nMem;
2919       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
2920       if( pX->op==TK_LT || pX->op==TK_GT ){
2921         testOp = bRev ? OP_Le : OP_Ge;
2922       }else{
2923         testOp = bRev ? OP_Lt : OP_Gt;
2924       }
2925       disableTerm(pLevel, pEnd);
2926     }
2927     start = sqlite3VdbeCurrentAddr(v);
2928     pLevel->op = bRev ? OP_Prev : OP_Next;
2929     pLevel->p1 = iCur;
2930     pLevel->p2 = start;
2931     assert( pLevel->p5==0 );
2932     if( testOp!=OP_Noop ){
2933       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
2934       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
2935       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
2936       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
2937       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
2938     }
2939   }else if( pLoop->wsFlags & WHERE_INDEXED ){
2940     /* Case 4: A scan using an index.
2941     **
2942     **         The WHERE clause may contain zero or more equality
2943     **         terms ("==" or "IN" operators) that refer to the N
2944     **         left-most columns of the index. It may also contain
2945     **         inequality constraints (>, <, >= or <=) on the indexed
2946     **         column that immediately follows the N equalities. Only
2947     **         the right-most column can be an inequality - the rest must
2948     **         use the "==" and "IN" operators. For example, if the
2949     **         index is on (x,y,z), then the following clauses are all
2950     **         optimized:
2951     **
2952     **            x=5
2953     **            x=5 AND y=10
2954     **            x=5 AND y<10
2955     **            x=5 AND y>5 AND y<10
2956     **            x=5 AND y=5 AND z<=10
2957     **
2958     **         The z<10 term of the following cannot be used, only
2959     **         the x=5 term:
2960     **
2961     **            x=5 AND z<10
2962     **
2963     **         N may be zero if there are inequality constraints.
2964     **         If there are no inequality constraints, then N is at
2965     **         least one.
2966     **
2967     **         This case is also used when there are no WHERE clause
2968     **         constraints but an index is selected anyway, in order
2969     **         to force the output order to conform to an ORDER BY.
2970     */
2971     static const u8 aStartOp[] = {
2972       0,
2973       0,
2974       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
2975       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
2976       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
2977       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
2978       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
2979       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
2980     };
2981     static const u8 aEndOp[] = {
2982       OP_Noop,             /* 0: (!end_constraints) */
2983       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
2984       OP_IdxLT             /* 2: (end_constraints && bRev) */
2985     };
2986     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
2987     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
2988     int regBase;                 /* Base register holding constraint values */
2989     int r1;                      /* Temp register */
2990     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
2991     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
2992     int startEq;                 /* True if range start uses ==, >= or <= */
2993     int endEq;                   /* True if range end uses ==, >= or <= */
2994     int start_constraints;       /* Start of range is constrained */
2995     int nConstraint;             /* Number of constraint terms */
2996     Index *pIdx;                 /* The index we will be using */
2997     int iIdxCur;                 /* The VDBE cursor for the index */
2998     int nExtraReg = 0;           /* Number of extra registers needed */
2999     int op;                      /* Instruction opcode */
3000     char *zStartAff;             /* Affinity for start of range constraint */
3001     char cEndAff = 0;            /* Affinity for end of range constraint */
3002 
3003     pIdx = pLoop->u.btree.pIndex;
3004     iIdxCur = pLevel->iIdxCur;
3005     assert( nEq>=pLoop->u.btree.nSkip );
3006 
3007     /* If this loop satisfies a sort order (pOrderBy) request that
3008     ** was passed to this function to implement a "SELECT min(x) ..."
3009     ** query, then the caller will only allow the loop to run for
3010     ** a single iteration. This means that the first row returned
3011     ** should not have a NULL value stored in 'x'. If column 'x' is
3012     ** the first one after the nEq equality constraints in the index,
3013     ** this requires some special handling.
3014     */
3015     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
3016      && (pWInfo->bOBSat!=0)
3017      && (pIdx->nKeyCol>nEq)
3018     ){
3019       assert( pLoop->u.btree.nSkip==0 );
3020       isMinQuery = 1;
3021       nExtraReg = 1;
3022     }
3023 
3024     /* Find any inequality constraint terms for the start and end
3025     ** of the range.
3026     */
3027     j = nEq;
3028     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
3029       pRangeStart = pLoop->aLTerm[j++];
3030       nExtraReg = 1;
3031     }
3032     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
3033       pRangeEnd = pLoop->aLTerm[j++];
3034       nExtraReg = 1;
3035     }
3036 
3037     /* Generate code to evaluate all constraint terms using == or IN
3038     ** and store the values of those terms in an array of registers
3039     ** starting at regBase.
3040     */
3041     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
3042     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
3043     if( zStartAff ) cEndAff = zStartAff[nEq];
3044     addrNxt = pLevel->addrNxt;
3045 
3046     /* If we are doing a reverse order scan on an ascending index, or
3047     ** a forward order scan on a descending index, interchange the
3048     ** start and end terms (pRangeStart and pRangeEnd).
3049     */
3050     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3051      || (bRev && pIdx->nKeyCol==nEq)
3052     ){
3053       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3054     }
3055 
3056     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3057     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3058     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3059     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
3060     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3061     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3062     start_constraints = pRangeStart || nEq>0;
3063 
3064     /* Seek the index cursor to the start of the range. */
3065     nConstraint = nEq;
3066     if( pRangeStart ){
3067       Expr *pRight = pRangeStart->pExpr->pRight;
3068       sqlite3ExprCode(pParse, pRight, regBase+nEq);
3069       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3070         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3071       }
3072       if( zStartAff ){
3073         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
3074           /* Since the comparison is to be performed with no conversions
3075           ** applied to the operands, set the affinity to apply to pRight to
3076           ** SQLITE_AFF_NONE.  */
3077           zStartAff[nEq] = SQLITE_AFF_NONE;
3078         }
3079         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3080           zStartAff[nEq] = SQLITE_AFF_NONE;
3081         }
3082       }
3083       nConstraint++;
3084       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
3085     }else if( isMinQuery ){
3086       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3087       nConstraint++;
3088       startEq = 0;
3089       start_constraints = 1;
3090     }
3091     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
3092     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3093     assert( op!=0 );
3094     testcase( op==OP_Rewind );
3095     testcase( op==OP_Last );
3096     testcase( op==OP_SeekGt );
3097     testcase( op==OP_SeekGe );
3098     testcase( op==OP_SeekLe );
3099     testcase( op==OP_SeekLt );
3100     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
3101 
3102     /* Load the value for the inequality constraint at the end of the
3103     ** range (if any).
3104     */
3105     nConstraint = nEq;
3106     if( pRangeEnd ){
3107       Expr *pRight = pRangeEnd->pExpr->pRight;
3108       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
3109       sqlite3ExprCode(pParse, pRight, regBase+nEq);
3110       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3111         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3112       }
3113       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
3114        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
3115       ){
3116         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
3117       }
3118       nConstraint++;
3119       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
3120     }
3121     sqlite3DbFree(db, zStartAff);
3122 
3123     /* Top of the loop body */
3124     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3125 
3126     /* Check if the index cursor is past the end of the range. */
3127     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3128     testcase( op==OP_Noop );
3129     testcase( op==OP_IdxGE );
3130     testcase( op==OP_IdxLT );
3131     if( op!=OP_Noop ){
3132       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
3133       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3134     }
3135 
3136     /* If there are inequality constraints, check that the value
3137     ** of the table column that the inequality contrains is not NULL.
3138     ** If it is, jump to the next iteration of the loop.
3139     */
3140     r1 = sqlite3GetTempReg(pParse);
3141     testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
3142     testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
3143     if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
3144      && (j = pIdx->aiColumn[nEq])>=0
3145      && pIdx->pTable->aCol[j].notNull==0
3146      && (nEq || (pLoop->wsFlags & WHERE_BTM_LIMIT)==0)
3147     ){
3148       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3149       VdbeComment((v, "%s", pIdx->pTable->aCol[j].zName));
3150       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3151     }
3152     sqlite3ReleaseTempReg(pParse, r1);
3153 
3154     /* Seek the table cursor, if required */
3155     disableTerm(pLevel, pRangeStart);
3156     disableTerm(pLevel, pRangeEnd);
3157     if( omitTable ){
3158       /* pIdx is a covering index.  No need to access the main table. */
3159     }else if( HasRowid(pIdx->pTable) ){
3160       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3161       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
3162       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
3163       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
3164     }else{
3165       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
3166       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
3167       for(j=0; j<pPk->nKeyCol; j++){
3168         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
3169         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
3170       }
3171       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
3172                            iRowidReg, pPk->nKeyCol);
3173     }
3174 
3175     /* Record the instruction used to terminate the loop. Disable
3176     ** WHERE clause terms made redundant by the index range scan.
3177     */
3178     if( pLoop->wsFlags & WHERE_ONEROW ){
3179       pLevel->op = OP_Noop;
3180     }else if( bRev ){
3181       pLevel->op = OP_Prev;
3182     }else{
3183       pLevel->op = OP_Next;
3184     }
3185     pLevel->p1 = iIdxCur;
3186     assert( (WHERE_UNQ_WANTED>>16)==1 );
3187     pLevel->p3 = (pLoop->wsFlags>>16)&1;
3188     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
3189       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3190     }else{
3191       assert( pLevel->p5==0 );
3192     }
3193   }else
3194 
3195 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
3196   if( pLoop->wsFlags & WHERE_MULTI_OR ){
3197     /* Case 5:  Two or more separately indexed terms connected by OR
3198     **
3199     ** Example:
3200     **
3201     **   CREATE TABLE t1(a,b,c,d);
3202     **   CREATE INDEX i1 ON t1(a);
3203     **   CREATE INDEX i2 ON t1(b);
3204     **   CREATE INDEX i3 ON t1(c);
3205     **
3206     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3207     **
3208     ** In the example, there are three indexed terms connected by OR.
3209     ** The top of the loop looks like this:
3210     **
3211     **          Null       1                # Zero the rowset in reg 1
3212     **
3213     ** Then, for each indexed term, the following. The arguments to
3214     ** RowSetTest are such that the rowid of the current row is inserted
3215     ** into the RowSet. If it is already present, control skips the
3216     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
3217     **
3218     **        sqlite3WhereBegin(<term>)
3219     **          RowSetTest                  # Insert rowid into rowset
3220     **          Gosub      2 A
3221     **        sqlite3WhereEnd()
3222     **
3223     ** Following the above, code to terminate the loop. Label A, the target
3224     ** of the Gosub above, jumps to the instruction right after the Goto.
3225     **
3226     **          Null       1                # Zero the rowset in reg 1
3227     **          Goto       B                # The loop is finished.
3228     **
3229     **       A: <loop body>                 # Return data, whatever.
3230     **
3231     **          Return     2                # Jump back to the Gosub
3232     **
3233     **       B: <after the loop>
3234     **
3235     */
3236     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
3237     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
3238     Index *pCov = 0;             /* Potential covering index (or NULL) */
3239     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
3240 
3241     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
3242     int regRowset = 0;                        /* Register for RowSet object */
3243     int regRowid = 0;                         /* Register holding rowid */
3244     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
3245     int iRetInit;                             /* Address of regReturn init */
3246     int untestedTerms = 0;             /* Some terms not completely tested */
3247     int ii;                            /* Loop counter */
3248     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
3249 
3250     pTerm = pLoop->aLTerm[0];
3251     assert( pTerm!=0 );
3252     assert( pTerm->eOperator & WO_OR );
3253     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3254     pOrWc = &pTerm->u.pOrInfo->wc;
3255     pLevel->op = OP_Return;
3256     pLevel->p1 = regReturn;
3257 
3258     /* Set up a new SrcList in pOrTab containing the table being scanned
3259     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3260     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3261     */
3262     if( pWInfo->nLevel>1 ){
3263       int nNotReady;                 /* The number of notReady tables */
3264       struct SrcList_item *origSrc;     /* Original list of tables */
3265       nNotReady = pWInfo->nLevel - iLevel - 1;
3266       pOrTab = sqlite3StackAllocRaw(db,
3267                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3268       if( pOrTab==0 ) return notReady;
3269       pOrTab->nAlloc = (u8)(nNotReady + 1);
3270       pOrTab->nSrc = pOrTab->nAlloc;
3271       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3272       origSrc = pWInfo->pTabList->a;
3273       for(k=1; k<=nNotReady; k++){
3274         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3275       }
3276     }else{
3277       pOrTab = pWInfo->pTabList;
3278     }
3279 
3280     /* Initialize the rowset register to contain NULL. An SQL NULL is
3281     ** equivalent to an empty rowset.
3282     **
3283     ** Also initialize regReturn to contain the address of the instruction
3284     ** immediately following the OP_Return at the bottom of the loop. This
3285     ** is required in a few obscure LEFT JOIN cases where control jumps
3286     ** over the top of the loop into the body of it. In this case the
3287     ** correct response for the end-of-loop code (the OP_Return) is to
3288     ** fall through to the next instruction, just as an OP_Next does if
3289     ** called on an uninitialized cursor.
3290     */
3291     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
3292       regRowset = ++pParse->nMem;
3293       regRowid = ++pParse->nMem;
3294       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3295     }
3296     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3297 
3298     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
3299     ** Then for every term xN, evaluate as the subexpression: xN AND z
3300     ** That way, terms in y that are factored into the disjunction will
3301     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
3302     **
3303     ** Actually, each subexpression is converted to "xN AND w" where w is
3304     ** the "interesting" terms of z - terms that did not originate in the
3305     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3306     ** indices.
3307     **
3308     ** This optimization also only applies if the (x1 OR x2 OR ...) term
3309     ** is not contained in the ON clause of a LEFT JOIN.
3310     ** See ticket http://www.sqlite.org/src/info/f2369304e4
3311     */
3312     if( pWC->nTerm>1 ){
3313       int iTerm;
3314       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3315         Expr *pExpr = pWC->a[iTerm].pExpr;
3316         if( &pWC->a[iTerm] == pTerm ) continue;
3317         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
3318         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
3319         testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
3320         if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
3321         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
3322         pExpr = sqlite3ExprDup(db, pExpr, 0);
3323         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
3324       }
3325       if( pAndExpr ){
3326         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3327       }
3328     }
3329 
3330     for(ii=0; ii<pOrWc->nTerm; ii++){
3331       WhereTerm *pOrTerm = &pOrWc->a[ii];
3332       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
3333         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
3334         Expr *pOrExpr = pOrTerm->pExpr;
3335         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
3336           pAndExpr->pLeft = pOrExpr;
3337           pOrExpr = pAndExpr;
3338         }
3339         /* Loop through table entries that match term pOrTerm. */
3340         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
3341                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
3342                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
3343         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
3344         if( pSubWInfo ){
3345           WhereLoop *pSubLoop;
3346           explainOneScan(
3347               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
3348           );
3349           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
3350             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3351             int r;
3352             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
3353                                          regRowid, 0);
3354             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3355                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
3356           }
3357           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3358 
3359           /* The pSubWInfo->untestedTerms flag means that this OR term
3360           ** contained one or more AND term from a notReady table.  The
3361           ** terms from the notReady table could not be tested and will
3362           ** need to be tested later.
3363           */
3364           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3365 
3366           /* If all of the OR-connected terms are optimized using the same
3367           ** index, and the index is opened using the same cursor number
3368           ** by each call to sqlite3WhereBegin() made by this loop, it may
3369           ** be possible to use that index as a covering index.
3370           **
3371           ** If the call to sqlite3WhereBegin() above resulted in a scan that
3372           ** uses an index, and this is either the first OR-connected term
3373           ** processed or the index is the same as that used by all previous
3374           ** terms, set pCov to the candidate covering index. Otherwise, set
3375           ** pCov to NULL to indicate that no candidate covering index will
3376           ** be available.
3377           */
3378           pSubLoop = pSubWInfo->a[0].pWLoop;
3379           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
3380           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
3381            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
3382           ){
3383             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
3384             pCov = pSubLoop->u.btree.pIndex;
3385           }else{
3386             pCov = 0;
3387           }
3388 
3389           /* Finish the loop through table entries that match term pOrTerm. */
3390           sqlite3WhereEnd(pSubWInfo);
3391         }
3392       }
3393     }
3394     pLevel->u.pCovidx = pCov;
3395     if( pCov ) pLevel->iIdxCur = iCovCur;
3396     if( pAndExpr ){
3397       pAndExpr->pLeft = 0;
3398       sqlite3ExprDelete(db, pAndExpr);
3399     }
3400     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
3401     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3402     sqlite3VdbeResolveLabel(v, iLoopBody);
3403 
3404     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
3405     if( !untestedTerms ) disableTerm(pLevel, pTerm);
3406   }else
3407 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
3408 
3409   {
3410     /* Case 6:  There is no usable index.  We must do a complete
3411     **          scan of the entire table.
3412     */
3413     static const u8 aStep[] = { OP_Next, OP_Prev };
3414     static const u8 aStart[] = { OP_Rewind, OP_Last };
3415     assert( bRev==0 || bRev==1 );
3416     if( pTabItem->isRecursive ){
3417       /* Tables marked isRecursive have only a single row that is stored in
3418       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
3419       pLevel->op = OP_Noop;
3420     }else{
3421       pLevel->op = aStep[bRev];
3422       pLevel->p1 = iCur;
3423       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
3424       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3425     }
3426   }
3427 
3428   /* Insert code to test every subexpression that can be completely
3429   ** computed using the current set of tables.
3430   */
3431   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3432     Expr *pE;
3433     testcase( pTerm->wtFlags & TERM_VIRTUAL );
3434     testcase( pTerm->wtFlags & TERM_CODED );
3435     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3436     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
3437       testcase( pWInfo->untestedTerms==0
3438                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3439       pWInfo->untestedTerms = 1;
3440       continue;
3441     }
3442     pE = pTerm->pExpr;
3443     assert( pE!=0 );
3444     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3445       continue;
3446     }
3447     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
3448     pTerm->wtFlags |= TERM_CODED;
3449   }
3450 
3451   /* Insert code to test for implied constraints based on transitivity
3452   ** of the "==" operator.
3453   **
3454   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3455   ** and we are coding the t1 loop and the t2 loop has not yet coded,
3456   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3457   ** the implied "t1.a=123" constraint.
3458   */
3459   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3460     Expr *pE, *pEAlt;
3461     WhereTerm *pAlt;
3462     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3463     if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3464     if( pTerm->leftCursor!=iCur ) continue;
3465     if( pLevel->iLeftJoin ) continue;
3466     pE = pTerm->pExpr;
3467     assert( !ExprHasProperty(pE, EP_FromJoin) );
3468     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
3469     pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3470     if( pAlt==0 ) continue;
3471     if( pAlt->wtFlags & (TERM_CODED) ) continue;
3472     testcase( pAlt->eOperator & WO_EQ );
3473     testcase( pAlt->eOperator & WO_IN );
3474     VdbeModuleComment((v, "begin transitive constraint"));
3475     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3476     if( pEAlt ){
3477       *pEAlt = *pAlt->pExpr;
3478       pEAlt->pLeft = pE->pLeft;
3479       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3480       sqlite3StackFree(db, pEAlt);
3481     }
3482   }
3483 
3484   /* For a LEFT OUTER JOIN, generate code that will record the fact that
3485   ** at least one row of the right table has matched the left table.
3486   */
3487   if( pLevel->iLeftJoin ){
3488     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3489     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3490     VdbeComment((v, "record LEFT JOIN hit"));
3491     sqlite3ExprCacheClear(pParse);
3492     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
3493       testcase( pTerm->wtFlags & TERM_VIRTUAL );
3494       testcase( pTerm->wtFlags & TERM_CODED );
3495       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3496       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
3497         assert( pWInfo->untestedTerms );
3498         continue;
3499       }
3500       assert( pTerm->pExpr );
3501       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3502       pTerm->wtFlags |= TERM_CODED;
3503     }
3504   }
3505   sqlite3ReleaseTempReg(pParse, iReleaseReg);
3506 
3507   return pLevel->notReady;
3508 }
3509 
3510 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
3511 /*
3512 ** Generate "Explanation" text for a WhereTerm.
3513 */
3514 static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
3515   char zType[4];
3516   memcpy(zType, "...", 4);
3517   if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
3518   if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
3519   if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
3520   sqlite3ExplainPrintf(v, "%s ", zType);
3521   sqlite3ExplainExpr(v, pTerm->pExpr);
3522 }
3523 #endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
3524 
3525 
3526 #ifdef WHERETRACE_ENABLED
3527 /*
3528 ** Print a WhereLoop object for debugging purposes
3529 */
3530 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
3531   WhereInfo *pWInfo = pWC->pWInfo;
3532   int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
3533   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
3534   Table *pTab = pItem->pTab;
3535   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
3536                      p->iTab, nb, p->maskSelf, nb, p->prereq);
3537   sqlite3DebugPrintf(" %12s",
3538                      pItem->zAlias ? pItem->zAlias : pTab->zName);
3539   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
3540      const char *zName;
3541      if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
3542       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3543         int i = sqlite3Strlen30(zName) - 1;
3544         while( zName[i]!='_' ) i--;
3545         zName += i;
3546       }
3547       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
3548     }else{
3549       sqlite3DebugPrintf("%20s","");
3550     }
3551   }else{
3552     char *z;
3553     if( p->u.vtab.idxStr ){
3554       z = sqlite3_mprintf("(%d,\"%s\",%x)",
3555                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
3556     }else{
3557       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
3558     }
3559     sqlite3DebugPrintf(" %-19s", z);
3560     sqlite3_free(z);
3561   }
3562   sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
3563   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
3564 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
3565   /* If the 0x100 bit of wheretracing is set, then show all of the constraint
3566   ** expressions in the WhereLoop.aLTerm[] array.
3567   */
3568   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){  /* WHERETRACE 0x100 */
3569     int i;
3570     Vdbe *v = pWInfo->pParse->pVdbe;
3571     sqlite3ExplainBegin(v);
3572     for(i=0; i<p->nLTerm; i++){
3573       WhereTerm *pTerm = p->aLTerm[i];
3574       if( pTerm==0 ) continue;
3575       sqlite3ExplainPrintf(v, "  (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
3576       sqlite3ExplainPush(v);
3577       whereExplainTerm(v, pTerm);
3578       sqlite3ExplainPop(v);
3579       sqlite3ExplainNL(v);
3580     }
3581     sqlite3ExplainFinish(v);
3582     sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
3583   }
3584 #endif
3585 }
3586 #endif
3587 
3588 /*
3589 ** Convert bulk memory into a valid WhereLoop that can be passed
3590 ** to whereLoopClear harmlessly.
3591 */
3592 static void whereLoopInit(WhereLoop *p){
3593   p->aLTerm = p->aLTermSpace;
3594   p->nLTerm = 0;
3595   p->nLSlot = ArraySize(p->aLTermSpace);
3596   p->wsFlags = 0;
3597 }
3598 
3599 /*
3600 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
3601 */
3602 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
3603   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
3604     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
3605       sqlite3_free(p->u.vtab.idxStr);
3606       p->u.vtab.needFree = 0;
3607       p->u.vtab.idxStr = 0;
3608     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
3609       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
3610       sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
3611       sqlite3DbFree(db, p->u.btree.pIndex);
3612       p->u.btree.pIndex = 0;
3613     }
3614   }
3615 }
3616 
3617 /*
3618 ** Deallocate internal memory used by a WhereLoop object
3619 */
3620 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
3621   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3622   whereLoopClearUnion(db, p);
3623   whereLoopInit(p);
3624 }
3625 
3626 /*
3627 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
3628 */
3629 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
3630   WhereTerm **paNew;
3631   if( p->nLSlot>=n ) return SQLITE_OK;
3632   n = (n+7)&~7;
3633   paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
3634   if( paNew==0 ) return SQLITE_NOMEM;
3635   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
3636   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
3637   p->aLTerm = paNew;
3638   p->nLSlot = n;
3639   return SQLITE_OK;
3640 }
3641 
3642 /*
3643 ** Transfer content from the second pLoop into the first.
3644 */
3645 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
3646   whereLoopClearUnion(db, pTo);
3647   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
3648     memset(&pTo->u, 0, sizeof(pTo->u));
3649     return SQLITE_NOMEM;
3650   }
3651   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
3652   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
3653   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
3654     pFrom->u.vtab.needFree = 0;
3655   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
3656     pFrom->u.btree.pIndex = 0;
3657   }
3658   return SQLITE_OK;
3659 }
3660 
3661 /*
3662 ** Delete a WhereLoop object
3663 */
3664 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
3665   whereLoopClear(db, p);
3666   sqlite3DbFree(db, p);
3667 }
3668 
3669 /*
3670 ** Free a WhereInfo structure
3671 */
3672 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
3673   if( ALWAYS(pWInfo) ){
3674     whereClauseClear(&pWInfo->sWC);
3675     while( pWInfo->pLoops ){
3676       WhereLoop *p = pWInfo->pLoops;
3677       pWInfo->pLoops = p->pNextLoop;
3678       whereLoopDelete(db, p);
3679     }
3680     sqlite3DbFree(db, pWInfo);
3681   }
3682 }
3683 
3684 /*
3685 ** Insert or replace a WhereLoop entry using the template supplied.
3686 **
3687 ** An existing WhereLoop entry might be overwritten if the new template
3688 ** is better and has fewer dependencies.  Or the template will be ignored
3689 ** and no insert will occur if an existing WhereLoop is faster and has
3690 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
3691 ** added based on the template.
3692 **
3693 ** If pBuilder->pOrSet is not NULL then we only care about only the
3694 ** prerequisites and rRun and nOut costs of the N best loops.  That
3695 ** information is gathered in the pBuilder->pOrSet object.  This special
3696 ** processing mode is used only for OR clause processing.
3697 **
3698 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
3699 ** still might overwrite similar loops with the new template if the
3700 ** template is better.  Loops may be overwritten if the following
3701 ** conditions are met:
3702 **
3703 **    (1)  They have the same iTab.
3704 **    (2)  They have the same iSortIdx.
3705 **    (3)  The template has same or fewer dependencies than the current loop
3706 **    (4)  The template has the same or lower cost than the current loop
3707 **    (5)  The template uses more terms of the same index but has no additional
3708 **         dependencies
3709 */
3710 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
3711   WhereLoop **ppPrev, *p, *pNext = 0;
3712   WhereInfo *pWInfo = pBuilder->pWInfo;
3713   sqlite3 *db = pWInfo->pParse->db;
3714 
3715   /* If pBuilder->pOrSet is defined, then only keep track of the costs
3716   ** and prereqs.
3717   */
3718   if( pBuilder->pOrSet!=0 ){
3719 #if WHERETRACE_ENABLED
3720     u16 n = pBuilder->pOrSet->n;
3721     int x =
3722 #endif
3723     whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
3724                                     pTemplate->nOut);
3725 #if WHERETRACE_ENABLED /* 0x8 */
3726     if( sqlite3WhereTrace & 0x8 ){
3727       sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
3728       whereLoopPrint(pTemplate, pBuilder->pWC);
3729     }
3730 #endif
3731     return SQLITE_OK;
3732   }
3733 
3734   /* Search for an existing WhereLoop to overwrite, or which takes
3735   ** priority over pTemplate.
3736   */
3737   for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
3738     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
3739       /* If either the iTab or iSortIdx values for two WhereLoop are different
3740       ** then those WhereLoops need to be considered separately.  Neither is
3741       ** a candidate to replace the other. */
3742       continue;
3743     }
3744     /* In the current implementation, the rSetup value is either zero
3745     ** or the cost of building an automatic index (NlogN) and the NlogN
3746     ** is the same for compatible WhereLoops. */
3747     assert( p->rSetup==0 || pTemplate->rSetup==0
3748                  || p->rSetup==pTemplate->rSetup );
3749 
3750     /* whereLoopAddBtree() always generates and inserts the automatic index
3751     ** case first.  Hence compatible candidate WhereLoops never have a larger
3752     ** rSetup. Call this SETUP-INVARIANT */
3753     assert( p->rSetup>=pTemplate->rSetup );
3754 
3755     if( (p->prereq & pTemplate->prereq)==p->prereq
3756      && p->rSetup<=pTemplate->rSetup
3757      && p->rRun<=pTemplate->rRun
3758      && p->nOut<=pTemplate->nOut
3759     ){
3760       /* This branch taken when p is equal or better than pTemplate in
3761       ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
3762       ** (4) number of output rows. */
3763       assert( p->rSetup==pTemplate->rSetup );
3764       if( p->prereq==pTemplate->prereq
3765        && p->nLTerm<pTemplate->nLTerm
3766        && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
3767        && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
3768           || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
3769       ){
3770         /* Overwrite an existing WhereLoop with an similar one that uses
3771         ** more terms of the index */
3772         pNext = p->pNextLoop;
3773         break;
3774       }else{
3775         /* pTemplate is not helpful.
3776         ** Return without changing or adding anything */
3777         goto whereLoopInsert_noop;
3778       }
3779     }
3780     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
3781      && p->rRun>=pTemplate->rRun
3782      && p->nOut>=pTemplate->nOut
3783     ){
3784       /* Overwrite an existing WhereLoop with a better one: one that is
3785       ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
3786       ** or (4) number of output rows, and is no worse in any of those
3787       ** categories. */
3788       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
3789       pNext = p->pNextLoop;
3790       break;
3791     }
3792   }
3793 
3794   /* If we reach this point it means that either p[] should be overwritten
3795   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
3796   ** WhereLoop and insert it.
3797   */
3798 #if WHERETRACE_ENABLED /* 0x8 */
3799   if( sqlite3WhereTrace & 0x8 ){
3800     if( p!=0 ){
3801       sqlite3DebugPrintf("ins-del:  ");
3802       whereLoopPrint(p, pBuilder->pWC);
3803     }
3804     sqlite3DebugPrintf("ins-new:  ");
3805     whereLoopPrint(pTemplate, pBuilder->pWC);
3806   }
3807 #endif
3808   if( p==0 ){
3809     p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
3810     if( p==0 ) return SQLITE_NOMEM;
3811     whereLoopInit(p);
3812   }
3813   whereLoopXfer(db, p, pTemplate);
3814   p->pNextLoop = pNext;
3815   *ppPrev = p;
3816   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
3817     Index *pIndex = p->u.btree.pIndex;
3818     if( pIndex && pIndex->tnum==0 ){
3819       p->u.btree.pIndex = 0;
3820     }
3821   }
3822   return SQLITE_OK;
3823 
3824   /* Jump here if the insert is a no-op */
3825 whereLoopInsert_noop:
3826 #if WHERETRACE_ENABLED /* 0x8 */
3827   if( sqlite3WhereTrace & 0x8 ){
3828     sqlite3DebugPrintf("ins-noop: ");
3829     whereLoopPrint(pTemplate, pBuilder->pWC);
3830   }
3831 #endif
3832   return SQLITE_OK;
3833 }
3834 
3835 /*
3836 ** Adjust the WhereLoop.nOut value downward to account for terms of the
3837 ** WHERE clause that reference the loop but which are not used by an
3838 ** index.
3839 **
3840 ** In the current implementation, the first extra WHERE clause term reduces
3841 ** the number of output rows by a factor of 10 and each additional term
3842 ** reduces the number of output rows by sqrt(2).
3843 */
3844 static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
3845   WhereTerm *pTerm, *pX;
3846   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
3847   int i, j;
3848 
3849   if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
3850     return;
3851   }
3852   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
3853     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
3854     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
3855     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
3856     for(j=pLoop->nLTerm-1; j>=0; j--){
3857       pX = pLoop->aLTerm[j];
3858       if( pX==0 ) continue;
3859       if( pX==pTerm ) break;
3860       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
3861     }
3862     if( j<0 ) pLoop->nOut += pTerm->truthProb;
3863   }
3864 }
3865 
3866 /*
3867 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
3868 ** Try to match one more.
3869 **
3870 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
3871 ** INTEGER PRIMARY KEY.
3872 */
3873 static int whereLoopAddBtreeIndex(
3874   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
3875   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
3876   Index *pProbe,                  /* An index on pSrc */
3877   LogEst nInMul                   /* log(Number of iterations due to IN) */
3878 ){
3879   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
3880   Parse *pParse = pWInfo->pParse;        /* Parsing context */
3881   sqlite3 *db = pParse->db;       /* Database connection malloc context */
3882   WhereLoop *pNew;                /* Template WhereLoop under construction */
3883   WhereTerm *pTerm;               /* A WhereTerm under consideration */
3884   int opMask;                     /* Valid operators for constraints */
3885   WhereScan scan;                 /* Iterator for WHERE terms */
3886   Bitmask saved_prereq;           /* Original value of pNew->prereq */
3887   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
3888   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
3889   u16 saved_nSkip;                /* Original value of pNew->u.btree.nSkip */
3890   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
3891   LogEst saved_nOut;              /* Original value of pNew->nOut */
3892   int iCol;                       /* Index of the column in the table */
3893   int rc = SQLITE_OK;             /* Return code */
3894   LogEst nRowEst;                 /* Estimated index selectivity */
3895   LogEst rLogSize;                /* Logarithm of table size */
3896   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
3897 
3898   pNew = pBuilder->pNew;
3899   if( db->mallocFailed ) return SQLITE_NOMEM;
3900 
3901   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
3902   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
3903   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
3904     opMask = WO_LT|WO_LE;
3905   }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
3906     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
3907   }else{
3908     opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
3909   }
3910   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
3911 
3912   assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
3913   if( pNew->u.btree.nEq < pProbe->nKeyCol ){
3914     iCol = pProbe->aiColumn[pNew->u.btree.nEq];
3915     nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
3916     if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
3917   }else{
3918     iCol = -1;
3919     nRowEst = 0;
3920   }
3921   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
3922                         opMask, pProbe);
3923   saved_nEq = pNew->u.btree.nEq;
3924   saved_nSkip = pNew->u.btree.nSkip;
3925   saved_nLTerm = pNew->nLTerm;
3926   saved_wsFlags = pNew->wsFlags;
3927   saved_prereq = pNew->prereq;
3928   saved_nOut = pNew->nOut;
3929   pNew->rSetup = 0;
3930   rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
3931 
3932   /* Consider using a skip-scan if there are no WHERE clause constraints
3933   ** available for the left-most terms of the index, and if the average
3934   ** number of repeats in the left-most terms is at least 18.  The magic
3935   ** number 18 was found by experimentation to be the payoff point where
3936   ** skip-scan become faster than a full-scan.
3937   */
3938   if( pTerm==0
3939    && saved_nEq==saved_nSkip
3940    && saved_nEq+1<pProbe->nKeyCol
3941    && pProbe->aiRowEst[saved_nEq+1]>=18  /* TUNING: Minimum for skip-scan */
3942    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
3943   ){
3944     LogEst nIter;
3945     pNew->u.btree.nEq++;
3946     pNew->u.btree.nSkip++;
3947     pNew->aLTerm[pNew->nLTerm++] = 0;
3948     pNew->wsFlags |= WHERE_SKIPSCAN;
3949     nIter = sqlite3LogEst(pProbe->aiRowEst[0]/pProbe->aiRowEst[saved_nEq+1]);
3950     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter);
3951   }
3952   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
3953     int nIn = 0;
3954 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
3955     int nRecValid = pBuilder->nRecValid;
3956 #endif
3957     if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
3958      && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
3959     ){
3960       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
3961     }
3962     if( pTerm->prereqRight & pNew->maskSelf ) continue;
3963 
3964     assert( pNew->nOut==saved_nOut );
3965 
3966     pNew->wsFlags = saved_wsFlags;
3967     pNew->u.btree.nEq = saved_nEq;
3968     pNew->nLTerm = saved_nLTerm;
3969     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3970     pNew->aLTerm[pNew->nLTerm++] = pTerm;
3971     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
3972     pNew->rRun = rLogSize; /* Baseline cost is log2(N).  Adjustments below */
3973     if( pTerm->eOperator & WO_IN ){
3974       Expr *pExpr = pTerm->pExpr;
3975       pNew->wsFlags |= WHERE_COLUMN_IN;
3976       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3977         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
3978         nIn = 46;  assert( 46==sqlite3LogEst(25) );
3979       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3980         /* "x IN (value, value, ...)" */
3981         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
3982       }
3983       pNew->rRun += nIn;
3984       pNew->u.btree.nEq++;
3985       pNew->nOut = nRowEst + nInMul + nIn;
3986     }else if( pTerm->eOperator & (WO_EQ) ){
3987       assert(
3988         (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN|WHERE_SKIPSCAN))!=0
3989         || nInMul==0
3990       );
3991       pNew->wsFlags |= WHERE_COLUMN_EQ;
3992       if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1)){
3993         assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
3994         if( iCol>=0 && pProbe->onError==OE_None ){
3995           pNew->wsFlags |= WHERE_UNQ_WANTED;
3996         }else{
3997           pNew->wsFlags |= WHERE_ONEROW;
3998         }
3999       }
4000       pNew->u.btree.nEq++;
4001       pNew->nOut = nRowEst + nInMul;
4002     }else if( pTerm->eOperator & (WO_ISNULL) ){
4003       pNew->wsFlags |= WHERE_COLUMN_NULL;
4004       pNew->u.btree.nEq++;
4005       /* TUNING: IS NULL selects 2 rows */
4006       nIn = 10;  assert( 10==sqlite3LogEst(2) );
4007       pNew->nOut = nRowEst + nInMul + nIn;
4008     }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
4009       testcase( pTerm->eOperator & WO_GT );
4010       testcase( pTerm->eOperator & WO_GE );
4011       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
4012       pBtm = pTerm;
4013       pTop = 0;
4014     }else{
4015       assert( pTerm->eOperator & (WO_LT|WO_LE) );
4016       testcase( pTerm->eOperator & WO_LT );
4017       testcase( pTerm->eOperator & WO_LE );
4018       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
4019       pTop = pTerm;
4020       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
4021                      pNew->aLTerm[pNew->nLTerm-2] : 0;
4022     }
4023     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4024       /* Adjust nOut and rRun for STAT3 range values */
4025       assert( pNew->nOut==saved_nOut );
4026       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
4027     }
4028 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
4029     if( nInMul==0
4030      && pProbe->nSample
4031      && pNew->u.btree.nEq<=pProbe->nSampleCol
4032      && OptimizationEnabled(db, SQLITE_Stat3)
4033     ){
4034       Expr *pExpr = pTerm->pExpr;
4035       tRowcnt nOut = 0;
4036       if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
4037         testcase( pTerm->eOperator & WO_EQ );
4038         testcase( pTerm->eOperator & WO_ISNULL );
4039         rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
4040       }else if( (pTerm->eOperator & WO_IN)
4041              &&  !ExprHasProperty(pExpr, EP_xIsSelect)  ){
4042         rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
4043       }
4044       assert( nOut==0 || rc==SQLITE_OK );
4045       if( nOut ){
4046         pNew->nOut = sqlite3LogEst(nOut);
4047         if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
4048       }
4049     }
4050 #endif
4051     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
4052       /* Each row involves a step of the index, then a binary search of
4053       ** the main table */
4054       pNew->rRun =  sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
4055     }
4056     /* Step cost for each output row */
4057     pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
4058     whereLoopOutputAdjust(pBuilder->pWC, pNew);
4059     rc = whereLoopInsert(pBuilder, pNew);
4060     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
4061      && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
4062     ){
4063       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
4064     }
4065     pNew->nOut = saved_nOut;
4066 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
4067     pBuilder->nRecValid = nRecValid;
4068 #endif
4069   }
4070   pNew->prereq = saved_prereq;
4071   pNew->u.btree.nEq = saved_nEq;
4072   pNew->u.btree.nSkip = saved_nSkip;
4073   pNew->wsFlags = saved_wsFlags;
4074   pNew->nOut = saved_nOut;
4075   pNew->nLTerm = saved_nLTerm;
4076   return rc;
4077 }
4078 
4079 /*
4080 ** Return True if it is possible that pIndex might be useful in
4081 ** implementing the ORDER BY clause in pBuilder.
4082 **
4083 ** Return False if pBuilder does not contain an ORDER BY clause or
4084 ** if there is no way for pIndex to be useful in implementing that
4085 ** ORDER BY clause.
4086 */
4087 static int indexMightHelpWithOrderBy(
4088   WhereLoopBuilder *pBuilder,
4089   Index *pIndex,
4090   int iCursor
4091 ){
4092   ExprList *pOB;
4093   int ii, jj;
4094 
4095   if( pIndex->bUnordered ) return 0;
4096   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
4097   for(ii=0; ii<pOB->nExpr; ii++){
4098     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
4099     if( pExpr->op!=TK_COLUMN ) return 0;
4100     if( pExpr->iTable==iCursor ){
4101       for(jj=0; jj<pIndex->nKeyCol; jj++){
4102         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4103       }
4104     }
4105   }
4106   return 0;
4107 }
4108 
4109 /*
4110 ** Return a bitmask where 1s indicate that the corresponding column of
4111 ** the table is used by an index.  Only the first 63 columns are considered.
4112 */
4113 static Bitmask columnsInIndex(Index *pIdx){
4114   Bitmask m = 0;
4115   int j;
4116   for(j=pIdx->nColumn-1; j>=0; j--){
4117     int x = pIdx->aiColumn[j];
4118     if( x>=0 ){
4119       testcase( x==BMS-1 );
4120       testcase( x==BMS-2 );
4121       if( x<BMS-1 ) m |= MASKBIT(x);
4122     }
4123   }
4124   return m;
4125 }
4126 
4127 /* Check to see if a partial index with pPartIndexWhere can be used
4128 ** in the current query.  Return true if it can be and false if not.
4129 */
4130 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4131   int i;
4132   WhereTerm *pTerm;
4133   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
4134     if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
4135   }
4136   return 0;
4137 }
4138 
4139 /*
4140 ** Add all WhereLoop objects for a single table of the join where the table
4141 ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
4142 ** a b-tree table, not a virtual table.
4143 */
4144 static int whereLoopAddBtree(
4145   WhereLoopBuilder *pBuilder, /* WHERE clause information */
4146   Bitmask mExtra              /* Extra prerequesites for using this table */
4147 ){
4148   WhereInfo *pWInfo;          /* WHERE analysis context */
4149   Index *pProbe;              /* An index we are evaluating */
4150   Index sPk;                  /* A fake index object for the primary key */
4151   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
4152   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
4153   SrcList *pTabList;          /* The FROM clause */
4154   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
4155   WhereLoop *pNew;            /* Template WhereLoop object */
4156   int rc = SQLITE_OK;         /* Return code */
4157   int iSortIdx = 1;           /* Index number */
4158   int b;                      /* A boolean value */
4159   LogEst rSize;               /* number of rows in the table */
4160   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
4161   WhereClause *pWC;           /* The parsed WHERE clause */
4162   Table *pTab;                /* Table being queried */
4163 
4164   pNew = pBuilder->pNew;
4165   pWInfo = pBuilder->pWInfo;
4166   pTabList = pWInfo->pTabList;
4167   pSrc = pTabList->a + pNew->iTab;
4168   pTab = pSrc->pTab;
4169   pWC = pBuilder->pWC;
4170   assert( !IsVirtual(pSrc->pTab) );
4171 
4172   if( pSrc->pIndex ){
4173     /* An INDEXED BY clause specifies a particular index to use */
4174     pProbe = pSrc->pIndex;
4175   }else if( !HasRowid(pTab) ){
4176     pProbe = pTab->pIndex;
4177   }else{
4178     /* There is no INDEXED BY clause.  Create a fake Index object in local
4179     ** variable sPk to represent the rowid primary key index.  Make this
4180     ** fake index the first in a chain of Index objects with all of the real
4181     ** indices to follow */
4182     Index *pFirst;                  /* First of real indices on the table */
4183     memset(&sPk, 0, sizeof(Index));
4184     sPk.nKeyCol = 1;
4185     sPk.aiColumn = &aiColumnPk;
4186     sPk.aiRowEst = aiRowEstPk;
4187     sPk.onError = OE_Replace;
4188     sPk.pTable = pTab;
4189     aiRowEstPk[0] = pTab->nRowEst;
4190     aiRowEstPk[1] = 1;
4191     pFirst = pSrc->pTab->pIndex;
4192     if( pSrc->notIndexed==0 ){
4193       /* The real indices of the table are only considered if the
4194       ** NOT INDEXED qualifier is omitted from the FROM clause */
4195       sPk.pNext = pFirst;
4196     }
4197     pProbe = &sPk;
4198   }
4199   rSize = sqlite3LogEst(pTab->nRowEst);
4200   rLogSize = estLog(rSize);
4201 
4202 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
4203   /* Automatic indexes */
4204   if( !pBuilder->pOrSet
4205    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4206    && pSrc->pIndex==0
4207    && !pSrc->viaCoroutine
4208    && !pSrc->notIndexed
4209    && HasRowid(pTab)
4210    && !pSrc->isCorrelated
4211    && !pSrc->isRecursive
4212   ){
4213     /* Generate auto-index WhereLoops */
4214     WhereTerm *pTerm;
4215     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4216     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
4217       if( pTerm->prereqRight & pNew->maskSelf ) continue;
4218       if( termCanDriveIndex(pTerm, pSrc, 0) ){
4219         pNew->u.btree.nEq = 1;
4220         pNew->u.btree.nSkip = 0;
4221         pNew->u.btree.pIndex = 0;
4222         pNew->nLTerm = 1;
4223         pNew->aLTerm[0] = pTerm;
4224         /* TUNING: One-time cost for computing the automatic index is
4225         ** approximately 7*N*log2(N) where N is the number of rows in
4226         ** the table being indexed. */
4227         pNew->rSetup = rLogSize + rSize + 28;  assert( 28==sqlite3LogEst(7) );
4228         /* TUNING: Each index lookup yields 20 rows in the table.  This
4229         ** is more than the usual guess of 10 rows, since we have no way
4230         ** of knowning how selective the index will ultimately be.  It would
4231         ** not be unreasonable to make this value much larger. */
4232         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
4233         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
4234         pNew->wsFlags = WHERE_AUTO_INDEX;
4235         pNew->prereq = mExtra | pTerm->prereqRight;
4236         rc = whereLoopInsert(pBuilder, pNew);
4237       }
4238     }
4239   }
4240 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
4241 
4242   /* Loop over all indices
4243   */
4244   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
4245     if( pProbe->pPartIdxWhere!=0
4246      && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
4247       continue;  /* Partial index inappropriate for this query */
4248     }
4249     pNew->u.btree.nEq = 0;
4250     pNew->u.btree.nSkip = 0;
4251     pNew->nLTerm = 0;
4252     pNew->iSortIdx = 0;
4253     pNew->rSetup = 0;
4254     pNew->prereq = mExtra;
4255     pNew->nOut = rSize;
4256     pNew->u.btree.pIndex = pProbe;
4257     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
4258     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4259     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
4260     if( pProbe->tnum<=0 ){
4261       /* Integer primary key index */
4262       pNew->wsFlags = WHERE_IPK;
4263 
4264       /* Full table scan */
4265       pNew->iSortIdx = b ? iSortIdx : 0;
4266       /* TUNING: Cost of full table scan is 3*(N + log2(N)).
4267       **  +  The extra 3 factor is to encourage the use of indexed lookups
4268       **     over full scans.  FIXME */
4269       pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
4270       whereLoopOutputAdjust(pWC, pNew);
4271       rc = whereLoopInsert(pBuilder, pNew);
4272       pNew->nOut = rSize;
4273       if( rc ) break;
4274     }else{
4275       Bitmask m;
4276       if( pProbe->isCovering ){
4277         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
4278         m = 0;
4279       }else{
4280         m = pSrc->colUsed & ~columnsInIndex(pProbe);
4281         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
4282       }
4283 
4284       /* Full scan via index */
4285       if( b
4286        || !HasRowid(pTab)
4287        || ( m==0
4288          && pProbe->bUnordered==0
4289          && (pProbe->szIdxRow<pTab->szTabRow)
4290          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4291          && sqlite3GlobalConfig.bUseCis
4292          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4293           )
4294       ){
4295         pNew->iSortIdx = b ? iSortIdx : 0;
4296         if( m==0 ){
4297           /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
4298           **  +  The extra factor K of between 1.1 and 3.0 that depends
4299           **     on the relative sizes of the table and the index.  K
4300           **     is smaller for smaller indices, thus favoring them.
4301           */
4302           pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
4303                         (15*pProbe->szIdxRow)/pTab->szTabRow;
4304         }else{
4305           /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
4306           ** which we will simplify to just N*log2(N) */
4307           pNew->rRun = rSize + rLogSize;
4308         }
4309         whereLoopOutputAdjust(pWC, pNew);
4310         rc = whereLoopInsert(pBuilder, pNew);
4311         pNew->nOut = rSize;
4312         if( rc ) break;
4313       }
4314     }
4315 
4316     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
4317 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
4318     sqlite3Stat4ProbeFree(pBuilder->pRec);
4319     pBuilder->nRecValid = 0;
4320     pBuilder->pRec = 0;
4321 #endif
4322 
4323     /* If there was an INDEXED BY clause, then only that one index is
4324     ** considered. */
4325     if( pSrc->pIndex ) break;
4326   }
4327   return rc;
4328 }
4329 
4330 #ifndef SQLITE_OMIT_VIRTUALTABLE
4331 /*
4332 ** Add all WhereLoop objects for a table of the join identified by
4333 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
4334 */
4335 static int whereLoopAddVirtual(
4336   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
4337   Bitmask mExtra
4338 ){
4339   WhereInfo *pWInfo;           /* WHERE analysis context */
4340   Parse *pParse;               /* The parsing context */
4341   WhereClause *pWC;            /* The WHERE clause */
4342   struct SrcList_item *pSrc;   /* The FROM clause term to search */
4343   Table *pTab;
4344   sqlite3 *db;
4345   sqlite3_index_info *pIdxInfo;
4346   struct sqlite3_index_constraint *pIdxCons;
4347   struct sqlite3_index_constraint_usage *pUsage;
4348   WhereTerm *pTerm;
4349   int i, j;
4350   int iTerm, mxTerm;
4351   int nConstraint;
4352   int seenIn = 0;              /* True if an IN operator is seen */
4353   int seenVar = 0;             /* True if a non-constant constraint is seen */
4354   int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
4355   WhereLoop *pNew;
4356   int rc = SQLITE_OK;
4357 
4358   pWInfo = pBuilder->pWInfo;
4359   pParse = pWInfo->pParse;
4360   db = pParse->db;
4361   pWC = pBuilder->pWC;
4362   pNew = pBuilder->pNew;
4363   pSrc = &pWInfo->pTabList->a[pNew->iTab];
4364   pTab = pSrc->pTab;
4365   assert( IsVirtual(pTab) );
4366   pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
4367   if( pIdxInfo==0 ) return SQLITE_NOMEM;
4368   pNew->prereq = 0;
4369   pNew->rSetup = 0;
4370   pNew->wsFlags = WHERE_VIRTUALTABLE;
4371   pNew->nLTerm = 0;
4372   pNew->u.vtab.needFree = 0;
4373   pUsage = pIdxInfo->aConstraintUsage;
4374   nConstraint = pIdxInfo->nConstraint;
4375   if( whereLoopResize(db, pNew, nConstraint) ){
4376     sqlite3DbFree(db, pIdxInfo);
4377     return SQLITE_NOMEM;
4378   }
4379 
4380   for(iPhase=0; iPhase<=3; iPhase++){
4381     if( !seenIn && (iPhase&1)!=0 ){
4382       iPhase++;
4383       if( iPhase>3 ) break;
4384     }
4385     if( !seenVar && iPhase>1 ) break;
4386     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4387     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4388       j = pIdxCons->iTermOffset;
4389       pTerm = &pWC->a[j];
4390       switch( iPhase ){
4391         case 0:    /* Constants without IN operator */
4392           pIdxCons->usable = 0;
4393           if( (pTerm->eOperator & WO_IN)!=0 ){
4394             seenIn = 1;
4395           }
4396           if( pTerm->prereqRight!=0 ){
4397             seenVar = 1;
4398           }else if( (pTerm->eOperator & WO_IN)==0 ){
4399             pIdxCons->usable = 1;
4400           }
4401           break;
4402         case 1:    /* Constants with IN operators */
4403           assert( seenIn );
4404           pIdxCons->usable = (pTerm->prereqRight==0);
4405           break;
4406         case 2:    /* Variables without IN */
4407           assert( seenVar );
4408           pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4409           break;
4410         default:   /* Variables with IN */
4411           assert( seenVar && seenIn );
4412           pIdxCons->usable = 1;
4413           break;
4414       }
4415     }
4416     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4417     if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4418     pIdxInfo->idxStr = 0;
4419     pIdxInfo->idxNum = 0;
4420     pIdxInfo->needToFreeIdxStr = 0;
4421     pIdxInfo->orderByConsumed = 0;
4422     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
4423     pIdxInfo->estimatedRows = 25;
4424     rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4425     if( rc ) goto whereLoopAddVtab_exit;
4426     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4427     pNew->prereq = mExtra;
4428     mxTerm = -1;
4429     assert( pNew->nLSlot>=nConstraint );
4430     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
4431     pNew->u.vtab.omitMask = 0;
4432     for(i=0; i<nConstraint; i++, pIdxCons++){
4433       if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4434         j = pIdxCons->iTermOffset;
4435         if( iTerm>=nConstraint
4436          || j<0
4437          || j>=pWC->nTerm
4438          || pNew->aLTerm[iTerm]!=0
4439         ){
4440           rc = SQLITE_ERROR;
4441           sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4442           goto whereLoopAddVtab_exit;
4443         }
4444         testcase( iTerm==nConstraint-1 );
4445         testcase( j==0 );
4446         testcase( j==pWC->nTerm-1 );
4447         pTerm = &pWC->a[j];
4448         pNew->prereq |= pTerm->prereqRight;
4449         assert( iTerm<pNew->nLSlot );
4450         pNew->aLTerm[iTerm] = pTerm;
4451         if( iTerm>mxTerm ) mxTerm = iTerm;
4452         testcase( iTerm==15 );
4453         testcase( iTerm==16 );
4454         if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
4455         if( (pTerm->eOperator & WO_IN)!=0 ){
4456           if( pUsage[i].omit==0 ){
4457             /* Do not attempt to use an IN constraint if the virtual table
4458             ** says that the equivalent EQ constraint cannot be safely omitted.
4459             ** If we do attempt to use such a constraint, some rows might be
4460             ** repeated in the output. */
4461             break;
4462           }
4463           /* A virtual table that is constrained by an IN clause may not
4464           ** consume the ORDER BY clause because (1) the order of IN terms
4465           ** is not necessarily related to the order of output terms and
4466           ** (2) Multiple outputs from a single IN value will not merge
4467           ** together.  */
4468           pIdxInfo->orderByConsumed = 0;
4469         }
4470       }
4471     }
4472     if( i>=nConstraint ){
4473       pNew->nLTerm = mxTerm+1;
4474       assert( pNew->nLTerm<=pNew->nLSlot );
4475       pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4476       pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4477       pIdxInfo->needToFreeIdxStr = 0;
4478       pNew->u.vtab.idxStr = pIdxInfo->idxStr;
4479       pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4480                                      && pIdxInfo->orderByConsumed);
4481       pNew->rSetup = 0;
4482       pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
4483       pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
4484       whereLoopInsert(pBuilder, pNew);
4485       if( pNew->u.vtab.needFree ){
4486         sqlite3_free(pNew->u.vtab.idxStr);
4487         pNew->u.vtab.needFree = 0;
4488       }
4489     }
4490   }
4491 
4492 whereLoopAddVtab_exit:
4493   if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4494   sqlite3DbFree(db, pIdxInfo);
4495   return rc;
4496 }
4497 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4498 
4499 /*
4500 ** Add WhereLoop entries to handle OR terms.  This works for either
4501 ** btrees or virtual tables.
4502 */
4503 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
4504   WhereInfo *pWInfo = pBuilder->pWInfo;
4505   WhereClause *pWC;
4506   WhereLoop *pNew;
4507   WhereTerm *pTerm, *pWCEnd;
4508   int rc = SQLITE_OK;
4509   int iCur;
4510   WhereClause tempWC;
4511   WhereLoopBuilder sSubBuild;
4512   WhereOrSet sSum, sCur, sPrev;
4513   struct SrcList_item *pItem;
4514 
4515   pWC = pBuilder->pWC;
4516   if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
4517   pWCEnd = pWC->a + pWC->nTerm;
4518   pNew = pBuilder->pNew;
4519   memset(&sSum, 0, sizeof(sSum));
4520   pItem = pWInfo->pTabList->a + pNew->iTab;
4521   if( !HasRowid(pItem->pTab) ) return SQLITE_OK;
4522   iCur = pItem->iCursor;
4523 
4524   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4525     if( (pTerm->eOperator & WO_OR)!=0
4526      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4527     ){
4528       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4529       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4530       WhereTerm *pOrTerm;
4531       int once = 1;
4532       int i, j;
4533 
4534       sSubBuild = *pBuilder;
4535       sSubBuild.pOrderBy = 0;
4536       sSubBuild.pOrSet = &sCur;
4537 
4538       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
4539         if( (pOrTerm->eOperator & WO_AND)!=0 ){
4540           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4541         }else if( pOrTerm->leftCursor==iCur ){
4542           tempWC.pWInfo = pWC->pWInfo;
4543           tempWC.pOuter = pWC;
4544           tempWC.op = TK_AND;
4545           tempWC.nTerm = 1;
4546           tempWC.a = pOrTerm;
4547           sSubBuild.pWC = &tempWC;
4548         }else{
4549           continue;
4550         }
4551         sCur.n = 0;
4552 #ifndef SQLITE_OMIT_VIRTUALTABLE
4553         if( IsVirtual(pItem->pTab) ){
4554           rc = whereLoopAddVirtual(&sSubBuild, mExtra);
4555         }else
4556 #endif
4557         {
4558           rc = whereLoopAddBtree(&sSubBuild, mExtra);
4559         }
4560         assert( rc==SQLITE_OK || sCur.n==0 );
4561         if( sCur.n==0 ){
4562           sSum.n = 0;
4563           break;
4564         }else if( once ){
4565           whereOrMove(&sSum, &sCur);
4566           once = 0;
4567         }else{
4568           whereOrMove(&sPrev, &sSum);
4569           sSum.n = 0;
4570           for(i=0; i<sPrev.n; i++){
4571             for(j=0; j<sCur.n; j++){
4572               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4573                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4574                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4575             }
4576           }
4577         }
4578       }
4579       pNew->nLTerm = 1;
4580       pNew->aLTerm[0] = pTerm;
4581       pNew->wsFlags = WHERE_MULTI_OR;
4582       pNew->rSetup = 0;
4583       pNew->iSortIdx = 0;
4584       memset(&pNew->u, 0, sizeof(pNew->u));
4585       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
4586         /* TUNING: Multiple by 3.5 for the secondary table lookup */
4587         pNew->rRun = sSum.a[i].rRun + 18;
4588         pNew->nOut = sSum.a[i].nOut;
4589         pNew->prereq = sSum.a[i].prereq;
4590         rc = whereLoopInsert(pBuilder, pNew);
4591       }
4592     }
4593   }
4594   return rc;
4595 }
4596 
4597 /*
4598 ** Add all WhereLoop objects for all tables
4599 */
4600 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
4601   WhereInfo *pWInfo = pBuilder->pWInfo;
4602   Bitmask mExtra = 0;
4603   Bitmask mPrior = 0;
4604   int iTab;
4605   SrcList *pTabList = pWInfo->pTabList;
4606   struct SrcList_item *pItem;
4607   sqlite3 *db = pWInfo->pParse->db;
4608   int nTabList = pWInfo->nLevel;
4609   int rc = SQLITE_OK;
4610   u8 priorJoinType = 0;
4611   WhereLoop *pNew;
4612 
4613   /* Loop over the tables in the join, from left to right */
4614   pNew = pBuilder->pNew;
4615   whereLoopInit(pNew);
4616   for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
4617     pNew->iTab = iTab;
4618     pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
4619     if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
4620       mExtra = mPrior;
4621     }
4622     priorJoinType = pItem->jointype;
4623     if( IsVirtual(pItem->pTab) ){
4624       rc = whereLoopAddVirtual(pBuilder, mExtra);
4625     }else{
4626       rc = whereLoopAddBtree(pBuilder, mExtra);
4627     }
4628     if( rc==SQLITE_OK ){
4629       rc = whereLoopAddOr(pBuilder, mExtra);
4630     }
4631     mPrior |= pNew->maskSelf;
4632     if( rc || db->mallocFailed ) break;
4633   }
4634   whereLoopClear(db, pNew);
4635   return rc;
4636 }
4637 
4638 /*
4639 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
4640 ** parameters) to see if it outputs rows in the requested ORDER BY
4641 ** (or GROUP BY) without requiring a separate sort operation.  Return:
4642 **
4643 **    0:  ORDER BY is not satisfied.  Sorting required
4644 **    1:  ORDER BY is satisfied.      Omit sorting
4645 **   -1:  Unknown at this time
4646 **
4647 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4648 ** strict.  With GROUP BY and DISTINCT the only requirement is that
4649 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
4650 ** and DISTINT do not require rows to appear in any particular order as long
4651 ** as equivelent rows are grouped together.  Thus for GROUP BY and DISTINCT
4652 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
4653 ** pOrderBy terms must be matched in strict left-to-right order.
4654 */
4655 static int wherePathSatisfiesOrderBy(
4656   WhereInfo *pWInfo,    /* The WHERE clause */
4657   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
4658   WherePath *pPath,     /* The WherePath to check */
4659   u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
4660   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
4661   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
4662   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
4663 ){
4664   u8 revSet;            /* True if rev is known */
4665   u8 rev;               /* Composite sort order */
4666   u8 revIdx;            /* Index sort order */
4667   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
4668   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
4669   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
4670   u16 nKeyCol;          /* Number of key columns in pIndex */
4671   u16 nColumn;          /* Total number of ordered columns in the index */
4672   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
4673   int iLoop;            /* Index of WhereLoop in pPath being processed */
4674   int i, j;             /* Loop counters */
4675   int iCur;             /* Cursor number for current WhereLoop */
4676   int iColumn;          /* A column number within table iCur */
4677   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
4678   WhereTerm *pTerm;     /* A single term of the WHERE clause */
4679   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
4680   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
4681   Index *pIndex;        /* The index associated with pLoop */
4682   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
4683   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
4684   Bitmask obDone;       /* Mask of all ORDER BY terms */
4685   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
4686   Bitmask ready;              /* Mask of inner loops */
4687 
4688   /*
4689   ** We say the WhereLoop is "one-row" if it generates no more than one
4690   ** row of output.  A WhereLoop is one-row if all of the following are true:
4691   **  (a) All index columns match with WHERE_COLUMN_EQ.
4692   **  (b) The index is unique
4693   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4694   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
4695   **
4696   ** We say the WhereLoop is "order-distinct" if the set of columns from
4697   ** that WhereLoop that are in the ORDER BY clause are different for every
4698   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
4699   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
4700   ** is not order-distinct. To be order-distinct is not quite the same as being
4701   ** UNIQUE since a UNIQUE column or index can have multiple rows that
4702   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4703   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4704   **
4705   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4706   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4707   ** automatically order-distinct.
4708   */
4709 
4710   assert( pOrderBy!=0 );
4711 
4712   /* Sortability of virtual tables is determined by the xBestIndex method
4713   ** of the virtual table itself */
4714   if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
4715     testcase( nLoop>0 );  /* True when outer loops are one-row and match
4716                           ** no ORDER BY terms */
4717     return pLast->u.vtab.isOrdered;
4718   }
4719   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
4720 
4721   nOrderBy = pOrderBy->nExpr;
4722   testcase( nOrderBy==BMS-1 );
4723   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
4724   isOrderDistinct = 1;
4725   obDone = MASKBIT(nOrderBy)-1;
4726   orderDistinctMask = 0;
4727   ready = 0;
4728   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
4729     if( iLoop>0 ) ready |= pLoop->maskSelf;
4730     pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
4731     assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
4732     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
4733 
4734     /* Mark off any ORDER BY term X that is a column in the table of
4735     ** the current loop for which there is term in the WHERE
4736     ** clause of the form X IS NULL or X=? that reference only outer
4737     ** loops.
4738     */
4739     for(i=0; i<nOrderBy; i++){
4740       if( MASKBIT(i) & obSat ) continue;
4741       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
4742       if( pOBExpr->op!=TK_COLUMN ) continue;
4743       if( pOBExpr->iTable!=iCur ) continue;
4744       pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4745                        ~ready, WO_EQ|WO_ISNULL, 0);
4746       if( pTerm==0 ) continue;
4747       if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
4748         const char *z1, *z2;
4749         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4750         if( !pColl ) pColl = db->pDfltColl;
4751         z1 = pColl->zName;
4752         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
4753         if( !pColl ) pColl = db->pDfltColl;
4754         z2 = pColl->zName;
4755         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
4756       }
4757       obSat |= MASKBIT(i);
4758     }
4759 
4760     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4761       if( pLoop->wsFlags & WHERE_IPK ){
4762         pIndex = 0;
4763         nKeyCol = 0;
4764         nColumn = 1;
4765       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
4766         return 0;
4767       }else{
4768         nKeyCol = pIndex->nKeyCol;
4769         nColumn = pIndex->nColumn;
4770         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4771         assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
4772         isOrderDistinct = pIndex->onError!=OE_None;
4773       }
4774 
4775       /* Loop through all columns of the index and deal with the ones
4776       ** that are not constrained by == or IN.
4777       */
4778       rev = revSet = 0;
4779       distinctColumns = 0;
4780       for(j=0; j<nColumn; j++){
4781         u8 bOnce;   /* True to run the ORDER BY search loop */
4782 
4783         /* Skip over == and IS NULL terms */
4784         if( j<pLoop->u.btree.nEq
4785          && pLoop->u.btree.nSkip==0
4786          && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
4787         ){
4788           if( i & WO_ISNULL ){
4789             testcase( isOrderDistinct );
4790             isOrderDistinct = 0;
4791           }
4792           continue;
4793         }
4794 
4795         /* Get the column number in the table (iColumn) and sort order
4796         ** (revIdx) for the j-th column of the index.
4797         */
4798         if( pIndex ){
4799           iColumn = pIndex->aiColumn[j];
4800           revIdx = pIndex->aSortOrder[j];
4801           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
4802         }else{
4803           iColumn = -1;
4804           revIdx = 0;
4805         }
4806 
4807         /* An unconstrained column that might be NULL means that this
4808         ** WhereLoop is not well-ordered
4809         */
4810         if( isOrderDistinct
4811          && iColumn>=0
4812          && j>=pLoop->u.btree.nEq
4813          && pIndex->pTable->aCol[iColumn].notNull==0
4814         ){
4815           isOrderDistinct = 0;
4816         }
4817 
4818         /* Find the ORDER BY term that corresponds to the j-th column
4819         ** of the index and and mark that ORDER BY term off
4820         */
4821         bOnce = 1;
4822         isMatch = 0;
4823         for(i=0; bOnce && i<nOrderBy; i++){
4824           if( MASKBIT(i) & obSat ) continue;
4825           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
4826           testcase( wctrlFlags & WHERE_GROUPBY );
4827           testcase( wctrlFlags & WHERE_DISTINCTBY );
4828           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
4829           if( pOBExpr->op!=TK_COLUMN ) continue;
4830           if( pOBExpr->iTable!=iCur ) continue;
4831           if( pOBExpr->iColumn!=iColumn ) continue;
4832           if( iColumn>=0 ){
4833             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4834             if( !pColl ) pColl = db->pDfltColl;
4835             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4836           }
4837           isMatch = 1;
4838           break;
4839         }
4840         if( isMatch ){
4841           if( iColumn<0 ){
4842             testcase( distinctColumns==0 );
4843             distinctColumns = 1;
4844           }
4845           obSat |= MASKBIT(i);
4846           if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
4847             /* Make sure the sort order is compatible in an ORDER BY clause.
4848             ** Sort order is irrelevant for a GROUP BY clause. */
4849             if( revSet ){
4850               if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
4851             }else{
4852               rev = revIdx ^ pOrderBy->a[i].sortOrder;
4853               if( rev ) *pRevMask |= MASKBIT(iLoop);
4854               revSet = 1;
4855             }
4856           }
4857         }else{
4858           /* No match found */
4859           if( j==0 || j<nKeyCol ){
4860             testcase( isOrderDistinct!=0 );
4861             isOrderDistinct = 0;
4862           }
4863           break;
4864         }
4865       } /* end Loop over all index columns */
4866       if( distinctColumns ){
4867         testcase( isOrderDistinct==0 );
4868         isOrderDistinct = 1;
4869       }
4870     } /* end-if not one-row */
4871 
4872     /* Mark off any other ORDER BY terms that reference pLoop */
4873     if( isOrderDistinct ){
4874       orderDistinctMask |= pLoop->maskSelf;
4875       for(i=0; i<nOrderBy; i++){
4876         Expr *p;
4877         if( MASKBIT(i) & obSat ) continue;
4878         p = pOrderBy->a[i].pExpr;
4879         if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
4880           obSat |= MASKBIT(i);
4881         }
4882       }
4883     }
4884   } /* End the loop over all WhereLoops from outer-most down to inner-most */
4885   if( obSat==obDone ) return 1;
4886   if( !isOrderDistinct ) return 0;
4887   return -1;
4888 }
4889 
4890 #ifdef WHERETRACE_ENABLED
4891 /* For debugging use only: */
4892 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4893   static char zName[65];
4894   int i;
4895   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
4896   if( pLast ) zName[i++] = pLast->cId;
4897   zName[i] = 0;
4898   return zName;
4899 }
4900 #endif
4901 
4902 
4903 /*
4904 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
4905 ** attempts to find the lowest cost path that visits each WhereLoop
4906 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
4907 **
4908 ** Assume that the total number of output rows that will need to be sorted
4909 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
4910 ** costs if nRowEst==0.
4911 **
4912 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
4913 ** error occurs.
4914 */
4915 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
4916   int mxChoice;             /* Maximum number of simultaneous paths tracked */
4917   int nLoop;                /* Number of terms in the join */
4918   Parse *pParse;            /* Parsing context */
4919   sqlite3 *db;              /* The database connection */
4920   int iLoop;                /* Loop counter over the terms of the join */
4921   int ii, jj;               /* Loop counters */
4922   int mxI = 0;              /* Index of next entry to replace */
4923   LogEst rCost;             /* Cost of a path */
4924   LogEst nOut;              /* Number of outputs */
4925   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
4926   LogEst mxOut = 0;         /* Maximum nOut value on the set of paths */
4927   LogEst rSortCost;         /* Cost to do a sort */
4928   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
4929   WherePath *aFrom;         /* All nFrom paths at the previous level */
4930   WherePath *aTo;           /* The nTo best paths at the current level */
4931   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
4932   WherePath *pTo;           /* An element of aTo[] that we are working on */
4933   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
4934   WhereLoop **pX;           /* Used to divy up the pSpace memory */
4935   char *pSpace;             /* Temporary memory used by this routine */
4936 
4937   pParse = pWInfo->pParse;
4938   db = pParse->db;
4939   nLoop = pWInfo->nLevel;
4940   /* TUNING: For simple queries, only the best path is tracked.
4941   ** For 2-way joins, the 5 best paths are followed.
4942   ** For joins of 3 or more tables, track the 10 best paths */
4943   mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
4944   assert( nLoop<=pWInfo->pTabList->nSrc );
4945   WHERETRACE(0x002, ("---- begin solver\n"));
4946 
4947   /* Allocate and initialize space for aTo and aFrom */
4948   ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
4949   pSpace = sqlite3DbMallocRaw(db, ii);
4950   if( pSpace==0 ) return SQLITE_NOMEM;
4951   aTo = (WherePath*)pSpace;
4952   aFrom = aTo+mxChoice;
4953   memset(aFrom, 0, sizeof(aFrom[0]));
4954   pX = (WhereLoop**)(aFrom+mxChoice);
4955   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
4956     pFrom->aLoop = pX;
4957   }
4958 
4959   /* Seed the search with a single WherePath containing zero WhereLoops.
4960   **
4961   ** TUNING: Do not let the number of iterations go above 25.  If the cost
4962   ** of computing an automatic index is not paid back within the first 25
4963   ** rows, then do not use the automatic index. */
4964   aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
4965   nFrom = 1;
4966 
4967   /* Precompute the cost of sorting the final result set, if the caller
4968   ** to sqlite3WhereBegin() was concerned about sorting */
4969   rSortCost = 0;
4970   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
4971     aFrom[0].isOrderedValid = 1;
4972   }else{
4973     /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
4974     ** number of output rows. The 48 is the expected size of a row to sort.
4975     ** FIXME:  compute a better estimate of the 48 multiplier based on the
4976     ** result set expressions. */
4977     rSortCost = nRowEst + estLog(nRowEst);
4978     WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
4979   }
4980 
4981   /* Compute successively longer WherePaths using the previous generation
4982   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
4983   ** best paths at each generation */
4984   for(iLoop=0; iLoop<nLoop; iLoop++){
4985     nTo = 0;
4986     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
4987       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
4988         Bitmask maskNew;
4989         Bitmask revMask = 0;
4990         u8 isOrderedValid = pFrom->isOrderedValid;
4991         u8 isOrdered = pFrom->isOrdered;
4992         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
4993         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
4994         /* At this point, pWLoop is a candidate to be the next loop.
4995         ** Compute its cost */
4996         rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
4997         rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
4998         nOut = pFrom->nRow + pWLoop->nOut;
4999         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
5000         if( !isOrderedValid ){
5001           switch( wherePathSatisfiesOrderBy(pWInfo,
5002                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
5003                        iLoop, pWLoop, &revMask) ){
5004             case 1:  /* Yes.  pFrom+pWLoop does satisfy the ORDER BY clause */
5005               isOrdered = 1;
5006               isOrderedValid = 1;
5007               break;
5008             case 0:  /* No.  pFrom+pWLoop will require a separate sort */
5009               isOrdered = 0;
5010               isOrderedValid = 1;
5011               rCost = sqlite3LogEstAdd(rCost, rSortCost);
5012               break;
5013             default: /* Cannot tell yet.  Try again on the next iteration */
5014               break;
5015           }
5016         }else{
5017           revMask = pFrom->revLoop;
5018         }
5019         /* Check to see if pWLoop should be added to the mxChoice best so far */
5020         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5021           if( pTo->maskLoop==maskNew
5022            && pTo->isOrderedValid==isOrderedValid
5023            && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
5024                 (pTo->rCost>=rCost && pTo->nRow>=nOut))
5025           ){
5026             testcase( jj==nTo-1 );
5027             break;
5028           }
5029         }
5030         if( jj>=nTo ){
5031           if( nTo>=mxChoice && rCost>=mxCost ){
5032 #ifdef WHERETRACE_ENABLED /* 0x4 */
5033             if( sqlite3WhereTrace&0x4 ){
5034               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
5035                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
5036                   isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5037             }
5038 #endif
5039             continue;
5040           }
5041           /* Add a new Path to the aTo[] set */
5042           if( nTo<mxChoice ){
5043             /* Increase the size of the aTo set by one */
5044             jj = nTo++;
5045           }else{
5046             /* New path replaces the prior worst to keep count below mxChoice */
5047             jj = mxI;
5048           }
5049           pTo = &aTo[jj];
5050 #ifdef WHERETRACE_ENABLED /* 0x4 */
5051           if( sqlite3WhereTrace&0x4 ){
5052             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
5053                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
5054                 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5055           }
5056 #endif
5057         }else{
5058           if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
5059 #ifdef WHERETRACE_ENABLED /* 0x4 */
5060             if( sqlite3WhereTrace&0x4 ){
5061               sqlite3DebugPrintf(
5062                   "Skip   %s cost=%-3d,%3d order=%c",
5063                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
5064                   isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5065               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
5066                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5067                   pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5068             }
5069 #endif
5070             testcase( pTo->rCost==rCost );
5071             continue;
5072           }
5073           testcase( pTo->rCost==rCost+1 );
5074           /* A new and better score for a previously created equivalent path */
5075 #ifdef WHERETRACE_ENABLED /* 0x4 */
5076           if( sqlite3WhereTrace&0x4 ){
5077             sqlite3DebugPrintf(
5078                 "Update %s cost=%-3d,%3d order=%c",
5079                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
5080                 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5081             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
5082                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5083                 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5084           }
5085 #endif
5086         }
5087         /* pWLoop is a winner.  Add it to the set of best so far */
5088         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
5089         pTo->revLoop = revMask;
5090         pTo->nRow = nOut;
5091         pTo->rCost = rCost;
5092         pTo->isOrderedValid = isOrderedValid;
5093         pTo->isOrdered = isOrdered;
5094         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5095         pTo->aLoop[iLoop] = pWLoop;
5096         if( nTo>=mxChoice ){
5097           mxI = 0;
5098           mxCost = aTo[0].rCost;
5099           mxOut = aTo[0].nRow;
5100           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5101             if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
5102               mxCost = pTo->rCost;
5103               mxOut = pTo->nRow;
5104               mxI = jj;
5105             }
5106           }
5107         }
5108       }
5109     }
5110 
5111 #ifdef WHERETRACE_ENABLED  /* >=2 */
5112     if( sqlite3WhereTrace>=2 ){
5113       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
5114       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
5115         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
5116            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5117            pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5118         if( pTo->isOrderedValid && pTo->isOrdered ){
5119           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5120         }else{
5121           sqlite3DebugPrintf("\n");
5122         }
5123       }
5124     }
5125 #endif
5126 
5127     /* Swap the roles of aFrom and aTo for the next generation */
5128     pFrom = aTo;
5129     aTo = aFrom;
5130     aFrom = pFrom;
5131     nFrom = nTo;
5132   }
5133 
5134   if( nFrom==0 ){
5135     sqlite3ErrorMsg(pParse, "no query solution");
5136     sqlite3DbFree(db, pSpace);
5137     return SQLITE_ERROR;
5138   }
5139 
5140   /* Find the lowest cost path.  pFrom will be left pointing to that path */
5141   pFrom = aFrom;
5142   for(ii=1; ii<nFrom; ii++){
5143     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5144   }
5145   assert( pWInfo->nLevel==nLoop );
5146   /* Load the lowest cost path into pWInfo */
5147   for(iLoop=0; iLoop<nLoop; iLoop++){
5148     WhereLevel *pLevel = pWInfo->a + iLoop;
5149     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
5150     pLevel->iFrom = pWLoop->iTab;
5151     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
5152   }
5153   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5154    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5155    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
5156    && nRowEst
5157   ){
5158     Bitmask notUsed;
5159     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
5160                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
5161     if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5162   }
5163   if( pFrom->isOrdered ){
5164     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5165       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5166     }else{
5167       pWInfo->bOBSat = 1;
5168       pWInfo->revMask = pFrom->revLoop;
5169     }
5170   }
5171   pWInfo->nRowOut = pFrom->nRow;
5172 
5173   /* Free temporary memory and return success */
5174   sqlite3DbFree(db, pSpace);
5175   return SQLITE_OK;
5176 }
5177 
5178 /*
5179 ** Most queries use only a single table (they are not joins) and have
5180 ** simple == constraints against indexed fields.  This routine attempts
5181 ** to plan those simple cases using much less ceremony than the
5182 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5183 ** times for the common case.
5184 **
5185 ** Return non-zero on success, if this query can be handled by this
5186 ** no-frills query planner.  Return zero if this query needs the
5187 ** general-purpose query planner.
5188 */
5189 static int whereShortCut(WhereLoopBuilder *pBuilder){
5190   WhereInfo *pWInfo;
5191   struct SrcList_item *pItem;
5192   WhereClause *pWC;
5193   WhereTerm *pTerm;
5194   WhereLoop *pLoop;
5195   int iCur;
5196   int j;
5197   Table *pTab;
5198   Index *pIdx;
5199 
5200   pWInfo = pBuilder->pWInfo;
5201   if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
5202   assert( pWInfo->pTabList->nSrc>=1 );
5203   pItem = pWInfo->pTabList->a;
5204   pTab = pItem->pTab;
5205   if( IsVirtual(pTab) ) return 0;
5206   if( pItem->zIndex ) return 0;
5207   iCur = pItem->iCursor;
5208   pWC = &pWInfo->sWC;
5209   pLoop = pBuilder->pNew;
5210   pLoop->wsFlags = 0;
5211   pLoop->u.btree.nSkip = 0;
5212   pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
5213   if( pTerm ){
5214     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5215     pLoop->aLTerm[0] = pTerm;
5216     pLoop->nLTerm = 1;
5217     pLoop->u.btree.nEq = 1;
5218     /* TUNING: Cost of a rowid lookup is 10 */
5219     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
5220   }else{
5221     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5222       assert( pLoop->aLTermSpace==pLoop->aLTerm );
5223       assert( ArraySize(pLoop->aLTermSpace)==4 );
5224       if( pIdx->onError==OE_None
5225        || pIdx->pPartIdxWhere!=0
5226        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
5227       ) continue;
5228       for(j=0; j<pIdx->nKeyCol; j++){
5229         pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
5230         if( pTerm==0 ) break;
5231         pLoop->aLTerm[j] = pTerm;
5232       }
5233       if( j!=pIdx->nKeyCol ) continue;
5234       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
5235       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
5236         pLoop->wsFlags |= WHERE_IDX_ONLY;
5237       }
5238       pLoop->nLTerm = j;
5239       pLoop->u.btree.nEq = j;
5240       pLoop->u.btree.pIndex = pIdx;
5241       /* TUNING: Cost of a unique index lookup is 15 */
5242       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
5243       break;
5244     }
5245   }
5246   if( pLoop->wsFlags ){
5247     pLoop->nOut = (LogEst)1;
5248     pWInfo->a[0].pWLoop = pLoop;
5249     pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5250     pWInfo->a[0].iTabCur = iCur;
5251     pWInfo->nRowOut = 1;
5252     if( pWInfo->pOrderBy ) pWInfo->bOBSat =  1;
5253     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5254       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5255     }
5256 #ifdef SQLITE_DEBUG
5257     pLoop->cId = '0';
5258 #endif
5259     return 1;
5260   }
5261   return 0;
5262 }
5263 
5264 /*
5265 ** Generate the beginning of the loop used for WHERE clause processing.
5266 ** The return value is a pointer to an opaque structure that contains
5267 ** information needed to terminate the loop.  Later, the calling routine
5268 ** should invoke sqlite3WhereEnd() with the return value of this function
5269 ** in order to complete the WHERE clause processing.
5270 **
5271 ** If an error occurs, this routine returns NULL.
5272 **
5273 ** The basic idea is to do a nested loop, one loop for each table in
5274 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
5275 ** same as a SELECT with only a single table in the FROM clause.)  For
5276 ** example, if the SQL is this:
5277 **
5278 **       SELECT * FROM t1, t2, t3 WHERE ...;
5279 **
5280 ** Then the code generated is conceptually like the following:
5281 **
5282 **      foreach row1 in t1 do       \    Code generated
5283 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
5284 **          foreach row3 in t3 do   /
5285 **            ...
5286 **          end                     \    Code generated
5287 **        end                        |-- by sqlite3WhereEnd()
5288 **      end                         /
5289 **
5290 ** Note that the loops might not be nested in the order in which they
5291 ** appear in the FROM clause if a different order is better able to make
5292 ** use of indices.  Note also that when the IN operator appears in
5293 ** the WHERE clause, it might result in additional nested loops for
5294 ** scanning through all values on the right-hand side of the IN.
5295 **
5296 ** There are Btree cursors associated with each table.  t1 uses cursor
5297 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
5298 ** And so forth.  This routine generates code to open those VDBE cursors
5299 ** and sqlite3WhereEnd() generates the code to close them.
5300 **
5301 ** The code that sqlite3WhereBegin() generates leaves the cursors named
5302 ** in pTabList pointing at their appropriate entries.  The [...] code
5303 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
5304 ** data from the various tables of the loop.
5305 **
5306 ** If the WHERE clause is empty, the foreach loops must each scan their
5307 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
5308 ** the tables have indices and there are terms in the WHERE clause that
5309 ** refer to those indices, a complete table scan can be avoided and the
5310 ** code will run much faster.  Most of the work of this routine is checking
5311 ** to see if there are indices that can be used to speed up the loop.
5312 **
5313 ** Terms of the WHERE clause are also used to limit which rows actually
5314 ** make it to the "..." in the middle of the loop.  After each "foreach",
5315 ** terms of the WHERE clause that use only terms in that loop and outer
5316 ** loops are evaluated and if false a jump is made around all subsequent
5317 ** inner loops (or around the "..." if the test occurs within the inner-
5318 ** most loop)
5319 **
5320 ** OUTER JOINS
5321 **
5322 ** An outer join of tables t1 and t2 is conceptally coded as follows:
5323 **
5324 **    foreach row1 in t1 do
5325 **      flag = 0
5326 **      foreach row2 in t2 do
5327 **        start:
5328 **          ...
5329 **          flag = 1
5330 **      end
5331 **      if flag==0 then
5332 **        move the row2 cursor to a null row
5333 **        goto start
5334 **      fi
5335 **    end
5336 **
5337 ** ORDER BY CLAUSE PROCESSING
5338 **
5339 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5340 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
5341 ** if there is one.  If there is no ORDER BY clause or if this routine
5342 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
5343 **
5344 ** The iIdxCur parameter is the cursor number of an index.  If
5345 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
5346 ** to use for OR clause processing.  The WHERE clause should use this
5347 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5348 ** the first cursor in an array of cursors for all indices.  iIdxCur should
5349 ** be used to compute the appropriate cursor depending on which index is
5350 ** used.
5351 */
5352 WhereInfo *sqlite3WhereBegin(
5353   Parse *pParse,        /* The parser context */
5354   SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
5355   Expr *pWhere,         /* The WHERE clause */
5356   ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
5357   ExprList *pResultSet, /* Result set of the query */
5358   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
5359   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
5360 ){
5361   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
5362   int nTabList;              /* Number of elements in pTabList */
5363   WhereInfo *pWInfo;         /* Will become the return value of this function */
5364   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
5365   Bitmask notReady;          /* Cursors that are not yet positioned */
5366   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
5367   WhereMaskSet *pMaskSet;    /* The expression mask set */
5368   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
5369   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
5370   int ii;                    /* Loop counter */
5371   sqlite3 *db;               /* Database connection */
5372   int rc;                    /* Return code */
5373 
5374 
5375   /* Variable initialization */
5376   db = pParse->db;
5377   memset(&sWLB, 0, sizeof(sWLB));
5378   sWLB.pOrderBy = pOrderBy;
5379 
5380   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5381   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5382   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5383     wctrlFlags &= ~WHERE_WANT_DISTINCT;
5384   }
5385 
5386   /* The number of tables in the FROM clause is limited by the number of
5387   ** bits in a Bitmask
5388   */
5389   testcase( pTabList->nSrc==BMS );
5390   if( pTabList->nSrc>BMS ){
5391     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
5392     return 0;
5393   }
5394 
5395   /* This function normally generates a nested loop for all tables in
5396   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
5397   ** only generate code for the first table in pTabList and assume that
5398   ** any cursors associated with subsequent tables are uninitialized.
5399   */
5400   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5401 
5402   /* Allocate and initialize the WhereInfo structure that will become the
5403   ** return value. A single allocation is used to store the WhereInfo
5404   ** struct, the contents of WhereInfo.a[], the WhereClause structure
5405   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5406   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5407   ** some architectures. Hence the ROUND8() below.
5408   */
5409   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
5410   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
5411   if( db->mallocFailed ){
5412     sqlite3DbFree(db, pWInfo);
5413     pWInfo = 0;
5414     goto whereBeginError;
5415   }
5416   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
5417   pWInfo->nLevel = nTabList;
5418   pWInfo->pParse = pParse;
5419   pWInfo->pTabList = pTabList;
5420   pWInfo->pOrderBy = pOrderBy;
5421   pWInfo->pResultSet = pResultSet;
5422   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
5423   pWInfo->wctrlFlags = wctrlFlags;
5424   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
5425   pMaskSet = &pWInfo->sMaskSet;
5426   sWLB.pWInfo = pWInfo;
5427   sWLB.pWC = &pWInfo->sWC;
5428   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5429   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
5430   whereLoopInit(sWLB.pNew);
5431 #ifdef SQLITE_DEBUG
5432   sWLB.pNew->cId = '*';
5433 #endif
5434 
5435   /* Split the WHERE clause into separate subexpressions where each
5436   ** subexpression is separated by an AND operator.
5437   */
5438   initMaskSet(pMaskSet);
5439   whereClauseInit(&pWInfo->sWC, pWInfo);
5440   whereSplit(&pWInfo->sWC, pWhere, TK_AND);
5441 
5442   /* Special case: a WHERE clause that is constant.  Evaluate the
5443   ** expression and either jump over all of the code or fall thru.
5444   */
5445   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
5446     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
5447       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
5448                          SQLITE_JUMPIFNULL);
5449       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
5450     }
5451   }
5452 
5453   /* Special case: No FROM clause
5454   */
5455   if( nTabList==0 ){
5456     if( pOrderBy ) pWInfo->bOBSat = 1;
5457     if( wctrlFlags & WHERE_WANT_DISTINCT ){
5458       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5459     }
5460   }
5461 
5462   /* Assign a bit from the bitmask to every term in the FROM clause.
5463   **
5464   ** When assigning bitmask values to FROM clause cursors, it must be
5465   ** the case that if X is the bitmask for the N-th FROM clause term then
5466   ** the bitmask for all FROM clause terms to the left of the N-th term
5467   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
5468   ** its Expr.iRightJoinTable value to find the bitmask of the right table
5469   ** of the join.  Subtracting one from the right table bitmask gives a
5470   ** bitmask for all tables to the left of the join.  Knowing the bitmask
5471   ** for all tables to the left of a left join is important.  Ticket #3015.
5472   **
5473   ** Note that bitmasks are created for all pTabList->nSrc tables in
5474   ** pTabList, not just the first nTabList tables.  nTabList is normally
5475   ** equal to pTabList->nSrc but might be shortened to 1 if the
5476   ** WHERE_ONETABLE_ONLY flag is set.
5477   */
5478   for(ii=0; ii<pTabList->nSrc; ii++){
5479     createMask(pMaskSet, pTabList->a[ii].iCursor);
5480   }
5481 #ifndef NDEBUG
5482   {
5483     Bitmask toTheLeft = 0;
5484     for(ii=0; ii<pTabList->nSrc; ii++){
5485       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
5486       assert( (m-1)==toTheLeft );
5487       toTheLeft |= m;
5488     }
5489   }
5490 #endif
5491 
5492   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
5493   ** add new virtual terms onto the end of the WHERE clause.  We do not
5494   ** want to analyze these virtual terms, so start analyzing at the end
5495   ** and work forward so that the added virtual terms are never processed.
5496   */
5497   exprAnalyzeAll(pTabList, &pWInfo->sWC);
5498   if( db->mallocFailed ){
5499     goto whereBeginError;
5500   }
5501 
5502   /* If the ORDER BY (or GROUP BY) clause contains references to general
5503   ** expressions, then we won't be able to satisfy it using indices, so
5504   ** go ahead and disable it now.
5505   */
5506   if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
5507     for(ii=0; ii<pOrderBy->nExpr; ii++){
5508       Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
5509       if( pExpr->op!=TK_COLUMN ){
5510         pWInfo->pOrderBy = pOrderBy = 0;
5511         break;
5512       }else if( pExpr->iColumn<0 ){
5513         break;
5514       }
5515     }
5516   }
5517 
5518   if( wctrlFlags & WHERE_WANT_DISTINCT ){
5519     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5520       /* The DISTINCT marking is pointless.  Ignore it. */
5521       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5522     }else if( pOrderBy==0 ){
5523       /* Try to ORDER BY the result set to make distinct processing easier */
5524       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
5525       pWInfo->pOrderBy = pResultSet;
5526     }
5527   }
5528 
5529   /* Construct the WhereLoop objects */
5530   WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
5531   /* Display all terms of the WHERE clause */
5532 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
5533   if( sqlite3WhereTrace & 0x100 ){
5534     int i;
5535     Vdbe *v = pParse->pVdbe;
5536     sqlite3ExplainBegin(v);
5537     for(i=0; i<sWLB.pWC->nTerm; i++){
5538       sqlite3ExplainPrintf(v, "#%-2d ", i);
5539       sqlite3ExplainPush(v);
5540       whereExplainTerm(v, &sWLB.pWC->a[i]);
5541       sqlite3ExplainPop(v);
5542       sqlite3ExplainNL(v);
5543     }
5544     sqlite3ExplainFinish(v);
5545     sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
5546   }
5547 #endif
5548   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
5549     rc = whereLoopAddAll(&sWLB);
5550     if( rc ) goto whereBeginError;
5551 
5552     /* Display all of the WhereLoop objects if wheretrace is enabled */
5553 #ifdef WHERETRACE_ENABLED /* !=0 */
5554     if( sqlite3WhereTrace ){
5555       WhereLoop *p;
5556       int i;
5557       static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5558                                        "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5559       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5560         p->cId = zLabel[i%sizeof(zLabel)];
5561         whereLoopPrint(p, sWLB.pWC);
5562       }
5563     }
5564 #endif
5565 
5566     wherePathSolver(pWInfo, 0);
5567     if( db->mallocFailed ) goto whereBeginError;
5568     if( pWInfo->pOrderBy ){
5569        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
5570        if( db->mallocFailed ) goto whereBeginError;
5571     }
5572   }
5573   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
5574      pWInfo->revMask = (Bitmask)(-1);
5575   }
5576   if( pParse->nErr || NEVER(db->mallocFailed) ){
5577     goto whereBeginError;
5578   }
5579 #ifdef WHERETRACE_ENABLED /* !=0 */
5580   if( sqlite3WhereTrace ){
5581     int ii;
5582     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5583     if( pWInfo->bOBSat ){
5584       sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
5585     }
5586     switch( pWInfo->eDistinct ){
5587       case WHERE_DISTINCT_UNIQUE: {
5588         sqlite3DebugPrintf("  DISTINCT=unique");
5589         break;
5590       }
5591       case WHERE_DISTINCT_ORDERED: {
5592         sqlite3DebugPrintf("  DISTINCT=ordered");
5593         break;
5594       }
5595       case WHERE_DISTINCT_UNORDERED: {
5596         sqlite3DebugPrintf("  DISTINCT=unordered");
5597         break;
5598       }
5599     }
5600     sqlite3DebugPrintf("\n");
5601     for(ii=0; ii<pWInfo->nLevel; ii++){
5602       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
5603     }
5604   }
5605 #endif
5606   /* Attempt to omit tables from the join that do not effect the result */
5607   if( pWInfo->nLevel>=2
5608    && pResultSet!=0
5609    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5610   ){
5611     Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
5612     if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
5613     while( pWInfo->nLevel>=2 ){
5614       WhereTerm *pTerm, *pEnd;
5615       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
5616       if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5617       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5618        && (pLoop->wsFlags & WHERE_ONEROW)==0
5619       ){
5620         break;
5621       }
5622       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
5623       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5624       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5625         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5626          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5627         ){
5628           break;
5629         }
5630       }
5631       if( pTerm<pEnd ) break;
5632       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5633       pWInfo->nLevel--;
5634       nTabList--;
5635     }
5636   }
5637   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
5638   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
5639 
5640   /* If the caller is an UPDATE or DELETE statement that is requesting
5641   ** to use a one-pass algorithm, determine if this is appropriate.
5642   ** The one-pass algorithm only works if the WHERE clause constrains
5643   ** the statement to update a single row.
5644   */
5645   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
5646   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5647    && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
5648     pWInfo->okOnePass = 1;
5649     if( HasRowid(pTabList->a[0].pTab) ){
5650       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
5651     }
5652   }
5653 
5654   /* Open all tables in the pTabList and any indices selected for
5655   ** searching those tables.
5656   */
5657   notReady = ~(Bitmask)0;
5658   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
5659     Table *pTab;     /* Table to open */
5660     int iDb;         /* Index of database containing table/index */
5661     struct SrcList_item *pTabItem;
5662 
5663     pTabItem = &pTabList->a[pLevel->iFrom];
5664     pTab = pTabItem->pTab;
5665     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
5666     pLoop = pLevel->pWLoop;
5667     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
5668       /* Do nothing */
5669     }else
5670 #ifndef SQLITE_OMIT_VIRTUALTABLE
5671     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
5672       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
5673       int iCur = pTabItem->iCursor;
5674       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
5675     }else if( IsVirtual(pTab) ){
5676       /* noop */
5677     }else
5678 #endif
5679     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
5680          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
5681       int op = OP_OpenRead;
5682       if( pWInfo->okOnePass ){
5683         op = OP_OpenWrite;
5684         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
5685       };
5686       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
5687       assert( pTabItem->iCursor==pLevel->iTabCur );
5688       testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5689       testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
5690       if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
5691         Bitmask b = pTabItem->colUsed;
5692         int n = 0;
5693         for(; b; b=b>>1, n++){}
5694         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5695                             SQLITE_INT_TO_PTR(n), P4_INT32);
5696         assert( n<=pTab->nCol );
5697       }
5698     }else{
5699       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5700     }
5701     if( pLoop->wsFlags & WHERE_INDEXED ){
5702       Index *pIx = pLoop->u.btree.pIndex;
5703       int iIndexCur;
5704       int op = OP_OpenRead;
5705       /* iIdxCur is always set if to a positive value if ONEPASS is possible */
5706       assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
5707       if( pWInfo->okOnePass ){
5708         Index *pJ = pTabItem->pTab->pIndex;
5709         iIndexCur = iIdxCur;
5710         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
5711         while( ALWAYS(pJ) && pJ!=pIx ){
5712           iIndexCur++;
5713           pJ = pJ->pNext;
5714         }
5715         op = OP_OpenWrite;
5716         pWInfo->aiCurOnePass[1] = iIndexCur;
5717       }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
5718         iIndexCur = iIdxCur;
5719       }else{
5720         iIndexCur = pParse->nTab++;
5721       }
5722       pLevel->iIdxCur = iIndexCur;
5723       assert( pIx->pSchema==pTab->pSchema );
5724       assert( iIndexCur>=0 );
5725       sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
5726       sqlite3VdbeSetP4KeyInfo(pParse, pIx);
5727       VdbeComment((v, "%s", pIx->zName));
5728     }
5729     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
5730     notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
5731   }
5732   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
5733   if( db->mallocFailed ) goto whereBeginError;
5734 
5735   /* Generate the code to do the search.  Each iteration of the for
5736   ** loop below generates code for a single nested loop of the VM
5737   ** program.
5738   */
5739   notReady = ~(Bitmask)0;
5740   for(ii=0; ii<nTabList; ii++){
5741     pLevel = &pWInfo->a[ii];
5742 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
5743     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
5744       constructAutomaticIndex(pParse, &pWInfo->sWC,
5745                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
5746       if( db->mallocFailed ) goto whereBeginError;
5747     }
5748 #endif
5749     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
5750     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
5751     notReady = codeOneLoopStart(pWInfo, ii, notReady);
5752     pWInfo->iContinue = pLevel->addrCont;
5753   }
5754 
5755   /* Done. */
5756   VdbeModuleComment((v, "Begin WHERE-core"));
5757   return pWInfo;
5758 
5759   /* Jump here if malloc fails */
5760 whereBeginError:
5761   if( pWInfo ){
5762     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5763     whereInfoFree(db, pWInfo);
5764   }
5765   return 0;
5766 }
5767 
5768 /*
5769 ** Generate the end of the WHERE loop.  See comments on
5770 ** sqlite3WhereBegin() for additional information.
5771 */
5772 void sqlite3WhereEnd(WhereInfo *pWInfo){
5773   Parse *pParse = pWInfo->pParse;
5774   Vdbe *v = pParse->pVdbe;
5775   int i;
5776   WhereLevel *pLevel;
5777   WhereLoop *pLoop;
5778   SrcList *pTabList = pWInfo->pTabList;
5779   sqlite3 *db = pParse->db;
5780 
5781   /* Generate loop termination code.
5782   */
5783   VdbeModuleComment((v, "End WHERE-core"));
5784   sqlite3ExprCacheClear(pParse);
5785   for(i=pWInfo->nLevel-1; i>=0; i--){
5786     int addr;
5787     pLevel = &pWInfo->a[i];
5788     pLoop = pLevel->pWLoop;
5789     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
5790     if( pLevel->op!=OP_Noop ){
5791       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
5792       sqlite3VdbeChangeP5(v, pLevel->p5);
5793     }
5794     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
5795       struct InLoop *pIn;
5796       int j;
5797       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
5798       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
5799         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
5800         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
5801         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
5802       }
5803       sqlite3DbFree(db, pLevel->u.in.aInLoop);
5804     }
5805     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
5806     if( pLevel->addrSkip ){
5807       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
5808       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
5809       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
5810       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
5811     }
5812     if( pLevel->iLeftJoin ){
5813       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
5814       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
5815            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
5816       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
5817         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5818       }
5819       if( pLoop->wsFlags & WHERE_INDEXED ){
5820         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
5821       }
5822       if( pLevel->op==OP_Return ){
5823         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5824       }else{
5825         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5826       }
5827       sqlite3VdbeJumpHere(v, addr);
5828     }
5829     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
5830                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
5831   }
5832 
5833   /* The "break" point is here, just past the end of the outer loop.
5834   ** Set it.
5835   */
5836   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
5837 
5838   assert( pWInfo->nLevel<=pTabList->nSrc );
5839   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
5840     int k, last;
5841     VdbeOp *pOp;
5842     Index *pIdx = 0;
5843     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
5844     Table *pTab = pTabItem->pTab;
5845     assert( pTab!=0 );
5846     pLoop = pLevel->pWLoop;
5847 
5848     /* For a co-routine, change all OP_Column references to the table of
5849     ** the co-routine into OP_SCopy of result contained in a register.
5850     ** OP_Rowid becomes OP_Null.
5851     */
5852     if( pTabItem->viaCoroutine ){
5853       last = sqlite3VdbeCurrentAddr(v);
5854       k = pLevel->addrBody;
5855       pOp = sqlite3VdbeGetOp(v, k);
5856       for(; k<last; k++, pOp++){
5857         if( pOp->p1!=pLevel->iTabCur ) continue;
5858         if( pOp->opcode==OP_Column ){
5859           pOp->opcode = OP_SCopy;
5860           pOp->p1 = pOp->p2 + pTabItem->regResult;
5861           pOp->p2 = pOp->p3;
5862           pOp->p3 = 0;
5863         }else if( pOp->opcode==OP_Rowid ){
5864           pOp->opcode = OP_Null;
5865           pOp->p1 = 0;
5866           pOp->p3 = 0;
5867         }
5868       }
5869       continue;
5870     }
5871 
5872     /* Close all of the cursors that were opened by sqlite3WhereBegin.
5873     ** Except, do not close cursors that will be reused by the OR optimization
5874     ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
5875     ** created for the ONEPASS optimization.
5876     */
5877     if( (pTab->tabFlags & TF_Ephemeral)==0
5878      && pTab->pSelect==0
5879      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
5880     ){
5881       int ws = pLoop->wsFlags;
5882       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
5883         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5884       }
5885       if( (ws & WHERE_INDEXED)!=0
5886        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
5887        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
5888       ){
5889         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5890       }
5891     }
5892 
5893     /* If this scan uses an index, make VDBE code substitutions to read data
5894     ** from the index instead of from the table where possible.  In some cases
5895     ** this optimization prevents the table from ever being read, which can
5896     ** yield a significant performance boost.
5897     **
5898     ** Calls to the code generator in between sqlite3WhereBegin and
5899     ** sqlite3WhereEnd will have created code that references the table
5900     ** directly.  This loop scans all that code looking for opcodes
5901     ** that reference the table and converts them into opcodes that
5902     ** reference the index.
5903     */
5904     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
5905       pIdx = pLoop->u.btree.pIndex;
5906     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
5907       pIdx = pLevel->u.pCovidx;
5908     }
5909     if( pIdx && !db->mallocFailed ){
5910       last = sqlite3VdbeCurrentAddr(v);
5911       k = pLevel->addrBody;
5912       pOp = sqlite3VdbeGetOp(v, k);
5913       for(; k<last; k++, pOp++){
5914         if( pOp->p1!=pLevel->iTabCur ) continue;
5915         if( pOp->opcode==OP_Column ){
5916           int x = pOp->p2;
5917           assert( pIdx->pTable==pTab );
5918           if( !HasRowid(pTab) ){
5919             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
5920             x = pPk->aiColumn[x];
5921           }
5922           x = sqlite3ColumnOfIndex(pIdx, x);
5923           if( x>=0 ){
5924             pOp->p2 = x;
5925             pOp->p1 = pLevel->iIdxCur;
5926           }
5927           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
5928         }else if( pOp->opcode==OP_Rowid ){
5929           pOp->p1 = pLevel->iIdxCur;
5930           pOp->opcode = OP_IdxRowid;
5931         }
5932       }
5933     }
5934   }
5935 
5936   /* Final cleanup
5937   */
5938   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5939   whereInfoFree(db, pWInfo);
5940   return;
5941 }
5942