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