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