xref: /sqlite-3.40.0/src/where.c (revision 3f09beda)
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 /* Forward declaration of methods */
23 static int whereLoopResize(sqlite3*, WhereLoop*, int);
24 
25 /* Test variable that can be set to enable WHERE tracing */
26 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
27 /***/ int sqlite3WhereTrace = 0;
28 #endif
29 
30 
31 /*
32 ** Return the estimated number of output rows from a WHERE clause
33 */
34 u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
35   return sqlite3LogEstToInt(pWInfo->nRowOut);
36 }
37 
38 /*
39 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
40 ** WHERE clause returns outputs for DISTINCT processing.
41 */
42 int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
43   return pWInfo->eDistinct;
44 }
45 
46 /*
47 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
48 ** Return FALSE if the output needs to be sorted.
49 */
50 int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
51   return pWInfo->nOBSat;
52 }
53 
54 /*
55 ** Return the VDBE address or label to jump to in order to continue
56 ** immediately with the next row of a WHERE clause.
57 */
58 int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
59   assert( pWInfo->iContinue!=0 );
60   return pWInfo->iContinue;
61 }
62 
63 /*
64 ** Return the VDBE address or label to jump to in order to break
65 ** out of a WHERE loop.
66 */
67 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
68   return pWInfo->iBreak;
69 }
70 
71 /*
72 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
73 ** the rowids returned by a WHERE clause.  Return FALSE if doing an
74 ** UPDATE or DELETE might change subsequent WHERE clause results.
75 **
76 ** If the ONEPASS optimization is used (if this routine returns true)
77 ** then also write the indices of open cursors used by ONEPASS
78 ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
79 ** table and iaCur[1] gets the cursor used by an auxiliary index.
80 ** Either value may be -1, indicating that cursor is not used.
81 ** Any cursors returned will have been opened for writing.
82 **
83 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
84 ** unable to use the ONEPASS optimization.
85 */
86 int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
87   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
88   return pWInfo->okOnePass;
89 }
90 
91 /*
92 ** Move the content of pSrc into pDest
93 */
94 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
95   pDest->n = pSrc->n;
96   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
97 }
98 
99 /*
100 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
101 **
102 ** The new entry might overwrite an existing entry, or it might be
103 ** appended, or it might be discarded.  Do whatever is the right thing
104 ** so that pSet keeps the N_OR_COST best entries seen so far.
105 */
106 static int whereOrInsert(
107   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
108   Bitmask prereq,        /* Prerequisites of the new entry */
109   LogEst rRun,           /* Run-cost of the new entry */
110   LogEst nOut            /* Number of outputs for the new entry */
111 ){
112   u16 i;
113   WhereOrCost *p;
114   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
115     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
116       goto whereOrInsert_done;
117     }
118     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
119       return 0;
120     }
121   }
122   if( pSet->n<N_OR_COST ){
123     p = &pSet->a[pSet->n++];
124     p->nOut = nOut;
125   }else{
126     p = pSet->a;
127     for(i=1; i<pSet->n; i++){
128       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
129     }
130     if( p->rRun<=rRun ) return 0;
131   }
132 whereOrInsert_done:
133   p->prereq = prereq;
134   p->rRun = rRun;
135   if( p->nOut>nOut ) p->nOut = nOut;
136   return 1;
137 }
138 
139 /*
140 ** Return the bitmask for the given cursor number.  Return 0 if
141 ** iCursor is not in the set.
142 */
143 Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
144   int i;
145   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
146   for(i=0; i<pMaskSet->n; i++){
147     if( pMaskSet->ix[i]==iCursor ){
148       return MASKBIT(i);
149     }
150   }
151   return 0;
152 }
153 
154 /*
155 ** Create a new mask for cursor iCursor.
156 **
157 ** There is one cursor per table in the FROM clause.  The number of
158 ** tables in the FROM clause is limited by a test early in the
159 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
160 ** array will never overflow.
161 */
162 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
163   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
164   pMaskSet->ix[pMaskSet->n++] = iCursor;
165 }
166 
167 /*
168 ** Advance to the next WhereTerm that matches according to the criteria
169 ** established when the pScan object was initialized by whereScanInit().
170 ** Return NULL if there are no more matching WhereTerms.
171 */
172 static WhereTerm *whereScanNext(WhereScan *pScan){
173   int iCur;            /* The cursor on the LHS of the term */
174   int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
175   Expr *pX;            /* An expression being tested */
176   WhereClause *pWC;    /* Shorthand for pScan->pWC */
177   WhereTerm *pTerm;    /* The term being tested */
178   int k = pScan->k;    /* Where to start scanning */
179 
180   while( pScan->iEquiv<=pScan->nEquiv ){
181     iCur = pScan->aEquiv[pScan->iEquiv-2];
182     iColumn = pScan->aEquiv[pScan->iEquiv-1];
183     while( (pWC = pScan->pWC)!=0 ){
184       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
185         if( pTerm->leftCursor==iCur
186          && pTerm->u.leftColumn==iColumn
187          && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
188         ){
189           if( (pTerm->eOperator & WO_EQUIV)!=0
190            && pScan->nEquiv<ArraySize(pScan->aEquiv)
191           ){
192             int j;
193             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
194             assert( pX->op==TK_COLUMN );
195             for(j=0; j<pScan->nEquiv; j+=2){
196               if( pScan->aEquiv[j]==pX->iTable
197                && pScan->aEquiv[j+1]==pX->iColumn ){
198                   break;
199               }
200             }
201             if( j==pScan->nEquiv ){
202               pScan->aEquiv[j] = pX->iTable;
203               pScan->aEquiv[j+1] = pX->iColumn;
204               pScan->nEquiv += 2;
205             }
206           }
207           if( (pTerm->eOperator & pScan->opMask)!=0 ){
208             /* Verify the affinity and collating sequence match */
209             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
210               CollSeq *pColl;
211               Parse *pParse = pWC->pWInfo->pParse;
212               pX = pTerm->pExpr;
213               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
214                 continue;
215               }
216               assert(pX->pLeft);
217               pColl = sqlite3BinaryCompareCollSeq(pParse,
218                                                   pX->pLeft, pX->pRight);
219               if( pColl==0 ) pColl = pParse->db->pDfltColl;
220               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
221                 continue;
222               }
223             }
224             if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
225              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
226              && pX->iTable==pScan->aEquiv[0]
227              && pX->iColumn==pScan->aEquiv[1]
228             ){
229               testcase( pTerm->eOperator & WO_IS );
230               continue;
231             }
232             pScan->k = k+1;
233             return pTerm;
234           }
235         }
236       }
237       pScan->pWC = pScan->pWC->pOuter;
238       k = 0;
239     }
240     pScan->pWC = pScan->pOrigWC;
241     k = 0;
242     pScan->iEquiv += 2;
243   }
244   return 0;
245 }
246 
247 /*
248 ** Initialize a WHERE clause scanner object.  Return a pointer to the
249 ** first match.  Return NULL if there are no matches.
250 **
251 ** The scanner will be searching the WHERE clause pWC.  It will look
252 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
253 ** iCur.  The <op> must be one of the operators described by opMask.
254 **
255 ** If the search is for X and the WHERE clause contains terms of the
256 ** form X=Y then this routine might also return terms of the form
257 ** "Y <op> <expr>".  The number of levels of transitivity is limited,
258 ** but is enough to handle most commonly occurring SQL statements.
259 **
260 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
261 ** index pIdx.
262 */
263 static WhereTerm *whereScanInit(
264   WhereScan *pScan,       /* The WhereScan object being initialized */
265   WhereClause *pWC,       /* The WHERE clause to be scanned */
266   int iCur,               /* Cursor to scan for */
267   int iColumn,            /* Column to scan for */
268   u32 opMask,             /* Operator(s) to scan for */
269   Index *pIdx             /* Must be compatible with this index */
270 ){
271   int j;
272 
273   /* memset(pScan, 0, sizeof(*pScan)); */
274   pScan->pOrigWC = pWC;
275   pScan->pWC = pWC;
276   if( pIdx && iColumn>=0 ){
277     pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
278     for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
279       if( NEVER(j>pIdx->nColumn) ) return 0;
280     }
281     pScan->zCollName = pIdx->azColl[j];
282   }else{
283     pScan->idxaff = 0;
284     pScan->zCollName = 0;
285   }
286   pScan->opMask = opMask;
287   pScan->k = 0;
288   pScan->aEquiv[0] = iCur;
289   pScan->aEquiv[1] = iColumn;
290   pScan->nEquiv = 2;
291   pScan->iEquiv = 2;
292   return whereScanNext(pScan);
293 }
294 
295 /*
296 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
297 ** where X is a reference to the iColumn of table iCur and <op> is one of
298 ** the WO_xx operator codes specified by the op parameter.
299 ** Return a pointer to the term.  Return 0 if not found.
300 **
301 ** The term returned might by Y=<expr> if there is another constraint in
302 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
303 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
304 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
305 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
306 ** and the second is for the column number.  There are 22 slots in aEquiv[]
307 ** so that means we can look for X plus up to 10 other equivalent values.
308 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
309 ** and ... and A9=A10 and A10=<expr>.
310 **
311 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
312 ** then try for the one with no dependencies on <expr> - in other words where
313 ** <expr> is a constant expression of some kind.  Only return entries of
314 ** the form "X <op> Y" where Y is a column in another table if no terms of
315 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
316 ** exist, try to return a term that does not use WO_EQUIV.
317 */
318 WhereTerm *sqlite3WhereFindTerm(
319   WhereClause *pWC,     /* The WHERE clause to be searched */
320   int iCur,             /* Cursor number of LHS */
321   int iColumn,          /* Column number of LHS */
322   Bitmask notReady,     /* RHS must not overlap with this mask */
323   u32 op,               /* Mask of WO_xx values describing operator */
324   Index *pIdx           /* Must be compatible with this index, if not NULL */
325 ){
326   WhereTerm *pResult = 0;
327   WhereTerm *p;
328   WhereScan scan;
329 
330   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
331   op &= WO_EQ|WO_IS;
332   while( p ){
333     if( (p->prereqRight & notReady)==0 ){
334       if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
335         testcase( p->eOperator & WO_IS );
336         return p;
337       }
338       if( pResult==0 ) pResult = p;
339     }
340     p = whereScanNext(&scan);
341   }
342   return pResult;
343 }
344 
345 /*
346 ** This function searches pList for an entry that matches the iCol-th column
347 ** of index pIdx.
348 **
349 ** If such an expression is found, its index in pList->a[] is returned. If
350 ** no expression is found, -1 is returned.
351 */
352 static int findIndexCol(
353   Parse *pParse,                  /* Parse context */
354   ExprList *pList,                /* Expression list to search */
355   int iBase,                      /* Cursor for table associated with pIdx */
356   Index *pIdx,                    /* Index to match column of */
357   int iCol                        /* Column of index to match */
358 ){
359   int i;
360   const char *zColl = pIdx->azColl[iCol];
361 
362   for(i=0; i<pList->nExpr; i++){
363     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
364     if( p->op==TK_COLUMN
365      && p->iColumn==pIdx->aiColumn[iCol]
366      && p->iTable==iBase
367     ){
368       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
369       if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
370         return i;
371       }
372     }
373   }
374 
375   return -1;
376 }
377 
378 /*
379 ** Return true if the DISTINCT expression-list passed as the third argument
380 ** is redundant.
381 **
382 ** A DISTINCT list is redundant if any subset of the columns in the
383 ** DISTINCT list are collectively unique and individually non-null.
384 */
385 static int isDistinctRedundant(
386   Parse *pParse,            /* Parsing context */
387   SrcList *pTabList,        /* The FROM clause */
388   WhereClause *pWC,         /* The WHERE clause */
389   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
390 ){
391   Table *pTab;
392   Index *pIdx;
393   int i;
394   int iBase;
395 
396   /* If there is more than one table or sub-select in the FROM clause of
397   ** this query, then it will not be possible to show that the DISTINCT
398   ** clause is redundant. */
399   if( pTabList->nSrc!=1 ) return 0;
400   iBase = pTabList->a[0].iCursor;
401   pTab = pTabList->a[0].pTab;
402 
403   /* If any of the expressions is an IPK column on table iBase, then return
404   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
405   ** current SELECT is a correlated sub-query.
406   */
407   for(i=0; i<pDistinct->nExpr; i++){
408     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
409     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
410   }
411 
412   /* Loop through all indices on the table, checking each to see if it makes
413   ** the DISTINCT qualifier redundant. It does so if:
414   **
415   **   1. The index is itself UNIQUE, and
416   **
417   **   2. All of the columns in the index are either part of the pDistinct
418   **      list, or else the WHERE clause contains a term of the form "col=X",
419   **      where X is a constant value. The collation sequences of the
420   **      comparison and select-list expressions must match those of the index.
421   **
422   **   3. All of those index columns for which the WHERE clause does not
423   **      contain a "col=X" term are subject to a NOT NULL constraint.
424   */
425   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
426     if( !IsUniqueIndex(pIdx) ) continue;
427     for(i=0; i<pIdx->nKeyCol; i++){
428       i16 iCol = pIdx->aiColumn[i];
429       if( 0==sqlite3WhereFindTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
430         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
431         if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
432           break;
433         }
434       }
435     }
436     if( i==pIdx->nKeyCol ){
437       /* This index implies that the DISTINCT qualifier is redundant. */
438       return 1;
439     }
440   }
441 
442   return 0;
443 }
444 
445 
446 /*
447 ** Estimate the logarithm of the input value to base 2.
448 */
449 static LogEst estLog(LogEst N){
450   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
451 }
452 
453 /*
454 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
455 **
456 ** This routine runs over generated VDBE code and translates OP_Column
457 ** opcodes into OP_Copy, and OP_Rowid into OP_Null, when the table is being
458 ** accessed via co-routine instead of via table lookup.
459 */
460 static void translateColumnToCopy(
461   Vdbe *v,            /* The VDBE containing code to translate */
462   int iStart,         /* Translate from this opcode to the end */
463   int iTabCur,        /* OP_Column/OP_Rowid references to this table */
464   int iRegister       /* The first column is in this register */
465 ){
466   VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
467   int iEnd = sqlite3VdbeCurrentAddr(v);
468   for(; iStart<iEnd; iStart++, pOp++){
469     if( pOp->p1!=iTabCur ) continue;
470     if( pOp->opcode==OP_Column ){
471       pOp->opcode = OP_Copy;
472       pOp->p1 = pOp->p2 + iRegister;
473       pOp->p2 = pOp->p3;
474       pOp->p3 = 0;
475     }else if( pOp->opcode==OP_Rowid ){
476       pOp->opcode = OP_Null;
477       pOp->p1 = 0;
478       pOp->p3 = 0;
479     }
480   }
481 }
482 
483 /*
484 ** Two routines for printing the content of an sqlite3_index_info
485 ** structure.  Used for testing and debugging only.  If neither
486 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
487 ** are no-ops.
488 */
489 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
490 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
491   int i;
492   if( !sqlite3WhereTrace ) return;
493   for(i=0; i<p->nConstraint; i++){
494     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
495        i,
496        p->aConstraint[i].iColumn,
497        p->aConstraint[i].iTermOffset,
498        p->aConstraint[i].op,
499        p->aConstraint[i].usable);
500   }
501   for(i=0; i<p->nOrderBy; i++){
502     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
503        i,
504        p->aOrderBy[i].iColumn,
505        p->aOrderBy[i].desc);
506   }
507 }
508 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
509   int i;
510   if( !sqlite3WhereTrace ) return;
511   for(i=0; i<p->nConstraint; i++){
512     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
513        i,
514        p->aConstraintUsage[i].argvIndex,
515        p->aConstraintUsage[i].omit);
516   }
517   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
518   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
519   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
520   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
521   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
522 }
523 #else
524 #define TRACE_IDX_INPUTS(A)
525 #define TRACE_IDX_OUTPUTS(A)
526 #endif
527 
528 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
529 /*
530 ** Return TRUE if the WHERE clause term pTerm is of a form where it
531 ** could be used with an index to access pSrc, assuming an appropriate
532 ** index existed.
533 */
534 static int termCanDriveIndex(
535   WhereTerm *pTerm,              /* WHERE clause term to check */
536   struct SrcList_item *pSrc,     /* Table we are trying to access */
537   Bitmask notReady               /* Tables in outer loops of the join */
538 ){
539   char aff;
540   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
541   if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
542   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
543   if( pTerm->u.leftColumn<0 ) return 0;
544   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
545   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
546   testcase( pTerm->pExpr->op==TK_IS );
547   return 1;
548 }
549 #endif
550 
551 
552 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
553 /*
554 ** Generate code to construct the Index object for an automatic index
555 ** and to set up the WhereLevel object pLevel so that the code generator
556 ** makes use of the automatic index.
557 */
558 static void constructAutomaticIndex(
559   Parse *pParse,              /* The parsing context */
560   WhereClause *pWC,           /* The WHERE clause */
561   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
562   Bitmask notReady,           /* Mask of cursors that are not available */
563   WhereLevel *pLevel          /* Write new index here */
564 ){
565   int nKeyCol;                /* Number of columns in the constructed index */
566   WhereTerm *pTerm;           /* A single term of the WHERE clause */
567   WhereTerm *pWCEnd;          /* End of pWC->a[] */
568   Index *pIdx;                /* Object describing the transient index */
569   Vdbe *v;                    /* Prepared statement under construction */
570   int addrInit;               /* Address of the initialization bypass jump */
571   Table *pTable;              /* The table being indexed */
572   int addrTop;                /* Top of the index fill loop */
573   int regRecord;              /* Register holding an index record */
574   int n;                      /* Column counter */
575   int i;                      /* Loop counter */
576   int mxBitCol;               /* Maximum column in pSrc->colUsed */
577   CollSeq *pColl;             /* Collating sequence to on a column */
578   WhereLoop *pLoop;           /* The Loop object */
579   char *zNotUsed;             /* Extra space on the end of pIdx */
580   Bitmask idxCols;            /* Bitmap of columns used for indexing */
581   Bitmask extraCols;          /* Bitmap of additional columns */
582   u8 sentWarning = 0;         /* True if a warnning has been issued */
583   Expr *pPartial = 0;         /* Partial Index Expression */
584   int iContinue = 0;          /* Jump here to skip excluded rows */
585   struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
586 
587   /* Generate code to skip over the creation and initialization of the
588   ** transient index on 2nd and subsequent iterations of the loop. */
589   v = pParse->pVdbe;
590   assert( v!=0 );
591   addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
592 
593   /* Count the number of columns that will be added to the index
594   ** and used to match WHERE clause constraints */
595   nKeyCol = 0;
596   pTable = pSrc->pTab;
597   pWCEnd = &pWC->a[pWC->nTerm];
598   pLoop = pLevel->pWLoop;
599   idxCols = 0;
600   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
601     Expr *pExpr = pTerm->pExpr;
602     assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
603          || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
604          || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
605     if( pLoop->prereq==0
606      && (pTerm->wtFlags & TERM_VIRTUAL)==0
607      && !ExprHasProperty(pExpr, EP_FromJoin)
608      && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
609       pPartial = sqlite3ExprAnd(pParse->db, pPartial,
610                                 sqlite3ExprDup(pParse->db, pExpr, 0));
611     }
612     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
613       int iCol = pTerm->u.leftColumn;
614       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
615       testcase( iCol==BMS );
616       testcase( iCol==BMS-1 );
617       if( !sentWarning ){
618         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
619             "automatic index on %s(%s)", pTable->zName,
620             pTable->aCol[iCol].zName);
621         sentWarning = 1;
622       }
623       if( (idxCols & cMask)==0 ){
624         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
625           goto end_auto_index_create;
626         }
627         pLoop->aLTerm[nKeyCol++] = pTerm;
628         idxCols |= cMask;
629       }
630     }
631   }
632   assert( nKeyCol>0 );
633   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
634   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
635                      | WHERE_AUTO_INDEX;
636 
637   /* Count the number of additional columns needed to create a
638   ** covering index.  A "covering index" is an index that contains all
639   ** columns that are needed by the query.  With a covering index, the
640   ** original table never needs to be accessed.  Automatic indices must
641   ** be a covering index because the index will not be updated if the
642   ** original table changes and the index and table cannot both be used
643   ** if they go out of sync.
644   */
645   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
646   mxBitCol = MIN(BMS-1,pTable->nCol);
647   testcase( pTable->nCol==BMS-1 );
648   testcase( pTable->nCol==BMS-2 );
649   for(i=0; i<mxBitCol; i++){
650     if( extraCols & MASKBIT(i) ) nKeyCol++;
651   }
652   if( pSrc->colUsed & MASKBIT(BMS-1) ){
653     nKeyCol += pTable->nCol - BMS + 1;
654   }
655 
656   /* Construct the Index object to describe this index */
657   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
658   if( pIdx==0 ) goto end_auto_index_create;
659   pLoop->u.btree.pIndex = pIdx;
660   pIdx->zName = "auto-index";
661   pIdx->pTable = pTable;
662   n = 0;
663   idxCols = 0;
664   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
665     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
666       int iCol = pTerm->u.leftColumn;
667       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
668       testcase( iCol==BMS-1 );
669       testcase( iCol==BMS );
670       if( (idxCols & cMask)==0 ){
671         Expr *pX = pTerm->pExpr;
672         idxCols |= cMask;
673         pIdx->aiColumn[n] = pTerm->u.leftColumn;
674         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
675         pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
676         n++;
677       }
678     }
679   }
680   assert( (u32)n==pLoop->u.btree.nEq );
681 
682   /* Add additional columns needed to make the automatic index into
683   ** a covering index */
684   for(i=0; i<mxBitCol; i++){
685     if( extraCols & MASKBIT(i) ){
686       pIdx->aiColumn[n] = i;
687       pIdx->azColl[n] = "BINARY";
688       n++;
689     }
690   }
691   if( pSrc->colUsed & MASKBIT(BMS-1) ){
692     for(i=BMS-1; i<pTable->nCol; i++){
693       pIdx->aiColumn[n] = i;
694       pIdx->azColl[n] = "BINARY";
695       n++;
696     }
697   }
698   assert( n==nKeyCol );
699   pIdx->aiColumn[n] = -1;
700   pIdx->azColl[n] = "BINARY";
701 
702   /* Create the automatic index */
703   assert( pLevel->iIdxCur>=0 );
704   pLevel->iIdxCur = pParse->nTab++;
705   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
706   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
707   VdbeComment((v, "for %s", pTable->zName));
708 
709   /* Fill the automatic index with content */
710   sqlite3ExprCachePush(pParse);
711   pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
712   if( pTabItem->viaCoroutine ){
713     int regYield = pTabItem->regReturn;
714     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
715     addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
716     VdbeCoverage(v);
717     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
718   }else{
719     addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
720   }
721   if( pPartial ){
722     iContinue = sqlite3VdbeMakeLabel(v);
723     sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
724     pLoop->wsFlags |= WHERE_PARTIALIDX;
725   }
726   regRecord = sqlite3GetTempReg(pParse);
727   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
728   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
729   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
730   if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
731   if( pTabItem->viaCoroutine ){
732     translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult);
733     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
734     pTabItem->viaCoroutine = 0;
735   }else{
736     sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
737   }
738   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
739   sqlite3VdbeJumpHere(v, addrTop);
740   sqlite3ReleaseTempReg(pParse, regRecord);
741   sqlite3ExprCachePop(pParse);
742 
743   /* Jump here when skipping the initialization */
744   sqlite3VdbeJumpHere(v, addrInit);
745 
746 end_auto_index_create:
747   sqlite3ExprDelete(pParse->db, pPartial);
748 }
749 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
750 
751 #ifndef SQLITE_OMIT_VIRTUALTABLE
752 /*
753 ** Allocate and populate an sqlite3_index_info structure. It is the
754 ** responsibility of the caller to eventually release the structure
755 ** by passing the pointer returned by this function to sqlite3_free().
756 */
757 static sqlite3_index_info *allocateIndexInfo(
758   Parse *pParse,
759   WhereClause *pWC,
760   Bitmask mUnusable,              /* Ignore terms with these prereqs */
761   struct SrcList_item *pSrc,
762   ExprList *pOrderBy
763 ){
764   int i, j;
765   int nTerm;
766   struct sqlite3_index_constraint *pIdxCons;
767   struct sqlite3_index_orderby *pIdxOrderBy;
768   struct sqlite3_index_constraint_usage *pUsage;
769   WhereTerm *pTerm;
770   int nOrderBy;
771   sqlite3_index_info *pIdxInfo;
772 
773   /* Count the number of possible WHERE clause constraints referring
774   ** to this virtual table */
775   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
776     if( pTerm->leftCursor != pSrc->iCursor ) continue;
777     if( pTerm->prereqRight & mUnusable ) continue;
778     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
779     testcase( pTerm->eOperator & WO_IN );
780     testcase( pTerm->eOperator & WO_ISNULL );
781     testcase( pTerm->eOperator & WO_IS );
782     testcase( pTerm->eOperator & WO_ALL );
783     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
784     if( pTerm->wtFlags & TERM_VNULL ) continue;
785     nTerm++;
786   }
787 
788   /* If the ORDER BY clause contains only columns in the current
789   ** virtual table then allocate space for the aOrderBy part of
790   ** the sqlite3_index_info structure.
791   */
792   nOrderBy = 0;
793   if( pOrderBy ){
794     int n = pOrderBy->nExpr;
795     for(i=0; i<n; i++){
796       Expr *pExpr = pOrderBy->a[i].pExpr;
797       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
798     }
799     if( i==n){
800       nOrderBy = n;
801     }
802   }
803 
804   /* Allocate the sqlite3_index_info structure
805   */
806   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
807                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
808                            + sizeof(*pIdxOrderBy)*nOrderBy );
809   if( pIdxInfo==0 ){
810     sqlite3ErrorMsg(pParse, "out of memory");
811     return 0;
812   }
813 
814   /* Initialize the structure.  The sqlite3_index_info structure contains
815   ** many fields that are declared "const" to prevent xBestIndex from
816   ** changing them.  We have to do some funky casting in order to
817   ** initialize those fields.
818   */
819   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
820   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
821   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
822   *(int*)&pIdxInfo->nConstraint = nTerm;
823   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
824   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
825   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
826   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
827                                                                    pUsage;
828 
829   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
830     u8 op;
831     if( pTerm->leftCursor != pSrc->iCursor ) continue;
832     if( pTerm->prereqRight & mUnusable ) continue;
833     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
834     testcase( pTerm->eOperator & WO_IN );
835     testcase( pTerm->eOperator & WO_IS );
836     testcase( pTerm->eOperator & WO_ISNULL );
837     testcase( pTerm->eOperator & WO_ALL );
838     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
839     if( pTerm->wtFlags & TERM_VNULL ) continue;
840     pIdxCons[j].iColumn = pTerm->u.leftColumn;
841     pIdxCons[j].iTermOffset = i;
842     op = (u8)pTerm->eOperator & WO_ALL;
843     if( op==WO_IN ) op = WO_EQ;
844     pIdxCons[j].op = op;
845     /* The direct assignment in the previous line is possible only because
846     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
847     ** following asserts verify this fact. */
848     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
849     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
850     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
851     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
852     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
853     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
854     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
855     j++;
856   }
857   for(i=0; i<nOrderBy; i++){
858     Expr *pExpr = pOrderBy->a[i].pExpr;
859     pIdxOrderBy[i].iColumn = pExpr->iColumn;
860     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
861   }
862 
863   return pIdxInfo;
864 }
865 
866 /*
867 ** The table object reference passed as the second argument to this function
868 ** must represent a virtual table. This function invokes the xBestIndex()
869 ** method of the virtual table with the sqlite3_index_info object that
870 ** comes in as the 3rd argument to this function.
871 **
872 ** If an error occurs, pParse is populated with an error message and a
873 ** non-zero value is returned. Otherwise, 0 is returned and the output
874 ** part of the sqlite3_index_info structure is left populated.
875 **
876 ** Whether or not an error is returned, it is the responsibility of the
877 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
878 ** that this is required.
879 */
880 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
881   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
882   int i;
883   int rc;
884 
885   TRACE_IDX_INPUTS(p);
886   rc = pVtab->pModule->xBestIndex(pVtab, p);
887   TRACE_IDX_OUTPUTS(p);
888 
889   if( rc!=SQLITE_OK ){
890     if( rc==SQLITE_NOMEM ){
891       pParse->db->mallocFailed = 1;
892     }else if( !pVtab->zErrMsg ){
893       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
894     }else{
895       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
896     }
897   }
898   sqlite3_free(pVtab->zErrMsg);
899   pVtab->zErrMsg = 0;
900 
901   for(i=0; i<p->nConstraint; i++){
902     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
903       sqlite3ErrorMsg(pParse,
904           "table %s: xBestIndex returned an invalid plan", pTab->zName);
905     }
906   }
907 
908   return pParse->nErr;
909 }
910 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
911 
912 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
913 /*
914 ** Estimate the location of a particular key among all keys in an
915 ** index.  Store the results in aStat as follows:
916 **
917 **    aStat[0]      Est. number of rows less than pRec
918 **    aStat[1]      Est. number of rows equal to pRec
919 **
920 ** Return the index of the sample that is the smallest sample that
921 ** is greater than or equal to pRec. Note that this index is not an index
922 ** into the aSample[] array - it is an index into a virtual set of samples
923 ** based on the contents of aSample[] and the number of fields in record
924 ** pRec.
925 */
926 static int whereKeyStats(
927   Parse *pParse,              /* Database connection */
928   Index *pIdx,                /* Index to consider domain of */
929   UnpackedRecord *pRec,       /* Vector of values to consider */
930   int roundUp,                /* Round up if true.  Round down if false */
931   tRowcnt *aStat              /* OUT: stats written here */
932 ){
933   IndexSample *aSample = pIdx->aSample;
934   int iCol;                   /* Index of required stats in anEq[] etc. */
935   int i;                      /* Index of first sample >= pRec */
936   int iSample;                /* Smallest sample larger than or equal to pRec */
937   int iMin = 0;               /* Smallest sample not yet tested */
938   int iTest;                  /* Next sample to test */
939   int res;                    /* Result of comparison operation */
940   int nField;                 /* Number of fields in pRec */
941   tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
942 
943 #ifndef SQLITE_DEBUG
944   UNUSED_PARAMETER( pParse );
945 #endif
946   assert( pRec!=0 );
947   assert( pIdx->nSample>0 );
948   assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
949 
950   /* Do a binary search to find the first sample greater than or equal
951   ** to pRec. If pRec contains a single field, the set of samples to search
952   ** is simply the aSample[] array. If the samples in aSample[] contain more
953   ** than one fields, all fields following the first are ignored.
954   **
955   ** If pRec contains N fields, where N is more than one, then as well as the
956   ** samples in aSample[] (truncated to N fields), the search also has to
957   ** consider prefixes of those samples. For example, if the set of samples
958   ** in aSample is:
959   **
960   **     aSample[0] = (a, 5)
961   **     aSample[1] = (a, 10)
962   **     aSample[2] = (b, 5)
963   **     aSample[3] = (c, 100)
964   **     aSample[4] = (c, 105)
965   **
966   ** Then the search space should ideally be the samples above and the
967   ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
968   ** the code actually searches this set:
969   **
970   **     0: (a)
971   **     1: (a, 5)
972   **     2: (a, 10)
973   **     3: (a, 10)
974   **     4: (b)
975   **     5: (b, 5)
976   **     6: (c)
977   **     7: (c, 100)
978   **     8: (c, 105)
979   **     9: (c, 105)
980   **
981   ** For each sample in the aSample[] array, N samples are present in the
982   ** effective sample array. In the above, samples 0 and 1 are based on
983   ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
984   **
985   ** Often, sample i of each block of N effective samples has (i+1) fields.
986   ** Except, each sample may be extended to ensure that it is greater than or
987   ** equal to the previous sample in the array. For example, in the above,
988   ** sample 2 is the first sample of a block of N samples, so at first it
989   ** appears that it should be 1 field in size. However, that would make it
990   ** smaller than sample 1, so the binary search would not work. As a result,
991   ** it is extended to two fields. The duplicates that this creates do not
992   ** cause any problems.
993   */
994   nField = pRec->nField;
995   iCol = 0;
996   iSample = pIdx->nSample * nField;
997   do{
998     int iSamp;                    /* Index in aSample[] of test sample */
999     int n;                        /* Number of fields in test sample */
1000 
1001     iTest = (iMin+iSample)/2;
1002     iSamp = iTest / nField;
1003     if( iSamp>0 ){
1004       /* The proposed effective sample is a prefix of sample aSample[iSamp].
1005       ** Specifically, the shortest prefix of at least (1 + iTest%nField)
1006       ** fields that is greater than the previous effective sample.  */
1007       for(n=(iTest % nField) + 1; n<nField; n++){
1008         if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
1009       }
1010     }else{
1011       n = iTest + 1;
1012     }
1013 
1014     pRec->nField = n;
1015     res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
1016     if( res<0 ){
1017       iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
1018       iMin = iTest+1;
1019     }else if( res==0 && n<nField ){
1020       iLower = aSample[iSamp].anLt[n-1];
1021       iMin = iTest+1;
1022       res = -1;
1023     }else{
1024       iSample = iTest;
1025       iCol = n-1;
1026     }
1027   }while( res && iMin<iSample );
1028   i = iSample / nField;
1029 
1030 #ifdef SQLITE_DEBUG
1031   /* The following assert statements check that the binary search code
1032   ** above found the right answer. This block serves no purpose other
1033   ** than to invoke the asserts.  */
1034   if( pParse->db->mallocFailed==0 ){
1035     if( res==0 ){
1036       /* If (res==0) is true, then pRec must be equal to sample i. */
1037       assert( i<pIdx->nSample );
1038       assert( iCol==nField-1 );
1039       pRec->nField = nField;
1040       assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
1041            || pParse->db->mallocFailed
1042       );
1043     }else{
1044       /* Unless i==pIdx->nSample, indicating that pRec is larger than
1045       ** all samples in the aSample[] array, pRec must be smaller than the
1046       ** (iCol+1) field prefix of sample i.  */
1047       assert( i<=pIdx->nSample && i>=0 );
1048       pRec->nField = iCol+1;
1049       assert( i==pIdx->nSample
1050            || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
1051            || pParse->db->mallocFailed );
1052 
1053       /* if i==0 and iCol==0, then record pRec is smaller than all samples
1054       ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
1055       ** be greater than or equal to the (iCol) field prefix of sample i.
1056       ** If (i>0), then pRec must also be greater than sample (i-1).  */
1057       if( iCol>0 ){
1058         pRec->nField = iCol;
1059         assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
1060              || pParse->db->mallocFailed );
1061       }
1062       if( i>0 ){
1063         pRec->nField = nField;
1064         assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
1065              || pParse->db->mallocFailed );
1066       }
1067     }
1068   }
1069 #endif /* ifdef SQLITE_DEBUG */
1070 
1071   if( res==0 ){
1072     /* Record pRec is equal to sample i */
1073     assert( iCol==nField-1 );
1074     aStat[0] = aSample[i].anLt[iCol];
1075     aStat[1] = aSample[i].anEq[iCol];
1076   }else{
1077     /* At this point, the (iCol+1) field prefix of aSample[i] is the first
1078     ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
1079     ** is larger than all samples in the array. */
1080     tRowcnt iUpper, iGap;
1081     if( i>=pIdx->nSample ){
1082       iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
1083     }else{
1084       iUpper = aSample[i].anLt[iCol];
1085     }
1086 
1087     if( iLower>=iUpper ){
1088       iGap = 0;
1089     }else{
1090       iGap = iUpper - iLower;
1091     }
1092     if( roundUp ){
1093       iGap = (iGap*2)/3;
1094     }else{
1095       iGap = iGap/3;
1096     }
1097     aStat[0] = iLower + iGap;
1098     aStat[1] = pIdx->aAvgEq[iCol];
1099   }
1100 
1101   /* Restore the pRec->nField value before returning.  */
1102   pRec->nField = nField;
1103   return i;
1104 }
1105 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1106 
1107 /*
1108 ** If it is not NULL, pTerm is a term that provides an upper or lower
1109 ** bound on a range scan. Without considering pTerm, it is estimated
1110 ** that the scan will visit nNew rows. This function returns the number
1111 ** estimated to be visited after taking pTerm into account.
1112 **
1113 ** If the user explicitly specified a likelihood() value for this term,
1114 ** then the return value is the likelihood multiplied by the number of
1115 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
1116 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
1117 */
1118 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
1119   LogEst nRet = nNew;
1120   if( pTerm ){
1121     if( pTerm->truthProb<=0 ){
1122       nRet += pTerm->truthProb;
1123     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
1124       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
1125     }
1126   }
1127   return nRet;
1128 }
1129 
1130 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1131 /*
1132 ** This function is called to estimate the number of rows visited by a
1133 ** range-scan on a skip-scan index. For example:
1134 **
1135 **   CREATE INDEX i1 ON t1(a, b, c);
1136 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
1137 **
1138 ** Value pLoop->nOut is currently set to the estimated number of rows
1139 ** visited for scanning (a=? AND b=?). This function reduces that estimate
1140 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
1141 ** on the stat4 data for the index. this scan will be peformed multiple
1142 ** times (once for each (a,b) combination that matches a=?) is dealt with
1143 ** by the caller.
1144 **
1145 ** It does this by scanning through all stat4 samples, comparing values
1146 ** extracted from pLower and pUpper with the corresponding column in each
1147 ** sample. If L and U are the number of samples found to be less than or
1148 ** equal to the values extracted from pLower and pUpper respectively, and
1149 ** N is the total number of samples, the pLoop->nOut value is adjusted
1150 ** as follows:
1151 **
1152 **   nOut = nOut * ( min(U - L, 1) / N )
1153 **
1154 ** If pLower is NULL, or a value cannot be extracted from the term, L is
1155 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
1156 ** U is set to N.
1157 **
1158 ** Normally, this function sets *pbDone to 1 before returning. However,
1159 ** if no value can be extracted from either pLower or pUpper (and so the
1160 ** estimate of the number of rows delivered remains unchanged), *pbDone
1161 ** is left as is.
1162 **
1163 ** If an error occurs, an SQLite error code is returned. Otherwise,
1164 ** SQLITE_OK.
1165 */
1166 static int whereRangeSkipScanEst(
1167   Parse *pParse,       /* Parsing & code generating context */
1168   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
1169   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
1170   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
1171   int *pbDone          /* Set to true if at least one expr. value extracted */
1172 ){
1173   Index *p = pLoop->u.btree.pIndex;
1174   int nEq = pLoop->u.btree.nEq;
1175   sqlite3 *db = pParse->db;
1176   int nLower = -1;
1177   int nUpper = p->nSample+1;
1178   int rc = SQLITE_OK;
1179   int iCol = p->aiColumn[nEq];
1180   u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
1181   CollSeq *pColl;
1182 
1183   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
1184   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
1185   sqlite3_value *pVal = 0;        /* Value extracted from record */
1186 
1187   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
1188   if( pLower ){
1189     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
1190     nLower = 0;
1191   }
1192   if( pUpper && rc==SQLITE_OK ){
1193     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
1194     nUpper = p2 ? 0 : p->nSample;
1195   }
1196 
1197   if( p1 || p2 ){
1198     int i;
1199     int nDiff;
1200     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
1201       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
1202       if( rc==SQLITE_OK && p1 ){
1203         int res = sqlite3MemCompare(p1, pVal, pColl);
1204         if( res>=0 ) nLower++;
1205       }
1206       if( rc==SQLITE_OK && p2 ){
1207         int res = sqlite3MemCompare(p2, pVal, pColl);
1208         if( res>=0 ) nUpper++;
1209       }
1210     }
1211     nDiff = (nUpper - nLower);
1212     if( nDiff<=0 ) nDiff = 1;
1213 
1214     /* If there is both an upper and lower bound specified, and the
1215     ** comparisons indicate that they are close together, use the fallback
1216     ** method (assume that the scan visits 1/64 of the rows) for estimating
1217     ** the number of rows visited. Otherwise, estimate the number of rows
1218     ** using the method described in the header comment for this function. */
1219     if( nDiff!=1 || pUpper==0 || pLower==0 ){
1220       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
1221       pLoop->nOut -= nAdjust;
1222       *pbDone = 1;
1223       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
1224                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
1225     }
1226 
1227   }else{
1228     assert( *pbDone==0 );
1229   }
1230 
1231   sqlite3ValueFree(p1);
1232   sqlite3ValueFree(p2);
1233   sqlite3ValueFree(pVal);
1234 
1235   return rc;
1236 }
1237 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1238 
1239 /*
1240 ** This function is used to estimate the number of rows that will be visited
1241 ** by scanning an index for a range of values. The range may have an upper
1242 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
1243 ** and lower bounds are represented by pLower and pUpper respectively. For
1244 ** example, assuming that index p is on t1(a):
1245 **
1246 **   ... FROM t1 WHERE a > ? AND a < ? ...
1247 **                    |_____|   |_____|
1248 **                       |         |
1249 **                     pLower    pUpper
1250 **
1251 ** If either of the upper or lower bound is not present, then NULL is passed in
1252 ** place of the corresponding WhereTerm.
1253 **
1254 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
1255 ** column subject to the range constraint. Or, equivalently, the number of
1256 ** equality constraints optimized by the proposed index scan. For example,
1257 ** assuming index p is on t1(a, b), and the SQL query is:
1258 **
1259 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
1260 **
1261 ** then nEq is set to 1 (as the range restricted column, b, is the second
1262 ** left-most column of the index). Or, if the query is:
1263 **
1264 **   ... FROM t1 WHERE a > ? AND a < ? ...
1265 **
1266 ** then nEq is set to 0.
1267 **
1268 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
1269 ** number of rows that the index scan is expected to visit without
1270 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
1271 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
1272 ** to account for the range constraints pLower and pUpper.
1273 **
1274 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
1275 ** used, a single range inequality reduces the search space by a factor of 4.
1276 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
1277 ** rows visited by a factor of 64.
1278 */
1279 static int whereRangeScanEst(
1280   Parse *pParse,       /* Parsing & code generating context */
1281   WhereLoopBuilder *pBuilder,
1282   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
1283   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
1284   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
1285 ){
1286   int rc = SQLITE_OK;
1287   int nOut = pLoop->nOut;
1288   LogEst nNew;
1289 
1290 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1291   Index *p = pLoop->u.btree.pIndex;
1292   int nEq = pLoop->u.btree.nEq;
1293 
1294   if( p->nSample>0 && nEq<p->nSampleCol ){
1295     if( nEq==pBuilder->nRecValid ){
1296       UnpackedRecord *pRec = pBuilder->pRec;
1297       tRowcnt a[2];
1298       u8 aff;
1299 
1300       /* Variable iLower will be set to the estimate of the number of rows in
1301       ** the index that are less than the lower bound of the range query. The
1302       ** lower bound being the concatenation of $P and $L, where $P is the
1303       ** key-prefix formed by the nEq values matched against the nEq left-most
1304       ** columns of the index, and $L is the value in pLower.
1305       **
1306       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
1307       ** is not a simple variable or literal value), the lower bound of the
1308       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
1309       ** if $L is available, whereKeyStats() is called for both ($P) and
1310       ** ($P:$L) and the larger of the two returned values is used.
1311       **
1312       ** Similarly, iUpper is to be set to the estimate of the number of rows
1313       ** less than the upper bound of the range query. Where the upper bound
1314       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
1315       ** of iUpper are requested of whereKeyStats() and the smaller used.
1316       **
1317       ** The number of rows between the two bounds is then just iUpper-iLower.
1318       */
1319       tRowcnt iLower;     /* Rows less than the lower bound */
1320       tRowcnt iUpper;     /* Rows less than the upper bound */
1321       int iLwrIdx = -2;   /* aSample[] for the lower bound */
1322       int iUprIdx = -1;   /* aSample[] for the upper bound */
1323 
1324       if( pRec ){
1325         testcase( pRec->nField!=pBuilder->nRecValid );
1326         pRec->nField = pBuilder->nRecValid;
1327       }
1328       if( nEq==p->nKeyCol ){
1329         aff = SQLITE_AFF_INTEGER;
1330       }else{
1331         aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
1332       }
1333       /* Determine iLower and iUpper using ($P) only. */
1334       if( nEq==0 ){
1335         iLower = 0;
1336         iUpper = p->nRowEst0;
1337       }else{
1338         /* Note: this call could be optimized away - since the same values must
1339         ** have been requested when testing key $P in whereEqualScanEst().  */
1340         whereKeyStats(pParse, p, pRec, 0, a);
1341         iLower = a[0];
1342         iUpper = a[0] + a[1];
1343       }
1344 
1345       assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
1346       assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
1347       assert( p->aSortOrder!=0 );
1348       if( p->aSortOrder[nEq] ){
1349         /* The roles of pLower and pUpper are swapped for a DESC index */
1350         SWAP(WhereTerm*, pLower, pUpper);
1351       }
1352 
1353       /* If possible, improve on the iLower estimate using ($P:$L). */
1354       if( pLower ){
1355         int bOk;                    /* True if value is extracted from pExpr */
1356         Expr *pExpr = pLower->pExpr->pRight;
1357         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
1358         if( rc==SQLITE_OK && bOk ){
1359           tRowcnt iNew;
1360           iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
1361           iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
1362           if( iNew>iLower ) iLower = iNew;
1363           nOut--;
1364           pLower = 0;
1365         }
1366       }
1367 
1368       /* If possible, improve on the iUpper estimate using ($P:$U). */
1369       if( pUpper ){
1370         int bOk;                    /* True if value is extracted from pExpr */
1371         Expr *pExpr = pUpper->pExpr->pRight;
1372         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
1373         if( rc==SQLITE_OK && bOk ){
1374           tRowcnt iNew;
1375           iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
1376           iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
1377           if( iNew<iUpper ) iUpper = iNew;
1378           nOut--;
1379           pUpper = 0;
1380         }
1381       }
1382 
1383       pBuilder->pRec = pRec;
1384       if( rc==SQLITE_OK ){
1385         if( iUpper>iLower ){
1386           nNew = sqlite3LogEst(iUpper - iLower);
1387           /* TUNING:  If both iUpper and iLower are derived from the same
1388           ** sample, then assume they are 4x more selective.  This brings
1389           ** the estimated selectivity more in line with what it would be
1390           ** if estimated without the use of STAT3/4 tables. */
1391           if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
1392         }else{
1393           nNew = 10;        assert( 10==sqlite3LogEst(2) );
1394         }
1395         if( nNew<nOut ){
1396           nOut = nNew;
1397         }
1398         WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
1399                            (u32)iLower, (u32)iUpper, nOut));
1400       }
1401     }else{
1402       int bDone = 0;
1403       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
1404       if( bDone ) return rc;
1405     }
1406   }
1407 #else
1408   UNUSED_PARAMETER(pParse);
1409   UNUSED_PARAMETER(pBuilder);
1410   assert( pLower || pUpper );
1411 #endif
1412   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
1413   nNew = whereRangeAdjust(pLower, nOut);
1414   nNew = whereRangeAdjust(pUpper, nNew);
1415 
1416   /* TUNING: If there is both an upper and lower limit and neither limit
1417   ** has an application-defined likelihood(), assume the range is
1418   ** reduced by an additional 75%. This means that, by default, an open-ended
1419   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
1420   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
1421   ** match 1/64 of the index. */
1422   if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
1423     nNew -= 20;
1424   }
1425 
1426   nOut -= (pLower!=0) + (pUpper!=0);
1427   if( nNew<10 ) nNew = 10;
1428   if( nNew<nOut ) nOut = nNew;
1429 #if defined(WHERETRACE_ENABLED)
1430   if( pLoop->nOut>nOut ){
1431     WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
1432                     pLoop->nOut, nOut));
1433   }
1434 #endif
1435   pLoop->nOut = (LogEst)nOut;
1436   return rc;
1437 }
1438 
1439 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1440 /*
1441 ** Estimate the number of rows that will be returned based on
1442 ** an equality constraint x=VALUE and where that VALUE occurs in
1443 ** the histogram data.  This only works when x is the left-most
1444 ** column of an index and sqlite_stat3 histogram data is available
1445 ** for that index.  When pExpr==NULL that means the constraint is
1446 ** "x IS NULL" instead of "x=VALUE".
1447 **
1448 ** Write the estimated row count into *pnRow and return SQLITE_OK.
1449 ** If unable to make an estimate, leave *pnRow unchanged and return
1450 ** non-zero.
1451 **
1452 ** This routine can fail if it is unable to load a collating sequence
1453 ** required for string comparison, or if unable to allocate memory
1454 ** for a UTF conversion required for comparison.  The error is stored
1455 ** in the pParse structure.
1456 */
1457 static int whereEqualScanEst(
1458   Parse *pParse,       /* Parsing & code generating context */
1459   WhereLoopBuilder *pBuilder,
1460   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
1461   tRowcnt *pnRow       /* Write the revised row estimate here */
1462 ){
1463   Index *p = pBuilder->pNew->u.btree.pIndex;
1464   int nEq = pBuilder->pNew->u.btree.nEq;
1465   UnpackedRecord *pRec = pBuilder->pRec;
1466   u8 aff;                   /* Column affinity */
1467   int rc;                   /* Subfunction return code */
1468   tRowcnt a[2];             /* Statistics */
1469   int bOk;
1470 
1471   assert( nEq>=1 );
1472   assert( nEq<=p->nColumn );
1473   assert( p->aSample!=0 );
1474   assert( p->nSample>0 );
1475   assert( pBuilder->nRecValid<nEq );
1476 
1477   /* If values are not available for all fields of the index to the left
1478   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
1479   if( pBuilder->nRecValid<(nEq-1) ){
1480     return SQLITE_NOTFOUND;
1481   }
1482 
1483   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
1484   ** below would return the same value.  */
1485   if( nEq>=p->nColumn ){
1486     *pnRow = 1;
1487     return SQLITE_OK;
1488   }
1489 
1490   aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
1491   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
1492   pBuilder->pRec = pRec;
1493   if( rc!=SQLITE_OK ) return rc;
1494   if( bOk==0 ) return SQLITE_NOTFOUND;
1495   pBuilder->nRecValid = nEq;
1496 
1497   whereKeyStats(pParse, p, pRec, 0, a);
1498   WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
1499   *pnRow = a[1];
1500 
1501   return rc;
1502 }
1503 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1504 
1505 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1506 /*
1507 ** Estimate the number of rows that will be returned based on
1508 ** an IN constraint where the right-hand side of the IN operator
1509 ** is a list of values.  Example:
1510 **
1511 **        WHERE x IN (1,2,3,4)
1512 **
1513 ** Write the estimated row count into *pnRow and return SQLITE_OK.
1514 ** If unable to make an estimate, leave *pnRow unchanged and return
1515 ** non-zero.
1516 **
1517 ** This routine can fail if it is unable to load a collating sequence
1518 ** required for string comparison, or if unable to allocate memory
1519 ** for a UTF conversion required for comparison.  The error is stored
1520 ** in the pParse structure.
1521 */
1522 static int whereInScanEst(
1523   Parse *pParse,       /* Parsing & code generating context */
1524   WhereLoopBuilder *pBuilder,
1525   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
1526   tRowcnt *pnRow       /* Write the revised row estimate here */
1527 ){
1528   Index *p = pBuilder->pNew->u.btree.pIndex;
1529   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
1530   int nRecValid = pBuilder->nRecValid;
1531   int rc = SQLITE_OK;     /* Subfunction return code */
1532   tRowcnt nEst;           /* Number of rows for a single term */
1533   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
1534   int i;                  /* Loop counter */
1535 
1536   assert( p->aSample!=0 );
1537   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
1538     nEst = nRow0;
1539     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
1540     nRowEst += nEst;
1541     pBuilder->nRecValid = nRecValid;
1542   }
1543 
1544   if( rc==SQLITE_OK ){
1545     if( nRowEst > nRow0 ) nRowEst = nRow0;
1546     *pnRow = nRowEst;
1547     WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
1548   }
1549   assert( pBuilder->nRecValid==nRecValid );
1550   return rc;
1551 }
1552 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1553 
1554 
1555 #ifdef WHERETRACE_ENABLED
1556 /*
1557 ** Print the content of a WhereTerm object
1558 */
1559 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
1560   if( pTerm==0 ){
1561     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
1562   }else{
1563     char zType[4];
1564     memcpy(zType, "...", 4);
1565     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
1566     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
1567     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
1568     sqlite3DebugPrintf(
1569        "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
1570        iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
1571        pTerm->eOperator, pTerm->wtFlags);
1572     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
1573   }
1574 }
1575 #endif
1576 
1577 #ifdef WHERETRACE_ENABLED
1578 /*
1579 ** Print a WhereLoop object for debugging purposes
1580 */
1581 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
1582   WhereInfo *pWInfo = pWC->pWInfo;
1583   int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
1584   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
1585   Table *pTab = pItem->pTab;
1586   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
1587                      p->iTab, nb, p->maskSelf, nb, p->prereq);
1588   sqlite3DebugPrintf(" %12s",
1589                      pItem->zAlias ? pItem->zAlias : pTab->zName);
1590   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
1591     const char *zName;
1592     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
1593       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
1594         int i = sqlite3Strlen30(zName) - 1;
1595         while( zName[i]!='_' ) i--;
1596         zName += i;
1597       }
1598       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
1599     }else{
1600       sqlite3DebugPrintf("%20s","");
1601     }
1602   }else{
1603     char *z;
1604     if( p->u.vtab.idxStr ){
1605       z = sqlite3_mprintf("(%d,\"%s\",%x)",
1606                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
1607     }else{
1608       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
1609     }
1610     sqlite3DebugPrintf(" %-19s", z);
1611     sqlite3_free(z);
1612   }
1613   if( p->wsFlags & WHERE_SKIPSCAN ){
1614     sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
1615   }else{
1616     sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
1617   }
1618   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
1619   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
1620     int i;
1621     for(i=0; i<p->nLTerm; i++){
1622       whereTermPrint(p->aLTerm[i], i);
1623     }
1624   }
1625 }
1626 #endif
1627 
1628 /*
1629 ** Convert bulk memory into a valid WhereLoop that can be passed
1630 ** to whereLoopClear harmlessly.
1631 */
1632 static void whereLoopInit(WhereLoop *p){
1633   p->aLTerm = p->aLTermSpace;
1634   p->nLTerm = 0;
1635   p->nLSlot = ArraySize(p->aLTermSpace);
1636   p->wsFlags = 0;
1637 }
1638 
1639 /*
1640 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
1641 */
1642 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
1643   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
1644     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
1645       sqlite3_free(p->u.vtab.idxStr);
1646       p->u.vtab.needFree = 0;
1647       p->u.vtab.idxStr = 0;
1648     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
1649       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
1650       sqlite3DbFree(db, p->u.btree.pIndex);
1651       p->u.btree.pIndex = 0;
1652     }
1653   }
1654 }
1655 
1656 /*
1657 ** Deallocate internal memory used by a WhereLoop object
1658 */
1659 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
1660   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
1661   whereLoopClearUnion(db, p);
1662   whereLoopInit(p);
1663 }
1664 
1665 /*
1666 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
1667 */
1668 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
1669   WhereTerm **paNew;
1670   if( p->nLSlot>=n ) return SQLITE_OK;
1671   n = (n+7)&~7;
1672   paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
1673   if( paNew==0 ) return SQLITE_NOMEM;
1674   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
1675   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
1676   p->aLTerm = paNew;
1677   p->nLSlot = n;
1678   return SQLITE_OK;
1679 }
1680 
1681 /*
1682 ** Transfer content from the second pLoop into the first.
1683 */
1684 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
1685   whereLoopClearUnion(db, pTo);
1686   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
1687     memset(&pTo->u, 0, sizeof(pTo->u));
1688     return SQLITE_NOMEM;
1689   }
1690   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
1691   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
1692   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
1693     pFrom->u.vtab.needFree = 0;
1694   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
1695     pFrom->u.btree.pIndex = 0;
1696   }
1697   return SQLITE_OK;
1698 }
1699 
1700 /*
1701 ** Delete a WhereLoop object
1702 */
1703 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
1704   whereLoopClear(db, p);
1705   sqlite3DbFree(db, p);
1706 }
1707 
1708 /*
1709 ** Free a WhereInfo structure
1710 */
1711 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
1712   if( ALWAYS(pWInfo) ){
1713     int i;
1714     for(i=0; i<pWInfo->nLevel; i++){
1715       WhereLevel *pLevel = &pWInfo->a[i];
1716       if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
1717         sqlite3DbFree(db, pLevel->u.in.aInLoop);
1718       }
1719     }
1720     sqlite3WhereClauseClear(&pWInfo->sWC);
1721     while( pWInfo->pLoops ){
1722       WhereLoop *p = pWInfo->pLoops;
1723       pWInfo->pLoops = p->pNextLoop;
1724       whereLoopDelete(db, p);
1725     }
1726     sqlite3DbFree(db, pWInfo);
1727   }
1728 }
1729 
1730 /*
1731 ** Return TRUE if all of the following are true:
1732 **
1733 **   (1)  X has the same or lower cost that Y
1734 **   (2)  X is a proper subset of Y
1735 **   (3)  X skips at least as many columns as Y
1736 **
1737 ** By "proper subset" we mean that X uses fewer WHERE clause terms
1738 ** than Y and that every WHERE clause term used by X is also used
1739 ** by Y.
1740 **
1741 ** If X is a proper subset of Y then Y is a better choice and ought
1742 ** to have a lower cost.  This routine returns TRUE when that cost
1743 ** relationship is inverted and needs to be adjusted.  The third rule
1744 ** was added because if X uses skip-scan less than Y it still might
1745 ** deserve a lower cost even if it is a proper subset of Y.
1746 */
1747 static int whereLoopCheaperProperSubset(
1748   const WhereLoop *pX,       /* First WhereLoop to compare */
1749   const WhereLoop *pY        /* Compare against this WhereLoop */
1750 ){
1751   int i, j;
1752   if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
1753     return 0; /* X is not a subset of Y */
1754   }
1755   if( pY->nSkip > pX->nSkip ) return 0;
1756   if( pX->rRun >= pY->rRun ){
1757     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
1758     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
1759   }
1760   for(i=pX->nLTerm-1; i>=0; i--){
1761     if( pX->aLTerm[i]==0 ) continue;
1762     for(j=pY->nLTerm-1; j>=0; j--){
1763       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
1764     }
1765     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
1766   }
1767   return 1;  /* All conditions meet */
1768 }
1769 
1770 /*
1771 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
1772 ** that:
1773 **
1774 **   (1) pTemplate costs less than any other WhereLoops that are a proper
1775 **       subset of pTemplate
1776 **
1777 **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
1778 **       is a proper subset.
1779 **
1780 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
1781 ** WHERE clause terms than Y and that every WHERE clause term used by X is
1782 ** also used by Y.
1783 */
1784 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
1785   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
1786   for(; p; p=p->pNextLoop){
1787     if( p->iTab!=pTemplate->iTab ) continue;
1788     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
1789     if( whereLoopCheaperProperSubset(p, pTemplate) ){
1790       /* Adjust pTemplate cost downward so that it is cheaper than its
1791       ** subset p. */
1792       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
1793                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
1794       pTemplate->rRun = p->rRun;
1795       pTemplate->nOut = p->nOut - 1;
1796     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
1797       /* Adjust pTemplate cost upward so that it is costlier than p since
1798       ** pTemplate is a proper subset of p */
1799       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
1800                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
1801       pTemplate->rRun = p->rRun;
1802       pTemplate->nOut = p->nOut + 1;
1803     }
1804   }
1805 }
1806 
1807 /*
1808 ** Search the list of WhereLoops in *ppPrev looking for one that can be
1809 ** supplanted by pTemplate.
1810 **
1811 ** Return NULL if the WhereLoop list contains an entry that can supplant
1812 ** pTemplate, in other words if pTemplate does not belong on the list.
1813 **
1814 ** If pX is a WhereLoop that pTemplate can supplant, then return the
1815 ** link that points to pX.
1816 **
1817 ** If pTemplate cannot supplant any existing element of the list but needs
1818 ** to be added to the list, then return a pointer to the tail of the list.
1819 */
1820 static WhereLoop **whereLoopFindLesser(
1821   WhereLoop **ppPrev,
1822   const WhereLoop *pTemplate
1823 ){
1824   WhereLoop *p;
1825   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
1826     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
1827       /* If either the iTab or iSortIdx values for two WhereLoop are different
1828       ** then those WhereLoops need to be considered separately.  Neither is
1829       ** a candidate to replace the other. */
1830       continue;
1831     }
1832     /* In the current implementation, the rSetup value is either zero
1833     ** or the cost of building an automatic index (NlogN) and the NlogN
1834     ** is the same for compatible WhereLoops. */
1835     assert( p->rSetup==0 || pTemplate->rSetup==0
1836                  || p->rSetup==pTemplate->rSetup );
1837 
1838     /* whereLoopAddBtree() always generates and inserts the automatic index
1839     ** case first.  Hence compatible candidate WhereLoops never have a larger
1840     ** rSetup. Call this SETUP-INVARIANT */
1841     assert( p->rSetup>=pTemplate->rSetup );
1842 
1843     /* Any loop using an appliation-defined index (or PRIMARY KEY or
1844     ** UNIQUE constraint) with one or more == constraints is better
1845     ** than an automatic index. Unless it is a skip-scan. */
1846     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
1847      && (pTemplate->nSkip)==0
1848      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
1849      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
1850      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
1851     ){
1852       break;
1853     }
1854 
1855     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
1856     ** discarded.  WhereLoop p is better if:
1857     **   (1)  p has no more dependencies than pTemplate, and
1858     **   (2)  p has an equal or lower cost than pTemplate
1859     */
1860     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
1861      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
1862      && p->rRun<=pTemplate->rRun                      /* (2b) */
1863      && p->nOut<=pTemplate->nOut                      /* (2c) */
1864     ){
1865       return 0;  /* Discard pTemplate */
1866     }
1867 
1868     /* If pTemplate is always better than p, then cause p to be overwritten
1869     ** with pTemplate.  pTemplate is better than p if:
1870     **   (1)  pTemplate has no more dependences than p, and
1871     **   (2)  pTemplate has an equal or lower cost than p.
1872     */
1873     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
1874      && p->rRun>=pTemplate->rRun                             /* (2a) */
1875      && p->nOut>=pTemplate->nOut                             /* (2b) */
1876     ){
1877       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
1878       break;   /* Cause p to be overwritten by pTemplate */
1879     }
1880   }
1881   return ppPrev;
1882 }
1883 
1884 /*
1885 ** Insert or replace a WhereLoop entry using the template supplied.
1886 **
1887 ** An existing WhereLoop entry might be overwritten if the new template
1888 ** is better and has fewer dependencies.  Or the template will be ignored
1889 ** and no insert will occur if an existing WhereLoop is faster and has
1890 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
1891 ** added based on the template.
1892 **
1893 ** If pBuilder->pOrSet is not NULL then we care about only the
1894 ** prerequisites and rRun and nOut costs of the N best loops.  That
1895 ** information is gathered in the pBuilder->pOrSet object.  This special
1896 ** processing mode is used only for OR clause processing.
1897 **
1898 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
1899 ** still might overwrite similar loops with the new template if the
1900 ** new template is better.  Loops may be overwritten if the following
1901 ** conditions are met:
1902 **
1903 **    (1)  They have the same iTab.
1904 **    (2)  They have the same iSortIdx.
1905 **    (3)  The template has same or fewer dependencies than the current loop
1906 **    (4)  The template has the same or lower cost than the current loop
1907 */
1908 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
1909   WhereLoop **ppPrev, *p;
1910   WhereInfo *pWInfo = pBuilder->pWInfo;
1911   sqlite3 *db = pWInfo->pParse->db;
1912 
1913   /* If pBuilder->pOrSet is defined, then only keep track of the costs
1914   ** and prereqs.
1915   */
1916   if( pBuilder->pOrSet!=0 ){
1917 #if WHERETRACE_ENABLED
1918     u16 n = pBuilder->pOrSet->n;
1919     int x =
1920 #endif
1921     whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
1922                                     pTemplate->nOut);
1923 #if WHERETRACE_ENABLED /* 0x8 */
1924     if( sqlite3WhereTrace & 0x8 ){
1925       sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
1926       whereLoopPrint(pTemplate, pBuilder->pWC);
1927     }
1928 #endif
1929     return SQLITE_OK;
1930   }
1931 
1932   /* Look for an existing WhereLoop to replace with pTemplate
1933   */
1934   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
1935   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
1936 
1937   if( ppPrev==0 ){
1938     /* There already exists a WhereLoop on the list that is better
1939     ** than pTemplate, so just ignore pTemplate */
1940 #if WHERETRACE_ENABLED /* 0x8 */
1941     if( sqlite3WhereTrace & 0x8 ){
1942       sqlite3DebugPrintf("   skip: ");
1943       whereLoopPrint(pTemplate, pBuilder->pWC);
1944     }
1945 #endif
1946     return SQLITE_OK;
1947   }else{
1948     p = *ppPrev;
1949   }
1950 
1951   /* If we reach this point it means that either p[] should be overwritten
1952   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
1953   ** WhereLoop and insert it.
1954   */
1955 #if WHERETRACE_ENABLED /* 0x8 */
1956   if( sqlite3WhereTrace & 0x8 ){
1957     if( p!=0 ){
1958       sqlite3DebugPrintf("replace: ");
1959       whereLoopPrint(p, pBuilder->pWC);
1960     }
1961     sqlite3DebugPrintf("    add: ");
1962     whereLoopPrint(pTemplate, pBuilder->pWC);
1963   }
1964 #endif
1965   if( p==0 ){
1966     /* Allocate a new WhereLoop to add to the end of the list */
1967     *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
1968     if( p==0 ) return SQLITE_NOMEM;
1969     whereLoopInit(p);
1970     p->pNextLoop = 0;
1971   }else{
1972     /* We will be overwriting WhereLoop p[].  But before we do, first
1973     ** go through the rest of the list and delete any other entries besides
1974     ** p[] that are also supplated by pTemplate */
1975     WhereLoop **ppTail = &p->pNextLoop;
1976     WhereLoop *pToDel;
1977     while( *ppTail ){
1978       ppTail = whereLoopFindLesser(ppTail, pTemplate);
1979       if( ppTail==0 ) break;
1980       pToDel = *ppTail;
1981       if( pToDel==0 ) break;
1982       *ppTail = pToDel->pNextLoop;
1983 #if WHERETRACE_ENABLED /* 0x8 */
1984       if( sqlite3WhereTrace & 0x8 ){
1985         sqlite3DebugPrintf(" delete: ");
1986         whereLoopPrint(pToDel, pBuilder->pWC);
1987       }
1988 #endif
1989       whereLoopDelete(db, pToDel);
1990     }
1991   }
1992   whereLoopXfer(db, p, pTemplate);
1993   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
1994     Index *pIndex = p->u.btree.pIndex;
1995     if( pIndex && pIndex->tnum==0 ){
1996       p->u.btree.pIndex = 0;
1997     }
1998   }
1999   return SQLITE_OK;
2000 }
2001 
2002 /*
2003 ** Adjust the WhereLoop.nOut value downward to account for terms of the
2004 ** WHERE clause that reference the loop but which are not used by an
2005 ** index.
2006 *
2007 ** For every WHERE clause term that is not used by the index
2008 ** and which has a truth probability assigned by one of the likelihood(),
2009 ** likely(), or unlikely() SQL functions, reduce the estimated number
2010 ** of output rows by the probability specified.
2011 **
2012 ** TUNING:  For every WHERE clause term that is not used by the index
2013 ** and which does not have an assigned truth probability, heuristics
2014 ** described below are used to try to estimate the truth probability.
2015 ** TODO --> Perhaps this is something that could be improved by better
2016 ** table statistics.
2017 **
2018 ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
2019 ** value corresponds to -1 in LogEst notation, so this means decrement
2020 ** the WhereLoop.nOut field for every such WHERE clause term.
2021 **
2022 ** Heuristic 2:  If there exists one or more WHERE clause terms of the
2023 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
2024 ** final output row estimate is no greater than 1/4 of the total number
2025 ** of rows in the table.  In other words, assume that x==EXPR will filter
2026 ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
2027 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
2028 ** on the "x" column and so in that case only cap the output row estimate
2029 ** at 1/2 instead of 1/4.
2030 */
2031 static void whereLoopOutputAdjust(
2032   WhereClause *pWC,      /* The WHERE clause */
2033   WhereLoop *pLoop,      /* The loop to adjust downward */
2034   LogEst nRow            /* Number of rows in the entire table */
2035 ){
2036   WhereTerm *pTerm, *pX;
2037   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
2038   int i, j, k;
2039   LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
2040 
2041   assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
2042   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
2043     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
2044     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
2045     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
2046     for(j=pLoop->nLTerm-1; j>=0; j--){
2047       pX = pLoop->aLTerm[j];
2048       if( pX==0 ) continue;
2049       if( pX==pTerm ) break;
2050       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
2051     }
2052     if( j<0 ){
2053       if( pTerm->truthProb<=0 ){
2054         /* If a truth probability is specified using the likelihood() hints,
2055         ** then use the probability provided by the application. */
2056         pLoop->nOut += pTerm->truthProb;
2057       }else{
2058         /* In the absence of explicit truth probabilities, use heuristics to
2059         ** guess a reasonable truth probability. */
2060         pLoop->nOut--;
2061         if( pTerm->eOperator&(WO_EQ|WO_IS) ){
2062           Expr *pRight = pTerm->pExpr->pRight;
2063           testcase( pTerm->pExpr->op==TK_IS );
2064           if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
2065             k = 10;
2066           }else{
2067             k = 20;
2068           }
2069           if( iReduce<k ) iReduce = k;
2070         }
2071       }
2072     }
2073   }
2074   if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
2075 }
2076 
2077 /*
2078 ** Adjust the cost C by the costMult facter T.  This only occurs if
2079 ** compiled with -DSQLITE_ENABLE_COSTMULT
2080 */
2081 #ifdef SQLITE_ENABLE_COSTMULT
2082 # define ApplyCostMultiplier(C,T)  C += T
2083 #else
2084 # define ApplyCostMultiplier(C,T)
2085 #endif
2086 
2087 /*
2088 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
2089 ** index pIndex. Try to match one more.
2090 **
2091 ** When this function is called, pBuilder->pNew->nOut contains the
2092 ** number of rows expected to be visited by filtering using the nEq
2093 ** terms only. If it is modified, this value is restored before this
2094 ** function returns.
2095 **
2096 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
2097 ** INTEGER PRIMARY KEY.
2098 */
2099 static int whereLoopAddBtreeIndex(
2100   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
2101   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
2102   Index *pProbe,                  /* An index on pSrc */
2103   LogEst nInMul                   /* log(Number of iterations due to IN) */
2104 ){
2105   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
2106   Parse *pParse = pWInfo->pParse;        /* Parsing context */
2107   sqlite3 *db = pParse->db;       /* Database connection malloc context */
2108   WhereLoop *pNew;                /* Template WhereLoop under construction */
2109   WhereTerm *pTerm;               /* A WhereTerm under consideration */
2110   int opMask;                     /* Valid operators for constraints */
2111   WhereScan scan;                 /* Iterator for WHERE terms */
2112   Bitmask saved_prereq;           /* Original value of pNew->prereq */
2113   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
2114   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
2115   u16 saved_nSkip;                /* Original value of pNew->nSkip */
2116   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
2117   LogEst saved_nOut;              /* Original value of pNew->nOut */
2118   int iCol;                       /* Index of the column in the table */
2119   int rc = SQLITE_OK;             /* Return code */
2120   LogEst rSize;                   /* Number of rows in the table */
2121   LogEst rLogSize;                /* Logarithm of table size */
2122   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
2123 
2124   pNew = pBuilder->pNew;
2125   if( db->mallocFailed ) return SQLITE_NOMEM;
2126 
2127   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
2128   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
2129   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
2130     opMask = WO_LT|WO_LE;
2131   }else if( /*pProbe->tnum<=0 ||*/ (pSrc->jointype & JT_LEFT)!=0 ){
2132     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
2133   }else{
2134     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
2135   }
2136   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
2137 
2138   assert( pNew->u.btree.nEq<pProbe->nColumn );
2139   iCol = pProbe->aiColumn[pNew->u.btree.nEq];
2140 
2141   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
2142                         opMask, pProbe);
2143   saved_nEq = pNew->u.btree.nEq;
2144   saved_nSkip = pNew->nSkip;
2145   saved_nLTerm = pNew->nLTerm;
2146   saved_wsFlags = pNew->wsFlags;
2147   saved_prereq = pNew->prereq;
2148   saved_nOut = pNew->nOut;
2149   pNew->rSetup = 0;
2150   rSize = pProbe->aiRowLogEst[0];
2151   rLogSize = estLog(rSize);
2152   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
2153     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
2154     LogEst rCostIdx;
2155     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
2156     int nIn = 0;
2157 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
2158     int nRecValid = pBuilder->nRecValid;
2159 #endif
2160     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
2161      && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
2162     ){
2163       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
2164     }
2165     if( pTerm->prereqRight & pNew->maskSelf ) continue;
2166 
2167     /* Do not allow the upper bound of a LIKE optimization range constraint
2168     ** to mix with a lower range bound from some other source */
2169     if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
2170 
2171     pNew->wsFlags = saved_wsFlags;
2172     pNew->u.btree.nEq = saved_nEq;
2173     pNew->nLTerm = saved_nLTerm;
2174     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
2175     pNew->aLTerm[pNew->nLTerm++] = pTerm;
2176     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
2177 
2178     assert( nInMul==0
2179         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
2180         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
2181         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
2182     );
2183 
2184     if( eOp & WO_IN ){
2185       Expr *pExpr = pTerm->pExpr;
2186       pNew->wsFlags |= WHERE_COLUMN_IN;
2187       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2188         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
2189         nIn = 46;  assert( 46==sqlite3LogEst(25) );
2190       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
2191         /* "x IN (value, value, ...)" */
2192         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
2193       }
2194       assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
2195                         ** changes "x IN (?)" into "x=?". */
2196 
2197     }else if( eOp & (WO_EQ|WO_IS) ){
2198       pNew->wsFlags |= WHERE_COLUMN_EQ;
2199       if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
2200         if( iCol>=0 && pProbe->uniqNotNull==0 ){
2201           pNew->wsFlags |= WHERE_UNQ_WANTED;
2202         }else{
2203           pNew->wsFlags |= WHERE_ONEROW;
2204         }
2205       }
2206     }else if( eOp & WO_ISNULL ){
2207       pNew->wsFlags |= WHERE_COLUMN_NULL;
2208     }else if( eOp & (WO_GT|WO_GE) ){
2209       testcase( eOp & WO_GT );
2210       testcase( eOp & WO_GE );
2211       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
2212       pBtm = pTerm;
2213       pTop = 0;
2214       if( pTerm->wtFlags & TERM_LIKEOPT ){
2215         /* Range contraints that come from the LIKE optimization are
2216         ** always used in pairs. */
2217         pTop = &pTerm[1];
2218         assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
2219         assert( pTop->wtFlags & TERM_LIKEOPT );
2220         assert( pTop->eOperator==WO_LT );
2221         if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
2222         pNew->aLTerm[pNew->nLTerm++] = pTop;
2223         pNew->wsFlags |= WHERE_TOP_LIMIT;
2224       }
2225     }else{
2226       assert( eOp & (WO_LT|WO_LE) );
2227       testcase( eOp & WO_LT );
2228       testcase( eOp & WO_LE );
2229       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
2230       pTop = pTerm;
2231       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
2232                      pNew->aLTerm[pNew->nLTerm-2] : 0;
2233     }
2234 
2235     /* At this point pNew->nOut is set to the number of rows expected to
2236     ** be visited by the index scan before considering term pTerm, or the
2237     ** values of nIn and nInMul. In other words, assuming that all
2238     ** "x IN(...)" terms are replaced with "x = ?". This block updates
2239     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
2240     assert( pNew->nOut==saved_nOut );
2241     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
2242       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
2243       ** data, using some other estimate.  */
2244       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
2245     }else{
2246       int nEq = ++pNew->u.btree.nEq;
2247       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
2248 
2249       assert( pNew->nOut==saved_nOut );
2250       if( pTerm->truthProb<=0 && iCol>=0 ){
2251         assert( (eOp & WO_IN) || nIn==0 );
2252         testcase( eOp & WO_IN );
2253         pNew->nOut += pTerm->truthProb;
2254         pNew->nOut -= nIn;
2255       }else{
2256 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
2257         tRowcnt nOut = 0;
2258         if( nInMul==0
2259          && pProbe->nSample
2260          && pNew->u.btree.nEq<=pProbe->nSampleCol
2261          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
2262         ){
2263           Expr *pExpr = pTerm->pExpr;
2264           if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
2265             testcase( eOp & WO_EQ );
2266             testcase( eOp & WO_IS );
2267             testcase( eOp & WO_ISNULL );
2268             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
2269           }else{
2270             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
2271           }
2272           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
2273           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
2274           if( nOut ){
2275             pNew->nOut = sqlite3LogEst(nOut);
2276             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
2277             pNew->nOut -= nIn;
2278           }
2279         }
2280         if( nOut==0 )
2281 #endif
2282         {
2283           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
2284           if( eOp & WO_ISNULL ){
2285             /* TUNING: If there is no likelihood() value, assume that a
2286             ** "col IS NULL" expression matches twice as many rows
2287             ** as (col=?). */
2288             pNew->nOut += 10;
2289           }
2290         }
2291       }
2292     }
2293 
2294     /* Set rCostIdx to the cost of visiting selected rows in index. Add
2295     ** it to pNew->rRun, which is currently set to the cost of the index
2296     ** seek only. Then, if this is a non-covering index, add the cost of
2297     ** visiting the rows in the main table.  */
2298     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
2299     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
2300     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
2301       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
2302     }
2303     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
2304 
2305     nOutUnadjusted = pNew->nOut;
2306     pNew->rRun += nInMul + nIn;
2307     pNew->nOut += nInMul + nIn;
2308     whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
2309     rc = whereLoopInsert(pBuilder, pNew);
2310 
2311     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
2312       pNew->nOut = saved_nOut;
2313     }else{
2314       pNew->nOut = nOutUnadjusted;
2315     }
2316 
2317     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
2318      && pNew->u.btree.nEq<pProbe->nColumn
2319     ){
2320       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
2321     }
2322     pNew->nOut = saved_nOut;
2323 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
2324     pBuilder->nRecValid = nRecValid;
2325 #endif
2326   }
2327   pNew->prereq = saved_prereq;
2328   pNew->u.btree.nEq = saved_nEq;
2329   pNew->nSkip = saved_nSkip;
2330   pNew->wsFlags = saved_wsFlags;
2331   pNew->nOut = saved_nOut;
2332   pNew->nLTerm = saved_nLTerm;
2333 
2334   /* Consider using a skip-scan if there are no WHERE clause constraints
2335   ** available for the left-most terms of the index, and if the average
2336   ** number of repeats in the left-most terms is at least 18.
2337   **
2338   ** The magic number 18 is selected on the basis that scanning 17 rows
2339   ** is almost always quicker than an index seek (even though if the index
2340   ** contains fewer than 2^17 rows we assume otherwise in other parts of
2341   ** the code). And, even if it is not, it should not be too much slower.
2342   ** On the other hand, the extra seeks could end up being significantly
2343   ** more expensive.  */
2344   assert( 42==sqlite3LogEst(18) );
2345   if( saved_nEq==saved_nSkip
2346    && saved_nEq+1<pProbe->nKeyCol
2347    && pProbe->noSkipScan==0
2348    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
2349    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
2350   ){
2351     LogEst nIter;
2352     pNew->u.btree.nEq++;
2353     pNew->nSkip++;
2354     pNew->aLTerm[pNew->nLTerm++] = 0;
2355     pNew->wsFlags |= WHERE_SKIPSCAN;
2356     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
2357     pNew->nOut -= nIter;
2358     /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
2359     ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
2360     nIter += 5;
2361     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
2362     pNew->nOut = saved_nOut;
2363     pNew->u.btree.nEq = saved_nEq;
2364     pNew->nSkip = saved_nSkip;
2365     pNew->wsFlags = saved_wsFlags;
2366   }
2367 
2368   return rc;
2369 }
2370 
2371 /*
2372 ** Return True if it is possible that pIndex might be useful in
2373 ** implementing the ORDER BY clause in pBuilder.
2374 **
2375 ** Return False if pBuilder does not contain an ORDER BY clause or
2376 ** if there is no way for pIndex to be useful in implementing that
2377 ** ORDER BY clause.
2378 */
2379 static int indexMightHelpWithOrderBy(
2380   WhereLoopBuilder *pBuilder,
2381   Index *pIndex,
2382   int iCursor
2383 ){
2384   ExprList *pOB;
2385   int ii, jj;
2386 
2387   if( pIndex->bUnordered ) return 0;
2388   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
2389   for(ii=0; ii<pOB->nExpr; ii++){
2390     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
2391     if( pExpr->op!=TK_COLUMN ) return 0;
2392     if( pExpr->iTable==iCursor ){
2393       if( pExpr->iColumn<0 ) return 1;
2394       for(jj=0; jj<pIndex->nKeyCol; jj++){
2395         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
2396       }
2397     }
2398   }
2399   return 0;
2400 }
2401 
2402 /*
2403 ** Return a bitmask where 1s indicate that the corresponding column of
2404 ** the table is used by an index.  Only the first 63 columns are considered.
2405 */
2406 static Bitmask columnsInIndex(Index *pIdx){
2407   Bitmask m = 0;
2408   int j;
2409   for(j=pIdx->nColumn-1; j>=0; j--){
2410     int x = pIdx->aiColumn[j];
2411     if( x>=0 ){
2412       testcase( x==BMS-1 );
2413       testcase( x==BMS-2 );
2414       if( x<BMS-1 ) m |= MASKBIT(x);
2415     }
2416   }
2417   return m;
2418 }
2419 
2420 /* Check to see if a partial index with pPartIndexWhere can be used
2421 ** in the current query.  Return true if it can be and false if not.
2422 */
2423 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
2424   int i;
2425   WhereTerm *pTerm;
2426   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2427     Expr *pExpr = pTerm->pExpr;
2428     if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
2429      && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
2430     ){
2431       return 1;
2432     }
2433   }
2434   return 0;
2435 }
2436 
2437 /*
2438 ** Add all WhereLoop objects for a single table of the join where the table
2439 ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
2440 ** a b-tree table, not a virtual table.
2441 **
2442 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
2443 ** are calculated as follows:
2444 **
2445 ** For a full scan, assuming the table (or index) contains nRow rows:
2446 **
2447 **     cost = nRow * 3.0                    // full-table scan
2448 **     cost = nRow * K                      // scan of covering index
2449 **     cost = nRow * (K+3.0)                // scan of non-covering index
2450 **
2451 ** where K is a value between 1.1 and 3.0 set based on the relative
2452 ** estimated average size of the index and table records.
2453 **
2454 ** For an index scan, where nVisit is the number of index rows visited
2455 ** by the scan, and nSeek is the number of seek operations required on
2456 ** the index b-tree:
2457 **
2458 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
2459 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
2460 **
2461 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
2462 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
2463 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
2464 **
2465 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
2466 ** of uncertainty.  For this reason, scoring is designed to pick plans that
2467 ** "do the least harm" if the estimates are inaccurate.  For example, a
2468 ** log(nRow) factor is omitted from a non-covering index scan in order to
2469 ** bias the scoring in favor of using an index, since the worst-case
2470 ** performance of using an index is far better than the worst-case performance
2471 ** of a full table scan.
2472 */
2473 static int whereLoopAddBtree(
2474   WhereLoopBuilder *pBuilder, /* WHERE clause information */
2475   Bitmask mExtra              /* Extra prerequesites for using this table */
2476 ){
2477   WhereInfo *pWInfo;          /* WHERE analysis context */
2478   Index *pProbe;              /* An index we are evaluating */
2479   Index sPk;                  /* A fake index object for the primary key */
2480   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
2481   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
2482   SrcList *pTabList;          /* The FROM clause */
2483   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
2484   WhereLoop *pNew;            /* Template WhereLoop object */
2485   int rc = SQLITE_OK;         /* Return code */
2486   int iSortIdx = 1;           /* Index number */
2487   int b;                      /* A boolean value */
2488   LogEst rSize;               /* number of rows in the table */
2489   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
2490   WhereClause *pWC;           /* The parsed WHERE clause */
2491   Table *pTab;                /* Table being queried */
2492 
2493   pNew = pBuilder->pNew;
2494   pWInfo = pBuilder->pWInfo;
2495   pTabList = pWInfo->pTabList;
2496   pSrc = pTabList->a + pNew->iTab;
2497   pTab = pSrc->pTab;
2498   pWC = pBuilder->pWC;
2499   assert( !IsVirtual(pSrc->pTab) );
2500 
2501   if( pSrc->pIndex ){
2502     /* An INDEXED BY clause specifies a particular index to use */
2503     pProbe = pSrc->pIndex;
2504   }else if( !HasRowid(pTab) ){
2505     pProbe = pTab->pIndex;
2506   }else{
2507     /* There is no INDEXED BY clause.  Create a fake Index object in local
2508     ** variable sPk to represent the rowid primary key index.  Make this
2509     ** fake index the first in a chain of Index objects with all of the real
2510     ** indices to follow */
2511     Index *pFirst;                  /* First of real indices on the table */
2512     memset(&sPk, 0, sizeof(Index));
2513     sPk.nKeyCol = 1;
2514     sPk.nColumn = 1;
2515     sPk.aiColumn = &aiColumnPk;
2516     sPk.aiRowLogEst = aiRowEstPk;
2517     sPk.onError = OE_Replace;
2518     sPk.pTable = pTab;
2519     sPk.szIdxRow = pTab->szTabRow;
2520     aiRowEstPk[0] = pTab->nRowLogEst;
2521     aiRowEstPk[1] = 0;
2522     pFirst = pSrc->pTab->pIndex;
2523     if( pSrc->notIndexed==0 ){
2524       /* The real indices of the table are only considered if the
2525       ** NOT INDEXED qualifier is omitted from the FROM clause */
2526       sPk.pNext = pFirst;
2527     }
2528     pProbe = &sPk;
2529   }
2530   rSize = pTab->nRowLogEst;
2531   rLogSize = estLog(rSize);
2532 
2533 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
2534   /* Automatic indexes */
2535   if( !pBuilder->pOrSet   /* Not part of an OR optimization */
2536    && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
2537    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
2538    && pSrc->pIndex==0     /* Has no INDEXED BY clause */
2539    && !pSrc->notIndexed   /* Has no NOT INDEXED clause */
2540    && HasRowid(pTab)      /* Is not a WITHOUT ROWID table. (FIXME: Why not?) */
2541    && !pSrc->isCorrelated /* Not a correlated subquery */
2542    && !pSrc->isRecursive  /* Not a recursive common table expression. */
2543   ){
2544     /* Generate auto-index WhereLoops */
2545     WhereTerm *pTerm;
2546     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
2547     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
2548       if( pTerm->prereqRight & pNew->maskSelf ) continue;
2549       if( termCanDriveIndex(pTerm, pSrc, 0) ){
2550         pNew->u.btree.nEq = 1;
2551         pNew->nSkip = 0;
2552         pNew->u.btree.pIndex = 0;
2553         pNew->nLTerm = 1;
2554         pNew->aLTerm[0] = pTerm;
2555         /* TUNING: One-time cost for computing the automatic index is
2556         ** estimated to be X*N*log2(N) where N is the number of rows in
2557         ** the table being indexed and where X is 7 (LogEst=28) for normal
2558         ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
2559         ** of X is smaller for views and subqueries so that the query planner
2560         ** will be more aggressive about generating automatic indexes for
2561         ** those objects, since there is no opportunity to add schema
2562         ** indexes on subqueries and views. */
2563         pNew->rSetup = rLogSize + rSize + 4;
2564         if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
2565           pNew->rSetup += 24;
2566         }
2567         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
2568         /* TUNING: Each index lookup yields 20 rows in the table.  This
2569         ** is more than the usual guess of 10 rows, since we have no way
2570         ** of knowing how selective the index will ultimately be.  It would
2571         ** not be unreasonable to make this value much larger. */
2572         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
2573         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
2574         pNew->wsFlags = WHERE_AUTO_INDEX;
2575         pNew->prereq = mExtra | pTerm->prereqRight;
2576         rc = whereLoopInsert(pBuilder, pNew);
2577       }
2578     }
2579   }
2580 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
2581 
2582   /* Loop over all indices
2583   */
2584   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
2585     if( pProbe->pPartIdxWhere!=0
2586      && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
2587       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
2588       continue;  /* Partial index inappropriate for this query */
2589     }
2590     rSize = pProbe->aiRowLogEst[0];
2591     pNew->u.btree.nEq = 0;
2592     pNew->nSkip = 0;
2593     pNew->nLTerm = 0;
2594     pNew->iSortIdx = 0;
2595     pNew->rSetup = 0;
2596     pNew->prereq = mExtra;
2597     pNew->nOut = rSize;
2598     pNew->u.btree.pIndex = pProbe;
2599     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
2600     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
2601     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
2602     if( pProbe->tnum<=0 ){
2603       /* Integer primary key index */
2604       pNew->wsFlags = WHERE_IPK;
2605 
2606       /* Full table scan */
2607       pNew->iSortIdx = b ? iSortIdx : 0;
2608       /* TUNING: Cost of full table scan is (N*3.0). */
2609       pNew->rRun = rSize + 16;
2610       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
2611       whereLoopOutputAdjust(pWC, pNew, rSize);
2612       rc = whereLoopInsert(pBuilder, pNew);
2613       pNew->nOut = rSize;
2614       if( rc ) break;
2615     }else{
2616       Bitmask m;
2617       if( pProbe->isCovering ){
2618         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
2619         m = 0;
2620       }else{
2621         m = pSrc->colUsed & ~columnsInIndex(pProbe);
2622         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
2623       }
2624 
2625       /* Full scan via index */
2626       if( b
2627        || !HasRowid(pTab)
2628        || ( m==0
2629          && pProbe->bUnordered==0
2630          && (pProbe->szIdxRow<pTab->szTabRow)
2631          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
2632          && sqlite3GlobalConfig.bUseCis
2633          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
2634           )
2635       ){
2636         pNew->iSortIdx = b ? iSortIdx : 0;
2637 
2638         /* The cost of visiting the index rows is N*K, where K is
2639         ** between 1.1 and 3.0, depending on the relative sizes of the
2640         ** index and table rows. If this is a non-covering index scan,
2641         ** also add the cost of visiting table rows (N*3.0).  */
2642         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
2643         if( m!=0 ){
2644           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
2645         }
2646         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
2647         whereLoopOutputAdjust(pWC, pNew, rSize);
2648         rc = whereLoopInsert(pBuilder, pNew);
2649         pNew->nOut = rSize;
2650         if( rc ) break;
2651       }
2652     }
2653 
2654     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
2655 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
2656     sqlite3Stat4ProbeFree(pBuilder->pRec);
2657     pBuilder->nRecValid = 0;
2658     pBuilder->pRec = 0;
2659 #endif
2660 
2661     /* If there was an INDEXED BY clause, then only that one index is
2662     ** considered. */
2663     if( pSrc->pIndex ) break;
2664   }
2665   return rc;
2666 }
2667 
2668 #ifndef SQLITE_OMIT_VIRTUALTABLE
2669 /*
2670 ** Add all WhereLoop objects for a table of the join identified by
2671 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
2672 **
2673 ** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
2674 ** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
2675 ** entries that occur before the virtual table in the FROM clause and are
2676 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
2677 ** mUnusable mask contains all FROM clause entries that occur after the
2678 ** virtual table and are separated from it by at least one LEFT or
2679 ** CROSS JOIN.
2680 **
2681 ** For example, if the query were:
2682 **
2683 **   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
2684 **
2685 ** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
2686 **
2687 ** All the tables in mExtra must be scanned before the current virtual
2688 ** table. So any terms for which all prerequisites are satisfied by
2689 ** mExtra may be specified as "usable" in all calls to xBestIndex.
2690 ** Conversely, all tables in mUnusable must be scanned after the current
2691 ** virtual table, so any terms for which the prerequisites overlap with
2692 ** mUnusable should always be configured as "not-usable" for xBestIndex.
2693 */
2694 static int whereLoopAddVirtual(
2695   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
2696   Bitmask mExtra,              /* Tables that must be scanned before this one */
2697   Bitmask mUnusable            /* Tables that must be scanned after this one */
2698 ){
2699   WhereInfo *pWInfo;           /* WHERE analysis context */
2700   Parse *pParse;               /* The parsing context */
2701   WhereClause *pWC;            /* The WHERE clause */
2702   struct SrcList_item *pSrc;   /* The FROM clause term to search */
2703   Table *pTab;
2704   sqlite3 *db;
2705   sqlite3_index_info *pIdxInfo;
2706   struct sqlite3_index_constraint *pIdxCons;
2707   struct sqlite3_index_constraint_usage *pUsage;
2708   WhereTerm *pTerm;
2709   int i, j;
2710   int iTerm, mxTerm;
2711   int nConstraint;
2712   int seenIn = 0;              /* True if an IN operator is seen */
2713   int seenVar = 0;             /* True if a non-constant constraint is seen */
2714   int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
2715   WhereLoop *pNew;
2716   int rc = SQLITE_OK;
2717 
2718   assert( (mExtra & mUnusable)==0 );
2719   pWInfo = pBuilder->pWInfo;
2720   pParse = pWInfo->pParse;
2721   db = pParse->db;
2722   pWC = pBuilder->pWC;
2723   pNew = pBuilder->pNew;
2724   pSrc = &pWInfo->pTabList->a[pNew->iTab];
2725   pTab = pSrc->pTab;
2726   assert( IsVirtual(pTab) );
2727   pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
2728   if( pIdxInfo==0 ) return SQLITE_NOMEM;
2729   pNew->prereq = 0;
2730   pNew->rSetup = 0;
2731   pNew->wsFlags = WHERE_VIRTUALTABLE;
2732   pNew->nLTerm = 0;
2733   pNew->u.vtab.needFree = 0;
2734   pUsage = pIdxInfo->aConstraintUsage;
2735   nConstraint = pIdxInfo->nConstraint;
2736   if( whereLoopResize(db, pNew, nConstraint) ){
2737     sqlite3DbFree(db, pIdxInfo);
2738     return SQLITE_NOMEM;
2739   }
2740 
2741   for(iPhase=0; iPhase<=3; iPhase++){
2742     if( !seenIn && (iPhase&1)!=0 ){
2743       iPhase++;
2744       if( iPhase>3 ) break;
2745     }
2746     if( !seenVar && iPhase>1 ) break;
2747     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2748     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
2749       j = pIdxCons->iTermOffset;
2750       pTerm = &pWC->a[j];
2751       switch( iPhase ){
2752         case 0:    /* Constants without IN operator */
2753           pIdxCons->usable = 0;
2754           if( (pTerm->eOperator & WO_IN)!=0 ){
2755             seenIn = 1;
2756           }
2757           if( (pTerm->prereqRight & ~mExtra)!=0 ){
2758             seenVar = 1;
2759           }else if( (pTerm->eOperator & WO_IN)==0 ){
2760             pIdxCons->usable = 1;
2761           }
2762           break;
2763         case 1:    /* Constants with IN operators */
2764           assert( seenIn );
2765           pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
2766           break;
2767         case 2:    /* Variables without IN */
2768           assert( seenVar );
2769           pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
2770           break;
2771         default:   /* Variables with IN */
2772           assert( seenVar && seenIn );
2773           pIdxCons->usable = 1;
2774           break;
2775       }
2776     }
2777     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
2778     if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
2779     pIdxInfo->idxStr = 0;
2780     pIdxInfo->idxNum = 0;
2781     pIdxInfo->needToFreeIdxStr = 0;
2782     pIdxInfo->orderByConsumed = 0;
2783     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
2784     pIdxInfo->estimatedRows = 25;
2785     rc = vtabBestIndex(pParse, pTab, pIdxInfo);
2786     if( rc ) goto whereLoopAddVtab_exit;
2787     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2788     pNew->prereq = mExtra;
2789     mxTerm = -1;
2790     assert( pNew->nLSlot>=nConstraint );
2791     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
2792     pNew->u.vtab.omitMask = 0;
2793     for(i=0; i<nConstraint; i++, pIdxCons++){
2794       if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
2795         j = pIdxCons->iTermOffset;
2796         if( iTerm>=nConstraint
2797          || j<0
2798          || j>=pWC->nTerm
2799          || pNew->aLTerm[iTerm]!=0
2800         ){
2801           rc = SQLITE_ERROR;
2802           sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
2803           goto whereLoopAddVtab_exit;
2804         }
2805         testcase( iTerm==nConstraint-1 );
2806         testcase( j==0 );
2807         testcase( j==pWC->nTerm-1 );
2808         pTerm = &pWC->a[j];
2809         pNew->prereq |= pTerm->prereqRight;
2810         assert( iTerm<pNew->nLSlot );
2811         pNew->aLTerm[iTerm] = pTerm;
2812         if( iTerm>mxTerm ) mxTerm = iTerm;
2813         testcase( iTerm==15 );
2814         testcase( iTerm==16 );
2815         if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
2816         if( (pTerm->eOperator & WO_IN)!=0 ){
2817           if( pUsage[i].omit==0 ){
2818             /* Do not attempt to use an IN constraint if the virtual table
2819             ** says that the equivalent EQ constraint cannot be safely omitted.
2820             ** If we do attempt to use such a constraint, some rows might be
2821             ** repeated in the output. */
2822             break;
2823           }
2824           /* A virtual table that is constrained by an IN clause may not
2825           ** consume the ORDER BY clause because (1) the order of IN terms
2826           ** is not necessarily related to the order of output terms and
2827           ** (2) Multiple outputs from a single IN value will not merge
2828           ** together.  */
2829           pIdxInfo->orderByConsumed = 0;
2830         }
2831       }
2832     }
2833     if( i>=nConstraint ){
2834       pNew->nLTerm = mxTerm+1;
2835       assert( pNew->nLTerm<=pNew->nLSlot );
2836       pNew->u.vtab.idxNum = pIdxInfo->idxNum;
2837       pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
2838       pIdxInfo->needToFreeIdxStr = 0;
2839       pNew->u.vtab.idxStr = pIdxInfo->idxStr;
2840       pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
2841                                       pIdxInfo->nOrderBy : 0);
2842       pNew->rSetup = 0;
2843       pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
2844       pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
2845       whereLoopInsert(pBuilder, pNew);
2846       if( pNew->u.vtab.needFree ){
2847         sqlite3_free(pNew->u.vtab.idxStr);
2848         pNew->u.vtab.needFree = 0;
2849       }
2850     }
2851   }
2852 
2853 whereLoopAddVtab_exit:
2854   if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
2855   sqlite3DbFree(db, pIdxInfo);
2856   return rc;
2857 }
2858 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2859 
2860 /*
2861 ** Add WhereLoop entries to handle OR terms.  This works for either
2862 ** btrees or virtual tables.
2863 */
2864 static int whereLoopAddOr(
2865   WhereLoopBuilder *pBuilder,
2866   Bitmask mExtra,
2867   Bitmask mUnusable
2868 ){
2869   WhereInfo *pWInfo = pBuilder->pWInfo;
2870   WhereClause *pWC;
2871   WhereLoop *pNew;
2872   WhereTerm *pTerm, *pWCEnd;
2873   int rc = SQLITE_OK;
2874   int iCur;
2875   WhereClause tempWC;
2876   WhereLoopBuilder sSubBuild;
2877   WhereOrSet sSum, sCur;
2878   struct SrcList_item *pItem;
2879 
2880   pWC = pBuilder->pWC;
2881   pWCEnd = pWC->a + pWC->nTerm;
2882   pNew = pBuilder->pNew;
2883   memset(&sSum, 0, sizeof(sSum));
2884   pItem = pWInfo->pTabList->a + pNew->iTab;
2885   iCur = pItem->iCursor;
2886 
2887   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
2888     if( (pTerm->eOperator & WO_OR)!=0
2889      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
2890     ){
2891       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
2892       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
2893       WhereTerm *pOrTerm;
2894       int once = 1;
2895       int i, j;
2896 
2897       sSubBuild = *pBuilder;
2898       sSubBuild.pOrderBy = 0;
2899       sSubBuild.pOrSet = &sCur;
2900 
2901       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
2902       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
2903         if( (pOrTerm->eOperator & WO_AND)!=0 ){
2904           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
2905         }else if( pOrTerm->leftCursor==iCur ){
2906           tempWC.pWInfo = pWC->pWInfo;
2907           tempWC.pOuter = pWC;
2908           tempWC.op = TK_AND;
2909           tempWC.nTerm = 1;
2910           tempWC.a = pOrTerm;
2911           sSubBuild.pWC = &tempWC;
2912         }else{
2913           continue;
2914         }
2915         sCur.n = 0;
2916 #ifdef WHERETRACE_ENABLED
2917         WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
2918                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
2919         if( sqlite3WhereTrace & 0x400 ){
2920           for(i=0; i<sSubBuild.pWC->nTerm; i++){
2921             whereTermPrint(&sSubBuild.pWC->a[i], i);
2922           }
2923         }
2924 #endif
2925 #ifndef SQLITE_OMIT_VIRTUALTABLE
2926         if( IsVirtual(pItem->pTab) ){
2927           rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
2928         }else
2929 #endif
2930         {
2931           rc = whereLoopAddBtree(&sSubBuild, mExtra);
2932         }
2933         if( rc==SQLITE_OK ){
2934           rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
2935         }
2936         assert( rc==SQLITE_OK || sCur.n==0 );
2937         if( sCur.n==0 ){
2938           sSum.n = 0;
2939           break;
2940         }else if( once ){
2941           whereOrMove(&sSum, &sCur);
2942           once = 0;
2943         }else{
2944           WhereOrSet sPrev;
2945           whereOrMove(&sPrev, &sSum);
2946           sSum.n = 0;
2947           for(i=0; i<sPrev.n; i++){
2948             for(j=0; j<sCur.n; j++){
2949               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
2950                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
2951                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
2952             }
2953           }
2954         }
2955       }
2956       pNew->nLTerm = 1;
2957       pNew->aLTerm[0] = pTerm;
2958       pNew->wsFlags = WHERE_MULTI_OR;
2959       pNew->rSetup = 0;
2960       pNew->iSortIdx = 0;
2961       memset(&pNew->u, 0, sizeof(pNew->u));
2962       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
2963         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
2964         ** of all sub-scans required by the OR-scan. However, due to rounding
2965         ** errors, it may be that the cost of the OR-scan is equal to its
2966         ** most expensive sub-scan. Add the smallest possible penalty
2967         ** (equivalent to multiplying the cost by 1.07) to ensure that
2968         ** this does not happen. Otherwise, for WHERE clauses such as the
2969         ** following where there is an index on "y":
2970         **
2971         **     WHERE likelihood(x=?, 0.99) OR y=?
2972         **
2973         ** the planner may elect to "OR" together a full-table scan and an
2974         ** index lookup. And other similarly odd results.  */
2975         pNew->rRun = sSum.a[i].rRun + 1;
2976         pNew->nOut = sSum.a[i].nOut;
2977         pNew->prereq = sSum.a[i].prereq;
2978         rc = whereLoopInsert(pBuilder, pNew);
2979       }
2980       WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
2981     }
2982   }
2983   return rc;
2984 }
2985 
2986 /*
2987 ** Add all WhereLoop objects for all tables
2988 */
2989 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
2990   WhereInfo *pWInfo = pBuilder->pWInfo;
2991   Bitmask mExtra = 0;
2992   Bitmask mPrior = 0;
2993   int iTab;
2994   SrcList *pTabList = pWInfo->pTabList;
2995   struct SrcList_item *pItem;
2996   struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
2997   sqlite3 *db = pWInfo->pParse->db;
2998   int rc = SQLITE_OK;
2999   WhereLoop *pNew;
3000   u8 priorJointype = 0;
3001 
3002   /* Loop over the tables in the join, from left to right */
3003   pNew = pBuilder->pNew;
3004   whereLoopInit(pNew);
3005   for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
3006     Bitmask mUnusable = 0;
3007     pNew->iTab = iTab;
3008     pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
3009     if( ((pItem->jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
3010       /* This condition is true when pItem is the FROM clause term on the
3011       ** right-hand-side of a LEFT or CROSS JOIN.  */
3012       mExtra = mPrior;
3013     }
3014     priorJointype = pItem->jointype;
3015     if( IsVirtual(pItem->pTab) ){
3016       struct SrcList_item *p;
3017       for(p=&pItem[1]; p<pEnd; p++){
3018         if( mUnusable || (p->jointype & (JT_LEFT|JT_CROSS)) ){
3019           mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
3020         }
3021       }
3022       rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
3023     }else{
3024       rc = whereLoopAddBtree(pBuilder, mExtra);
3025     }
3026     if( rc==SQLITE_OK ){
3027       rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
3028     }
3029     mPrior |= pNew->maskSelf;
3030     if( rc || db->mallocFailed ) break;
3031   }
3032 
3033   whereLoopClear(db, pNew);
3034   return rc;
3035 }
3036 
3037 /*
3038 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
3039 ** parameters) to see if it outputs rows in the requested ORDER BY
3040 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
3041 **
3042 **   N>0:   N terms of the ORDER BY clause are satisfied
3043 **   N==0:  No terms of the ORDER BY clause are satisfied
3044 **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
3045 **
3046 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
3047 ** strict.  With GROUP BY and DISTINCT the only requirement is that
3048 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
3049 ** and DISTINCT do not require rows to appear in any particular order as long
3050 ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
3051 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
3052 ** pOrderBy terms must be matched in strict left-to-right order.
3053 */
3054 static i8 wherePathSatisfiesOrderBy(
3055   WhereInfo *pWInfo,    /* The WHERE clause */
3056   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
3057   WherePath *pPath,     /* The WherePath to check */
3058   u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
3059   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
3060   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
3061   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
3062 ){
3063   u8 revSet;            /* True if rev is known */
3064   u8 rev;               /* Composite sort order */
3065   u8 revIdx;            /* Index sort order */
3066   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
3067   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
3068   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
3069   u16 nKeyCol;          /* Number of key columns in pIndex */
3070   u16 nColumn;          /* Total number of ordered columns in the index */
3071   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
3072   int iLoop;            /* Index of WhereLoop in pPath being processed */
3073   int i, j;             /* Loop counters */
3074   int iCur;             /* Cursor number for current WhereLoop */
3075   int iColumn;          /* A column number within table iCur */
3076   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
3077   WhereTerm *pTerm;     /* A single term of the WHERE clause */
3078   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
3079   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
3080   Index *pIndex;        /* The index associated with pLoop */
3081   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
3082   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
3083   Bitmask obDone;       /* Mask of all ORDER BY terms */
3084   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
3085   Bitmask ready;              /* Mask of inner loops */
3086 
3087   /*
3088   ** We say the WhereLoop is "one-row" if it generates no more than one
3089   ** row of output.  A WhereLoop is one-row if all of the following are true:
3090   **  (a) All index columns match with WHERE_COLUMN_EQ.
3091   **  (b) The index is unique
3092   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
3093   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
3094   **
3095   ** We say the WhereLoop is "order-distinct" if the set of columns from
3096   ** that WhereLoop that are in the ORDER BY clause are different for every
3097   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
3098   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
3099   ** is not order-distinct. To be order-distinct is not quite the same as being
3100   ** UNIQUE since a UNIQUE column or index can have multiple rows that
3101   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
3102   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
3103   **
3104   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
3105   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
3106   ** automatically order-distinct.
3107   */
3108 
3109   assert( pOrderBy!=0 );
3110   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
3111 
3112   nOrderBy = pOrderBy->nExpr;
3113   testcase( nOrderBy==BMS-1 );
3114   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
3115   isOrderDistinct = 1;
3116   obDone = MASKBIT(nOrderBy)-1;
3117   orderDistinctMask = 0;
3118   ready = 0;
3119   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
3120     if( iLoop>0 ) ready |= pLoop->maskSelf;
3121     pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
3122     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
3123       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
3124       break;
3125     }
3126     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
3127 
3128     /* Mark off any ORDER BY term X that is a column in the table of
3129     ** the current loop for which there is term in the WHERE
3130     ** clause of the form X IS NULL or X=? that reference only outer
3131     ** loops.
3132     */
3133     for(i=0; i<nOrderBy; i++){
3134       if( MASKBIT(i) & obSat ) continue;
3135       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
3136       if( pOBExpr->op!=TK_COLUMN ) continue;
3137       if( pOBExpr->iTable!=iCur ) continue;
3138       pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
3139                        ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
3140       if( pTerm==0 ) continue;
3141       if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
3142         const char *z1, *z2;
3143         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
3144         if( !pColl ) pColl = db->pDfltColl;
3145         z1 = pColl->zName;
3146         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
3147         if( !pColl ) pColl = db->pDfltColl;
3148         z2 = pColl->zName;
3149         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
3150         testcase( pTerm->pExpr->op==TK_IS );
3151       }
3152       obSat |= MASKBIT(i);
3153     }
3154 
3155     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
3156       if( pLoop->wsFlags & WHERE_IPK ){
3157         pIndex = 0;
3158         nKeyCol = 0;
3159         nColumn = 1;
3160       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
3161         return 0;
3162       }else{
3163         nKeyCol = pIndex->nKeyCol;
3164         nColumn = pIndex->nColumn;
3165         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
3166         assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
3167         isOrderDistinct = IsUniqueIndex(pIndex);
3168       }
3169 
3170       /* Loop through all columns of the index and deal with the ones
3171       ** that are not constrained by == or IN.
3172       */
3173       rev = revSet = 0;
3174       distinctColumns = 0;
3175       for(j=0; j<nColumn; j++){
3176         u8 bOnce;   /* True to run the ORDER BY search loop */
3177 
3178         /* Skip over == and IS NULL terms */
3179         if( j<pLoop->u.btree.nEq
3180          && pLoop->nSkip==0
3181          && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
3182         ){
3183           if( i & WO_ISNULL ){
3184             testcase( isOrderDistinct );
3185             isOrderDistinct = 0;
3186           }
3187           continue;
3188         }
3189 
3190         /* Get the column number in the table (iColumn) and sort order
3191         ** (revIdx) for the j-th column of the index.
3192         */
3193         if( pIndex ){
3194           iColumn = pIndex->aiColumn[j];
3195           revIdx = pIndex->aSortOrder[j];
3196           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
3197         }else{
3198           iColumn = -1;
3199           revIdx = 0;
3200         }
3201 
3202         /* An unconstrained column that might be NULL means that this
3203         ** WhereLoop is not well-ordered
3204         */
3205         if( isOrderDistinct
3206          && iColumn>=0
3207          && j>=pLoop->u.btree.nEq
3208          && pIndex->pTable->aCol[iColumn].notNull==0
3209         ){
3210           isOrderDistinct = 0;
3211         }
3212 
3213         /* Find the ORDER BY term that corresponds to the j-th column
3214         ** of the index and mark that ORDER BY term off
3215         */
3216         bOnce = 1;
3217         isMatch = 0;
3218         for(i=0; bOnce && i<nOrderBy; i++){
3219           if( MASKBIT(i) & obSat ) continue;
3220           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
3221           testcase( wctrlFlags & WHERE_GROUPBY );
3222           testcase( wctrlFlags & WHERE_DISTINCTBY );
3223           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
3224           if( pOBExpr->op!=TK_COLUMN ) continue;
3225           if( pOBExpr->iTable!=iCur ) continue;
3226           if( pOBExpr->iColumn!=iColumn ) continue;
3227           if( iColumn>=0 ){
3228             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
3229             if( !pColl ) pColl = db->pDfltColl;
3230             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
3231           }
3232           isMatch = 1;
3233           break;
3234         }
3235         if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
3236           /* Make sure the sort order is compatible in an ORDER BY clause.
3237           ** Sort order is irrelevant for a GROUP BY clause. */
3238           if( revSet ){
3239             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
3240           }else{
3241             rev = revIdx ^ pOrderBy->a[i].sortOrder;
3242             if( rev ) *pRevMask |= MASKBIT(iLoop);
3243             revSet = 1;
3244           }
3245         }
3246         if( isMatch ){
3247           if( iColumn<0 ){
3248             testcase( distinctColumns==0 );
3249             distinctColumns = 1;
3250           }
3251           obSat |= MASKBIT(i);
3252         }else{
3253           /* No match found */
3254           if( j==0 || j<nKeyCol ){
3255             testcase( isOrderDistinct!=0 );
3256             isOrderDistinct = 0;
3257           }
3258           break;
3259         }
3260       } /* end Loop over all index columns */
3261       if( distinctColumns ){
3262         testcase( isOrderDistinct==0 );
3263         isOrderDistinct = 1;
3264       }
3265     } /* end-if not one-row */
3266 
3267     /* Mark off any other ORDER BY terms that reference pLoop */
3268     if( isOrderDistinct ){
3269       orderDistinctMask |= pLoop->maskSelf;
3270       for(i=0; i<nOrderBy; i++){
3271         Expr *p;
3272         Bitmask mTerm;
3273         if( MASKBIT(i) & obSat ) continue;
3274         p = pOrderBy->a[i].pExpr;
3275         mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
3276         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
3277         if( (mTerm&~orderDistinctMask)==0 ){
3278           obSat |= MASKBIT(i);
3279         }
3280       }
3281     }
3282   } /* End the loop over all WhereLoops from outer-most down to inner-most */
3283   if( obSat==obDone ) return (i8)nOrderBy;
3284   if( !isOrderDistinct ){
3285     for(i=nOrderBy-1; i>0; i--){
3286       Bitmask m = MASKBIT(i) - 1;
3287       if( (obSat&m)==m ) return i;
3288     }
3289     return 0;
3290   }
3291   return -1;
3292 }
3293 
3294 
3295 /*
3296 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
3297 ** the planner assumes that the specified pOrderBy list is actually a GROUP
3298 ** BY clause - and so any order that groups rows as required satisfies the
3299 ** request.
3300 **
3301 ** Normally, in this case it is not possible for the caller to determine
3302 ** whether or not the rows are really being delivered in sorted order, or
3303 ** just in some other order that provides the required grouping. However,
3304 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
3305 ** this function may be called on the returned WhereInfo object. It returns
3306 ** true if the rows really will be sorted in the specified order, or false
3307 ** otherwise.
3308 **
3309 ** For example, assuming:
3310 **
3311 **   CREATE INDEX i1 ON t1(x, Y);
3312 **
3313 ** then
3314 **
3315 **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
3316 **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
3317 */
3318 int sqlite3WhereIsSorted(WhereInfo *pWInfo){
3319   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
3320   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
3321   return pWInfo->sorted;
3322 }
3323 
3324 #ifdef WHERETRACE_ENABLED
3325 /* For debugging use only: */
3326 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
3327   static char zName[65];
3328   int i;
3329   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
3330   if( pLast ) zName[i++] = pLast->cId;
3331   zName[i] = 0;
3332   return zName;
3333 }
3334 #endif
3335 
3336 /*
3337 ** Return the cost of sorting nRow rows, assuming that the keys have
3338 ** nOrderby columns and that the first nSorted columns are already in
3339 ** order.
3340 */
3341 static LogEst whereSortingCost(
3342   WhereInfo *pWInfo,
3343   LogEst nRow,
3344   int nOrderBy,
3345   int nSorted
3346 ){
3347   /* TUNING: Estimated cost of a full external sort, where N is
3348   ** the number of rows to sort is:
3349   **
3350   **   cost = (3.0 * N * log(N)).
3351   **
3352   ** Or, if the order-by clause has X terms but only the last Y
3353   ** terms are out of order, then block-sorting will reduce the
3354   ** sorting cost to:
3355   **
3356   **   cost = (3.0 * N * log(N)) * (Y/X)
3357   **
3358   ** The (Y/X) term is implemented using stack variable rScale
3359   ** below.  */
3360   LogEst rScale, rSortCost;
3361   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
3362   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
3363   rSortCost = nRow + estLog(nRow) + rScale + 16;
3364 
3365   /* TUNING: The cost of implementing DISTINCT using a B-TREE is
3366   ** similar but with a larger constant of proportionality.
3367   ** Multiply by an additional factor of 3.0.  */
3368   if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
3369     rSortCost += 16;
3370   }
3371 
3372   return rSortCost;
3373 }
3374 
3375 /*
3376 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
3377 ** attempts to find the lowest cost path that visits each WhereLoop
3378 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
3379 **
3380 ** Assume that the total number of output rows that will need to be sorted
3381 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
3382 ** costs if nRowEst==0.
3383 **
3384 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
3385 ** error occurs.
3386 */
3387 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
3388   int mxChoice;             /* Maximum number of simultaneous paths tracked */
3389   int nLoop;                /* Number of terms in the join */
3390   Parse *pParse;            /* Parsing context */
3391   sqlite3 *db;              /* The database connection */
3392   int iLoop;                /* Loop counter over the terms of the join */
3393   int ii, jj;               /* Loop counters */
3394   int mxI = 0;              /* Index of next entry to replace */
3395   int nOrderBy;             /* Number of ORDER BY clause terms */
3396   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
3397   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
3398   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
3399   WherePath *aFrom;         /* All nFrom paths at the previous level */
3400   WherePath *aTo;           /* The nTo best paths at the current level */
3401   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
3402   WherePath *pTo;           /* An element of aTo[] that we are working on */
3403   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
3404   WhereLoop **pX;           /* Used to divy up the pSpace memory */
3405   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
3406   char *pSpace;             /* Temporary memory used by this routine */
3407   int nSpace;               /* Bytes of space allocated at pSpace */
3408 
3409   pParse = pWInfo->pParse;
3410   db = pParse->db;
3411   nLoop = pWInfo->nLevel;
3412   /* TUNING: For simple queries, only the best path is tracked.
3413   ** For 2-way joins, the 5 best paths are followed.
3414   ** For joins of 3 or more tables, track the 10 best paths */
3415   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
3416   assert( nLoop<=pWInfo->pTabList->nSrc );
3417   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
3418 
3419   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
3420   ** case the purpose of this call is to estimate the number of rows returned
3421   ** by the overall query. Once this estimate has been obtained, the caller
3422   ** will invoke this function a second time, passing the estimate as the
3423   ** nRowEst parameter.  */
3424   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
3425     nOrderBy = 0;
3426   }else{
3427     nOrderBy = pWInfo->pOrderBy->nExpr;
3428   }
3429 
3430   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
3431   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
3432   nSpace += sizeof(LogEst) * nOrderBy;
3433   pSpace = sqlite3DbMallocRaw(db, nSpace);
3434   if( pSpace==0 ) return SQLITE_NOMEM;
3435   aTo = (WherePath*)pSpace;
3436   aFrom = aTo+mxChoice;
3437   memset(aFrom, 0, sizeof(aFrom[0]));
3438   pX = (WhereLoop**)(aFrom+mxChoice);
3439   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
3440     pFrom->aLoop = pX;
3441   }
3442   if( nOrderBy ){
3443     /* If there is an ORDER BY clause and it is not being ignored, set up
3444     ** space for the aSortCost[] array. Each element of the aSortCost array
3445     ** is either zero - meaning it has not yet been initialized - or the
3446     ** cost of sorting nRowEst rows of data where the first X terms of
3447     ** the ORDER BY clause are already in order, where X is the array
3448     ** index.  */
3449     aSortCost = (LogEst*)pX;
3450     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
3451   }
3452   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
3453   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
3454 
3455   /* Seed the search with a single WherePath containing zero WhereLoops.
3456   **
3457   ** TUNING: Do not let the number of iterations go above 28.  If the cost
3458   ** of computing an automatic index is not paid back within the first 28
3459   ** rows, then do not use the automatic index. */
3460   aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
3461   nFrom = 1;
3462   assert( aFrom[0].isOrdered==0 );
3463   if( nOrderBy ){
3464     /* If nLoop is zero, then there are no FROM terms in the query. Since
3465     ** in this case the query may return a maximum of one row, the results
3466     ** are already in the requested order. Set isOrdered to nOrderBy to
3467     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
3468     ** -1, indicating that the result set may or may not be ordered,
3469     ** depending on the loops added to the current plan.  */
3470     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
3471   }
3472 
3473   /* Compute successively longer WherePaths using the previous generation
3474   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
3475   ** best paths at each generation */
3476   for(iLoop=0; iLoop<nLoop; iLoop++){
3477     nTo = 0;
3478     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
3479       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
3480         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
3481         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
3482         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
3483         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
3484         Bitmask maskNew;                  /* Mask of src visited by (..) */
3485         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
3486 
3487         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
3488         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
3489         /* At this point, pWLoop is a candidate to be the next loop.
3490         ** Compute its cost */
3491         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
3492         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
3493         nOut = pFrom->nRow + pWLoop->nOut;
3494         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
3495         if( isOrdered<0 ){
3496           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
3497                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
3498                        iLoop, pWLoop, &revMask);
3499         }else{
3500           revMask = pFrom->revLoop;
3501         }
3502         if( isOrdered>=0 && isOrdered<nOrderBy ){
3503           if( aSortCost[isOrdered]==0 ){
3504             aSortCost[isOrdered] = whereSortingCost(
3505                 pWInfo, nRowEst, nOrderBy, isOrdered
3506             );
3507           }
3508           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
3509 
3510           WHERETRACE(0x002,
3511               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
3512                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
3513                rUnsorted, rCost));
3514         }else{
3515           rCost = rUnsorted;
3516         }
3517 
3518         /* Check to see if pWLoop should be added to the set of
3519         ** mxChoice best-so-far paths.
3520         **
3521         ** First look for an existing path among best-so-far paths
3522         ** that covers the same set of loops and has the same isOrdered
3523         ** setting as the current path candidate.
3524         **
3525         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
3526         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
3527         ** of legal values for isOrdered, -1..64.
3528         */
3529         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
3530           if( pTo->maskLoop==maskNew
3531            && ((pTo->isOrdered^isOrdered)&0x80)==0
3532           ){
3533             testcase( jj==nTo-1 );
3534             break;
3535           }
3536         }
3537         if( jj>=nTo ){
3538           /* None of the existing best-so-far paths match the candidate. */
3539           if( nTo>=mxChoice
3540            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
3541           ){
3542             /* The current candidate is no better than any of the mxChoice
3543             ** paths currently in the best-so-far buffer.  So discard
3544             ** this candidate as not viable. */
3545 #ifdef WHERETRACE_ENABLED /* 0x4 */
3546             if( sqlite3WhereTrace&0x4 ){
3547               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
3548                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
3549                   isOrdered>=0 ? isOrdered+'0' : '?');
3550             }
3551 #endif
3552             continue;
3553           }
3554           /* If we reach this points it means that the new candidate path
3555           ** needs to be added to the set of best-so-far paths. */
3556           if( nTo<mxChoice ){
3557             /* Increase the size of the aTo set by one */
3558             jj = nTo++;
3559           }else{
3560             /* New path replaces the prior worst to keep count below mxChoice */
3561             jj = mxI;
3562           }
3563           pTo = &aTo[jj];
3564 #ifdef WHERETRACE_ENABLED /* 0x4 */
3565           if( sqlite3WhereTrace&0x4 ){
3566             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
3567                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
3568                 isOrdered>=0 ? isOrdered+'0' : '?');
3569           }
3570 #endif
3571         }else{
3572           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
3573           ** same set of loops and has the sam isOrdered setting as the
3574           ** candidate path.  Check to see if the candidate should replace
3575           ** pTo or if the candidate should be skipped */
3576           if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
3577 #ifdef WHERETRACE_ENABLED /* 0x4 */
3578             if( sqlite3WhereTrace&0x4 ){
3579               sqlite3DebugPrintf(
3580                   "Skip   %s cost=%-3d,%3d order=%c",
3581                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
3582                   isOrdered>=0 ? isOrdered+'0' : '?');
3583               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
3584                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
3585                   pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
3586             }
3587 #endif
3588             /* Discard the candidate path from further consideration */
3589             testcase( pTo->rCost==rCost );
3590             continue;
3591           }
3592           testcase( pTo->rCost==rCost+1 );
3593           /* Control reaches here if the candidate path is better than the
3594           ** pTo path.  Replace pTo with the candidate. */
3595 #ifdef WHERETRACE_ENABLED /* 0x4 */
3596           if( sqlite3WhereTrace&0x4 ){
3597             sqlite3DebugPrintf(
3598                 "Update %s cost=%-3d,%3d order=%c",
3599                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
3600                 isOrdered>=0 ? isOrdered+'0' : '?');
3601             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
3602                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
3603                 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
3604           }
3605 #endif
3606         }
3607         /* pWLoop is a winner.  Add it to the set of best so far */
3608         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
3609         pTo->revLoop = revMask;
3610         pTo->nRow = nOut;
3611         pTo->rCost = rCost;
3612         pTo->rUnsorted = rUnsorted;
3613         pTo->isOrdered = isOrdered;
3614         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
3615         pTo->aLoop[iLoop] = pWLoop;
3616         if( nTo>=mxChoice ){
3617           mxI = 0;
3618           mxCost = aTo[0].rCost;
3619           mxUnsorted = aTo[0].nRow;
3620           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
3621             if( pTo->rCost>mxCost
3622              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
3623             ){
3624               mxCost = pTo->rCost;
3625               mxUnsorted = pTo->rUnsorted;
3626               mxI = jj;
3627             }
3628           }
3629         }
3630       }
3631     }
3632 
3633 #ifdef WHERETRACE_ENABLED  /* >=2 */
3634     if( sqlite3WhereTrace & 0x02 ){
3635       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
3636       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
3637         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
3638            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
3639            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
3640         if( pTo->isOrdered>0 ){
3641           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
3642         }else{
3643           sqlite3DebugPrintf("\n");
3644         }
3645       }
3646     }
3647 #endif
3648 
3649     /* Swap the roles of aFrom and aTo for the next generation */
3650     pFrom = aTo;
3651     aTo = aFrom;
3652     aFrom = pFrom;
3653     nFrom = nTo;
3654   }
3655 
3656   if( nFrom==0 ){
3657     sqlite3ErrorMsg(pParse, "no query solution");
3658     sqlite3DbFree(db, pSpace);
3659     return SQLITE_ERROR;
3660   }
3661 
3662   /* Find the lowest cost path.  pFrom will be left pointing to that path */
3663   pFrom = aFrom;
3664   for(ii=1; ii<nFrom; ii++){
3665     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
3666   }
3667   assert( pWInfo->nLevel==nLoop );
3668   /* Load the lowest cost path into pWInfo */
3669   for(iLoop=0; iLoop<nLoop; iLoop++){
3670     WhereLevel *pLevel = pWInfo->a + iLoop;
3671     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
3672     pLevel->iFrom = pWLoop->iTab;
3673     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
3674   }
3675   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
3676    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
3677    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
3678    && nRowEst
3679   ){
3680     Bitmask notUsed;
3681     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
3682                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
3683     if( rc==pWInfo->pResultSet->nExpr ){
3684       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
3685     }
3686   }
3687   if( pWInfo->pOrderBy ){
3688     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
3689       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
3690         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
3691       }
3692     }else{
3693       pWInfo->nOBSat = pFrom->isOrdered;
3694       if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
3695       pWInfo->revMask = pFrom->revLoop;
3696     }
3697     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
3698         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
3699     ){
3700       Bitmask revMask = 0;
3701       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
3702           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
3703       );
3704       assert( pWInfo->sorted==0 );
3705       if( nOrder==pWInfo->pOrderBy->nExpr ){
3706         pWInfo->sorted = 1;
3707         pWInfo->revMask = revMask;
3708       }
3709     }
3710   }
3711 
3712 
3713   pWInfo->nRowOut = pFrom->nRow;
3714 
3715   /* Free temporary memory and return success */
3716   sqlite3DbFree(db, pSpace);
3717   return SQLITE_OK;
3718 }
3719 
3720 /*
3721 ** Most queries use only a single table (they are not joins) and have
3722 ** simple == constraints against indexed fields.  This routine attempts
3723 ** to plan those simple cases using much less ceremony than the
3724 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
3725 ** times for the common case.
3726 **
3727 ** Return non-zero on success, if this query can be handled by this
3728 ** no-frills query planner.  Return zero if this query needs the
3729 ** general-purpose query planner.
3730 */
3731 static int whereShortCut(WhereLoopBuilder *pBuilder){
3732   WhereInfo *pWInfo;
3733   struct SrcList_item *pItem;
3734   WhereClause *pWC;
3735   WhereTerm *pTerm;
3736   WhereLoop *pLoop;
3737   int iCur;
3738   int j;
3739   Table *pTab;
3740   Index *pIdx;
3741 
3742   pWInfo = pBuilder->pWInfo;
3743   if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
3744   assert( pWInfo->pTabList->nSrc>=1 );
3745   pItem = pWInfo->pTabList->a;
3746   pTab = pItem->pTab;
3747   if( IsVirtual(pTab) ) return 0;
3748   if( pItem->zIndexedBy ) return 0;
3749   iCur = pItem->iCursor;
3750   pWC = &pWInfo->sWC;
3751   pLoop = pBuilder->pNew;
3752   pLoop->wsFlags = 0;
3753   pLoop->nSkip = 0;
3754   pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
3755   if( pTerm ){
3756     testcase( pTerm->eOperator & WO_IS );
3757     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
3758     pLoop->aLTerm[0] = pTerm;
3759     pLoop->nLTerm = 1;
3760     pLoop->u.btree.nEq = 1;
3761     /* TUNING: Cost of a rowid lookup is 10 */
3762     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
3763   }else{
3764     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3765       int opMask;
3766       assert( pLoop->aLTermSpace==pLoop->aLTerm );
3767       if( !IsUniqueIndex(pIdx)
3768        || pIdx->pPartIdxWhere!=0
3769        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
3770       ) continue;
3771       opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
3772       for(j=0; j<pIdx->nKeyCol; j++){
3773         pTerm = sqlite3WhereFindTerm(pWC, iCur, pIdx->aiColumn[j], 0, opMask, pIdx);
3774         if( pTerm==0 ) break;
3775         testcase( pTerm->eOperator & WO_IS );
3776         pLoop->aLTerm[j] = pTerm;
3777       }
3778       if( j!=pIdx->nKeyCol ) continue;
3779       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
3780       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
3781         pLoop->wsFlags |= WHERE_IDX_ONLY;
3782       }
3783       pLoop->nLTerm = j;
3784       pLoop->u.btree.nEq = j;
3785       pLoop->u.btree.pIndex = pIdx;
3786       /* TUNING: Cost of a unique index lookup is 15 */
3787       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
3788       break;
3789     }
3790   }
3791   if( pLoop->wsFlags ){
3792     pLoop->nOut = (LogEst)1;
3793     pWInfo->a[0].pWLoop = pLoop;
3794     pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
3795     pWInfo->a[0].iTabCur = iCur;
3796     pWInfo->nRowOut = 1;
3797     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
3798     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
3799       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
3800     }
3801 #ifdef SQLITE_DEBUG
3802     pLoop->cId = '0';
3803 #endif
3804     return 1;
3805   }
3806   return 0;
3807 }
3808 
3809 /*
3810 ** Generate the beginning of the loop used for WHERE clause processing.
3811 ** The return value is a pointer to an opaque structure that contains
3812 ** information needed to terminate the loop.  Later, the calling routine
3813 ** should invoke sqlite3WhereEnd() with the return value of this function
3814 ** in order to complete the WHERE clause processing.
3815 **
3816 ** If an error occurs, this routine returns NULL.
3817 **
3818 ** The basic idea is to do a nested loop, one loop for each table in
3819 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
3820 ** same as a SELECT with only a single table in the FROM clause.)  For
3821 ** example, if the SQL is this:
3822 **
3823 **       SELECT * FROM t1, t2, t3 WHERE ...;
3824 **
3825 ** Then the code generated is conceptually like the following:
3826 **
3827 **      foreach row1 in t1 do       \    Code generated
3828 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
3829 **          foreach row3 in t3 do   /
3830 **            ...
3831 **          end                     \    Code generated
3832 **        end                        |-- by sqlite3WhereEnd()
3833 **      end                         /
3834 **
3835 ** Note that the loops might not be nested in the order in which they
3836 ** appear in the FROM clause if a different order is better able to make
3837 ** use of indices.  Note also that when the IN operator appears in
3838 ** the WHERE clause, it might result in additional nested loops for
3839 ** scanning through all values on the right-hand side of the IN.
3840 **
3841 ** There are Btree cursors associated with each table.  t1 uses cursor
3842 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
3843 ** And so forth.  This routine generates code to open those VDBE cursors
3844 ** and sqlite3WhereEnd() generates the code to close them.
3845 **
3846 ** The code that sqlite3WhereBegin() generates leaves the cursors named
3847 ** in pTabList pointing at their appropriate entries.  The [...] code
3848 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
3849 ** data from the various tables of the loop.
3850 **
3851 ** If the WHERE clause is empty, the foreach loops must each scan their
3852 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
3853 ** the tables have indices and there are terms in the WHERE clause that
3854 ** refer to those indices, a complete table scan can be avoided and the
3855 ** code will run much faster.  Most of the work of this routine is checking
3856 ** to see if there are indices that can be used to speed up the loop.
3857 **
3858 ** Terms of the WHERE clause are also used to limit which rows actually
3859 ** make it to the "..." in the middle of the loop.  After each "foreach",
3860 ** terms of the WHERE clause that use only terms in that loop and outer
3861 ** loops are evaluated and if false a jump is made around all subsequent
3862 ** inner loops (or around the "..." if the test occurs within the inner-
3863 ** most loop)
3864 **
3865 ** OUTER JOINS
3866 **
3867 ** An outer join of tables t1 and t2 is conceptally coded as follows:
3868 **
3869 **    foreach row1 in t1 do
3870 **      flag = 0
3871 **      foreach row2 in t2 do
3872 **        start:
3873 **          ...
3874 **          flag = 1
3875 **      end
3876 **      if flag==0 then
3877 **        move the row2 cursor to a null row
3878 **        goto start
3879 **      fi
3880 **    end
3881 **
3882 ** ORDER BY CLAUSE PROCESSING
3883 **
3884 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
3885 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
3886 ** if there is one.  If there is no ORDER BY clause or if this routine
3887 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
3888 **
3889 ** The iIdxCur parameter is the cursor number of an index.  If
3890 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
3891 ** to use for OR clause processing.  The WHERE clause should use this
3892 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
3893 ** the first cursor in an array of cursors for all indices.  iIdxCur should
3894 ** be used to compute the appropriate cursor depending on which index is
3895 ** used.
3896 */
3897 WhereInfo *sqlite3WhereBegin(
3898   Parse *pParse,        /* The parser context */
3899   SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
3900   Expr *pWhere,         /* The WHERE clause */
3901   ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
3902   ExprList *pResultSet, /* Result set of the query */
3903   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
3904   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
3905 ){
3906   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
3907   int nTabList;              /* Number of elements in pTabList */
3908   WhereInfo *pWInfo;         /* Will become the return value of this function */
3909   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
3910   Bitmask notReady;          /* Cursors that are not yet positioned */
3911   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
3912   WhereMaskSet *pMaskSet;    /* The expression mask set */
3913   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
3914   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
3915   int ii;                    /* Loop counter */
3916   sqlite3 *db;               /* Database connection */
3917   int rc;                    /* Return code */
3918 
3919 
3920   /* Variable initialization */
3921   db = pParse->db;
3922   memset(&sWLB, 0, sizeof(sWLB));
3923 
3924   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
3925   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
3926   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
3927   sWLB.pOrderBy = pOrderBy;
3928 
3929   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
3930   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
3931   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
3932     wctrlFlags &= ~WHERE_WANT_DISTINCT;
3933   }
3934 
3935   /* The number of tables in the FROM clause is limited by the number of
3936   ** bits in a Bitmask
3937   */
3938   testcase( pTabList->nSrc==BMS );
3939   if( pTabList->nSrc>BMS ){
3940     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
3941     return 0;
3942   }
3943 
3944   /* This function normally generates a nested loop for all tables in
3945   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
3946   ** only generate code for the first table in pTabList and assume that
3947   ** any cursors associated with subsequent tables are uninitialized.
3948   */
3949   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
3950 
3951   /* Allocate and initialize the WhereInfo structure that will become the
3952   ** return value. A single allocation is used to store the WhereInfo
3953   ** struct, the contents of WhereInfo.a[], the WhereClause structure
3954   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
3955   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
3956   ** some architectures. Hence the ROUND8() below.
3957   */
3958   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
3959   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
3960   if( db->mallocFailed ){
3961     sqlite3DbFree(db, pWInfo);
3962     pWInfo = 0;
3963     goto whereBeginError;
3964   }
3965   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
3966   pWInfo->nLevel = nTabList;
3967   pWInfo->pParse = pParse;
3968   pWInfo->pTabList = pTabList;
3969   pWInfo->pOrderBy = pOrderBy;
3970   pWInfo->pResultSet = pResultSet;
3971   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
3972   pWInfo->wctrlFlags = wctrlFlags;
3973   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
3974   pMaskSet = &pWInfo->sMaskSet;
3975   sWLB.pWInfo = pWInfo;
3976   sWLB.pWC = &pWInfo->sWC;
3977   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
3978   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
3979   whereLoopInit(sWLB.pNew);
3980 #ifdef SQLITE_DEBUG
3981   sWLB.pNew->cId = '*';
3982 #endif
3983 
3984   /* Split the WHERE clause into separate subexpressions where each
3985   ** subexpression is separated by an AND operator.
3986   */
3987   initMaskSet(pMaskSet);
3988   sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
3989   sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
3990 
3991   /* Special case: a WHERE clause that is constant.  Evaluate the
3992   ** expression and either jump over all of the code or fall thru.
3993   */
3994   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
3995     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
3996       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
3997                          SQLITE_JUMPIFNULL);
3998       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
3999     }
4000   }
4001 
4002   /* Special case: No FROM clause
4003   */
4004   if( nTabList==0 ){
4005     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
4006     if( wctrlFlags & WHERE_WANT_DISTINCT ){
4007       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
4008     }
4009   }
4010 
4011   /* Assign a bit from the bitmask to every term in the FROM clause.
4012   **
4013   ** When assigning bitmask values to FROM clause cursors, it must be
4014   ** the case that if X is the bitmask for the N-th FROM clause term then
4015   ** the bitmask for all FROM clause terms to the left of the N-th term
4016   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
4017   ** its Expr.iRightJoinTable value to find the bitmask of the right table
4018   ** of the join.  Subtracting one from the right table bitmask gives a
4019   ** bitmask for all tables to the left of the join.  Knowing the bitmask
4020   ** for all tables to the left of a left join is important.  Ticket #3015.
4021   **
4022   ** Note that bitmasks are created for all pTabList->nSrc tables in
4023   ** pTabList, not just the first nTabList tables.  nTabList is normally
4024   ** equal to pTabList->nSrc but might be shortened to 1 if the
4025   ** WHERE_ONETABLE_ONLY flag is set.
4026   */
4027   for(ii=0; ii<pTabList->nSrc; ii++){
4028     createMask(pMaskSet, pTabList->a[ii].iCursor);
4029   }
4030 #ifndef NDEBUG
4031   {
4032     Bitmask toTheLeft = 0;
4033     for(ii=0; ii<pTabList->nSrc; ii++){
4034       Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
4035       assert( (m-1)==toTheLeft );
4036       toTheLeft |= m;
4037     }
4038   }
4039 #endif
4040 
4041   /* Analyze all of the subexpressions. */
4042   sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
4043   if( db->mallocFailed ) goto whereBeginError;
4044 
4045   if( wctrlFlags & WHERE_WANT_DISTINCT ){
4046     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
4047       /* The DISTINCT marking is pointless.  Ignore it. */
4048       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
4049     }else if( pOrderBy==0 ){
4050       /* Try to ORDER BY the result set to make distinct processing easier */
4051       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
4052       pWInfo->pOrderBy = pResultSet;
4053     }
4054   }
4055 
4056   /* Construct the WhereLoop objects */
4057   WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
4058 #if defined(WHERETRACE_ENABLED)
4059   if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
4060     int i;
4061     for(i=0; i<sWLB.pWC->nTerm; i++){
4062       whereTermPrint(&sWLB.pWC->a[i], i);
4063     }
4064   }
4065 #endif
4066 
4067   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
4068     rc = whereLoopAddAll(&sWLB);
4069     if( rc ) goto whereBeginError;
4070 
4071 #ifdef WHERETRACE_ENABLED
4072     if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
4073       WhereLoop *p;
4074       int i;
4075       static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
4076                                              "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
4077       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
4078         p->cId = zLabel[i%sizeof(zLabel)];
4079         whereLoopPrint(p, sWLB.pWC);
4080       }
4081     }
4082 #endif
4083 
4084     wherePathSolver(pWInfo, 0);
4085     if( db->mallocFailed ) goto whereBeginError;
4086     if( pWInfo->pOrderBy ){
4087        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
4088        if( db->mallocFailed ) goto whereBeginError;
4089     }
4090   }
4091   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
4092      pWInfo->revMask = (Bitmask)(-1);
4093   }
4094   if( pParse->nErr || NEVER(db->mallocFailed) ){
4095     goto whereBeginError;
4096   }
4097 #ifdef WHERETRACE_ENABLED
4098   if( sqlite3WhereTrace ){
4099     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
4100     if( pWInfo->nOBSat>0 ){
4101       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
4102     }
4103     switch( pWInfo->eDistinct ){
4104       case WHERE_DISTINCT_UNIQUE: {
4105         sqlite3DebugPrintf("  DISTINCT=unique");
4106         break;
4107       }
4108       case WHERE_DISTINCT_ORDERED: {
4109         sqlite3DebugPrintf("  DISTINCT=ordered");
4110         break;
4111       }
4112       case WHERE_DISTINCT_UNORDERED: {
4113         sqlite3DebugPrintf("  DISTINCT=unordered");
4114         break;
4115       }
4116     }
4117     sqlite3DebugPrintf("\n");
4118     for(ii=0; ii<pWInfo->nLevel; ii++){
4119       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
4120     }
4121   }
4122 #endif
4123   /* Attempt to omit tables from the join that do not effect the result */
4124   if( pWInfo->nLevel>=2
4125    && pResultSet!=0
4126    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
4127   ){
4128     Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
4129     if( sWLB.pOrderBy ){
4130       tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
4131     }
4132     while( pWInfo->nLevel>=2 ){
4133       WhereTerm *pTerm, *pEnd;
4134       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
4135       if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
4136       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
4137        && (pLoop->wsFlags & WHERE_ONEROW)==0
4138       ){
4139         break;
4140       }
4141       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
4142       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
4143       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
4144         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
4145          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
4146         ){
4147           break;
4148         }
4149       }
4150       if( pTerm<pEnd ) break;
4151       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
4152       pWInfo->nLevel--;
4153       nTabList--;
4154     }
4155   }
4156   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
4157   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
4158 
4159   /* If the caller is an UPDATE or DELETE statement that is requesting
4160   ** to use a one-pass algorithm, determine if this is appropriate.
4161   ** The one-pass algorithm only works if the WHERE clause constrains
4162   ** the statement to update or delete a single row.
4163   */
4164   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
4165   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
4166    && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
4167     pWInfo->okOnePass = 1;
4168     if( HasRowid(pTabList->a[0].pTab) ){
4169       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
4170     }
4171   }
4172 
4173   /* Open all tables in the pTabList and any indices selected for
4174   ** searching those tables.
4175   */
4176   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
4177     Table *pTab;     /* Table to open */
4178     int iDb;         /* Index of database containing table/index */
4179     struct SrcList_item *pTabItem;
4180 
4181     pTabItem = &pTabList->a[pLevel->iFrom];
4182     pTab = pTabItem->pTab;
4183     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4184     pLoop = pLevel->pWLoop;
4185     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
4186       /* Do nothing */
4187     }else
4188 #ifndef SQLITE_OMIT_VIRTUALTABLE
4189     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
4190       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
4191       int iCur = pTabItem->iCursor;
4192       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
4193     }else if( IsVirtual(pTab) ){
4194       /* noop */
4195     }else
4196 #endif
4197     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
4198          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
4199       int op = OP_OpenRead;
4200       if( pWInfo->okOnePass ){
4201         op = OP_OpenWrite;
4202         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
4203       };
4204       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
4205       assert( pTabItem->iCursor==pLevel->iTabCur );
4206       testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
4207       testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
4208       if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
4209         Bitmask b = pTabItem->colUsed;
4210         int n = 0;
4211         for(; b; b=b>>1, n++){}
4212         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
4213                             SQLITE_INT_TO_PTR(n), P4_INT32);
4214         assert( n<=pTab->nCol );
4215       }
4216 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4217       sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
4218                             (const u8*)&pTabItem->colUsed, P4_INT64);
4219 #endif
4220     }else{
4221       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
4222     }
4223     if( pLoop->wsFlags & WHERE_INDEXED ){
4224       Index *pIx = pLoop->u.btree.pIndex;
4225       int iIndexCur;
4226       int op = OP_OpenRead;
4227       /* iIdxCur is always set if to a positive value if ONEPASS is possible */
4228       assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
4229       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
4230        && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
4231       ){
4232         /* This is one term of an OR-optimization using the PRIMARY KEY of a
4233         ** WITHOUT ROWID table.  No need for a separate index */
4234         iIndexCur = pLevel->iTabCur;
4235         op = 0;
4236       }else if( pWInfo->okOnePass ){
4237         Index *pJ = pTabItem->pTab->pIndex;
4238         iIndexCur = iIdxCur;
4239         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
4240         while( ALWAYS(pJ) && pJ!=pIx ){
4241           iIndexCur++;
4242           pJ = pJ->pNext;
4243         }
4244         op = OP_OpenWrite;
4245         pWInfo->aiCurOnePass[1] = iIndexCur;
4246       }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
4247         iIndexCur = iIdxCur;
4248         if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
4249       }else{
4250         iIndexCur = pParse->nTab++;
4251       }
4252       pLevel->iIdxCur = iIndexCur;
4253       assert( pIx->pSchema==pTab->pSchema );
4254       assert( iIndexCur>=0 );
4255       if( op ){
4256         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
4257         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
4258         if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
4259          && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
4260          && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
4261         ){
4262           sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
4263         }
4264         VdbeComment((v, "%s", pIx->zName));
4265 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
4266         {
4267           u64 colUsed = 0;
4268           int ii, jj;
4269           for(ii=0; ii<pIx->nColumn; ii++){
4270             jj = pIx->aiColumn[ii];
4271             if( jj<0 ) continue;
4272             if( jj>63 ) jj = 63;
4273             if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
4274             colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
4275           }
4276           sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
4277                                 (u8*)&colUsed, P4_INT64);
4278         }
4279 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
4280       }
4281     }
4282     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
4283   }
4284   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
4285   if( db->mallocFailed ) goto whereBeginError;
4286 
4287   /* Generate the code to do the search.  Each iteration of the for
4288   ** loop below generates code for a single nested loop of the VM
4289   ** program.
4290   */
4291   notReady = ~(Bitmask)0;
4292   for(ii=0; ii<nTabList; ii++){
4293     int addrExplain;
4294     int wsFlags;
4295     pLevel = &pWInfo->a[ii];
4296     wsFlags = pLevel->pWLoop->wsFlags;
4297 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
4298     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
4299       constructAutomaticIndex(pParse, &pWInfo->sWC,
4300                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
4301       if( db->mallocFailed ) goto whereBeginError;
4302     }
4303 #endif
4304     addrExplain = sqlite3WhereExplainOneScan(
4305         pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
4306     );
4307     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
4308     notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
4309     pWInfo->iContinue = pLevel->addrCont;
4310     if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
4311       sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
4312     }
4313   }
4314 
4315   /* Done. */
4316   VdbeModuleComment((v, "Begin WHERE-core"));
4317   return pWInfo;
4318 
4319   /* Jump here if malloc fails */
4320 whereBeginError:
4321   if( pWInfo ){
4322     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
4323     whereInfoFree(db, pWInfo);
4324   }
4325   return 0;
4326 }
4327 
4328 /*
4329 ** Generate the end of the WHERE loop.  See comments on
4330 ** sqlite3WhereBegin() for additional information.
4331 */
4332 void sqlite3WhereEnd(WhereInfo *pWInfo){
4333   Parse *pParse = pWInfo->pParse;
4334   Vdbe *v = pParse->pVdbe;
4335   int i;
4336   WhereLevel *pLevel;
4337   WhereLoop *pLoop;
4338   SrcList *pTabList = pWInfo->pTabList;
4339   sqlite3 *db = pParse->db;
4340 
4341   /* Generate loop termination code.
4342   */
4343   VdbeModuleComment((v, "End WHERE-core"));
4344   sqlite3ExprCacheClear(pParse);
4345   for(i=pWInfo->nLevel-1; i>=0; i--){
4346     int addr;
4347     pLevel = &pWInfo->a[i];
4348     pLoop = pLevel->pWLoop;
4349     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
4350     if( pLevel->op!=OP_Noop ){
4351       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
4352       sqlite3VdbeChangeP5(v, pLevel->p5);
4353       VdbeCoverage(v);
4354       VdbeCoverageIf(v, pLevel->op==OP_Next);
4355       VdbeCoverageIf(v, pLevel->op==OP_Prev);
4356       VdbeCoverageIf(v, pLevel->op==OP_VNext);
4357     }
4358     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
4359       struct InLoop *pIn;
4360       int j;
4361       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
4362       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
4363         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
4364         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
4365         VdbeCoverage(v);
4366         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
4367         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
4368         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
4369       }
4370     }
4371     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
4372     if( pLevel->addrSkip ){
4373       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
4374       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
4375       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
4376       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
4377     }
4378     if( pLevel->addrLikeRep ){
4379       int op;
4380       if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
4381         op = OP_DecrJumpZero;
4382       }else{
4383         op = OP_JumpZeroIncr;
4384       }
4385       sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
4386       VdbeCoverage(v);
4387     }
4388     if( pLevel->iLeftJoin ){
4389       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
4390       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
4391            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
4392       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
4393         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
4394       }
4395       if( pLoop->wsFlags & WHERE_INDEXED ){
4396         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
4397       }
4398       if( pLevel->op==OP_Return ){
4399         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
4400       }else{
4401         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
4402       }
4403       sqlite3VdbeJumpHere(v, addr);
4404     }
4405     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
4406                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
4407   }
4408 
4409   /* The "break" point is here, just past the end of the outer loop.
4410   ** Set it.
4411   */
4412   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
4413 
4414   assert( pWInfo->nLevel<=pTabList->nSrc );
4415   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
4416     int k, last;
4417     VdbeOp *pOp;
4418     Index *pIdx = 0;
4419     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
4420     Table *pTab = pTabItem->pTab;
4421     assert( pTab!=0 );
4422     pLoop = pLevel->pWLoop;
4423 
4424     /* For a co-routine, change all OP_Column references to the table of
4425     ** the co-routine into OP_Copy of result contained in a register.
4426     ** OP_Rowid becomes OP_Null.
4427     */
4428     if( pTabItem->viaCoroutine && !db->mallocFailed ){
4429       translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
4430                             pTabItem->regResult);
4431       continue;
4432     }
4433 
4434     /* Close all of the cursors that were opened by sqlite3WhereBegin.
4435     ** Except, do not close cursors that will be reused by the OR optimization
4436     ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
4437     ** created for the ONEPASS optimization.
4438     */
4439     if( (pTab->tabFlags & TF_Ephemeral)==0
4440      && pTab->pSelect==0
4441      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
4442     ){
4443       int ws = pLoop->wsFlags;
4444       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
4445         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
4446       }
4447       if( (ws & WHERE_INDEXED)!=0
4448        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
4449        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
4450       ){
4451         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
4452       }
4453     }
4454 
4455     /* If this scan uses an index, make VDBE code substitutions to read data
4456     ** from the index instead of from the table where possible.  In some cases
4457     ** this optimization prevents the table from ever being read, which can
4458     ** yield a significant performance boost.
4459     **
4460     ** Calls to the code generator in between sqlite3WhereBegin and
4461     ** sqlite3WhereEnd will have created code that references the table
4462     ** directly.  This loop scans all that code looking for opcodes
4463     ** that reference the table and converts them into opcodes that
4464     ** reference the index.
4465     */
4466     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
4467       pIdx = pLoop->u.btree.pIndex;
4468     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
4469       pIdx = pLevel->u.pCovidx;
4470     }
4471     if( pIdx && !db->mallocFailed ){
4472       last = sqlite3VdbeCurrentAddr(v);
4473       k = pLevel->addrBody;
4474       pOp = sqlite3VdbeGetOp(v, k);
4475       for(; k<last; k++, pOp++){
4476         if( pOp->p1!=pLevel->iTabCur ) continue;
4477         if( pOp->opcode==OP_Column ){
4478           int x = pOp->p2;
4479           assert( pIdx->pTable==pTab );
4480           if( !HasRowid(pTab) ){
4481             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
4482             x = pPk->aiColumn[x];
4483           }
4484           x = sqlite3ColumnOfIndex(pIdx, x);
4485           if( x>=0 ){
4486             pOp->p2 = x;
4487             pOp->p1 = pLevel->iIdxCur;
4488           }
4489           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
4490         }else if( pOp->opcode==OP_Rowid ){
4491           pOp->p1 = pLevel->iIdxCur;
4492           pOp->opcode = OP_IdxRowid;
4493         }
4494       }
4495     }
4496   }
4497 
4498   /* Final cleanup
4499   */
4500   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
4501   whereInfoFree(db, pWInfo);
4502   return;
4503 }
4504