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