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