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