Another very minor tweak to code on this branch to save cycles.
[sqlite.git] / src / where.c
blobb961417be592f3dfa04da51d712513bd6264ca15
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.
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".
19 #include "sqliteInt.h"
20 #include "whereInt.h"
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.
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.
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 */
43 /* Forward declaration of methods */
44 static int whereLoopResize(sqlite3*, WhereLoop*, int);
47 ** Return the estimated number of output rows from a WHERE clause
49 LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
50 return pWInfo->nRowOut;
54 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
55 ** WHERE clause returns outputs for DISTINCT processing.
57 int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
58 return pWInfo->eDistinct;
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.
69 int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
70 return pWInfo->nOBSat<0 ? 0 : pWInfo->nOBSat;
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.
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.
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.
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.
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;
103 pInner = &pWInfo->a[pWInfo->nLevel-1];
104 assert( pInner->addrNxt!=0 );
105 return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt;
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.
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.
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;
131 sqlite3VdbeGoto(v, pWInfo->iBreak);
135 ** Return the VDBE address or label to jump to in order to continue
136 ** immediately with the next row of a WHERE clause.
138 int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
139 assert( pWInfo->iContinue!=0 );
140 return pWInfo->iContinue;
144 ** Return the VDBE address or label to jump to in order to break
145 ** out of a WHERE loop.
147 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
148 return pWInfo->iBreak;
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
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.
165 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
166 ** unable to use the ONEPASS optimization.
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]);
176 #endif
177 return pWInfo->eOnePass;
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.
184 int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
185 return pWInfo->bDeferredSeek;
189 ** Move the content of pSrc into pDest
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]));
197 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
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.
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 */
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;
215 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
216 return 0;
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;
227 if( p->rRun<=rRun ) return 0;
229 whereOrInsert_done:
230 p->prereq = prereq;
231 p->rRun = rRun;
232 if( p->nOut>nOut ) p->nOut = nOut;
233 return 1;
237 ** Return the bitmask for the given cursor number. Return 0 if
238 ** iCursor is not in the set.
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;
248 for(i=1; i<pMaskSet->n; i++){
249 if( pMaskSet->ix[i]==iCursor ){
250 return MASKBIT(i);
253 return 0;
256 /* Allocate memory that is automatically freed when pWInfo is freed.
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++;
267 return (void*)pBlock;
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);
277 return pNew;
281 ** Create a new mask for cursor iCursor.
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.
288 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
289 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
290 pMaskSet->ix[pMaskSet->n++] = iCursor;
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.
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;
302 return 0;
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.
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 */
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 );
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))
335 if( (pTerm->eOperator & WO_EQUIV)!=0
336 && pScan->nEquiv<ArraySize(pScan->aiCur)
337 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
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;
346 if( j==pScan->nEquiv ){
347 pScan->aiCur[j] = pX->iTable;
348 pScan->aiColumn[j] = pX->iColumn;
349 pScan->nEquiv++;
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;
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;
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]
374 testcase( pTerm->eOperator & WO_IS );
375 continue;
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]);
388 sqlite3DebugPrintf("\n");
390 #endif
391 return pTerm;
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++;
403 return 0;
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.
412 static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
413 pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
414 return whereScanNext(pScan);
418 ** Initialize a WHERE clause scanner object. Return a pointer to the
419 ** first match. Return NULL if there are no matches.
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.
426 ** The <op> must be one of the operators described by opMask.
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.
433 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
434 ** index pIdx.
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 */
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);
468 }else if( iColumn==XN_EXPR ){
469 return 0;
471 pScan->aiColumn[0] = iColumn;
472 return whereScanNext(pScan);
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.
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.
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>.
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.
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 */
508 WhereTerm *pResult = 0;
509 WhereTerm *p;
510 WhereScan scan;
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;
520 if( pResult==0 ) pResult = p;
522 p = whereScanNext(&scan);
524 return pResult;
528 ** This function searches pList for an entry that matches the iCol-th column
529 ** of index pIdx.
531 ** If such an expression is found, its index in pList->a[] is returned. If
532 ** no expression is found, -1 is returned.
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 */
541 int i;
542 const char *zColl = pIdx->azColl[iCol];
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
551 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
552 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
553 return i;
558 return -1;
562 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
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 */
581 ** Return true if the DISTINCT expression-list passed as the third argument
582 ** is redundant.
584 ** A DISTINCT list is redundant if any subset of the columns in the
585 ** DISTINCT list are collectively unique and individually non-null.
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 */
593 Table *pTab;
594 Index *pIdx;
595 int i;
596 int iBase;
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;
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.
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;
616 /* Loop through all indices on the table, checking each to see if it makes
617 ** the DISTINCT qualifier redundant. It does so if:
619 ** 1. The index is itself UNIQUE, and
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.
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.
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;
638 if( i==pIdx->nKeyCol ){
639 /* This index implies that the DISTINCT qualifier is redundant. */
640 return 1;
644 return 0;
649 ** Estimate the logarithm of the input value to base 2.
651 static LogEst estLog(LogEst N){
652 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
656 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
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.
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.
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 */
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 pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */
686 }else if( pOp->opcode==OP_Rowid ){
687 pOp->opcode = OP_Sequence;
688 pOp->p1 = iAutoidxCur;
689 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
690 if( iAutoidxCur==0 ){
691 pOp->opcode = OP_Null;
692 pOp->p3 = 0;
694 #endif
700 ** Two routines for printing the content of an sqlite3_index_info
701 ** structure. Used for testing and debugging only. If neither
702 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
703 ** are no-ops.
705 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
706 static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
707 int i;
708 if( (sqlite3WhereTrace & 0x10)==0 ) return;
709 for(i=0; i<p->nConstraint; i++){
710 sqlite3DebugPrintf(
711 " constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",
713 p->aConstraint[i].iColumn,
714 p->aConstraint[i].iTermOffset,
715 p->aConstraint[i].op,
716 p->aConstraint[i].usable,
717 sqlite3_vtab_collation(p,i));
719 for(i=0; i<p->nOrderBy; i++){
720 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
722 p->aOrderBy[i].iColumn,
723 p->aOrderBy[i].desc);
726 static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
727 int i;
728 if( (sqlite3WhereTrace & 0x10)==0 ) return;
729 for(i=0; i<p->nConstraint; i++){
730 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
732 p->aConstraintUsage[i].argvIndex,
733 p->aConstraintUsage[i].omit);
735 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
736 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
737 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
738 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
739 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
741 #else
742 #define whereTraceIndexInfoInputs(A)
743 #define whereTraceIndexInfoOutputs(A)
744 #endif
747 ** We know that pSrc is an operand of an outer join. Return true if
748 ** pTerm is a constraint that is compatible with that join.
750 ** pTerm must be EP_OuterON if pSrc is the right operand of an
751 ** outer join. pTerm can be either EP_OuterON or EP_InnerON if pSrc
752 ** is the left operand of a RIGHT join.
754 ** See https://sqlite.org/forum/forumpost/206d99a16dd9212f
755 ** for an example of a WHERE clause constraints that may not be used on
756 ** the right table of a RIGHT JOIN because the constraint implies a
757 ** not-NULL condition on the left table of the RIGHT JOIN.
759 static int constraintCompatibleWithOuterJoin(
760 const WhereTerm *pTerm, /* WHERE clause term to check */
761 const SrcItem *pSrc /* Table we are trying to access */
763 assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */
764 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT );
765 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ );
766 testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) )
767 testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) );
768 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON)
769 || pTerm->pExpr->w.iJoin != pSrc->iCursor
771 return 0;
773 if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0
774 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
776 return 0;
778 return 1;
783 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
785 ** Return TRUE if the WHERE clause term pTerm is of a form where it
786 ** could be used with an index to access pSrc, assuming an appropriate
787 ** index existed.
789 static int termCanDriveIndex(
790 const WhereTerm *pTerm, /* WHERE clause term to check */
791 const SrcItem *pSrc, /* Table we are trying to access */
792 const Bitmask notReady /* Tables in outer loops of the join */
794 char aff;
795 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
796 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
797 assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
798 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
799 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
801 return 0; /* See https://sqlite.org/forum/forumpost/51e6959f61 */
803 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
804 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
805 if( pTerm->u.x.leftColumn<0 ) return 0;
806 aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
807 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
808 testcase( pTerm->pExpr->op==TK_IS );
809 return 1;
811 #endif
814 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
816 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
818 ** Argument pIdx represents an automatic index that the current statement
819 ** will create and populate. Add an OP_Explain with text of the form:
821 ** CREATE AUTOMATIC INDEX ON <table>(<cols>) [WHERE <expr>]
823 ** This is only required if sqlite3_stmt_scanstatus() is enabled, to
824 ** associate an SQLITE_SCANSTAT_NCYCLE and SQLITE_SCANSTAT_NLOOP
825 ** values with. In order to avoid breaking legacy code and test cases,
826 ** the OP_Explain is not added if this is an EXPLAIN QUERY PLAN command.
828 static void explainAutomaticIndex(
829 Parse *pParse,
830 Index *pIdx, /* Automatic index to explain */
831 int bPartial, /* True if pIdx is a partial index */
832 int *pAddrExplain /* OUT: Address of OP_Explain */
834 if( IS_STMT_SCANSTATUS(pParse->db) && pParse->explain!=2 ){
835 Table *pTab = pIdx->pTable;
836 const char *zSep = "";
837 char *zText = 0;
838 int ii = 0;
839 sqlite3_str *pStr = sqlite3_str_new(pParse->db);
840 sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName);
841 assert( pIdx->nColumn>1 );
842 assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID );
843 for(ii=0; ii<(pIdx->nColumn-1); ii++){
844 const char *zName = 0;
845 int iCol = pIdx->aiColumn[ii];
847 zName = pTab->aCol[iCol].zCnName;
848 sqlite3_str_appendf(pStr, "%s%s", zSep, zName);
849 zSep = ", ";
851 zText = sqlite3_str_finish(pStr);
852 if( zText==0 ){
853 sqlite3OomFault(pParse->db);
854 }else{
855 *pAddrExplain = sqlite3VdbeExplain(
856 pParse, 0, "%s)%s", zText, (bPartial ? " WHERE <expr>" : "")
858 sqlite3_free(zText);
862 #else
863 # define explainAutomaticIndex(a,b,c,d)
864 #endif
867 ** Generate code to construct the Index object for an automatic index
868 ** and to set up the WhereLevel object pLevel so that the code generator
869 ** makes use of the automatic index.
871 static SQLITE_NOINLINE void constructAutomaticIndex(
872 Parse *pParse, /* The parsing context */
873 WhereClause *pWC, /* The WHERE clause */
874 const Bitmask notReady, /* Mask of cursors that are not available */
875 WhereLevel *pLevel /* Write new index here */
877 int nKeyCol; /* Number of columns in the constructed index */
878 WhereTerm *pTerm; /* A single term of the WHERE clause */
879 WhereTerm *pWCEnd; /* End of pWC->a[] */
880 Index *pIdx; /* Object describing the transient index */
881 Vdbe *v; /* Prepared statement under construction */
882 int addrInit; /* Address of the initialization bypass jump */
883 Table *pTable; /* The table being indexed */
884 int addrTop; /* Top of the index fill loop */
885 int regRecord; /* Register holding an index record */
886 int n; /* Column counter */
887 int i; /* Loop counter */
888 int mxBitCol; /* Maximum column in pSrc->colUsed */
889 CollSeq *pColl; /* Collating sequence to on a column */
890 WhereLoop *pLoop; /* The Loop object */
891 char *zNotUsed; /* Extra space on the end of pIdx */
892 Bitmask idxCols; /* Bitmap of columns used for indexing */
893 Bitmask extraCols; /* Bitmap of additional columns */
894 u8 sentWarning = 0; /* True if a warning has been issued */
895 u8 useBloomFilter = 0; /* True to also add a Bloom filter */
896 Expr *pPartial = 0; /* Partial Index Expression */
897 int iContinue = 0; /* Jump here to skip excluded rows */
898 SrcList *pTabList; /* The complete FROM clause */
899 SrcItem *pSrc; /* The FROM clause term to get the next index */
900 int addrCounter = 0; /* Address where integer counter is initialized */
901 int regBase; /* Array of registers where record is assembled */
902 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
903 int addrExp = 0; /* Address of OP_Explain */
904 #endif
906 /* Generate code to skip over the creation and initialization of the
907 ** transient index on 2nd and subsequent iterations of the loop. */
908 v = pParse->pVdbe;
909 assert( v!=0 );
910 addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
912 /* Count the number of columns that will be added to the index
913 ** and used to match WHERE clause constraints */
914 nKeyCol = 0;
915 pTabList = pWC->pWInfo->pTabList;
916 pSrc = &pTabList->a[pLevel->iFrom];
917 pTable = pSrc->pTab;
918 pWCEnd = &pWC->a[pWC->nTerm];
919 pLoop = pLevel->pWLoop;
920 idxCols = 0;
921 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
922 Expr *pExpr = pTerm->pExpr;
923 /* Make the automatic index a partial index if there are terms in the
924 ** WHERE clause (or the ON clause of a LEFT join) that constrain which
925 ** rows of the target table (pSrc) that can be used. */
926 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
927 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, pLevel->iFrom)
929 pPartial = sqlite3ExprAnd(pParse, pPartial,
930 sqlite3ExprDup(pParse->db, pExpr, 0));
932 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
933 int iCol;
934 Bitmask cMask;
935 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
936 iCol = pTerm->u.x.leftColumn;
937 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
938 testcase( iCol==BMS );
939 testcase( iCol==BMS-1 );
940 if( !sentWarning ){
941 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
942 "automatic index on %s(%s)", pTable->zName,
943 pTable->aCol[iCol].zCnName);
944 sentWarning = 1;
946 if( (idxCols & cMask)==0 ){
947 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
948 goto end_auto_index_create;
950 pLoop->aLTerm[nKeyCol++] = pTerm;
951 idxCols |= cMask;
955 assert( nKeyCol>0 || pParse->db->mallocFailed );
956 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
957 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
958 | WHERE_AUTO_INDEX;
960 /* Count the number of additional columns needed to create a
961 ** covering index. A "covering index" is an index that contains all
962 ** columns that are needed by the query. With a covering index, the
963 ** original table never needs to be accessed. Automatic indices must
964 ** be a covering index because the index will not be updated if the
965 ** original table changes and the index and table cannot both be used
966 ** if they go out of sync.
968 if( IsView(pTable) ){
969 extraCols = ALLBITS;
970 }else{
971 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
973 mxBitCol = MIN(BMS-1,pTable->nCol);
974 testcase( pTable->nCol==BMS-1 );
975 testcase( pTable->nCol==BMS-2 );
976 for(i=0; i<mxBitCol; i++){
977 if( extraCols & MASKBIT(i) ) nKeyCol++;
979 if( pSrc->colUsed & MASKBIT(BMS-1) ){
980 nKeyCol += pTable->nCol - BMS + 1;
983 /* Construct the Index object to describe this index */
984 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
985 if( pIdx==0 ) goto end_auto_index_create;
986 pLoop->u.btree.pIndex = pIdx;
987 pIdx->zName = "auto-index";
988 pIdx->pTable = pTable;
989 n = 0;
990 idxCols = 0;
991 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
992 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
993 int iCol;
994 Bitmask cMask;
995 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
996 iCol = pTerm->u.x.leftColumn;
997 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
998 testcase( iCol==BMS-1 );
999 testcase( iCol==BMS );
1000 if( (idxCols & cMask)==0 ){
1001 Expr *pX = pTerm->pExpr;
1002 idxCols |= cMask;
1003 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
1004 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
1005 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
1006 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
1007 n++;
1008 if( ALWAYS(pX->pLeft!=0)
1009 && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT
1011 /* TUNING: only use a Bloom filter on an automatic index
1012 ** if one or more key columns has the ability to hold numeric
1013 ** values, since strings all have the same hash in the Bloom
1014 ** filter implementation and hence a Bloom filter on a text column
1015 ** is not usually helpful. */
1016 useBloomFilter = 1;
1021 assert( (u32)n==pLoop->u.btree.nEq );
1023 /* Add additional columns needed to make the automatic index into
1024 ** a covering index */
1025 for(i=0; i<mxBitCol; i++){
1026 if( extraCols & MASKBIT(i) ){
1027 pIdx->aiColumn[n] = i;
1028 pIdx->azColl[n] = sqlite3StrBINARY;
1029 n++;
1032 if( pSrc->colUsed & MASKBIT(BMS-1) ){
1033 for(i=BMS-1; i<pTable->nCol; i++){
1034 pIdx->aiColumn[n] = i;
1035 pIdx->azColl[n] = sqlite3StrBINARY;
1036 n++;
1039 assert( n==nKeyCol );
1040 pIdx->aiColumn[n] = XN_ROWID;
1041 pIdx->azColl[n] = sqlite3StrBINARY;
1043 /* Create the automatic index */
1044 explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp);
1045 assert( pLevel->iIdxCur>=0 );
1046 pLevel->iIdxCur = pParse->nTab++;
1047 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1048 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1049 VdbeComment((v, "for %s", pTable->zName));
1050 if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) && useBloomFilter ){
1051 sqlite3WhereExplainBloomFilter(pParse, pWC->pWInfo, pLevel);
1052 pLevel->regFilter = ++pParse->nMem;
1053 sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
1056 /* Fill the automatic index with content */
1057 assert( pSrc == &pWC->pWInfo->pTabList->a[pLevel->iFrom] );
1058 if( pSrc->fg.viaCoroutine ){
1059 int regYield = pSrc->regReturn;
1060 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
1061 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSrc->addrFillSub);
1062 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
1063 VdbeCoverage(v);
1064 VdbeComment((v, "next row of %s", pSrc->pTab->zName));
1065 }else{
1066 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
1068 if( pPartial ){
1069 iContinue = sqlite3VdbeMakeLabel(pParse);
1070 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
1071 pLoop->wsFlags |= WHERE_PARTIALIDX;
1073 regRecord = sqlite3GetTempReg(pParse);
1074 regBase = sqlite3GenerateIndexKey(
1075 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
1077 if( pLevel->regFilter ){
1078 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
1079 regBase, pLoop->u.btree.nEq);
1081 sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
1082 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1083 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1084 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
1085 if( pSrc->fg.viaCoroutine ){
1086 sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
1087 testcase( pParse->db->mallocFailed );
1088 assert( pLevel->iIdxCur>0 );
1089 translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
1090 pSrc->regResult, pLevel->iIdxCur);
1091 sqlite3VdbeGoto(v, addrTop);
1092 pSrc->fg.viaCoroutine = 0;
1093 }else{
1094 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
1095 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
1097 sqlite3VdbeJumpHere(v, addrTop);
1098 sqlite3ReleaseTempReg(pParse, regRecord);
1100 /* Jump here when skipping the initialization */
1101 sqlite3VdbeJumpHere(v, addrInit);
1102 sqlite3VdbeScanStatusRange(v, addrExp, addrExp, -1);
1104 end_auto_index_create:
1105 sqlite3ExprDelete(pParse->db, pPartial);
1107 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1110 ** Generate bytecode that will initialize a Bloom filter that is appropriate
1111 ** for pLevel.
1113 ** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER
1114 ** flag set, initialize a Bloomfilter for them as well. Except don't do
1115 ** this recursive initialization if the SQLITE_BloomPulldown optimization has
1116 ** been turned off.
1118 ** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared
1119 ** from the loop, but the regFilter value is set to a register that implements
1120 ** the Bloom filter. When regFilter is positive, the
1121 ** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter
1122 ** and skip the subsequence B-Tree seek if the Bloom filter indicates that
1123 ** no matching rows exist.
1125 ** This routine may only be called if it has previously been determined that
1126 ** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit
1127 ** is set.
1129 static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
1130 WhereInfo *pWInfo, /* The WHERE clause */
1131 int iLevel, /* Index in pWInfo->a[] that is pLevel */
1132 WhereLevel *pLevel, /* Make a Bloom filter for this FROM term */
1133 Bitmask notReady /* Loops that are not ready */
1135 int addrOnce; /* Address of opening OP_Once */
1136 int addrTop; /* Address of OP_Rewind */
1137 int addrCont; /* Jump here to skip a row */
1138 const WhereTerm *pTerm; /* For looping over WHERE clause terms */
1139 const WhereTerm *pWCEnd; /* Last WHERE clause term */
1140 Parse *pParse = pWInfo->pParse; /* Parsing context */
1141 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
1142 WhereLoop *pLoop = pLevel->pWLoop; /* The loop being coded */
1143 int iCur; /* Cursor for table getting the filter */
1144 IndexedExpr *saved_pIdxEpr; /* saved copy of Parse.pIdxEpr */
1145 IndexedExpr *saved_pIdxPartExpr; /* saved copy of Parse.pIdxPartExpr */
1147 saved_pIdxEpr = pParse->pIdxEpr;
1148 saved_pIdxPartExpr = pParse->pIdxPartExpr;
1149 pParse->pIdxEpr = 0;
1150 pParse->pIdxPartExpr = 0;
1152 assert( pLoop!=0 );
1153 assert( v!=0 );
1154 assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
1155 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 );
1157 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
1159 const SrcList *pTabList;
1160 const SrcItem *pItem;
1161 const Table *pTab;
1162 u64 sz;
1163 int iSrc;
1164 sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
1165 addrCont = sqlite3VdbeMakeLabel(pParse);
1166 iCur = pLevel->iTabCur;
1167 pLevel->regFilter = ++pParse->nMem;
1169 /* The Bloom filter is a Blob held in a register. Initialize it
1170 ** to zero-filled blob of at least 80K bits, but maybe more if the
1171 ** estimated size of the table is larger. We could actually
1172 ** measure the size of the table at run-time using OP_Count with
1173 ** P3==1 and use that value to initialize the blob. But that makes
1174 ** testing complicated. By basing the blob size on the value in the
1175 ** sqlite_stat1 table, testing is much easier.
1177 pTabList = pWInfo->pTabList;
1178 iSrc = pLevel->iFrom;
1179 pItem = &pTabList->a[iSrc];
1180 assert( pItem!=0 );
1181 pTab = pItem->pTab;
1182 assert( pTab!=0 );
1183 sz = sqlite3LogEstToInt(pTab->nRowLogEst);
1184 if( sz<10000 ){
1185 sz = 10000;
1186 }else if( sz>10000000 ){
1187 sz = 10000000;
1189 sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
1191 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
1192 pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
1193 for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
1194 Expr *pExpr = pTerm->pExpr;
1195 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
1196 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, iSrc)
1198 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1201 if( pLoop->wsFlags & WHERE_IPK ){
1202 int r1 = sqlite3GetTempReg(pParse);
1203 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
1204 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
1205 sqlite3ReleaseTempReg(pParse, r1);
1206 }else{
1207 Index *pIdx = pLoop->u.btree.pIndex;
1208 int n = pLoop->u.btree.nEq;
1209 int r1 = sqlite3GetTempRange(pParse, n);
1210 int jj;
1211 for(jj=0; jj<n; jj++){
1212 assert( pIdx->pTable==pItem->pTab );
1213 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
1215 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
1216 sqlite3ReleaseTempRange(pParse, r1, n);
1218 sqlite3VdbeResolveLabel(v, addrCont);
1219 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
1220 VdbeCoverage(v);
1221 sqlite3VdbeJumpHere(v, addrTop);
1222 pLoop->wsFlags &= ~WHERE_BLOOMFILTER;
1223 if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break;
1224 while( ++iLevel < pWInfo->nLevel ){
1225 const SrcItem *pTabItem;
1226 pLevel = &pWInfo->a[iLevel];
1227 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
1228 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ) ) continue;
1229 pLoop = pLevel->pWLoop;
1230 if( NEVER(pLoop==0) ) continue;
1231 if( pLoop->prereq & notReady ) continue;
1232 if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN))
1233 ==WHERE_BLOOMFILTER
1235 /* This is a candidate for bloom-filter pull-down (early evaluation).
1236 ** The test that WHERE_COLUMN_IN is omitted is important, as we are
1237 ** not able to do early evaluation of bloom filters that make use of
1238 ** the IN operator */
1239 break;
1242 }while( iLevel < pWInfo->nLevel );
1243 sqlite3VdbeJumpHere(v, addrOnce);
1244 pParse->pIdxEpr = saved_pIdxEpr;
1245 pParse->pIdxPartExpr = saved_pIdxPartExpr;
1249 #ifndef SQLITE_OMIT_VIRTUALTABLE
1251 ** Allocate and populate an sqlite3_index_info structure. It is the
1252 ** responsibility of the caller to eventually release the structure
1253 ** by passing the pointer returned by this function to freeIndexInfo().
1255 static sqlite3_index_info *allocateIndexInfo(
1256 WhereInfo *pWInfo, /* The WHERE clause */
1257 WhereClause *pWC, /* The WHERE clause being analyzed */
1258 Bitmask mUnusable, /* Ignore terms with these prereqs */
1259 SrcItem *pSrc, /* The FROM clause term that is the vtab */
1260 u16 *pmNoOmit /* Mask of terms not to omit */
1262 int i, j;
1263 int nTerm;
1264 Parse *pParse = pWInfo->pParse;
1265 struct sqlite3_index_constraint *pIdxCons;
1266 struct sqlite3_index_orderby *pIdxOrderBy;
1267 struct sqlite3_index_constraint_usage *pUsage;
1268 struct HiddenIndexInfo *pHidden;
1269 WhereTerm *pTerm;
1270 int nOrderBy;
1271 sqlite3_index_info *pIdxInfo;
1272 u16 mNoOmit = 0;
1273 const Table *pTab;
1274 int eDistinct = 0;
1275 ExprList *pOrderBy = pWInfo->pOrderBy;
1277 assert( pSrc!=0 );
1278 pTab = pSrc->pTab;
1279 assert( pTab!=0 );
1280 assert( IsVirtual(pTab) );
1282 /* Find all WHERE clause constraints referring to this virtual table.
1283 ** Mark each term with the TERM_OK flag. Set nTerm to the number of
1284 ** terms found.
1286 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1287 pTerm->wtFlags &= ~TERM_OK;
1288 if( pTerm->leftCursor != pSrc->iCursor ) continue;
1289 if( pTerm->prereqRight & mUnusable ) continue;
1290 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1291 testcase( pTerm->eOperator & WO_IN );
1292 testcase( pTerm->eOperator & WO_ISNULL );
1293 testcase( pTerm->eOperator & WO_IS );
1294 testcase( pTerm->eOperator & WO_ALL );
1295 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
1296 if( pTerm->wtFlags & TERM_VNULL ) continue;
1298 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
1299 assert( pTerm->u.x.leftColumn>=XN_ROWID );
1300 assert( pTerm->u.x.leftColumn<pTab->nCol );
1301 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
1302 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
1304 continue;
1306 nTerm++;
1307 pTerm->wtFlags |= TERM_OK;
1310 /* If the ORDER BY clause contains only columns in the current
1311 ** virtual table then allocate space for the aOrderBy part of
1312 ** the sqlite3_index_info structure.
1314 nOrderBy = 0;
1315 if( pOrderBy ){
1316 int n = pOrderBy->nExpr;
1317 for(i=0; i<n; i++){
1318 Expr *pExpr = pOrderBy->a[i].pExpr;
1319 Expr *pE2;
1321 /* Skip over constant terms in the ORDER BY clause */
1322 if( sqlite3ExprIsConstant(pExpr) ){
1323 continue;
1326 /* Virtual tables are unable to deal with NULLS FIRST */
1327 if( pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) break;
1329 /* First case - a direct column references without a COLLATE operator */
1330 if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){
1331 assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumn<pTab->nCol );
1332 continue;
1335 /* 2nd case - a column reference with a COLLATE operator. Only match
1336 ** of the COLLATE operator matches the collation of the column. */
1337 if( pExpr->op==TK_COLLATE
1338 && (pE2 = pExpr->pLeft)->op==TK_COLUMN
1339 && pE2->iTable==pSrc->iCursor
1341 const char *zColl; /* The collating sequence name */
1342 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1343 assert( pExpr->u.zToken!=0 );
1344 assert( pE2->iColumn>=XN_ROWID && pE2->iColumn<pTab->nCol );
1345 pExpr->iColumn = pE2->iColumn;
1346 if( pE2->iColumn<0 ) continue; /* Collseq does not matter for rowid */
1347 zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]);
1348 if( zColl==0 ) zColl = sqlite3StrBINARY;
1349 if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue;
1352 /* No matches cause a break out of the loop */
1353 break;
1355 if( i==n ){
1356 nOrderBy = n;
1357 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) ){
1358 eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
1359 }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
1360 eDistinct = 1;
1365 /* Allocate the sqlite3_index_info structure
1367 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1368 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1369 + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden)
1370 + sizeof(sqlite3_value*)*nTerm );
1371 if( pIdxInfo==0 ){
1372 sqlite3ErrorMsg(pParse, "out of memory");
1373 return 0;
1375 pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
1376 pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm];
1377 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1378 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1379 pIdxInfo->aConstraint = pIdxCons;
1380 pIdxInfo->aOrderBy = pIdxOrderBy;
1381 pIdxInfo->aConstraintUsage = pUsage;
1382 pHidden->pWC = pWC;
1383 pHidden->pParse = pParse;
1384 pHidden->eDistinct = eDistinct;
1385 pHidden->mIn = 0;
1386 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1387 u16 op;
1388 if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
1389 pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
1390 pIdxCons[j].iTermOffset = i;
1391 op = pTerm->eOperator & WO_ALL;
1392 if( op==WO_IN ){
1393 if( (pTerm->wtFlags & TERM_SLICE)==0 ){
1394 pHidden->mIn |= SMASKBIT32(j);
1396 op = WO_EQ;
1398 if( op==WO_AUX ){
1399 pIdxCons[j].op = pTerm->eMatchOp;
1400 }else if( op & (WO_ISNULL|WO_IS) ){
1401 if( op==WO_ISNULL ){
1402 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
1403 }else{
1404 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
1406 }else{
1407 pIdxCons[j].op = (u8)op;
1408 /* The direct assignment in the previous line is possible only because
1409 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1410 ** following asserts verify this fact. */
1411 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1412 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1413 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1414 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1415 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1416 assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
1418 if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
1419 && sqlite3ExprIsVector(pTerm->pExpr->pRight)
1421 testcase( j!=i );
1422 if( j<16 ) mNoOmit |= (1 << j);
1423 if( op==WO_LT ) pIdxCons[j].op = WO_LE;
1424 if( op==WO_GT ) pIdxCons[j].op = WO_GE;
1428 j++;
1430 assert( j==nTerm );
1431 pIdxInfo->nConstraint = j;
1432 for(i=j=0; i<nOrderBy; i++){
1433 Expr *pExpr = pOrderBy->a[i].pExpr;
1434 if( sqlite3ExprIsConstant(pExpr) ) continue;
1435 assert( pExpr->op==TK_COLUMN
1436 || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
1437 && pExpr->iColumn==pExpr->pLeft->iColumn) );
1438 pIdxOrderBy[j].iColumn = pExpr->iColumn;
1439 pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
1440 j++;
1442 pIdxInfo->nOrderBy = j;
1444 *pmNoOmit = mNoOmit;
1445 return pIdxInfo;
1449 ** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
1450 ** and possibly modified by xBestIndex methods.
1452 static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
1453 HiddenIndexInfo *pHidden;
1454 int i;
1455 assert( pIdxInfo!=0 );
1456 pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
1457 assert( pHidden->pParse!=0 );
1458 assert( pHidden->pParse->db==db );
1459 for(i=0; i<pIdxInfo->nConstraint; i++){
1460 sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
1461 pHidden->aRhs[i] = 0;
1463 sqlite3DbFree(db, pIdxInfo);
1467 ** The table object reference passed as the second argument to this function
1468 ** must represent a virtual table. This function invokes the xBestIndex()
1469 ** method of the virtual table with the sqlite3_index_info object that
1470 ** comes in as the 3rd argument to this function.
1472 ** If an error occurs, pParse is populated with an error message and an
1473 ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
1474 ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
1475 ** the current configuration of "unusable" flags in sqlite3_index_info can
1476 ** not result in a valid plan.
1478 ** Whether or not an error is returned, it is the responsibility of the
1479 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1480 ** that this is required.
1482 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
1483 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
1484 int rc;
1486 whereTraceIndexInfoInputs(p);
1487 pParse->db->nSchemaLock++;
1488 rc = pVtab->pModule->xBestIndex(pVtab, p);
1489 pParse->db->nSchemaLock--;
1490 whereTraceIndexInfoOutputs(p);
1492 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
1493 if( rc==SQLITE_NOMEM ){
1494 sqlite3OomFault(pParse->db);
1495 }else if( !pVtab->zErrMsg ){
1496 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1497 }else{
1498 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1501 if( pTab->u.vtab.p->bAllSchemas ){
1502 sqlite3VtabUsesAllSchemas(pParse);
1504 sqlite3_free(pVtab->zErrMsg);
1505 pVtab->zErrMsg = 0;
1506 return rc;
1508 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
1510 #ifdef SQLITE_ENABLE_STAT4
1512 ** Estimate the location of a particular key among all keys in an
1513 ** index. Store the results in aStat as follows:
1515 ** aStat[0] Est. number of rows less than pRec
1516 ** aStat[1] Est. number of rows equal to pRec
1518 ** Return the index of the sample that is the smallest sample that
1519 ** is greater than or equal to pRec. Note that this index is not an index
1520 ** into the aSample[] array - it is an index into a virtual set of samples
1521 ** based on the contents of aSample[] and the number of fields in record
1522 ** pRec.
1524 static int whereKeyStats(
1525 Parse *pParse, /* Database connection */
1526 Index *pIdx, /* Index to consider domain of */
1527 UnpackedRecord *pRec, /* Vector of values to consider */
1528 int roundUp, /* Round up if true. Round down if false */
1529 tRowcnt *aStat /* OUT: stats written here */
1531 IndexSample *aSample = pIdx->aSample;
1532 int iCol; /* Index of required stats in anEq[] etc. */
1533 int i; /* Index of first sample >= pRec */
1534 int iSample; /* Smallest sample larger than or equal to pRec */
1535 int iMin = 0; /* Smallest sample not yet tested */
1536 int iTest; /* Next sample to test */
1537 int res; /* Result of comparison operation */
1538 int nField; /* Number of fields in pRec */
1539 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
1541 #ifndef SQLITE_DEBUG
1542 UNUSED_PARAMETER( pParse );
1543 #endif
1544 assert( pRec!=0 );
1545 assert( pIdx->nSample>0 );
1546 assert( pRec->nField>0 );
1549 /* Do a binary search to find the first sample greater than or equal
1550 ** to pRec. If pRec contains a single field, the set of samples to search
1551 ** is simply the aSample[] array. If the samples in aSample[] contain more
1552 ** than one fields, all fields following the first are ignored.
1554 ** If pRec contains N fields, where N is more than one, then as well as the
1555 ** samples in aSample[] (truncated to N fields), the search also has to
1556 ** consider prefixes of those samples. For example, if the set of samples
1557 ** in aSample is:
1559 ** aSample[0] = (a, 5)
1560 ** aSample[1] = (a, 10)
1561 ** aSample[2] = (b, 5)
1562 ** aSample[3] = (c, 100)
1563 ** aSample[4] = (c, 105)
1565 ** Then the search space should ideally be the samples above and the
1566 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
1567 ** the code actually searches this set:
1569 ** 0: (a)
1570 ** 1: (a, 5)
1571 ** 2: (a, 10)
1572 ** 3: (a, 10)
1573 ** 4: (b)
1574 ** 5: (b, 5)
1575 ** 6: (c)
1576 ** 7: (c, 100)
1577 ** 8: (c, 105)
1578 ** 9: (c, 105)
1580 ** For each sample in the aSample[] array, N samples are present in the
1581 ** effective sample array. In the above, samples 0 and 1 are based on
1582 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
1584 ** Often, sample i of each block of N effective samples has (i+1) fields.
1585 ** Except, each sample may be extended to ensure that it is greater than or
1586 ** equal to the previous sample in the array. For example, in the above,
1587 ** sample 2 is the first sample of a block of N samples, so at first it
1588 ** appears that it should be 1 field in size. However, that would make it
1589 ** smaller than sample 1, so the binary search would not work. As a result,
1590 ** it is extended to two fields. The duplicates that this creates do not
1591 ** cause any problems.
1593 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
1594 nField = pIdx->nKeyCol;
1595 }else{
1596 nField = pIdx->nColumn;
1598 nField = MIN(pRec->nField, nField);
1599 iCol = 0;
1600 iSample = pIdx->nSample * nField;
1602 int iSamp; /* Index in aSample[] of test sample */
1603 int n; /* Number of fields in test sample */
1605 iTest = (iMin+iSample)/2;
1606 iSamp = iTest / nField;
1607 if( iSamp>0 ){
1608 /* The proposed effective sample is a prefix of sample aSample[iSamp].
1609 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
1610 ** fields that is greater than the previous effective sample. */
1611 for(n=(iTest % nField) + 1; n<nField; n++){
1612 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
1614 }else{
1615 n = iTest + 1;
1618 pRec->nField = n;
1619 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
1620 if( res<0 ){
1621 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
1622 iMin = iTest+1;
1623 }else if( res==0 && n<nField ){
1624 iLower = aSample[iSamp].anLt[n-1];
1625 iMin = iTest+1;
1626 res = -1;
1627 }else{
1628 iSample = iTest;
1629 iCol = n-1;
1631 }while( res && iMin<iSample );
1632 i = iSample / nField;
1634 #ifdef SQLITE_DEBUG
1635 /* The following assert statements check that the binary search code
1636 ** above found the right answer. This block serves no purpose other
1637 ** than to invoke the asserts. */
1638 if( pParse->db->mallocFailed==0 ){
1639 if( res==0 ){
1640 /* If (res==0) is true, then pRec must be equal to sample i. */
1641 assert( i<pIdx->nSample );
1642 assert( iCol==nField-1 );
1643 pRec->nField = nField;
1644 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
1645 || pParse->db->mallocFailed
1647 }else{
1648 /* Unless i==pIdx->nSample, indicating that pRec is larger than
1649 ** all samples in the aSample[] array, pRec must be smaller than the
1650 ** (iCol+1) field prefix of sample i. */
1651 assert( i<=pIdx->nSample && i>=0 );
1652 pRec->nField = iCol+1;
1653 assert( i==pIdx->nSample
1654 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
1655 || pParse->db->mallocFailed );
1657 /* if i==0 and iCol==0, then record pRec is smaller than all samples
1658 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
1659 ** be greater than or equal to the (iCol) field prefix of sample i.
1660 ** If (i>0), then pRec must also be greater than sample (i-1). */
1661 if( iCol>0 ){
1662 pRec->nField = iCol;
1663 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
1664 || pParse->db->mallocFailed || CORRUPT_DB );
1666 if( i>0 ){
1667 pRec->nField = nField;
1668 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
1669 || pParse->db->mallocFailed || CORRUPT_DB );
1673 #endif /* ifdef SQLITE_DEBUG */
1675 if( res==0 ){
1676 /* Record pRec is equal to sample i */
1677 assert( iCol==nField-1 );
1678 aStat[0] = aSample[i].anLt[iCol];
1679 aStat[1] = aSample[i].anEq[iCol];
1680 }else{
1681 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
1682 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
1683 ** is larger than all samples in the array. */
1684 tRowcnt iUpper, iGap;
1685 if( i>=pIdx->nSample ){
1686 iUpper = pIdx->nRowEst0;
1687 }else{
1688 iUpper = aSample[i].anLt[iCol];
1691 if( iLower>=iUpper ){
1692 iGap = 0;
1693 }else{
1694 iGap = iUpper - iLower;
1696 if( roundUp ){
1697 iGap = (iGap*2)/3;
1698 }else{
1699 iGap = iGap/3;
1701 aStat[0] = iLower + iGap;
1702 aStat[1] = pIdx->aAvgEq[nField-1];
1705 /* Restore the pRec->nField value before returning. */
1706 pRec->nField = nField;
1707 return i;
1709 #endif /* SQLITE_ENABLE_STAT4 */
1712 ** If it is not NULL, pTerm is a term that provides an upper or lower
1713 ** bound on a range scan. Without considering pTerm, it is estimated
1714 ** that the scan will visit nNew rows. This function returns the number
1715 ** estimated to be visited after taking pTerm into account.
1717 ** If the user explicitly specified a likelihood() value for this term,
1718 ** then the return value is the likelihood multiplied by the number of
1719 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
1720 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
1722 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
1723 LogEst nRet = nNew;
1724 if( pTerm ){
1725 if( pTerm->truthProb<=0 ){
1726 nRet += pTerm->truthProb;
1727 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
1728 nRet -= 20; assert( 20==sqlite3LogEst(4) );
1731 return nRet;
1735 #ifdef SQLITE_ENABLE_STAT4
1737 ** Return the affinity for a single column of an index.
1739 char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
1740 assert( iCol>=0 && iCol<pIdx->nColumn );
1741 if( !pIdx->zColAff ){
1742 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
1744 assert( pIdx->zColAff[iCol]!=0 );
1745 return pIdx->zColAff[iCol];
1747 #endif
1750 #ifdef SQLITE_ENABLE_STAT4
1752 ** This function is called to estimate the number of rows visited by a
1753 ** range-scan on a skip-scan index. For example:
1755 ** CREATE INDEX i1 ON t1(a, b, c);
1756 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
1758 ** Value pLoop->nOut is currently set to the estimated number of rows
1759 ** visited for scanning (a=? AND b=?). This function reduces that estimate
1760 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
1761 ** on the stat4 data for the index. this scan will be performed multiple
1762 ** times (once for each (a,b) combination that matches a=?) is dealt with
1763 ** by the caller.
1765 ** It does this by scanning through all stat4 samples, comparing values
1766 ** extracted from pLower and pUpper with the corresponding column in each
1767 ** sample. If L and U are the number of samples found to be less than or
1768 ** equal to the values extracted from pLower and pUpper respectively, and
1769 ** N is the total number of samples, the pLoop->nOut value is adjusted
1770 ** as follows:
1772 ** nOut = nOut * ( min(U - L, 1) / N )
1774 ** If pLower is NULL, or a value cannot be extracted from the term, L is
1775 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
1776 ** U is set to N.
1778 ** Normally, this function sets *pbDone to 1 before returning. However,
1779 ** if no value can be extracted from either pLower or pUpper (and so the
1780 ** estimate of the number of rows delivered remains unchanged), *pbDone
1781 ** is left as is.
1783 ** If an error occurs, an SQLite error code is returned. Otherwise,
1784 ** SQLITE_OK.
1786 static int whereRangeSkipScanEst(
1787 Parse *pParse, /* Parsing & code generating context */
1788 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
1789 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
1790 WhereLoop *pLoop, /* Update the .nOut value of this loop */
1791 int *pbDone /* Set to true if at least one expr. value extracted */
1793 Index *p = pLoop->u.btree.pIndex;
1794 int nEq = pLoop->u.btree.nEq;
1795 sqlite3 *db = pParse->db;
1796 int nLower = -1;
1797 int nUpper = p->nSample+1;
1798 int rc = SQLITE_OK;
1799 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
1800 CollSeq *pColl;
1802 sqlite3_value *p1 = 0; /* Value extracted from pLower */
1803 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
1804 sqlite3_value *pVal = 0; /* Value extracted from record */
1806 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
1807 if( pLower ){
1808 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
1809 nLower = 0;
1811 if( pUpper && rc==SQLITE_OK ){
1812 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
1813 nUpper = p2 ? 0 : p->nSample;
1816 if( p1 || p2 ){
1817 int i;
1818 int nDiff;
1819 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
1820 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
1821 if( rc==SQLITE_OK && p1 ){
1822 int res = sqlite3MemCompare(p1, pVal, pColl);
1823 if( res>=0 ) nLower++;
1825 if( rc==SQLITE_OK && p2 ){
1826 int res = sqlite3MemCompare(p2, pVal, pColl);
1827 if( res>=0 ) nUpper++;
1830 nDiff = (nUpper - nLower);
1831 if( nDiff<=0 ) nDiff = 1;
1833 /* If there is both an upper and lower bound specified, and the
1834 ** comparisons indicate that they are close together, use the fallback
1835 ** method (assume that the scan visits 1/64 of the rows) for estimating
1836 ** the number of rows visited. Otherwise, estimate the number of rows
1837 ** using the method described in the header comment for this function. */
1838 if( nDiff!=1 || pUpper==0 || pLower==0 ){
1839 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
1840 pLoop->nOut -= nAdjust;
1841 *pbDone = 1;
1842 WHERETRACE(0x20, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
1843 nLower, nUpper, nAdjust*-1, pLoop->nOut));
1846 }else{
1847 assert( *pbDone==0 );
1850 sqlite3ValueFree(p1);
1851 sqlite3ValueFree(p2);
1852 sqlite3ValueFree(pVal);
1854 return rc;
1856 #endif /* SQLITE_ENABLE_STAT4 */
1859 ** This function is used to estimate the number of rows that will be visited
1860 ** by scanning an index for a range of values. The range may have an upper
1861 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
1862 ** and lower bounds are represented by pLower and pUpper respectively. For
1863 ** example, assuming that index p is on t1(a):
1865 ** ... FROM t1 WHERE a > ? AND a < ? ...
1866 ** |_____| |_____|
1867 ** | |
1868 ** pLower pUpper
1870 ** If either of the upper or lower bound is not present, then NULL is passed in
1871 ** place of the corresponding WhereTerm.
1873 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
1874 ** column subject to the range constraint. Or, equivalently, the number of
1875 ** equality constraints optimized by the proposed index scan. For example,
1876 ** assuming index p is on t1(a, b), and the SQL query is:
1878 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
1880 ** then nEq is set to 1 (as the range restricted column, b, is the second
1881 ** left-most column of the index). Or, if the query is:
1883 ** ... FROM t1 WHERE a > ? AND a < ? ...
1885 ** then nEq is set to 0.
1887 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
1888 ** number of rows that the index scan is expected to visit without
1889 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
1890 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
1891 ** to account for the range constraints pLower and pUpper.
1893 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
1894 ** used, a single range inequality reduces the search space by a factor of 4.
1895 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
1896 ** rows visited by a factor of 64.
1898 static int whereRangeScanEst(
1899 Parse *pParse, /* Parsing & code generating context */
1900 WhereLoopBuilder *pBuilder,
1901 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
1902 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
1903 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
1905 int rc = SQLITE_OK;
1906 int nOut = pLoop->nOut;
1907 LogEst nNew;
1909 #ifdef SQLITE_ENABLE_STAT4
1910 Index *p = pLoop->u.btree.pIndex;
1911 int nEq = pLoop->u.btree.nEq;
1913 if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
1914 && OptimizationEnabled(pParse->db, SQLITE_Stat4)
1916 if( nEq==pBuilder->nRecValid ){
1917 UnpackedRecord *pRec = pBuilder->pRec;
1918 tRowcnt a[2];
1919 int nBtm = pLoop->u.btree.nBtm;
1920 int nTop = pLoop->u.btree.nTop;
1922 /* Variable iLower will be set to the estimate of the number of rows in
1923 ** the index that are less than the lower bound of the range query. The
1924 ** lower bound being the concatenation of $P and $L, where $P is the
1925 ** key-prefix formed by the nEq values matched against the nEq left-most
1926 ** columns of the index, and $L is the value in pLower.
1928 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
1929 ** is not a simple variable or literal value), the lower bound of the
1930 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
1931 ** if $L is available, whereKeyStats() is called for both ($P) and
1932 ** ($P:$L) and the larger of the two returned values is used.
1934 ** Similarly, iUpper is to be set to the estimate of the number of rows
1935 ** less than the upper bound of the range query. Where the upper bound
1936 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
1937 ** of iUpper are requested of whereKeyStats() and the smaller used.
1939 ** The number of rows between the two bounds is then just iUpper-iLower.
1941 tRowcnt iLower; /* Rows less than the lower bound */
1942 tRowcnt iUpper; /* Rows less than the upper bound */
1943 int iLwrIdx = -2; /* aSample[] for the lower bound */
1944 int iUprIdx = -1; /* aSample[] for the upper bound */
1946 if( pRec ){
1947 testcase( pRec->nField!=pBuilder->nRecValid );
1948 pRec->nField = pBuilder->nRecValid;
1950 /* Determine iLower and iUpper using ($P) only. */
1951 if( nEq==0 ){
1952 iLower = 0;
1953 iUpper = p->nRowEst0;
1954 }else{
1955 /* Note: this call could be optimized away - since the same values must
1956 ** have been requested when testing key $P in whereEqualScanEst(). */
1957 whereKeyStats(pParse, p, pRec, 0, a);
1958 iLower = a[0];
1959 iUpper = a[0] + a[1];
1962 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
1963 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
1964 assert( p->aSortOrder!=0 );
1965 if( p->aSortOrder[nEq] ){
1966 /* The roles of pLower and pUpper are swapped for a DESC index */
1967 SWAP(WhereTerm*, pLower, pUpper);
1968 SWAP(int, nBtm, nTop);
1971 /* If possible, improve on the iLower estimate using ($P:$L). */
1972 if( pLower ){
1973 int n; /* Values extracted from pExpr */
1974 Expr *pExpr = pLower->pExpr->pRight;
1975 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
1976 if( rc==SQLITE_OK && n ){
1977 tRowcnt iNew;
1978 u16 mask = WO_GT|WO_LE;
1979 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
1980 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
1981 iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
1982 if( iNew>iLower ) iLower = iNew;
1983 nOut--;
1984 pLower = 0;
1988 /* If possible, improve on the iUpper estimate using ($P:$U). */
1989 if( pUpper ){
1990 int n; /* Values extracted from pExpr */
1991 Expr *pExpr = pUpper->pExpr->pRight;
1992 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
1993 if( rc==SQLITE_OK && n ){
1994 tRowcnt iNew;
1995 u16 mask = WO_GT|WO_LE;
1996 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
1997 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
1998 iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
1999 if( iNew<iUpper ) iUpper = iNew;
2000 nOut--;
2001 pUpper = 0;
2005 pBuilder->pRec = pRec;
2006 if( rc==SQLITE_OK ){
2007 if( iUpper>iLower ){
2008 nNew = sqlite3LogEst(iUpper - iLower);
2009 /* TUNING: If both iUpper and iLower are derived from the same
2010 ** sample, then assume they are 4x more selective. This brings
2011 ** the estimated selectivity more in line with what it would be
2012 ** if estimated without the use of STAT4 tables. */
2013 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
2014 }else{
2015 nNew = 10; assert( 10==sqlite3LogEst(2) );
2017 if( nNew<nOut ){
2018 nOut = nNew;
2020 WHERETRACE(0x20, ("STAT4 range scan: %u..%u est=%d\n",
2021 (u32)iLower, (u32)iUpper, nOut));
2023 }else{
2024 int bDone = 0;
2025 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2026 if( bDone ) return rc;
2029 #else
2030 UNUSED_PARAMETER(pParse);
2031 UNUSED_PARAMETER(pBuilder);
2032 assert( pLower || pUpper );
2033 #endif
2034 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 || pParse->nErr>0 );
2035 nNew = whereRangeAdjust(pLower, nOut);
2036 nNew = whereRangeAdjust(pUpper, nNew);
2038 /* TUNING: If there is both an upper and lower limit and neither limit
2039 ** has an application-defined likelihood(), assume the range is
2040 ** reduced by an additional 75%. This means that, by default, an open-ended
2041 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2042 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2043 ** match 1/64 of the index. */
2044 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2045 nNew -= 20;
2048 nOut -= (pLower!=0) + (pUpper!=0);
2049 if( nNew<10 ) nNew = 10;
2050 if( nNew<nOut ) nOut = nNew;
2051 #if defined(WHERETRACE_ENABLED)
2052 if( pLoop->nOut>nOut ){
2053 WHERETRACE(0x20,("Range scan lowers nOut from %d to %d\n",
2054 pLoop->nOut, nOut));
2056 #endif
2057 pLoop->nOut = (LogEst)nOut;
2058 return rc;
2061 #ifdef SQLITE_ENABLE_STAT4
2063 ** Estimate the number of rows that will be returned based on
2064 ** an equality constraint x=VALUE and where that VALUE occurs in
2065 ** the histogram data. This only works when x is the left-most
2066 ** column of an index and sqlite_stat4 histogram data is available
2067 ** for that index. When pExpr==NULL that means the constraint is
2068 ** "x IS NULL" instead of "x=VALUE".
2070 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2071 ** If unable to make an estimate, leave *pnRow unchanged and return
2072 ** non-zero.
2074 ** This routine can fail if it is unable to load a collating sequence
2075 ** required for string comparison, or if unable to allocate memory
2076 ** for a UTF conversion required for comparison. The error is stored
2077 ** in the pParse structure.
2079 static int whereEqualScanEst(
2080 Parse *pParse, /* Parsing & code generating context */
2081 WhereLoopBuilder *pBuilder,
2082 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
2083 tRowcnt *pnRow /* Write the revised row estimate here */
2085 Index *p = pBuilder->pNew->u.btree.pIndex;
2086 int nEq = pBuilder->pNew->u.btree.nEq;
2087 UnpackedRecord *pRec = pBuilder->pRec;
2088 int rc; /* Subfunction return code */
2089 tRowcnt a[2]; /* Statistics */
2090 int bOk;
2092 assert( nEq>=1 );
2093 assert( nEq<=p->nColumn );
2094 assert( p->aSample!=0 );
2095 assert( p->nSample>0 );
2096 assert( pBuilder->nRecValid<nEq );
2098 /* If values are not available for all fields of the index to the left
2099 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2100 if( pBuilder->nRecValid<(nEq-1) ){
2101 return SQLITE_NOTFOUND;
2104 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2105 ** below would return the same value. */
2106 if( nEq>=p->nColumn ){
2107 *pnRow = 1;
2108 return SQLITE_OK;
2111 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
2112 pBuilder->pRec = pRec;
2113 if( rc!=SQLITE_OK ) return rc;
2114 if( bOk==0 ) return SQLITE_NOTFOUND;
2115 pBuilder->nRecValid = nEq;
2117 whereKeyStats(pParse, p, pRec, 0, a);
2118 WHERETRACE(0x20,("equality scan regions %s(%d): %d\n",
2119 p->zName, nEq-1, (int)a[1]));
2120 *pnRow = a[1];
2122 return rc;
2124 #endif /* SQLITE_ENABLE_STAT4 */
2126 #ifdef SQLITE_ENABLE_STAT4
2128 ** Estimate the number of rows that will be returned based on
2129 ** an IN constraint where the right-hand side of the IN operator
2130 ** is a list of values. Example:
2132 ** WHERE x IN (1,2,3,4)
2134 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2135 ** If unable to make an estimate, leave *pnRow unchanged and return
2136 ** non-zero.
2138 ** This routine can fail if it is unable to load a collating sequence
2139 ** required for string comparison, or if unable to allocate memory
2140 ** for a UTF conversion required for comparison. The error is stored
2141 ** in the pParse structure.
2143 static int whereInScanEst(
2144 Parse *pParse, /* Parsing & code generating context */
2145 WhereLoopBuilder *pBuilder,
2146 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
2147 tRowcnt *pnRow /* Write the revised row estimate here */
2149 Index *p = pBuilder->pNew->u.btree.pIndex;
2150 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
2151 int nRecValid = pBuilder->nRecValid;
2152 int rc = SQLITE_OK; /* Subfunction return code */
2153 tRowcnt nEst; /* Number of rows for a single term */
2154 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2155 int i; /* Loop counter */
2157 assert( p->aSample!=0 );
2158 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2159 nEst = nRow0;
2160 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
2161 nRowEst += nEst;
2162 pBuilder->nRecValid = nRecValid;
2165 if( rc==SQLITE_OK ){
2166 if( nRowEst > (tRowcnt)nRow0 ) nRowEst = nRow0;
2167 *pnRow = nRowEst;
2168 WHERETRACE(0x20,("IN row estimate: est=%d\n", nRowEst));
2170 assert( pBuilder->nRecValid==nRecValid );
2171 return rc;
2173 #endif /* SQLITE_ENABLE_STAT4 */
2176 #ifdef WHERETRACE_ENABLED
2178 ** Print the content of a WhereTerm object
2180 void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
2181 if( pTerm==0 ){
2182 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
2183 }else{
2184 char zType[8];
2185 char zLeft[50];
2186 memcpy(zType, "....", 5);
2187 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
2188 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
2189 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) zType[2] = 'L';
2190 if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C';
2191 if( pTerm->eOperator & WO_SINGLE ){
2192 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
2193 sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
2194 pTerm->leftCursor, pTerm->u.x.leftColumn);
2195 }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
2196 sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx",
2197 pTerm->u.pOrInfo->indexable);
2198 }else{
2199 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
2201 sqlite3DebugPrintf(
2202 "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
2203 iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
2204 /* The 0x10000 .wheretrace flag causes extra information to be
2205 ** shown about each Term */
2206 if( sqlite3WhereTrace & 0x10000 ){
2207 sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
2208 pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
2210 if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){
2211 sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
2213 if( pTerm->iParent>=0 ){
2214 sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
2216 sqlite3DebugPrintf("\n");
2217 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
2220 #endif
2222 #ifdef WHERETRACE_ENABLED
2224 ** Show the complete content of a WhereClause
2226 void sqlite3WhereClausePrint(WhereClause *pWC){
2227 int i;
2228 for(i=0; i<pWC->nTerm; i++){
2229 sqlite3WhereTermPrint(&pWC->a[i], i);
2232 #endif
2234 #ifdef WHERETRACE_ENABLED
2236 ** Print a WhereLoop object for debugging purposes
2238 void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
2239 WhereInfo *pWInfo = pWC->pWInfo;
2240 int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
2241 SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
2242 Table *pTab = pItem->pTab;
2243 Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
2244 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
2245 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
2246 sqlite3DebugPrintf(" %12s",
2247 pItem->zAlias ? pItem->zAlias : pTab->zName);
2248 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2249 const char *zName;
2250 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
2251 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
2252 int i = sqlite3Strlen30(zName) - 1;
2253 while( zName[i]!='_' ) i--;
2254 zName += i;
2256 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
2257 }else{
2258 sqlite3DebugPrintf("%20s","");
2260 }else{
2261 char *z;
2262 if( p->u.vtab.idxStr ){
2263 z = sqlite3_mprintf("(%d,\"%s\",%#x)",
2264 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
2265 }else{
2266 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
2268 sqlite3DebugPrintf(" %-19s", z);
2269 sqlite3_free(z);
2271 if( p->wsFlags & WHERE_SKIPSCAN ){
2272 sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
2273 }else{
2274 sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm);
2276 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
2277 if( p->nLTerm && (sqlite3WhereTrace & 0x4000)!=0 ){
2278 int i;
2279 for(i=0; i<p->nLTerm; i++){
2280 sqlite3WhereTermPrint(p->aLTerm[i], i);
2284 #endif
2287 ** Convert bulk memory into a valid WhereLoop that can be passed
2288 ** to whereLoopClear harmlessly.
2290 static void whereLoopInit(WhereLoop *p){
2291 p->aLTerm = p->aLTermSpace;
2292 p->nLTerm = 0;
2293 p->nLSlot = ArraySize(p->aLTermSpace);
2294 p->wsFlags = 0;
2298 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
2300 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
2301 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
2302 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
2303 sqlite3_free(p->u.vtab.idxStr);
2304 p->u.vtab.needFree = 0;
2305 p->u.vtab.idxStr = 0;
2306 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
2307 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
2308 sqlite3DbFreeNN(db, p->u.btree.pIndex);
2309 p->u.btree.pIndex = 0;
2315 ** Deallocate internal memory used by a WhereLoop object. Leave the
2316 ** object in an initialized state, as if it had been newly allocated.
2318 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
2319 if( p->aLTerm!=p->aLTermSpace ){
2320 sqlite3DbFreeNN(db, p->aLTerm);
2321 p->aLTerm = p->aLTermSpace;
2322 p->nLSlot = ArraySize(p->aLTermSpace);
2324 whereLoopClearUnion(db, p);
2325 p->nLTerm = 0;
2326 p->wsFlags = 0;
2330 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
2332 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
2333 WhereTerm **paNew;
2334 if( p->nLSlot>=n ) return SQLITE_OK;
2335 n = (n+7)&~7;
2336 paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
2337 if( paNew==0 ) return SQLITE_NOMEM_BKPT;
2338 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
2339 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
2340 p->aLTerm = paNew;
2341 p->nLSlot = n;
2342 return SQLITE_OK;
2346 ** Transfer content from the second pLoop into the first.
2348 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
2349 whereLoopClearUnion(db, pTo);
2350 if( pFrom->nLTerm > pTo->nLSlot
2351 && whereLoopResize(db, pTo, pFrom->nLTerm)
2353 memset(pTo, 0, WHERE_LOOP_XFER_SZ);
2354 return SQLITE_NOMEM_BKPT;
2356 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
2357 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
2358 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
2359 pFrom->u.vtab.needFree = 0;
2360 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
2361 pFrom->u.btree.pIndex = 0;
2363 return SQLITE_OK;
2367 ** Delete a WhereLoop object
2369 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
2370 assert( db!=0 );
2371 whereLoopClear(db, p);
2372 sqlite3DbNNFreeNN(db, p);
2376 ** Free a WhereInfo structure
2378 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
2379 assert( pWInfo!=0 );
2380 assert( db!=0 );
2381 sqlite3WhereClauseClear(&pWInfo->sWC);
2382 while( pWInfo->pLoops ){
2383 WhereLoop *p = pWInfo->pLoops;
2384 pWInfo->pLoops = p->pNextLoop;
2385 whereLoopDelete(db, p);
2387 while( pWInfo->pMemToFree ){
2388 WhereMemBlock *pNext = pWInfo->pMemToFree->pNext;
2389 sqlite3DbNNFreeNN(db, pWInfo->pMemToFree);
2390 pWInfo->pMemToFree = pNext;
2392 sqlite3DbNNFreeNN(db, pWInfo);
2396 ** Return TRUE if all of the following are true:
2398 ** (1) X has the same or lower cost, or returns the same or fewer rows,
2399 ** than Y.
2400 ** (2) X uses fewer WHERE clause terms than Y
2401 ** (3) Every WHERE clause term used by X is also used by Y
2402 ** (4) X skips at least as many columns as Y
2403 ** (5) If X is a covering index, than Y is too
2405 ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
2406 ** If X is a proper subset of Y then Y is a better choice and ought
2407 ** to have a lower cost. This routine returns TRUE when that cost
2408 ** relationship is inverted and needs to be adjusted. Constraint (4)
2409 ** was added because if X uses skip-scan less than Y it still might
2410 ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
2411 ** was added because a covering index probably deserves to have a lower cost
2412 ** than a non-covering index even if it is a proper subset.
2414 static int whereLoopCheaperProperSubset(
2415 const WhereLoop *pX, /* First WhereLoop to compare */
2416 const WhereLoop *pY /* Compare against this WhereLoop */
2418 int i, j;
2419 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
2420 return 0; /* X is not a subset of Y */
2422 if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0;
2423 if( pY->nSkip > pX->nSkip ) return 0;
2424 for(i=pX->nLTerm-1; i>=0; i--){
2425 if( pX->aLTerm[i]==0 ) continue;
2426 for(j=pY->nLTerm-1; j>=0; j--){
2427 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
2429 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
2431 if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
2432 && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
2433 return 0; /* Constraint (5) */
2435 return 1; /* All conditions meet */
2439 ** Try to adjust the cost and number of output rows of WhereLoop pTemplate
2440 ** upwards or downwards so that:
2442 ** (1) pTemplate costs less than any other WhereLoops that are a proper
2443 ** subset of pTemplate
2445 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
2446 ** is a proper subset.
2448 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
2449 ** WHERE clause terms than Y and that every WHERE clause term used by X is
2450 ** also used by Y.
2452 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
2453 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
2454 for(; p; p=p->pNextLoop){
2455 if( p->iTab!=pTemplate->iTab ) continue;
2456 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
2457 if( whereLoopCheaperProperSubset(p, pTemplate) ){
2458 /* Adjust pTemplate cost downward so that it is cheaper than its
2459 ** subset p. */
2460 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2461 pTemplate->rRun, pTemplate->nOut,
2462 MIN(p->rRun, pTemplate->rRun),
2463 MIN(p->nOut - 1, pTemplate->nOut)));
2464 pTemplate->rRun = MIN(p->rRun, pTemplate->rRun);
2465 pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut);
2466 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
2467 /* Adjust pTemplate cost upward so that it is costlier than p since
2468 ** pTemplate is a proper subset of p */
2469 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2470 pTemplate->rRun, pTemplate->nOut,
2471 MAX(p->rRun, pTemplate->rRun),
2472 MAX(p->nOut + 1, pTemplate->nOut)));
2473 pTemplate->rRun = MAX(p->rRun, pTemplate->rRun);
2474 pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut);
2480 ** Search the list of WhereLoops in *ppPrev looking for one that can be
2481 ** replaced by pTemplate.
2483 ** Return NULL if pTemplate does not belong on the WhereLoop list.
2484 ** In other words if pTemplate ought to be dropped from further consideration.
2486 ** If pX is a WhereLoop that pTemplate can replace, then return the
2487 ** link that points to pX.
2489 ** If pTemplate cannot replace any existing element of the list but needs
2490 ** to be added to the list as a new entry, then return a pointer to the
2491 ** tail of the list.
2493 static WhereLoop **whereLoopFindLesser(
2494 WhereLoop **ppPrev,
2495 const WhereLoop *pTemplate
2497 WhereLoop *p;
2498 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
2499 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
2500 /* If either the iTab or iSortIdx values for two WhereLoop are different
2501 ** then those WhereLoops need to be considered separately. Neither is
2502 ** a candidate to replace the other. */
2503 continue;
2505 /* In the current implementation, the rSetup value is either zero
2506 ** or the cost of building an automatic index (NlogN) and the NlogN
2507 ** is the same for compatible WhereLoops. */
2508 assert( p->rSetup==0 || pTemplate->rSetup==0
2509 || p->rSetup==pTemplate->rSetup );
2511 /* whereLoopAddBtree() always generates and inserts the automatic index
2512 ** case first. Hence compatible candidate WhereLoops never have a larger
2513 ** rSetup. Call this SETUP-INVARIANT */
2514 assert( p->rSetup>=pTemplate->rSetup );
2516 /* Any loop using an application-defined index (or PRIMARY KEY or
2517 ** UNIQUE constraint) with one or more == constraints is better
2518 ** than an automatic index. Unless it is a skip-scan. */
2519 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
2520 && (pTemplate->nSkip)==0
2521 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
2522 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
2523 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
2525 break;
2528 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
2529 ** discarded. WhereLoop p is better if:
2530 ** (1) p has no more dependencies than pTemplate, and
2531 ** (2) p has an equal or lower cost than pTemplate
2533 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
2534 && p->rSetup<=pTemplate->rSetup /* (2a) */
2535 && p->rRun<=pTemplate->rRun /* (2b) */
2536 && p->nOut<=pTemplate->nOut /* (2c) */
2538 return 0; /* Discard pTemplate */
2541 /* If pTemplate is always better than p, then cause p to be overwritten
2542 ** with pTemplate. pTemplate is better than p if:
2543 ** (1) pTemplate has no more dependencies than p, and
2544 ** (2) pTemplate has an equal or lower cost than p.
2546 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
2547 && p->rRun>=pTemplate->rRun /* (2a) */
2548 && p->nOut>=pTemplate->nOut /* (2b) */
2550 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
2551 break; /* Cause p to be overwritten by pTemplate */
2554 return ppPrev;
2558 ** Insert or replace a WhereLoop entry using the template supplied.
2560 ** An existing WhereLoop entry might be overwritten if the new template
2561 ** is better and has fewer dependencies. Or the template will be ignored
2562 ** and no insert will occur if an existing WhereLoop is faster and has
2563 ** fewer dependencies than the template. Otherwise a new WhereLoop is
2564 ** added based on the template.
2566 ** If pBuilder->pOrSet is not NULL then we care about only the
2567 ** prerequisites and rRun and nOut costs of the N best loops. That
2568 ** information is gathered in the pBuilder->pOrSet object. This special
2569 ** processing mode is used only for OR clause processing.
2571 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
2572 ** still might overwrite similar loops with the new template if the
2573 ** new template is better. Loops may be overwritten if the following
2574 ** conditions are met:
2576 ** (1) They have the same iTab.
2577 ** (2) They have the same iSortIdx.
2578 ** (3) The template has same or fewer dependencies than the current loop
2579 ** (4) The template has the same or lower cost than the current loop
2581 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
2582 WhereLoop **ppPrev, *p;
2583 WhereInfo *pWInfo = pBuilder->pWInfo;
2584 sqlite3 *db = pWInfo->pParse->db;
2585 int rc;
2587 /* Stop the search once we hit the query planner search limit */
2588 if( pBuilder->iPlanLimit==0 ){
2589 WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
2590 if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
2591 return SQLITE_DONE;
2593 pBuilder->iPlanLimit--;
2595 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
2597 /* If pBuilder->pOrSet is defined, then only keep track of the costs
2598 ** and prereqs.
2600 if( pBuilder->pOrSet!=0 ){
2601 if( pTemplate->nLTerm ){
2602 #if WHERETRACE_ENABLED
2603 u16 n = pBuilder->pOrSet->n;
2604 int x =
2605 #endif
2606 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
2607 pTemplate->nOut);
2608 #if WHERETRACE_ENABLED /* 0x8 */
2609 if( sqlite3WhereTrace & 0x8 ){
2610 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
2611 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2613 #endif
2615 return SQLITE_OK;
2618 /* Look for an existing WhereLoop to replace with pTemplate
2620 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
2622 if( ppPrev==0 ){
2623 /* There already exists a WhereLoop on the list that is better
2624 ** than pTemplate, so just ignore pTemplate */
2625 #if WHERETRACE_ENABLED /* 0x8 */
2626 if( sqlite3WhereTrace & 0x8 ){
2627 sqlite3DebugPrintf(" skip: ");
2628 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2630 #endif
2631 return SQLITE_OK;
2632 }else{
2633 p = *ppPrev;
2636 /* If we reach this point it means that either p[] should be overwritten
2637 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
2638 ** WhereLoop and insert it.
2640 #if WHERETRACE_ENABLED /* 0x8 */
2641 if( sqlite3WhereTrace & 0x8 ){
2642 if( p!=0 ){
2643 sqlite3DebugPrintf("replace: ");
2644 sqlite3WhereLoopPrint(p, pBuilder->pWC);
2645 sqlite3DebugPrintf(" with: ");
2646 }else{
2647 sqlite3DebugPrintf(" add: ");
2649 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2651 #endif
2652 if( p==0 ){
2653 /* Allocate a new WhereLoop to add to the end of the list */
2654 *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
2655 if( p==0 ) return SQLITE_NOMEM_BKPT;
2656 whereLoopInit(p);
2657 p->pNextLoop = 0;
2658 }else{
2659 /* We will be overwriting WhereLoop p[]. But before we do, first
2660 ** go through the rest of the list and delete any other entries besides
2661 ** p[] that are also supplanted by pTemplate */
2662 WhereLoop **ppTail = &p->pNextLoop;
2663 WhereLoop *pToDel;
2664 while( *ppTail ){
2665 ppTail = whereLoopFindLesser(ppTail, pTemplate);
2666 if( ppTail==0 ) break;
2667 pToDel = *ppTail;
2668 if( pToDel==0 ) break;
2669 *ppTail = pToDel->pNextLoop;
2670 #if WHERETRACE_ENABLED /* 0x8 */
2671 if( sqlite3WhereTrace & 0x8 ){
2672 sqlite3DebugPrintf(" delete: ");
2673 sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
2675 #endif
2676 whereLoopDelete(db, pToDel);
2679 rc = whereLoopXfer(db, p, pTemplate);
2680 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2681 Index *pIndex = p->u.btree.pIndex;
2682 if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
2683 p->u.btree.pIndex = 0;
2686 return rc;
2690 ** Adjust the WhereLoop.nOut value downward to account for terms of the
2691 ** WHERE clause that reference the loop but which are not used by an
2692 ** index.
2694 ** For every WHERE clause term that is not used by the index
2695 ** and which has a truth probability assigned by one of the likelihood(),
2696 ** likely(), or unlikely() SQL functions, reduce the estimated number
2697 ** of output rows by the probability specified.
2699 ** TUNING: For every WHERE clause term that is not used by the index
2700 ** and which does not have an assigned truth probability, heuristics
2701 ** described below are used to try to estimate the truth probability.
2702 ** TODO --> Perhaps this is something that could be improved by better
2703 ** table statistics.
2705 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
2706 ** value corresponds to -1 in LogEst notation, so this means decrement
2707 ** the WhereLoop.nOut field for every such WHERE clause term.
2709 ** Heuristic 2: If there exists one or more WHERE clause terms of the
2710 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
2711 ** final output row estimate is no greater than 1/4 of the total number
2712 ** of rows in the table. In other words, assume that x==EXPR will filter
2713 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
2714 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
2715 ** on the "x" column and so in that case only cap the output row estimate
2716 ** at 1/2 instead of 1/4.
2718 static void whereLoopOutputAdjust(
2719 WhereClause *pWC, /* The WHERE clause */
2720 WhereLoop *pLoop, /* The loop to adjust downward */
2721 LogEst nRow /* Number of rows in the entire table */
2723 WhereTerm *pTerm, *pX;
2724 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
2725 int i, j;
2726 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
2728 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
2729 for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){
2730 assert( pTerm!=0 );
2731 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
2732 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
2733 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue;
2734 for(j=pLoop->nLTerm-1; j>=0; j--){
2735 pX = pLoop->aLTerm[j];
2736 if( pX==0 ) continue;
2737 if( pX==pTerm ) break;
2738 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
2740 if( j<0 ){
2741 sqlite3ProgressCheck(pWC->pWInfo->pParse);
2742 if( pLoop->maskSelf==pTerm->prereqAll ){
2743 /* If there are extra terms in the WHERE clause not used by an index
2744 ** that depend only on the table being scanned, and that will tend to
2745 ** cause many rows to be omitted, then mark that table as
2746 ** "self-culling".
2748 ** 2022-03-24: Self-culling only applies if either the extra terms
2749 ** are straight comparison operators that are non-true with NULL
2750 ** operand, or if the loop is not an OUTER JOIN.
2752 if( (pTerm->eOperator & 0x3f)!=0
2753 || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype
2754 & (JT_LEFT|JT_LTORJ))==0
2756 pLoop->wsFlags |= WHERE_SELFCULL;
2759 if( pTerm->truthProb<=0 ){
2760 /* If a truth probability is specified using the likelihood() hints,
2761 ** then use the probability provided by the application. */
2762 pLoop->nOut += pTerm->truthProb;
2763 }else{
2764 /* In the absence of explicit truth probabilities, use heuristics to
2765 ** guess a reasonable truth probability. */
2766 pLoop->nOut--;
2767 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
2768 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */
2770 Expr *pRight = pTerm->pExpr->pRight;
2771 int k = 0;
2772 testcase( pTerm->pExpr->op==TK_IS );
2773 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
2774 k = 10;
2775 }else{
2776 k = 20;
2778 if( iReduce<k ){
2779 pTerm->wtFlags |= TERM_HEURTRUTH;
2780 iReduce = k;
2786 if( pLoop->nOut > nRow-iReduce ){
2787 pLoop->nOut = nRow - iReduce;
2792 ** Term pTerm is a vector range comparison operation. The first comparison
2793 ** in the vector can be optimized using column nEq of the index. This
2794 ** function returns the total number of vector elements that can be used
2795 ** as part of the range comparison.
2797 ** For example, if the query is:
2799 ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
2801 ** and the index:
2803 ** CREATE INDEX ... ON (a, b, c, d, e)
2805 ** then this function would be invoked with nEq=1. The value returned in
2806 ** this case is 3.
2808 static int whereRangeVectorLen(
2809 Parse *pParse, /* Parsing context */
2810 int iCur, /* Cursor open on pIdx */
2811 Index *pIdx, /* The index to be used for a inequality constraint */
2812 int nEq, /* Number of prior equality constraints on same index */
2813 WhereTerm *pTerm /* The vector inequality constraint */
2815 int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
2816 int i;
2818 nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
2819 for(i=1; i<nCmp; i++){
2820 /* Test if comparison i of pTerm is compatible with column (i+nEq)
2821 ** of the index. If not, exit the loop. */
2822 char aff; /* Comparison affinity */
2823 char idxaff = 0; /* Indexed columns affinity */
2824 CollSeq *pColl; /* Comparison collation sequence */
2825 Expr *pLhs, *pRhs;
2827 assert( ExprUseXList(pTerm->pExpr->pLeft) );
2828 pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
2829 pRhs = pTerm->pExpr->pRight;
2830 if( ExprUseXSelect(pRhs) ){
2831 pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
2832 }else{
2833 pRhs = pRhs->x.pList->a[i].pExpr;
2836 /* Check that the LHS of the comparison is a column reference to
2837 ** the right column of the right source table. And that the sort
2838 ** order of the index column is the same as the sort order of the
2839 ** leftmost index column. */
2840 if( pLhs->op!=TK_COLUMN
2841 || pLhs->iTable!=iCur
2842 || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
2843 || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
2845 break;
2848 testcase( pLhs->iColumn==XN_ROWID );
2849 aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
2850 idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
2851 if( aff!=idxaff ) break;
2853 pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2854 if( pColl==0 ) break;
2855 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
2857 return i;
2861 ** Adjust the cost C by the costMult factor T. This only occurs if
2862 ** compiled with -DSQLITE_ENABLE_COSTMULT
2864 #ifdef SQLITE_ENABLE_COSTMULT
2865 # define ApplyCostMultiplier(C,T) C += T
2866 #else
2867 # define ApplyCostMultiplier(C,T)
2868 #endif
2871 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
2872 ** index pIndex. Try to match one more.
2874 ** When this function is called, pBuilder->pNew->nOut contains the
2875 ** number of rows expected to be visited by filtering using the nEq
2876 ** terms only. If it is modified, this value is restored before this
2877 ** function returns.
2879 ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
2880 ** a fake index used for the INTEGER PRIMARY KEY.
2882 static int whereLoopAddBtreeIndex(
2883 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
2884 SrcItem *pSrc, /* FROM clause term being analyzed */
2885 Index *pProbe, /* An index on pSrc */
2886 LogEst nInMul /* log(Number of iterations due to IN) */
2888 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyze context */
2889 Parse *pParse = pWInfo->pParse; /* Parsing context */
2890 sqlite3 *db = pParse->db; /* Database connection malloc context */
2891 WhereLoop *pNew; /* Template WhereLoop under construction */
2892 WhereTerm *pTerm; /* A WhereTerm under consideration */
2893 int opMask; /* Valid operators for constraints */
2894 WhereScan scan; /* Iterator for WHERE terms */
2895 Bitmask saved_prereq; /* Original value of pNew->prereq */
2896 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
2897 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
2898 u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
2899 u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
2900 u16 saved_nSkip; /* Original value of pNew->nSkip */
2901 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
2902 LogEst saved_nOut; /* Original value of pNew->nOut */
2903 int rc = SQLITE_OK; /* Return code */
2904 LogEst rSize; /* Number of rows in the table */
2905 LogEst rLogSize; /* Logarithm of table size */
2906 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
2908 pNew = pBuilder->pNew;
2909 assert( db->mallocFailed==0 || pParse->nErr>0 );
2910 if( pParse->nErr ){
2911 return pParse->rc;
2913 WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n",
2914 pProbe->pTable->zName,pProbe->zName,
2915 pNew->u.btree.nEq, pNew->nSkip, pNew->rRun));
2917 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
2918 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
2919 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
2920 opMask = WO_LT|WO_LE;
2921 }else{
2922 assert( pNew->u.btree.nBtm==0 );
2923 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
2925 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
2927 assert( pNew->u.btree.nEq<pProbe->nColumn );
2928 assert( pNew->u.btree.nEq<pProbe->nKeyCol
2929 || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
2931 saved_nEq = pNew->u.btree.nEq;
2932 saved_nBtm = pNew->u.btree.nBtm;
2933 saved_nTop = pNew->u.btree.nTop;
2934 saved_nSkip = pNew->nSkip;
2935 saved_nLTerm = pNew->nLTerm;
2936 saved_wsFlags = pNew->wsFlags;
2937 saved_prereq = pNew->prereq;
2938 saved_nOut = pNew->nOut;
2939 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
2940 opMask, pProbe);
2941 pNew->rSetup = 0;
2942 rSize = pProbe->aiRowLogEst[0];
2943 rLogSize = estLog(rSize);
2944 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
2945 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
2946 LogEst rCostIdx;
2947 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
2948 int nIn = 0;
2949 #ifdef SQLITE_ENABLE_STAT4
2950 int nRecValid = pBuilder->nRecValid;
2951 #endif
2952 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
2953 && indexColumnNotNull(pProbe, saved_nEq)
2955 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
2957 if( pTerm->prereqRight & pNew->maskSelf ) continue;
2959 /* Do not allow the upper bound of a LIKE optimization range constraint
2960 ** to mix with a lower range bound from some other source */
2961 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
2963 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
2964 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
2966 continue;
2968 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
2969 pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
2970 }else{
2971 pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
2973 pNew->wsFlags = saved_wsFlags;
2974 pNew->u.btree.nEq = saved_nEq;
2975 pNew->u.btree.nBtm = saved_nBtm;
2976 pNew->u.btree.nTop = saved_nTop;
2977 pNew->nLTerm = saved_nLTerm;
2978 if( pNew->nLTerm>=pNew->nLSlot
2979 && whereLoopResize(db, pNew, pNew->nLTerm+1)
2981 break; /* OOM while trying to enlarge the pNew->aLTerm array */
2983 pNew->aLTerm[pNew->nLTerm++] = pTerm;
2984 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
2986 assert( nInMul==0
2987 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
2988 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
2989 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
2992 if( eOp & WO_IN ){
2993 Expr *pExpr = pTerm->pExpr;
2994 if( ExprUseXSelect(pExpr) ){
2995 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
2996 int i;
2997 nIn = 46; assert( 46==sqlite3LogEst(25) );
2999 /* The expression may actually be of the form (x, y) IN (SELECT...).
3000 ** In this case there is a separate term for each of (x) and (y).
3001 ** However, the nIn multiplier should only be applied once, not once
3002 ** for each such term. The following loop checks that pTerm is the
3003 ** first such term in use, and sets nIn back to 0 if it is not. */
3004 for(i=0; i<pNew->nLTerm-1; i++){
3005 if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
3007 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3008 /* "x IN (value, value, ...)" */
3009 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
3011 if( pProbe->hasStat1 && rLogSize>=10 ){
3012 LogEst M, logK, x;
3013 /* Let:
3014 ** N = the total number of rows in the table
3015 ** K = the number of entries on the RHS of the IN operator
3016 ** M = the number of rows in the table that match terms to the
3017 ** to the left in the same index. If the IN operator is on
3018 ** the left-most index column, M==N.
3020 ** Given the definitions above, it is better to omit the IN operator
3021 ** from the index lookup and instead do a scan of the M elements,
3022 ** testing each scanned row against the IN operator separately, if:
3024 ** M*log(K) < K*log(N)
3026 ** Our estimates for M, K, and N might be inaccurate, so we build in
3027 ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
3028 ** with the index, as using an index has better worst-case behavior.
3029 ** If we do not have real sqlite_stat1 data, always prefer to use
3030 ** the index. Do not bother with this optimization on very small
3031 ** tables (less than 2 rows) as it is pointless in that case.
3033 M = pProbe->aiRowLogEst[saved_nEq];
3034 logK = estLog(nIn);
3035 /* TUNING v----- 10 to bias toward indexed IN */
3036 x = M + logK + 10 - (nIn + rLogSize);
3037 if( x>=0 ){
3038 WHERETRACE(0x40,
3039 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) "
3040 "prefers indexed lookup\n",
3041 saved_nEq, M, logK, nIn, rLogSize, x));
3042 }else if( nInMul<2 && OptimizationEnabled(db, SQLITE_SeekScan) ){
3043 WHERETRACE(0x40,
3044 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3045 " nInMul=%d) prefers skip-scan\n",
3046 saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
3047 pNew->wsFlags |= WHERE_IN_SEEKSCAN;
3048 }else{
3049 WHERETRACE(0x40,
3050 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3051 " nInMul=%d) prefers normal scan\n",
3052 saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
3053 continue;
3056 pNew->wsFlags |= WHERE_COLUMN_IN;
3057 }else if( eOp & (WO_EQ|WO_IS) ){
3058 int iCol = pProbe->aiColumn[saved_nEq];
3059 pNew->wsFlags |= WHERE_COLUMN_EQ;
3060 assert( saved_nEq==pNew->u.btree.nEq );
3061 if( iCol==XN_ROWID
3062 || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
3064 if( iCol==XN_ROWID || pProbe->uniqNotNull
3065 || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
3067 pNew->wsFlags |= WHERE_ONEROW;
3068 }else{
3069 pNew->wsFlags |= WHERE_UNQ_WANTED;
3072 if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
3073 }else if( eOp & WO_ISNULL ){
3074 pNew->wsFlags |= WHERE_COLUMN_NULL;
3075 }else{
3076 int nVecLen = whereRangeVectorLen(
3077 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
3079 if( eOp & (WO_GT|WO_GE) ){
3080 testcase( eOp & WO_GT );
3081 testcase( eOp & WO_GE );
3082 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
3083 pNew->u.btree.nBtm = nVecLen;
3084 pBtm = pTerm;
3085 pTop = 0;
3086 if( pTerm->wtFlags & TERM_LIKEOPT ){
3087 /* Range constraints that come from the LIKE optimization are
3088 ** always used in pairs. */
3089 pTop = &pTerm[1];
3090 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
3091 assert( pTop->wtFlags & TERM_LIKEOPT );
3092 assert( pTop->eOperator==WO_LT );
3093 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3094 pNew->aLTerm[pNew->nLTerm++] = pTop;
3095 pNew->wsFlags |= WHERE_TOP_LIMIT;
3096 pNew->u.btree.nTop = 1;
3098 }else{
3099 assert( eOp & (WO_LT|WO_LE) );
3100 testcase( eOp & WO_LT );
3101 testcase( eOp & WO_LE );
3102 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
3103 pNew->u.btree.nTop = nVecLen;
3104 pTop = pTerm;
3105 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
3106 pNew->aLTerm[pNew->nLTerm-2] : 0;
3110 /* At this point pNew->nOut is set to the number of rows expected to
3111 ** be visited by the index scan before considering term pTerm, or the
3112 ** values of nIn and nInMul. In other words, assuming that all
3113 ** "x IN(...)" terms are replaced with "x = ?". This block updates
3114 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
3115 assert( pNew->nOut==saved_nOut );
3116 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3117 /* Adjust nOut using stat4 data. Or, if there is no stat4
3118 ** data, using some other estimate. */
3119 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
3120 }else{
3121 int nEq = ++pNew->u.btree.nEq;
3122 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
3124 assert( pNew->nOut==saved_nOut );
3125 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
3126 assert( (eOp & WO_IN) || nIn==0 );
3127 testcase( eOp & WO_IN );
3128 pNew->nOut += pTerm->truthProb;
3129 pNew->nOut -= nIn;
3130 }else{
3131 #ifdef SQLITE_ENABLE_STAT4
3132 tRowcnt nOut = 0;
3133 if( nInMul==0
3134 && pProbe->nSample
3135 && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol)
3136 && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr))
3137 && OptimizationEnabled(db, SQLITE_Stat4)
3139 Expr *pExpr = pTerm->pExpr;
3140 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
3141 testcase( eOp & WO_EQ );
3142 testcase( eOp & WO_IS );
3143 testcase( eOp & WO_ISNULL );
3144 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
3145 }else{
3146 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
3148 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
3149 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
3150 if( nOut ){
3151 pNew->nOut = sqlite3LogEst(nOut);
3152 if( nEq==1
3153 /* TUNING: Mark terms as "low selectivity" if they seem likely
3154 ** to be true for half or more of the rows in the table.
3155 ** See tag-202002240-1 */
3156 && pNew->nOut+10 > pProbe->aiRowLogEst[0]
3158 #if WHERETRACE_ENABLED /* 0x01 */
3159 if( sqlite3WhereTrace & 0x20 ){
3160 sqlite3DebugPrintf(
3161 "STAT4 determines term has low selectivity:\n");
3162 sqlite3WhereTermPrint(pTerm, 999);
3164 #endif
3165 pTerm->wtFlags |= TERM_HIGHTRUTH;
3166 if( pTerm->wtFlags & TERM_HEURTRUTH ){
3167 /* If the term has previously been used with an assumption of
3168 ** higher selectivity, then set the flag to rerun the
3169 ** loop computations. */
3170 pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
3173 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
3174 pNew->nOut -= nIn;
3177 if( nOut==0 )
3178 #endif
3180 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
3181 if( eOp & WO_ISNULL ){
3182 /* TUNING: If there is no likelihood() value, assume that a
3183 ** "col IS NULL" expression matches twice as many rows
3184 ** as (col=?). */
3185 pNew->nOut += 10;
3191 /* Set rCostIdx to the cost of visiting selected rows in index. Add
3192 ** it to pNew->rRun, which is currently set to the cost of the index
3193 ** seek only. Then, if this is a non-covering index, add the cost of
3194 ** visiting the rows in the main table. */
3195 assert( pSrc->pTab->szTabRow>0 );
3196 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
3197 /* The pProbe->szIdxRow is low for an IPK table since the interior
3198 ** pages are small. Thus szIdxRow gives a good estimate of seek cost.
3199 ** But the leaf pages are full-size, so pProbe->szIdxRow would badly
3200 ** under-estimate the scanning cost. */
3201 rCostIdx = pNew->nOut + 16;
3202 }else{
3203 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
3205 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
3206 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK|WHERE_EXPRIDX))==0 ){
3207 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
3209 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
3211 nOutUnadjusted = pNew->nOut;
3212 pNew->rRun += nInMul + nIn;
3213 pNew->nOut += nInMul + nIn;
3214 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
3215 rc = whereLoopInsert(pBuilder, pNew);
3217 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3218 pNew->nOut = saved_nOut;
3219 }else{
3220 pNew->nOut = nOutUnadjusted;
3223 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
3224 && pNew->u.btree.nEq<pProbe->nColumn
3225 && (pNew->u.btree.nEq<pProbe->nKeyCol ||
3226 pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)
3228 if( pNew->u.btree.nEq>3 ){
3229 sqlite3ProgressCheck(pParse);
3231 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
3233 pNew->nOut = saved_nOut;
3234 #ifdef SQLITE_ENABLE_STAT4
3235 pBuilder->nRecValid = nRecValid;
3236 #endif
3238 pNew->prereq = saved_prereq;
3239 pNew->u.btree.nEq = saved_nEq;
3240 pNew->u.btree.nBtm = saved_nBtm;
3241 pNew->u.btree.nTop = saved_nTop;
3242 pNew->nSkip = saved_nSkip;
3243 pNew->wsFlags = saved_wsFlags;
3244 pNew->nOut = saved_nOut;
3245 pNew->nLTerm = saved_nLTerm;
3247 /* Consider using a skip-scan if there are no WHERE clause constraints
3248 ** available for the left-most terms of the index, and if the average
3249 ** number of repeats in the left-most terms is at least 18.
3251 ** The magic number 18 is selected on the basis that scanning 17 rows
3252 ** is almost always quicker than an index seek (even though if the index
3253 ** contains fewer than 2^17 rows we assume otherwise in other parts of
3254 ** the code). And, even if it is not, it should not be too much slower.
3255 ** On the other hand, the extra seeks could end up being significantly
3256 ** more expensive. */
3257 assert( 42==sqlite3LogEst(18) );
3258 if( saved_nEq==saved_nSkip
3259 && saved_nEq+1<pProbe->nKeyCol
3260 && saved_nEq==pNew->nLTerm
3261 && pProbe->noSkipScan==0
3262 && pProbe->hasStat1!=0
3263 && OptimizationEnabled(db, SQLITE_SkipScan)
3264 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
3265 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
3267 LogEst nIter;
3268 pNew->u.btree.nEq++;
3269 pNew->nSkip++;
3270 pNew->aLTerm[pNew->nLTerm++] = 0;
3271 pNew->wsFlags |= WHERE_SKIPSCAN;
3272 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
3273 pNew->nOut -= nIter;
3274 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
3275 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
3276 nIter += 5;
3277 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
3278 pNew->nOut = saved_nOut;
3279 pNew->u.btree.nEq = saved_nEq;
3280 pNew->nSkip = saved_nSkip;
3281 pNew->wsFlags = saved_wsFlags;
3284 WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
3285 pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
3286 return rc;
3290 ** Return True if it is possible that pIndex might be useful in
3291 ** implementing the ORDER BY clause in pBuilder.
3293 ** Return False if pBuilder does not contain an ORDER BY clause or
3294 ** if there is no way for pIndex to be useful in implementing that
3295 ** ORDER BY clause.
3297 static int indexMightHelpWithOrderBy(
3298 WhereLoopBuilder *pBuilder,
3299 Index *pIndex,
3300 int iCursor
3302 ExprList *pOB;
3303 ExprList *aColExpr;
3304 int ii, jj;
3306 if( pIndex->bUnordered ) return 0;
3307 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
3308 for(ii=0; ii<pOB->nExpr; ii++){
3309 Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
3310 if( NEVER(pExpr==0) ) continue;
3311 if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
3312 if( pExpr->iColumn<0 ) return 1;
3313 for(jj=0; jj<pIndex->nKeyCol; jj++){
3314 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
3316 }else if( (aColExpr = pIndex->aColExpr)!=0 ){
3317 for(jj=0; jj<pIndex->nKeyCol; jj++){
3318 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
3319 if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
3320 return 1;
3325 return 0;
3328 /* Check to see if a partial index with pPartIndexWhere can be used
3329 ** in the current query. Return true if it can be and false if not.
3331 static int whereUsablePartialIndex(
3332 int iTab, /* The table for which we want an index */
3333 u8 jointype, /* The JT_* flags on the join */
3334 WhereClause *pWC, /* The WHERE clause of the query */
3335 Expr *pWhere /* The WHERE clause from the partial index */
3337 int i;
3338 WhereTerm *pTerm;
3339 Parse *pParse;
3341 if( jointype & JT_LTORJ ) return 0;
3342 pParse = pWC->pWInfo->pParse;
3343 while( pWhere->op==TK_AND ){
3344 if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0;
3345 pWhere = pWhere->pRight;
3347 if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
3348 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
3349 Expr *pExpr;
3350 pExpr = pTerm->pExpr;
3351 if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab)
3352 && ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON))
3353 && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
3354 && (pTerm->wtFlags & TERM_VNULL)==0
3356 return 1;
3359 return 0;
3363 ** pIdx is an index containing expressions. Check it see if any of the
3364 ** expressions in the index match the pExpr expression.
3366 static int exprIsCoveredByIndex(
3367 const Expr *pExpr,
3368 const Index *pIdx,
3369 int iTabCur
3371 int i;
3372 for(i=0; i<pIdx->nColumn; i++){
3373 if( pIdx->aiColumn[i]==XN_EXPR
3374 && sqlite3ExprCompare(0, pExpr, pIdx->aColExpr->a[i].pExpr, iTabCur)==0
3376 return 1;
3379 return 0;
3383 ** Structure passed to the whereIsCoveringIndex Walker callback.
3385 typedef struct CoveringIndexCheck CoveringIndexCheck;
3386 struct CoveringIndexCheck {
3387 Index *pIdx; /* The index */
3388 int iTabCur; /* Cursor number for the corresponding table */
3389 u8 bExpr; /* Uses an indexed expression */
3390 u8 bUnidx; /* Uses an unindexed column not within an indexed expr */
3394 ** Information passed in is pWalk->u.pCovIdxCk. Call it pCk.
3396 ** If the Expr node references the table with cursor pCk->iTabCur, then
3397 ** make sure that column is covered by the index pCk->pIdx. We know that
3398 ** all columns less than 63 (really BMS-1) are covered, so we don't need
3399 ** to check them. But we do need to check any column at 63 or greater.
3401 ** If the index does not cover the column, then set pWalk->eCode to
3402 ** non-zero and return WRC_Abort to stop the search.
3404 ** If this node does not disprove that the index can be a covering index,
3405 ** then just return WRC_Continue, to continue the search.
3407 ** If pCk->pIdx contains indexed expressions and one of those expressions
3408 ** matches pExpr, then prune the search.
3410 static int whereIsCoveringIndexWalkCallback(Walker *pWalk, Expr *pExpr){
3411 int i; /* Loop counter */
3412 const Index *pIdx; /* The index of interest */
3413 const i16 *aiColumn; /* Columns contained in the index */
3414 u16 nColumn; /* Number of columns in the index */
3415 CoveringIndexCheck *pCk; /* Info about this search */
3417 pCk = pWalk->u.pCovIdxCk;
3418 pIdx = pCk->pIdx;
3419 if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){
3420 /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
3421 if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue;
3422 pIdx = pWalk->u.pCovIdxCk->pIdx;
3423 aiColumn = pIdx->aiColumn;
3424 nColumn = pIdx->nColumn;
3425 for(i=0; i<nColumn; i++){
3426 if( aiColumn[i]==pExpr->iColumn ) return WRC_Continue;
3428 pCk->bUnidx = 1;
3429 return WRC_Abort;
3430 }else if( pIdx->bHasExpr
3431 && exprIsCoveredByIndex(pExpr, pIdx, pWalk->u.pCovIdxCk->iTabCur) ){
3432 pCk->bExpr = 1;
3433 return WRC_Prune;
3435 return WRC_Continue;
3440 ** pIdx is an index that covers all of the low-number columns used by
3441 ** pWInfo->pSelect (columns from 0 through 62) or an index that has
3442 ** expressions terms. Hence, we cannot determine whether or not it is
3443 ** a covering index by using the colUsed bitmasks. We have to do a search
3444 ** to see if the index is covering. This routine does that search.
3446 ** The return value is one of these:
3448 ** 0 The index is definitely not a covering index
3450 ** WHERE_IDX_ONLY The index is definitely a covering index
3452 ** WHERE_EXPRIDX The index is likely a covering index, but it is
3453 ** difficult to determine precisely because of the
3454 ** expressions that are indexed. Score it as a
3455 ** covering index, but still keep the main table open
3456 ** just in case we need it.
3458 ** This routine is an optimization. It is always safe to return zero.
3459 ** But returning one of the other two values when zero should have been
3460 ** returned can lead to incorrect bytecode and assertion faults.
3462 static SQLITE_NOINLINE u32 whereIsCoveringIndex(
3463 WhereInfo *pWInfo, /* The WHERE clause context */
3464 Index *pIdx, /* Index that is being tested */
3465 int iTabCur /* Cursor for the table being indexed */
3467 int i, rc;
3468 struct CoveringIndexCheck ck;
3469 Walker w;
3470 if( pWInfo->pSelect==0 ){
3471 /* We don't have access to the full query, so we cannot check to see
3472 ** if pIdx is covering. Assume it is not. */
3473 return 0;
3475 if( pIdx->bHasExpr==0 ){
3476 for(i=0; i<pIdx->nColumn; i++){
3477 if( pIdx->aiColumn[i]>=BMS-1 ) break;
3479 if( i>=pIdx->nColumn ){
3480 /* pIdx does not index any columns greater than 62, but we know from
3481 ** colMask that columns greater than 62 are used, so this is not a
3482 ** covering index */
3483 return 0;
3486 ck.pIdx = pIdx;
3487 ck.iTabCur = iTabCur;
3488 ck.bExpr = 0;
3489 ck.bUnidx = 0;
3490 memset(&w, 0, sizeof(w));
3491 w.xExprCallback = whereIsCoveringIndexWalkCallback;
3492 w.xSelectCallback = sqlite3SelectWalkNoop;
3493 w.u.pCovIdxCk = &ck;
3494 sqlite3WalkSelect(&w, pWInfo->pSelect);
3495 if( ck.bUnidx ){
3496 rc = 0;
3497 }else if( ck.bExpr ){
3498 rc = WHERE_EXPRIDX;
3499 }else{
3500 rc = WHERE_IDX_ONLY;
3502 return rc;
3506 ** This is an sqlite3ParserAddCleanup() callback that is invoked to
3507 ** free the Parse->pIdxEpr list when the Parse object is destroyed.
3509 static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){
3510 IndexedExpr **pp = (IndexedExpr**)pObject;
3511 while( *pp!=0 ){
3512 IndexedExpr *p = *pp;
3513 *pp = p->pIENext;
3514 sqlite3ExprDelete(db, p->pExpr);
3515 sqlite3DbFreeNN(db, p);
3520 ** This function is called for a partial index - one with a WHERE clause - in
3521 ** two scenarios. In both cases, it determines whether or not the WHERE
3522 ** clause on the index implies that a column of the table may be safely
3523 ** replaced by a constant expression. For example, in the following
3524 ** SELECT:
3526 ** CREATE INDEX i1 ON t1(b, c) WHERE a=<expr>;
3527 ** SELECT a, b, c FROM t1 WHERE a=<expr> AND b=?;
3529 ** The "a" in the select-list may be replaced by <expr>, iff:
3531 ** (a) <expr> is a constant expression, and
3532 ** (b) The (a=<expr>) comparison uses the BINARY collation sequence, and
3533 ** (c) Column "a" has an affinity other than NONE or BLOB.
3535 ** If argument pItem is NULL, then pMask must not be NULL. In this case this
3536 ** function is being called as part of determining whether or not pIdx
3537 ** is a covering index. This function clears any bits in (*pMask)
3538 ** corresponding to columns that may be replaced by constants as described
3539 ** above.
3541 ** Otherwise, if pItem is not NULL, then this function is being called
3542 ** as part of coding a loop that uses index pIdx. In this case, add entries
3543 ** to the Parse.pIdxPartExpr list for each column that can be replaced
3544 ** by a constant.
3546 static void wherePartIdxExpr(
3547 Parse *pParse, /* Parse context */
3548 Index *pIdx, /* Partial index being processed */
3549 Expr *pPart, /* WHERE clause being processed */
3550 Bitmask *pMask, /* Mask to clear bits in */
3551 int iIdxCur, /* Cursor number for index */
3552 SrcItem *pItem /* The FROM clause entry for the table */
3554 assert( pItem==0 || (pItem->fg.jointype & JT_RIGHT)==0 );
3555 assert( (pItem==0 || pMask==0) && (pMask!=0 || pItem!=0) );
3557 if( pPart->op==TK_AND ){
3558 wherePartIdxExpr(pParse, pIdx, pPart->pRight, pMask, iIdxCur, pItem);
3559 pPart = pPart->pLeft;
3562 if( (pPart->op==TK_EQ || pPart->op==TK_IS) ){
3563 Expr *pLeft = pPart->pLeft;
3564 Expr *pRight = pPart->pRight;
3565 u8 aff;
3567 if( pRight->op==TK_COLUMN ){
3568 SWAP(Expr*, pLeft, pRight);
3571 if( pLeft->op!=TK_COLUMN ) return;
3572 if( !sqlite3ExprIsConstant(pRight) ) return;
3573 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pParse, pPart)) ) return;
3574 if( pLeft->iColumn<0 ) return;
3575 aff = pIdx->pTable->aCol[pLeft->iColumn].affinity;
3576 if( aff>=SQLITE_AFF_TEXT ){
3577 if( pItem ){
3578 sqlite3 *db = pParse->db;
3579 IndexedExpr *p = (IndexedExpr*)sqlite3DbMallocRaw(db, sizeof(*p));
3580 if( p ){
3581 int bNullRow = (pItem->fg.jointype&(JT_LEFT|JT_LTORJ))!=0;
3582 p->pExpr = sqlite3ExprDup(db, pRight, 0);
3583 p->iDataCur = pItem->iCursor;
3584 p->iIdxCur = iIdxCur;
3585 p->iIdxCol = pLeft->iColumn;
3586 p->bMaybeNullRow = bNullRow;
3587 p->pIENext = pParse->pIdxPartExpr;
3588 p->aff = aff;
3589 pParse->pIdxPartExpr = p;
3590 if( p->pIENext==0 ){
3591 void *pArg = (void*)&pParse->pIdxPartExpr;
3592 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
3595 }else if( pLeft->iColumn<(BMS-1) ){
3596 *pMask &= ~((Bitmask)1 << pLeft->iColumn);
3604 ** Add all WhereLoop objects for a single table of the join where the table
3605 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
3606 ** a b-tree table, not a virtual table.
3608 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
3609 ** are calculated as follows:
3611 ** For a full scan, assuming the table (or index) contains nRow rows:
3613 ** cost = nRow * 3.0 // full-table scan
3614 ** cost = nRow * K // scan of covering index
3615 ** cost = nRow * (K+3.0) // scan of non-covering index
3617 ** where K is a value between 1.1 and 3.0 set based on the relative
3618 ** estimated average size of the index and table records.
3620 ** For an index scan, where nVisit is the number of index rows visited
3621 ** by the scan, and nSeek is the number of seek operations required on
3622 ** the index b-tree:
3624 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
3625 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
3627 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
3628 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
3629 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
3631 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
3632 ** of uncertainty. For this reason, scoring is designed to pick plans that
3633 ** "do the least harm" if the estimates are inaccurate. For example, a
3634 ** log(nRow) factor is omitted from a non-covering index scan in order to
3635 ** bias the scoring in favor of using an index, since the worst-case
3636 ** performance of using an index is far better than the worst-case performance
3637 ** of a full table scan.
3639 static int whereLoopAddBtree(
3640 WhereLoopBuilder *pBuilder, /* WHERE clause information */
3641 Bitmask mPrereq /* Extra prerequisites for using this table */
3643 WhereInfo *pWInfo; /* WHERE analysis context */
3644 Index *pProbe; /* An index we are evaluating */
3645 Index sPk; /* A fake index object for the primary key */
3646 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
3647 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
3648 SrcList *pTabList; /* The FROM clause */
3649 SrcItem *pSrc; /* The FROM clause btree term to add */
3650 WhereLoop *pNew; /* Template WhereLoop object */
3651 int rc = SQLITE_OK; /* Return code */
3652 int iSortIdx = 1; /* Index number */
3653 int b; /* A boolean value */
3654 LogEst rSize; /* number of rows in the table */
3655 WhereClause *pWC; /* The parsed WHERE clause */
3656 Table *pTab; /* Table being queried */
3658 pNew = pBuilder->pNew;
3659 pWInfo = pBuilder->pWInfo;
3660 pTabList = pWInfo->pTabList;
3661 pSrc = pTabList->a + pNew->iTab;
3662 pTab = pSrc->pTab;
3663 pWC = pBuilder->pWC;
3664 assert( !IsVirtual(pSrc->pTab) );
3666 if( pSrc->fg.isIndexedBy ){
3667 assert( pSrc->fg.isCte==0 );
3668 /* An INDEXED BY clause specifies a particular index to use */
3669 pProbe = pSrc->u2.pIBIndex;
3670 }else if( !HasRowid(pTab) ){
3671 pProbe = pTab->pIndex;
3672 }else{
3673 /* There is no INDEXED BY clause. Create a fake Index object in local
3674 ** variable sPk to represent the rowid primary key index. Make this
3675 ** fake index the first in a chain of Index objects with all of the real
3676 ** indices to follow */
3677 Index *pFirst; /* First of real indices on the table */
3678 memset(&sPk, 0, sizeof(Index));
3679 sPk.nKeyCol = 1;
3680 sPk.nColumn = 1;
3681 sPk.aiColumn = &aiColumnPk;
3682 sPk.aiRowLogEst = aiRowEstPk;
3683 sPk.onError = OE_Replace;
3684 sPk.pTable = pTab;
3685 sPk.szIdxRow = 3; /* TUNING: Interior rows of IPK table are very small */
3686 sPk.idxType = SQLITE_IDXTYPE_IPK;
3687 aiRowEstPk[0] = pTab->nRowLogEst;
3688 aiRowEstPk[1] = 0;
3689 pFirst = pSrc->pTab->pIndex;
3690 if( pSrc->fg.notIndexed==0 ){
3691 /* The real indices of the table are only considered if the
3692 ** NOT INDEXED qualifier is omitted from the FROM clause */
3693 sPk.pNext = pFirst;
3695 pProbe = &sPk;
3697 rSize = pTab->nRowLogEst;
3699 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
3700 /* Automatic indexes */
3701 if( !pBuilder->pOrSet /* Not part of an OR optimization */
3702 && (pWInfo->wctrlFlags & (WHERE_RIGHT_JOIN|WHERE_OR_SUBCLAUSE))==0
3703 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
3704 && !pSrc->fg.isIndexedBy /* Has no INDEXED BY clause */
3705 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
3706 && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
3707 && !pSrc->fg.isCorrelated /* Not a correlated subquery */
3708 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
3709 && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */
3711 /* Generate auto-index WhereLoops */
3712 LogEst rLogSize; /* Logarithm of the number of rows in the table */
3713 WhereTerm *pTerm;
3714 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
3715 rLogSize = estLog(rSize);
3716 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
3717 if( pTerm->prereqRight & pNew->maskSelf ) continue;
3718 if( termCanDriveIndex(pTerm, pSrc, 0) ){
3719 pNew->u.btree.nEq = 1;
3720 pNew->nSkip = 0;
3721 pNew->u.btree.pIndex = 0;
3722 pNew->nLTerm = 1;
3723 pNew->aLTerm[0] = pTerm;
3724 /* TUNING: One-time cost for computing the automatic index is
3725 ** estimated to be X*N*log2(N) where N is the number of rows in
3726 ** the table being indexed and where X is 7 (LogEst=28) for normal
3727 ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
3728 ** of X is smaller for views and subqueries so that the query planner
3729 ** will be more aggressive about generating automatic indexes for
3730 ** those objects, since there is no opportunity to add schema
3731 ** indexes on subqueries and views. */
3732 pNew->rSetup = rLogSize + rSize;
3733 if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){
3734 pNew->rSetup += 28;
3735 }else{
3736 pNew->rSetup -= 25; /* Greatly reduced setup cost for auto indexes
3737 ** on ephemeral materializations of views */
3739 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
3740 if( pNew->rSetup<0 ) pNew->rSetup = 0;
3741 /* TUNING: Each index lookup yields 20 rows in the table. This
3742 ** is more than the usual guess of 10 rows, since we have no way
3743 ** of knowing how selective the index will ultimately be. It would
3744 ** not be unreasonable to make this value much larger. */
3745 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
3746 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
3747 pNew->wsFlags = WHERE_AUTO_INDEX;
3748 pNew->prereq = mPrereq | pTerm->prereqRight;
3749 rc = whereLoopInsert(pBuilder, pNew);
3753 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
3755 /* Loop over all indices. If there was an INDEXED BY clause, then only
3756 ** consider index pProbe. */
3757 for(; rc==SQLITE_OK && pProbe;
3758 pProbe=(pSrc->fg.isIndexedBy ? 0 : pProbe->pNext), iSortIdx++
3760 if( pProbe->pPartIdxWhere!=0
3761 && !whereUsablePartialIndex(pSrc->iCursor, pSrc->fg.jointype, pWC,
3762 pProbe->pPartIdxWhere)
3764 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
3765 continue; /* Partial index inappropriate for this query */
3767 if( pProbe->bNoQuery ) continue;
3768 rSize = pProbe->aiRowLogEst[0];
3769 pNew->u.btree.nEq = 0;
3770 pNew->u.btree.nBtm = 0;
3771 pNew->u.btree.nTop = 0;
3772 pNew->nSkip = 0;
3773 pNew->nLTerm = 0;
3774 pNew->iSortIdx = 0;
3775 pNew->rSetup = 0;
3776 pNew->prereq = mPrereq;
3777 pNew->nOut = rSize;
3778 pNew->u.btree.pIndex = pProbe;
3779 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
3781 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
3782 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
3783 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
3784 /* Integer primary key index */
3785 pNew->wsFlags = WHERE_IPK;
3787 /* Full table scan */
3788 pNew->iSortIdx = b ? iSortIdx : 0;
3789 /* TUNING: Cost of full table scan is 3.0*N. The 3.0 factor is an
3790 ** extra cost designed to discourage the use of full table scans,
3791 ** since index lookups have better worst-case performance if our
3792 ** stat guesses are wrong. Reduce the 3.0 penalty slightly
3793 ** (to 2.75) if we have valid STAT4 information for the table.
3794 ** At 2.75, a full table scan is preferred over using an index on
3795 ** a column with just two distinct values where each value has about
3796 ** an equal number of appearances. Without STAT4 data, we still want
3797 ** to use an index in that case, since the constraint might be for
3798 ** the scarcer of the two values, and in that case an index lookup is
3799 ** better.
3801 #ifdef SQLITE_ENABLE_STAT4
3802 pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
3803 #else
3804 pNew->rRun = rSize + 16;
3805 #endif
3806 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3807 whereLoopOutputAdjust(pWC, pNew, rSize);
3808 rc = whereLoopInsert(pBuilder, pNew);
3809 pNew->nOut = rSize;
3810 if( rc ) break;
3811 }else{
3812 Bitmask m;
3813 if( pProbe->isCovering ){
3814 m = 0;
3815 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3816 }else{
3817 m = pSrc->colUsed & pProbe->colNotIdxed;
3818 if( pProbe->pPartIdxWhere ){
3819 wherePartIdxExpr(
3820 pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0
3823 pNew->wsFlags = WHERE_INDEXED;
3824 if( m==TOPBIT || (pProbe->bHasExpr && !pProbe->bHasVCol && m!=0) ){
3825 u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
3826 if( isCov==0 ){
3827 WHERETRACE(0x200,
3828 ("-> %s is not a covering index"
3829 " according to whereIsCoveringIndex()\n", pProbe->zName));
3830 assert( m!=0 );
3831 }else{
3832 m = 0;
3833 pNew->wsFlags |= isCov;
3834 if( isCov & WHERE_IDX_ONLY ){
3835 WHERETRACE(0x200,
3836 ("-> %s is a covering expression index"
3837 " according to whereIsCoveringIndex()\n", pProbe->zName));
3838 }else{
3839 assert( isCov==WHERE_EXPRIDX );
3840 WHERETRACE(0x200,
3841 ("-> %s might be a covering expression index"
3842 " according to whereIsCoveringIndex()\n", pProbe->zName));
3845 }else if( m==0 ){
3846 WHERETRACE(0x200,
3847 ("-> %s a covering index according to bitmasks\n",
3848 pProbe->zName, m==0 ? "is" : "is not"));
3849 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3853 /* Full scan via index */
3854 if( b
3855 || !HasRowid(pTab)
3856 || pProbe->pPartIdxWhere!=0
3857 || pSrc->fg.isIndexedBy
3858 || ( m==0
3859 && pProbe->bUnordered==0
3860 && (pProbe->szIdxRow<pTab->szTabRow)
3861 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3862 && sqlite3GlobalConfig.bUseCis
3863 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
3866 pNew->iSortIdx = b ? iSortIdx : 0;
3868 /* The cost of visiting the index rows is N*K, where K is
3869 ** between 1.1 and 3.0, depending on the relative sizes of the
3870 ** index and table rows. */
3871 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
3872 if( m!=0 ){
3873 /* If this is a non-covering index scan, add in the cost of
3874 ** doing table lookups. The cost will be 3x the number of
3875 ** lookups. Take into account WHERE clause terms that can be
3876 ** satisfied using just the index, and that do not require a
3877 ** table lookup. */
3878 LogEst nLookup = rSize + 16; /* Base cost: N*3 */
3879 int ii;
3880 int iCur = pSrc->iCursor;
3881 WhereClause *pWC2 = &pWInfo->sWC;
3882 for(ii=0; ii<pWC2->nTerm; ii++){
3883 WhereTerm *pTerm = &pWC2->a[ii];
3884 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
3885 break;
3887 /* pTerm can be evaluated using just the index. So reduce
3888 ** the expected number of table lookups accordingly */
3889 if( pTerm->truthProb<=0 ){
3890 nLookup += pTerm->truthProb;
3891 }else{
3892 nLookup--;
3893 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
3897 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
3899 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3900 whereLoopOutputAdjust(pWC, pNew, rSize);
3901 if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){
3902 /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
3903 ** because the cursor used to access the index might not be
3904 ** positioned to the correct row during the right-join no-match
3905 ** loop. */
3906 }else{
3907 rc = whereLoopInsert(pBuilder, pNew);
3909 pNew->nOut = rSize;
3910 if( rc ) break;
3914 pBuilder->bldFlags1 = 0;
3915 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
3916 if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
3917 /* If a non-unique index is used, or if a prefix of the key for
3918 ** unique index is used (making the index functionally non-unique)
3919 ** then the sqlite_stat1 data becomes important for scoring the
3920 ** plan */
3921 pTab->tabFlags |= TF_StatsUsed;
3923 #ifdef SQLITE_ENABLE_STAT4
3924 sqlite3Stat4ProbeFree(pBuilder->pRec);
3925 pBuilder->nRecValid = 0;
3926 pBuilder->pRec = 0;
3927 #endif
3929 return rc;
3932 #ifndef SQLITE_OMIT_VIRTUALTABLE
3935 ** Return true if pTerm is a virtual table LIMIT or OFFSET term.
3937 static int isLimitTerm(WhereTerm *pTerm){
3938 assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
3939 return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
3940 && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
3944 ** Argument pIdxInfo is already populated with all constraints that may
3945 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
3946 ** function marks a subset of those constraints usable, invokes the
3947 ** xBestIndex method and adds the returned plan to pBuilder.
3949 ** A constraint is marked usable if:
3951 ** * Argument mUsable indicates that its prerequisites are available, and
3953 ** * It is not one of the operators specified in the mExclude mask passed
3954 ** as the fourth argument (which in practice is either WO_IN or 0).
3956 ** Argument mPrereq is a mask of tables that must be scanned before the
3957 ** virtual table in question. These are added to the plans prerequisites
3958 ** before it is added to pBuilder.
3960 ** Output parameter *pbIn is set to true if the plan added to pBuilder
3961 ** uses one or more WO_IN terms, or false otherwise.
3963 static int whereLoopAddVirtualOne(
3964 WhereLoopBuilder *pBuilder,
3965 Bitmask mPrereq, /* Mask of tables that must be used. */
3966 Bitmask mUsable, /* Mask of usable tables */
3967 u16 mExclude, /* Exclude terms using these operators */
3968 sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
3969 u16 mNoOmit, /* Do not omit these constraints */
3970 int *pbIn, /* OUT: True if plan uses an IN(...) op */
3971 int *pbRetryLimit /* OUT: Retry without LIMIT/OFFSET */
3973 WhereClause *pWC = pBuilder->pWC;
3974 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
3975 struct sqlite3_index_constraint *pIdxCons;
3976 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
3977 int i;
3978 int mxTerm;
3979 int rc = SQLITE_OK;
3980 WhereLoop *pNew = pBuilder->pNew;
3981 Parse *pParse = pBuilder->pWInfo->pParse;
3982 SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
3983 int nConstraint = pIdxInfo->nConstraint;
3985 assert( (mUsable & mPrereq)==mPrereq );
3986 *pbIn = 0;
3987 pNew->prereq = mPrereq;
3989 /* Set the usable flag on the subset of constraints identified by
3990 ** arguments mUsable and mExclude. */
3991 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
3992 for(i=0; i<nConstraint; i++, pIdxCons++){
3993 WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
3994 pIdxCons->usable = 0;
3995 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
3996 && (pTerm->eOperator & mExclude)==0
3997 && (pbRetryLimit || !isLimitTerm(pTerm))
3999 pIdxCons->usable = 1;
4003 /* Initialize the output fields of the sqlite3_index_info structure */
4004 memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
4005 assert( pIdxInfo->needToFreeIdxStr==0 );
4006 pIdxInfo->idxStr = 0;
4007 pIdxInfo->idxNum = 0;
4008 pIdxInfo->orderByConsumed = 0;
4009 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
4010 pIdxInfo->estimatedRows = 25;
4011 pIdxInfo->idxFlags = 0;
4012 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
4013 pHidden->mHandleIn = 0;
4015 /* Invoke the virtual table xBestIndex() method */
4016 rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
4017 if( rc ){
4018 if( rc==SQLITE_CONSTRAINT ){
4019 /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
4020 ** that the particular combination of parameters provided is unusable.
4021 ** Make no entries in the loop table.
4023 WHERETRACE(0xffffffff, (" ^^^^--- non-viable plan rejected!\n"));
4024 return SQLITE_OK;
4026 return rc;
4029 mxTerm = -1;
4030 assert( pNew->nLSlot>=nConstraint );
4031 memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
4032 memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
4033 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4034 for(i=0; i<nConstraint; i++, pIdxCons++){
4035 int iTerm;
4036 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4037 WhereTerm *pTerm;
4038 int j = pIdxCons->iTermOffset;
4039 if( iTerm>=nConstraint
4040 || j<0
4041 || j>=pWC->nTerm
4042 || pNew->aLTerm[iTerm]!=0
4043 || pIdxCons->usable==0
4045 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
4046 testcase( pIdxInfo->needToFreeIdxStr );
4047 return SQLITE_ERROR;
4049 testcase( iTerm==nConstraint-1 );
4050 testcase( j==0 );
4051 testcase( j==pWC->nTerm-1 );
4052 pTerm = &pWC->a[j];
4053 pNew->prereq |= pTerm->prereqRight;
4054 assert( iTerm<pNew->nLSlot );
4055 pNew->aLTerm[iTerm] = pTerm;
4056 if( iTerm>mxTerm ) mxTerm = iTerm;
4057 testcase( iTerm==15 );
4058 testcase( iTerm==16 );
4059 if( pUsage[i].omit ){
4060 if( i<16 && ((1<<i)&mNoOmit)==0 ){
4061 testcase( i!=iTerm );
4062 pNew->u.vtab.omitMask |= 1<<iTerm;
4063 }else{
4064 testcase( i!=iTerm );
4066 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
4067 pNew->u.vtab.bOmitOffset = 1;
4070 if( SMASKBIT32(i) & pHidden->mHandleIn ){
4071 pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
4072 }else if( (pTerm->eOperator & WO_IN)!=0 ){
4073 /* A virtual table that is constrained by an IN clause may not
4074 ** consume the ORDER BY clause because (1) the order of IN terms
4075 ** is not necessarily related to the order of output terms and
4076 ** (2) Multiple outputs from a single IN value will not merge
4077 ** together. */
4078 pIdxInfo->orderByConsumed = 0;
4079 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
4080 *pbIn = 1; assert( (mExclude & WO_IN)==0 );
4083 assert( pbRetryLimit || !isLimitTerm(pTerm) );
4084 if( isLimitTerm(pTerm) && *pbIn ){
4085 /* If there is an IN(...) term handled as an == (separate call to
4086 ** xFilter for each value on the RHS of the IN) and a LIMIT or
4087 ** OFFSET term handled as well, the plan is unusable. Set output
4088 ** variable *pbRetryLimit to true to tell the caller to retry with
4089 ** LIMIT and OFFSET disabled. */
4090 if( pIdxInfo->needToFreeIdxStr ){
4091 sqlite3_free(pIdxInfo->idxStr);
4092 pIdxInfo->idxStr = 0;
4093 pIdxInfo->needToFreeIdxStr = 0;
4095 *pbRetryLimit = 1;
4096 return SQLITE_OK;
4101 pNew->nLTerm = mxTerm+1;
4102 for(i=0; i<=mxTerm; i++){
4103 if( pNew->aLTerm[i]==0 ){
4104 /* The non-zero argvIdx values must be contiguous. Raise an
4105 ** error if they are not */
4106 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
4107 testcase( pIdxInfo->needToFreeIdxStr );
4108 return SQLITE_ERROR;
4111 assert( pNew->nLTerm<=pNew->nLSlot );
4112 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4113 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4114 pIdxInfo->needToFreeIdxStr = 0;
4115 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
4116 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
4117 pIdxInfo->nOrderBy : 0);
4118 pNew->rSetup = 0;
4119 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
4120 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
4122 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
4123 ** that the scan will visit at most one row. Clear it otherwise. */
4124 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
4125 pNew->wsFlags |= WHERE_ONEROW;
4126 }else{
4127 pNew->wsFlags &= ~WHERE_ONEROW;
4129 rc = whereLoopInsert(pBuilder, pNew);
4130 if( pNew->u.vtab.needFree ){
4131 sqlite3_free(pNew->u.vtab.idxStr);
4132 pNew->u.vtab.needFree = 0;
4134 WHERETRACE(0xffffffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
4135 *pbIn, (sqlite3_uint64)mPrereq,
4136 (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
4138 return rc;
4142 ** Return the collating sequence for a constraint passed into xBestIndex.
4144 ** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
4145 ** This routine depends on there being a HiddenIndexInfo structure immediately
4146 ** following the sqlite3_index_info structure.
4148 ** Return a pointer to the collation name:
4150 ** 1. If there is an explicit COLLATE operator on the constraint, return it.
4152 ** 2. Else, if the column has an alternative collation, return that.
4154 ** 3. Otherwise, return "BINARY".
4156 const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
4157 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4158 const char *zRet = 0;
4159 if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
4160 CollSeq *pC = 0;
4161 int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
4162 Expr *pX = pHidden->pWC->a[iTerm].pExpr;
4163 if( pX->pLeft ){
4164 pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
4166 zRet = (pC ? pC->zName : sqlite3StrBINARY);
4168 return zRet;
4172 ** Return true if constraint iCons is really an IN(...) constraint, or
4173 ** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
4174 ** or clear (if bHandle==0) the flag to handle it using an iterator.
4176 int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){
4177 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4178 u32 m = SMASKBIT32(iCons);
4179 if( m & pHidden->mIn ){
4180 if( bHandle==0 ){
4181 pHidden->mHandleIn &= ~m;
4182 }else if( bHandle>0 ){
4183 pHidden->mHandleIn |= m;
4185 return 1;
4187 return 0;
4191 ** This interface is callable from within the xBestIndex callback only.
4193 ** If possible, set (*ppVal) to point to an object containing the value
4194 ** on the right-hand-side of constraint iCons.
4196 int sqlite3_vtab_rhs_value(
4197 sqlite3_index_info *pIdxInfo, /* Copy of first argument to xBestIndex */
4198 int iCons, /* Constraint for which RHS is wanted */
4199 sqlite3_value **ppVal /* Write value extracted here */
4201 HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
4202 sqlite3_value *pVal = 0;
4203 int rc = SQLITE_OK;
4204 if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
4205 rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */
4206 }else{
4207 if( pH->aRhs[iCons]==0 ){
4208 WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
4209 rc = sqlite3ValueFromExpr(
4210 pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
4211 SQLITE_AFF_BLOB, &pH->aRhs[iCons]
4213 testcase( rc!=SQLITE_OK );
4215 pVal = pH->aRhs[iCons];
4217 *ppVal = pVal;
4219 if( rc==SQLITE_OK && pVal==0 ){ /* IMP: R-19933-32160 */
4220 rc = SQLITE_NOTFOUND; /* IMP: R-36424-56542 */
4223 return rc;
4227 ** Return true if ORDER BY clause may be handled as DISTINCT.
4229 int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
4230 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4231 assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
4232 return pHidden->eDistinct;
4236 ** Cause the prepared statement that is associated with a call to
4237 ** xBestIndex to potentially use all schemas. If the statement being
4238 ** prepared is read-only, then just start read transactions on all
4239 ** schemas. But if this is a write operation, start writes on all
4240 ** schemas.
4242 ** This is used by the (built-in) sqlite_dbpage virtual table.
4244 void sqlite3VtabUsesAllSchemas(Parse *pParse){
4245 int nDb = pParse->db->nDb;
4246 int i;
4247 for(i=0; i<nDb; i++){
4248 sqlite3CodeVerifySchema(pParse, i);
4250 if( DbMaskNonZero(pParse->writeMask) ){
4251 for(i=0; i<nDb; i++){
4252 sqlite3BeginWriteOperation(pParse, 0, i);
4258 ** Add all WhereLoop objects for a table of the join identified by
4259 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
4261 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
4262 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
4263 ** entries that occur before the virtual table in the FROM clause and are
4264 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
4265 ** mUnusable mask contains all FROM clause entries that occur after the
4266 ** virtual table and are separated from it by at least one LEFT or
4267 ** CROSS JOIN.
4269 ** For example, if the query were:
4271 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
4273 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
4275 ** All the tables in mPrereq must be scanned before the current virtual
4276 ** table. So any terms for which all prerequisites are satisfied by
4277 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
4278 ** Conversely, all tables in mUnusable must be scanned after the current
4279 ** virtual table, so any terms for which the prerequisites overlap with
4280 ** mUnusable should always be configured as "not-usable" for xBestIndex.
4282 static int whereLoopAddVirtual(
4283 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4284 Bitmask mPrereq, /* Tables that must be scanned before this one */
4285 Bitmask mUnusable /* Tables that must be scanned after this one */
4287 int rc = SQLITE_OK; /* Return code */
4288 WhereInfo *pWInfo; /* WHERE analysis context */
4289 Parse *pParse; /* The parsing context */
4290 WhereClause *pWC; /* The WHERE clause */
4291 SrcItem *pSrc; /* The FROM clause term to search */
4292 sqlite3_index_info *p; /* Object to pass to xBestIndex() */
4293 int nConstraint; /* Number of constraints in p */
4294 int bIn; /* True if plan uses IN(...) operator */
4295 WhereLoop *pNew;
4296 Bitmask mBest; /* Tables used by best possible plan */
4297 u16 mNoOmit;
4298 int bRetry = 0; /* True to retry with LIMIT/OFFSET disabled */
4300 assert( (mPrereq & mUnusable)==0 );
4301 pWInfo = pBuilder->pWInfo;
4302 pParse = pWInfo->pParse;
4303 pWC = pBuilder->pWC;
4304 pNew = pBuilder->pNew;
4305 pSrc = &pWInfo->pTabList->a[pNew->iTab];
4306 assert( IsVirtual(pSrc->pTab) );
4307 p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit);
4308 if( p==0 ) return SQLITE_NOMEM_BKPT;
4309 pNew->rSetup = 0;
4310 pNew->wsFlags = WHERE_VIRTUALTABLE;
4311 pNew->nLTerm = 0;
4312 pNew->u.vtab.needFree = 0;
4313 nConstraint = p->nConstraint;
4314 if( whereLoopResize(pParse->db, pNew, nConstraint) ){
4315 freeIndexInfo(pParse->db, p);
4316 return SQLITE_NOMEM_BKPT;
4319 /* First call xBestIndex() with all constraints usable. */
4320 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
4321 WHERETRACE(0x800, (" VirtualOne: all usable\n"));
4322 rc = whereLoopAddVirtualOne(
4323 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry
4325 if( bRetry ){
4326 assert( rc==SQLITE_OK );
4327 rc = whereLoopAddVirtualOne(
4328 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0
4332 /* If the call to xBestIndex() with all terms enabled produced a plan
4333 ** that does not require any source tables (IOW: a plan with mBest==0)
4334 ** and does not use an IN(...) operator, then there is no point in making
4335 ** any further calls to xBestIndex() since they will all return the same
4336 ** result (if the xBestIndex() implementation is sane). */
4337 if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
4338 int seenZero = 0; /* True if a plan with no prereqs seen */
4339 int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
4340 Bitmask mPrev = 0;
4341 Bitmask mBestNoIn = 0;
4343 /* If the plan produced by the earlier call uses an IN(...) term, call
4344 ** xBestIndex again, this time with IN(...) terms disabled. */
4345 if( bIn ){
4346 WHERETRACE(0x800, (" VirtualOne: all usable w/o IN\n"));
4347 rc = whereLoopAddVirtualOne(
4348 pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0);
4349 assert( bIn==0 );
4350 mBestNoIn = pNew->prereq & ~mPrereq;
4351 if( mBestNoIn==0 ){
4352 seenZero = 1;
4353 seenZeroNoIN = 1;
4357 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
4358 ** in the set of terms that apply to the current virtual table. */
4359 while( rc==SQLITE_OK ){
4360 int i;
4361 Bitmask mNext = ALLBITS;
4362 assert( mNext>0 );
4363 for(i=0; i<nConstraint; i++){
4364 Bitmask mThis = (
4365 pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
4367 if( mThis>mPrev && mThis<mNext ) mNext = mThis;
4369 mPrev = mNext;
4370 if( mNext==ALLBITS ) break;
4371 if( mNext==mBest || mNext==mBestNoIn ) continue;
4372 WHERETRACE(0x800, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
4373 (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
4374 rc = whereLoopAddVirtualOne(
4375 pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn, 0);
4376 if( pNew->prereq==mPrereq ){
4377 seenZero = 1;
4378 if( bIn==0 ) seenZeroNoIN = 1;
4382 /* If the calls to xBestIndex() in the above loop did not find a plan
4383 ** that requires no source tables at all (i.e. one guaranteed to be
4384 ** usable), make a call here with all source tables disabled */
4385 if( rc==SQLITE_OK && seenZero==0 ){
4386 WHERETRACE(0x800, (" VirtualOne: all disabled\n"));
4387 rc = whereLoopAddVirtualOne(
4388 pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0);
4389 if( bIn==0 ) seenZeroNoIN = 1;
4392 /* If the calls to xBestIndex() have so far failed to find a plan
4393 ** that requires no source tables at all and does not use an IN(...)
4394 ** operator, make a final call to obtain one here. */
4395 if( rc==SQLITE_OK && seenZeroNoIN==0 ){
4396 WHERETRACE(0x800, (" VirtualOne: all disabled and w/o IN\n"));
4397 rc = whereLoopAddVirtualOne(
4398 pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
4402 if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
4403 freeIndexInfo(pParse->db, p);
4404 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
4405 return rc;
4407 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4410 ** Add WhereLoop entries to handle OR terms. This works for either
4411 ** btrees or virtual tables.
4413 static int whereLoopAddOr(
4414 WhereLoopBuilder *pBuilder,
4415 Bitmask mPrereq,
4416 Bitmask mUnusable
4418 WhereInfo *pWInfo = pBuilder->pWInfo;
4419 WhereClause *pWC;
4420 WhereLoop *pNew;
4421 WhereTerm *pTerm, *pWCEnd;
4422 int rc = SQLITE_OK;
4423 int iCur;
4424 WhereClause tempWC;
4425 WhereLoopBuilder sSubBuild;
4426 WhereOrSet sSum, sCur;
4427 SrcItem *pItem;
4429 pWC = pBuilder->pWC;
4430 pWCEnd = pWC->a + pWC->nTerm;
4431 pNew = pBuilder->pNew;
4432 memset(&sSum, 0, sizeof(sSum));
4433 pItem = pWInfo->pTabList->a + pNew->iTab;
4434 iCur = pItem->iCursor;
4436 /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
4437 if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK;
4439 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4440 if( (pTerm->eOperator & WO_OR)!=0
4441 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4443 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4444 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4445 WhereTerm *pOrTerm;
4446 int once = 1;
4447 int i, j;
4449 sSubBuild = *pBuilder;
4450 sSubBuild.pOrSet = &sCur;
4452 WHERETRACE(0x400, ("Begin processing OR-clause %p\n", pTerm));
4453 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
4454 if( (pOrTerm->eOperator & WO_AND)!=0 ){
4455 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4456 }else if( pOrTerm->leftCursor==iCur ){
4457 tempWC.pWInfo = pWC->pWInfo;
4458 tempWC.pOuter = pWC;
4459 tempWC.op = TK_AND;
4460 tempWC.nTerm = 1;
4461 tempWC.nBase = 1;
4462 tempWC.a = pOrTerm;
4463 sSubBuild.pWC = &tempWC;
4464 }else{
4465 continue;
4467 sCur.n = 0;
4468 #ifdef WHERETRACE_ENABLED
4469 WHERETRACE(0x400, ("OR-term %d of %p has %d subterms:\n",
4470 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
4471 if( sqlite3WhereTrace & 0x20000 ){
4472 sqlite3WhereClausePrint(sSubBuild.pWC);
4474 #endif
4475 #ifndef SQLITE_OMIT_VIRTUALTABLE
4476 if( IsVirtual(pItem->pTab) ){
4477 rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
4478 }else
4479 #endif
4481 rc = whereLoopAddBtree(&sSubBuild, mPrereq);
4483 if( rc==SQLITE_OK ){
4484 rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
4486 testcase( rc==SQLITE_NOMEM && sCur.n>0 );
4487 testcase( rc==SQLITE_DONE );
4488 if( sCur.n==0 ){
4489 sSum.n = 0;
4490 break;
4491 }else if( once ){
4492 whereOrMove(&sSum, &sCur);
4493 once = 0;
4494 }else{
4495 WhereOrSet sPrev;
4496 whereOrMove(&sPrev, &sSum);
4497 sSum.n = 0;
4498 for(i=0; i<sPrev.n; i++){
4499 for(j=0; j<sCur.n; j++){
4500 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4501 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4502 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4507 pNew->nLTerm = 1;
4508 pNew->aLTerm[0] = pTerm;
4509 pNew->wsFlags = WHERE_MULTI_OR;
4510 pNew->rSetup = 0;
4511 pNew->iSortIdx = 0;
4512 memset(&pNew->u, 0, sizeof(pNew->u));
4513 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
4514 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
4515 ** of all sub-scans required by the OR-scan. However, due to rounding
4516 ** errors, it may be that the cost of the OR-scan is equal to its
4517 ** most expensive sub-scan. Add the smallest possible penalty
4518 ** (equivalent to multiplying the cost by 1.07) to ensure that
4519 ** this does not happen. Otherwise, for WHERE clauses such as the
4520 ** following where there is an index on "y":
4522 ** WHERE likelihood(x=?, 0.99) OR y=?
4524 ** the planner may elect to "OR" together a full-table scan and an
4525 ** index lookup. And other similarly odd results. */
4526 pNew->rRun = sSum.a[i].rRun + 1;
4527 pNew->nOut = sSum.a[i].nOut;
4528 pNew->prereq = sSum.a[i].prereq;
4529 rc = whereLoopInsert(pBuilder, pNew);
4531 WHERETRACE(0x400, ("End processing OR-clause %p\n", pTerm));
4534 return rc;
4538 ** Add all WhereLoop objects for all tables
4540 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
4541 WhereInfo *pWInfo = pBuilder->pWInfo;
4542 Bitmask mPrereq = 0;
4543 Bitmask mPrior = 0;
4544 int iTab;
4545 SrcList *pTabList = pWInfo->pTabList;
4546 SrcItem *pItem;
4547 SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
4548 sqlite3 *db = pWInfo->pParse->db;
4549 int rc = SQLITE_OK;
4550 int bFirstPastRJ = 0;
4551 int hasRightJoin = 0;
4552 WhereLoop *pNew;
4555 /* Loop over the tables in the join, from left to right */
4556 pNew = pBuilder->pNew;
4558 /* Verify that pNew has already been initialized */
4559 assert( pNew->nLTerm==0 );
4560 assert( pNew->wsFlags==0 );
4561 assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) );
4562 assert( pNew->aLTerm!=0 );
4564 pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
4565 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
4566 Bitmask mUnusable = 0;
4567 pNew->iTab = iTab;
4568 pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
4569 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
4570 if( bFirstPastRJ
4571 || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0
4573 /* Add prerequisites to prevent reordering of FROM clause terms
4574 ** across CROSS joins and outer joins. The bFirstPastRJ boolean
4575 ** prevents the right operand of a RIGHT JOIN from being swapped with
4576 ** other elements even further to the right.
4578 ** The JT_LTORJ case and the hasRightJoin flag work together to
4579 ** prevent FROM-clause terms from moving from the right side of
4580 ** a LEFT JOIN over to the left side of that join if the LEFT JOIN
4581 ** is itself on the left side of a RIGHT JOIN.
4583 if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1;
4584 mPrereq |= mPrior;
4585 bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0;
4586 }else if( !hasRightJoin ){
4587 mPrereq = 0;
4589 #ifndef SQLITE_OMIT_VIRTUALTABLE
4590 if( IsVirtual(pItem->pTab) ){
4591 SrcItem *p;
4592 for(p=&pItem[1]; p<pEnd; p++){
4593 if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
4594 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
4597 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
4598 }else
4599 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4601 rc = whereLoopAddBtree(pBuilder, mPrereq);
4603 if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
4604 rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
4606 mPrior |= pNew->maskSelf;
4607 if( rc || db->mallocFailed ){
4608 if( rc==SQLITE_DONE ){
4609 /* We hit the query planner search limit set by iPlanLimit */
4610 sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
4611 rc = SQLITE_OK;
4612 }else{
4613 break;
4618 whereLoopClear(db, pNew);
4619 return rc;
4623 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
4624 ** parameters) to see if it outputs rows in the requested ORDER BY
4625 ** (or GROUP BY) without requiring a separate sort operation. Return N:
4627 ** N>0: N terms of the ORDER BY clause are satisfied
4628 ** N==0: No terms of the ORDER BY clause are satisfied
4629 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
4631 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4632 ** strict. With GROUP BY and DISTINCT the only requirement is that
4633 ** equivalent rows appear immediately adjacent to one another. GROUP BY
4634 ** and DISTINCT do not require rows to appear in any particular order as long
4635 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
4636 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
4637 ** pOrderBy terms must be matched in strict left-to-right order.
4639 static i8 wherePathSatisfiesOrderBy(
4640 WhereInfo *pWInfo, /* The WHERE clause */
4641 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
4642 WherePath *pPath, /* The WherePath to check */
4643 u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
4644 u16 nLoop, /* Number of entries in pPath->aLoop[] */
4645 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
4646 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
4648 u8 revSet; /* True if rev is known */
4649 u8 rev; /* Composite sort order */
4650 u8 revIdx; /* Index sort order */
4651 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4652 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4653 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
4654 u16 eqOpMask; /* Allowed equality operators */
4655 u16 nKeyCol; /* Number of key columns in pIndex */
4656 u16 nColumn; /* Total number of ordered columns in the index */
4657 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4658 int iLoop; /* Index of WhereLoop in pPath being processed */
4659 int i, j; /* Loop counters */
4660 int iCur; /* Cursor number for current WhereLoop */
4661 int iColumn; /* A column number within table iCur */
4662 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
4663 WhereTerm *pTerm; /* A single term of the WHERE clause */
4664 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4665 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4666 Index *pIndex; /* The index associated with pLoop */
4667 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4668 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4669 Bitmask obDone; /* Mask of all ORDER BY terms */
4670 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
4671 Bitmask ready; /* Mask of inner loops */
4674 ** We say the WhereLoop is "one-row" if it generates no more than one
4675 ** row of output. A WhereLoop is one-row if all of the following are true:
4676 ** (a) All index columns match with WHERE_COLUMN_EQ.
4677 ** (b) The index is unique
4678 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4679 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
4681 ** We say the WhereLoop is "order-distinct" if the set of columns from
4682 ** that WhereLoop that are in the ORDER BY clause are different for every
4683 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4684 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4685 ** is not order-distinct. To be order-distinct is not quite the same as being
4686 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4687 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4688 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4690 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4691 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4692 ** automatically order-distinct.
4695 assert( pOrderBy!=0 );
4696 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
4698 nOrderBy = pOrderBy->nExpr;
4699 testcase( nOrderBy==BMS-1 );
4700 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4701 isOrderDistinct = 1;
4702 obDone = MASKBIT(nOrderBy)-1;
4703 orderDistinctMask = 0;
4704 ready = 0;
4705 eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
4706 if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
4707 eqOpMask |= WO_IN;
4709 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
4710 if( iLoop>0 ) ready |= pLoop->maskSelf;
4711 if( iLoop<nLoop ){
4712 pLoop = pPath->aLoop[iLoop];
4713 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
4714 }else{
4715 pLoop = pLast;
4717 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
4718 if( pLoop->u.vtab.isOrdered
4719 && ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY)
4721 obSat = obDone;
4723 break;
4724 }else if( wctrlFlags & WHERE_DISTINCTBY ){
4725 pLoop->u.btree.nDistinctCol = 0;
4727 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
4729 /* Mark off any ORDER BY term X that is a column in the table of
4730 ** the current loop for which there is term in the WHERE
4731 ** clause of the form X IS NULL or X=? that reference only outer
4732 ** loops.
4734 for(i=0; i<nOrderBy; i++){
4735 if( MASKBIT(i) & obSat ) continue;
4736 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4737 if( NEVER(pOBExpr==0) ) continue;
4738 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4739 if( pOBExpr->iTable!=iCur ) continue;
4740 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4741 ~ready, eqOpMask, 0);
4742 if( pTerm==0 ) continue;
4743 if( pTerm->eOperator==WO_IN ){
4744 /* IN terms are only valid for sorting in the ORDER BY LIMIT
4745 ** optimization, and then only if they are actually used
4746 ** by the query plan */
4747 assert( wctrlFlags &
4748 (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
4749 for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
4750 if( j>=pLoop->nLTerm ) continue;
4752 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
4753 Parse *pParse = pWInfo->pParse;
4754 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
4755 CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
4756 assert( pColl1 );
4757 if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
4758 continue;
4760 testcase( pTerm->pExpr->op==TK_IS );
4762 obSat |= MASKBIT(i);
4765 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4766 if( pLoop->wsFlags & WHERE_IPK ){
4767 pIndex = 0;
4768 nKeyCol = 0;
4769 nColumn = 1;
4770 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
4771 return 0;
4772 }else{
4773 nKeyCol = pIndex->nKeyCol;
4774 nColumn = pIndex->nColumn;
4775 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4776 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
4777 || !HasRowid(pIndex->pTable));
4778 /* All relevant terms of the index must also be non-NULL in order
4779 ** for isOrderDistinct to be true. So the isOrderDistint value
4780 ** computed here might be a false positive. Corrections will be
4781 ** made at tag-20210426-1 below */
4782 isOrderDistinct = IsUniqueIndex(pIndex)
4783 && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
4786 /* Loop through all columns of the index and deal with the ones
4787 ** that are not constrained by == or IN.
4789 rev = revSet = 0;
4790 distinctColumns = 0;
4791 for(j=0; j<nColumn; j++){
4792 u8 bOnce = 1; /* True to run the ORDER BY search loop */
4794 assert( j>=pLoop->u.btree.nEq
4795 || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
4797 if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
4798 u16 eOp = pLoop->aLTerm[j]->eOperator;
4800 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
4801 ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL
4802 ** terms imply that the index is not UNIQUE NOT NULL in which case
4803 ** the loop need to be marked as not order-distinct because it can
4804 ** have repeated NULL rows.
4806 ** If the current term is a column of an ((?,?) IN (SELECT...))
4807 ** expression for which the SELECT returns more than one column,
4808 ** check that it is the only column used by this loop. Otherwise,
4809 ** if it is one of two or more, none of the columns can be
4810 ** considered to match an ORDER BY term.
4812 if( (eOp & eqOpMask)!=0 ){
4813 if( eOp & (WO_ISNULL|WO_IS) ){
4814 testcase( eOp & WO_ISNULL );
4815 testcase( eOp & WO_IS );
4816 testcase( isOrderDistinct );
4817 isOrderDistinct = 0;
4819 continue;
4820 }else if( ALWAYS(eOp & WO_IN) ){
4821 /* ALWAYS() justification: eOp is an equality operator due to the
4822 ** j<pLoop->u.btree.nEq constraint above. Any equality other
4823 ** than WO_IN is captured by the previous "if". So this one
4824 ** always has to be WO_IN. */
4825 Expr *pX = pLoop->aLTerm[j]->pExpr;
4826 for(i=j+1; i<pLoop->u.btree.nEq; i++){
4827 if( pLoop->aLTerm[i]->pExpr==pX ){
4828 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
4829 bOnce = 0;
4830 break;
4836 /* Get the column number in the table (iColumn) and sort order
4837 ** (revIdx) for the j-th column of the index.
4839 if( pIndex ){
4840 iColumn = pIndex->aiColumn[j];
4841 revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
4842 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
4843 }else{
4844 iColumn = XN_ROWID;
4845 revIdx = 0;
4848 /* An unconstrained column that might be NULL means that this
4849 ** WhereLoop is not well-ordered. tag-20210426-1
4851 if( isOrderDistinct ){
4852 if( iColumn>=0
4853 && j>=pLoop->u.btree.nEq
4854 && pIndex->pTable->aCol[iColumn].notNull==0
4856 isOrderDistinct = 0;
4858 if( iColumn==XN_EXPR ){
4859 isOrderDistinct = 0;
4863 /* Find the ORDER BY term that corresponds to the j-th column
4864 ** of the index and mark that ORDER BY term off
4866 isMatch = 0;
4867 for(i=0; bOnce && i<nOrderBy; i++){
4868 if( MASKBIT(i) & obSat ) continue;
4869 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4870 testcase( wctrlFlags & WHERE_GROUPBY );
4871 testcase( wctrlFlags & WHERE_DISTINCTBY );
4872 if( NEVER(pOBExpr==0) ) continue;
4873 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
4874 if( iColumn>=XN_ROWID ){
4875 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4876 if( pOBExpr->iTable!=iCur ) continue;
4877 if( pOBExpr->iColumn!=iColumn ) continue;
4878 }else{
4879 Expr *pIxExpr = pIndex->aColExpr->a[j].pExpr;
4880 if( sqlite3ExprCompareSkip(pOBExpr, pIxExpr, iCur) ){
4881 continue;
4884 if( iColumn!=XN_ROWID ){
4885 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4886 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4888 if( wctrlFlags & WHERE_DISTINCTBY ){
4889 pLoop->u.btree.nDistinctCol = j+1;
4891 isMatch = 1;
4892 break;
4894 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
4895 /* Make sure the sort order is compatible in an ORDER BY clause.
4896 ** Sort order is irrelevant for a GROUP BY clause. */
4897 if( revSet ){
4898 if( (rev ^ revIdx)
4899 != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC)
4901 isMatch = 0;
4903 }else{
4904 rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC);
4905 if( rev ) *pRevMask |= MASKBIT(iLoop);
4906 revSet = 1;
4909 if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){
4910 if( j==pLoop->u.btree.nEq ){
4911 pLoop->wsFlags |= WHERE_BIGNULL_SORT;
4912 }else{
4913 isMatch = 0;
4916 if( isMatch ){
4917 if( iColumn==XN_ROWID ){
4918 testcase( distinctColumns==0 );
4919 distinctColumns = 1;
4921 obSat |= MASKBIT(i);
4922 }else{
4923 /* No match found */
4924 if( j==0 || j<nKeyCol ){
4925 testcase( isOrderDistinct!=0 );
4926 isOrderDistinct = 0;
4928 break;
4930 } /* end Loop over all index columns */
4931 if( distinctColumns ){
4932 testcase( isOrderDistinct==0 );
4933 isOrderDistinct = 1;
4935 } /* end-if not one-row */
4937 /* Mark off any other ORDER BY terms that reference pLoop */
4938 if( isOrderDistinct ){
4939 orderDistinctMask |= pLoop->maskSelf;
4940 for(i=0; i<nOrderBy; i++){
4941 Expr *p;
4942 Bitmask mTerm;
4943 if( MASKBIT(i) & obSat ) continue;
4944 p = pOrderBy->a[i].pExpr;
4945 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
4946 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
4947 if( (mTerm&~orderDistinctMask)==0 ){
4948 obSat |= MASKBIT(i);
4952 } /* End the loop over all WhereLoops from outer-most down to inner-most */
4953 if( obSat==obDone ) return (i8)nOrderBy;
4954 if( !isOrderDistinct ){
4955 for(i=nOrderBy-1; i>0; i--){
4956 Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
4957 if( (obSat&m)==m ) return i;
4959 return 0;
4961 return -1;
4966 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
4967 ** the planner assumes that the specified pOrderBy list is actually a GROUP
4968 ** BY clause - and so any order that groups rows as required satisfies the
4969 ** request.
4971 ** Normally, in this case it is not possible for the caller to determine
4972 ** whether or not the rows are really being delivered in sorted order, or
4973 ** just in some other order that provides the required grouping. However,
4974 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
4975 ** this function may be called on the returned WhereInfo object. It returns
4976 ** true if the rows really will be sorted in the specified order, or false
4977 ** otherwise.
4979 ** For example, assuming:
4981 ** CREATE INDEX i1 ON t1(x, Y);
4983 ** then
4985 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
4986 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
4988 int sqlite3WhereIsSorted(WhereInfo *pWInfo){
4989 assert( pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) );
4990 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
4991 return pWInfo->sorted;
4994 #ifdef WHERETRACE_ENABLED
4995 /* For debugging use only: */
4996 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4997 static char zName[65];
4998 int i;
4999 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5000 if( pLast ) zName[i++] = pLast->cId;
5001 zName[i] = 0;
5002 return zName;
5004 #endif
5007 ** Return the cost of sorting nRow rows, assuming that the keys have
5008 ** nOrderby columns and that the first nSorted columns are already in
5009 ** order.
5011 static LogEst whereSortingCost(
5012 WhereInfo *pWInfo, /* Query planning context */
5013 LogEst nRow, /* Estimated number of rows to sort */
5014 int nOrderBy, /* Number of ORDER BY clause terms */
5015 int nSorted /* Number of initial ORDER BY terms naturally in order */
5017 /* Estimated cost of a full external sort, where N is
5018 ** the number of rows to sort is:
5020 ** cost = (K * N * log(N)).
5022 ** Or, if the order-by clause has X terms but only the last Y
5023 ** terms are out of order, then block-sorting will reduce the
5024 ** sorting cost to:
5026 ** cost = (K * N * log(N)) * (Y/X)
5028 ** The constant K is at least 2.0 but will be larger if there are a
5029 ** large number of columns to be sorted, as the sorting time is
5030 ** proportional to the amount of content to be sorted. The algorithm
5031 ** does not currently distinguish between fat columns (BLOBs and TEXTs)
5032 ** and skinny columns (INTs). It just uses the number of columns as
5033 ** an approximation for the row width.
5035 ** And extra factor of 2.0 or 3.0 is added to the sorting cost if the sort
5036 ** is built using OP_IdxInsert and OP_Sort rather than with OP_SorterInsert.
5038 LogEst rSortCost, nCol;
5039 assert( pWInfo->pSelect!=0 );
5040 assert( pWInfo->pSelect->pEList!=0 );
5041 /* TUNING: sorting cost proportional to the number of output columns: */
5042 nCol = sqlite3LogEst((pWInfo->pSelect->pEList->nExpr+59)/30);
5043 rSortCost = nRow + nCol;
5044 if( nSorted>0 ){
5045 /* Scale the result by (Y/X) */
5046 rSortCost += sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
5049 /* Multiple by log(M) where M is the number of output rows.
5050 ** Use the LIMIT for M if it is smaller. Or if this sort is for
5051 ** a DISTINCT operator, M will be the number of distinct output
5052 ** rows, so fudge it downwards a bit.
5054 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 ){
5055 rSortCost += 10; /* TUNING: Extra 2.0x if using LIMIT */
5056 if( nSorted!=0 ){
5057 rSortCost += 6; /* TUNING: Extra 1.5x if also using partial sort */
5059 if( pWInfo->iLimit<nRow ){
5060 nRow = pWInfo->iLimit;
5062 }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
5063 /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
5064 ** reduces the number of output rows by a factor of 2 */
5065 if( nRow>10 ){ nRow -= 10; assert( 10==sqlite3LogEst(2) ); }
5067 rSortCost += estLog(nRow);
5068 return rSortCost;
5072 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
5073 ** attempts to find the lowest cost path that visits each WhereLoop
5074 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5076 ** Assume that the total number of output rows that will need to be sorted
5077 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5078 ** costs if nRowEst==0.
5080 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5081 ** error occurs.
5083 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
5084 int mxChoice; /* Maximum number of simultaneous paths tracked */
5085 int nLoop; /* Number of terms in the join */
5086 Parse *pParse; /* Parsing context */
5087 int iLoop; /* Loop counter over the terms of the join */
5088 int ii, jj; /* Loop counters */
5089 int mxI = 0; /* Index of next entry to replace */
5090 int nOrderBy; /* Number of ORDER BY clause terms */
5091 LogEst mxCost = 0; /* Maximum cost of a set of paths */
5092 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
5093 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5094 WherePath *aFrom; /* All nFrom paths at the previous level */
5095 WherePath *aTo; /* The nTo best paths at the current level */
5096 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5097 WherePath *pTo; /* An element of aTo[] that we are working on */
5098 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5099 WhereLoop **pX; /* Used to divy up the pSpace memory */
5100 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
5101 char *pSpace; /* Temporary memory used by this routine */
5102 int nSpace; /* Bytes of space allocated at pSpace */
5104 pParse = pWInfo->pParse;
5105 nLoop = pWInfo->nLevel;
5106 /* TUNING: For simple queries, only the best path is tracked.
5107 ** For 2-way joins, the 5 best paths are followed.
5108 ** For joins of 3 or more tables, track the 10 best paths */
5109 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
5110 assert( nLoop<=pWInfo->pTabList->nSrc );
5111 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d, nQueryLoop=%d)\n",
5112 nRowEst, pParse->nQueryLoop));
5114 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5115 ** case the purpose of this call is to estimate the number of rows returned
5116 ** by the overall query. Once this estimate has been obtained, the caller
5117 ** will invoke this function a second time, passing the estimate as the
5118 ** nRowEst parameter. */
5119 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5120 nOrderBy = 0;
5121 }else{
5122 nOrderBy = pWInfo->pOrderBy->nExpr;
5125 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
5126 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5127 nSpace += sizeof(LogEst) * nOrderBy;
5128 pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace);
5129 if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
5130 aTo = (WherePath*)pSpace;
5131 aFrom = aTo+mxChoice;
5132 memset(aFrom, 0, sizeof(aFrom[0]));
5133 pX = (WhereLoop**)(aFrom+mxChoice);
5134 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
5135 pFrom->aLoop = pX;
5137 if( nOrderBy ){
5138 /* If there is an ORDER BY clause and it is not being ignored, set up
5139 ** space for the aSortCost[] array. Each element of the aSortCost array
5140 ** is either zero - meaning it has not yet been initialized - or the
5141 ** cost of sorting nRowEst rows of data where the first X terms of
5142 ** the ORDER BY clause are already in order, where X is the array
5143 ** index. */
5144 aSortCost = (LogEst*)pX;
5145 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
5147 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
5148 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
5150 /* Seed the search with a single WherePath containing zero WhereLoops.
5152 ** TUNING: Do not let the number of iterations go above 28. If the cost
5153 ** of computing an automatic index is not paid back within the first 28
5154 ** rows, then do not use the automatic index. */
5155 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
5156 nFrom = 1;
5157 assert( aFrom[0].isOrdered==0 );
5158 if( nOrderBy ){
5159 /* If nLoop is zero, then there are no FROM terms in the query. Since
5160 ** in this case the query may return a maximum of one row, the results
5161 ** are already in the requested order. Set isOrdered to nOrderBy to
5162 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
5163 ** -1, indicating that the result set may or may not be ordered,
5164 ** depending on the loops added to the current plan. */
5165 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
5168 /* Compute successively longer WherePaths using the previous generation
5169 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5170 ** best paths at each generation */
5171 for(iLoop=0; iLoop<nLoop; iLoop++){
5172 nTo = 0;
5173 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5174 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5175 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
5176 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
5177 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
5178 i8 isOrdered; /* isOrdered for (pFrom+pWLoop) */
5179 Bitmask maskNew; /* Mask of src visited by (..) */
5180 Bitmask revMask; /* Mask of rev-order loops for (..) */
5182 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5183 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
5184 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
5185 /* Do not use an automatic index if the this loop is expected
5186 ** to run less than 1.25 times. It is tempting to also exclude
5187 ** automatic index usage on an outer loop, but sometimes an automatic
5188 ** index is useful in the outer loop of a correlated subquery. */
5189 assert( 10==sqlite3LogEst(2) );
5190 continue;
5193 /* At this point, pWLoop is a candidate to be the next loop.
5194 ** Compute its cost */
5195 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5196 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
5197 nOut = pFrom->nRow + pWLoop->nOut;
5198 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
5199 isOrdered = pFrom->isOrdered;
5200 if( isOrdered<0 ){
5201 revMask = 0;
5202 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
5203 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
5204 iLoop, pWLoop, &revMask);
5205 }else{
5206 revMask = pFrom->revLoop;
5208 if( isOrdered>=0 && isOrdered<nOrderBy ){
5209 if( aSortCost[isOrdered]==0 ){
5210 aSortCost[isOrdered] = whereSortingCost(
5211 pWInfo, nRowEst, nOrderBy, isOrdered
5214 /* TUNING: Add a small extra penalty (3) to sorting as an
5215 ** extra encouragement to the query planner to select a plan
5216 ** where the rows emerge in the correct order without any sorting
5217 ** required. */
5218 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 3;
5220 WHERETRACE(0x002,
5221 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5222 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
5223 rUnsorted, rCost));
5224 }else{
5225 rCost = rUnsorted;
5226 rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
5229 /* Check to see if pWLoop should be added to the set of
5230 ** mxChoice best-so-far paths.
5232 ** First look for an existing path among best-so-far paths
5233 ** that covers the same set of loops and has the same isOrdered
5234 ** setting as the current path candidate.
5236 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
5237 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
5238 ** of legal values for isOrdered, -1..64.
5240 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5241 if( pTo->maskLoop==maskNew
5242 && ((pTo->isOrdered^isOrdered)&0x80)==0
5244 testcase( jj==nTo-1 );
5245 break;
5248 if( jj>=nTo ){
5249 /* None of the existing best-so-far paths match the candidate. */
5250 if( nTo>=mxChoice
5251 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
5253 /* The current candidate is no better than any of the mxChoice
5254 ** paths currently in the best-so-far buffer. So discard
5255 ** this candidate as not viable. */
5256 #ifdef WHERETRACE_ENABLED /* 0x4 */
5257 if( sqlite3WhereTrace&0x4 ){
5258 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
5259 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5260 isOrdered>=0 ? isOrdered+'0' : '?');
5262 #endif
5263 continue;
5265 /* If we reach this points it means that the new candidate path
5266 ** needs to be added to the set of best-so-far paths. */
5267 if( nTo<mxChoice ){
5268 /* Increase the size of the aTo set by one */
5269 jj = nTo++;
5270 }else{
5271 /* New path replaces the prior worst to keep count below mxChoice */
5272 jj = mxI;
5274 pTo = &aTo[jj];
5275 #ifdef WHERETRACE_ENABLED /* 0x4 */
5276 if( sqlite3WhereTrace&0x4 ){
5277 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
5278 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5279 isOrdered>=0 ? isOrdered+'0' : '?');
5281 #endif
5282 }else{
5283 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
5284 ** same set of loops and has the same isOrdered setting as the
5285 ** candidate path. Check to see if the candidate should replace
5286 ** pTo or if the candidate should be skipped.
5288 ** The conditional is an expanded vector comparison equivalent to:
5289 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
5291 if( pTo->rCost<rCost
5292 || (pTo->rCost==rCost
5293 && (pTo->nRow<nOut
5294 || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
5298 #ifdef WHERETRACE_ENABLED /* 0x4 */
5299 if( sqlite3WhereTrace&0x4 ){
5300 sqlite3DebugPrintf(
5301 "Skip %s cost=%-3d,%3d,%3d order=%c",
5302 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5303 isOrdered>=0 ? isOrdered+'0' : '?');
5304 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
5305 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5306 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5308 #endif
5309 /* Discard the candidate path from further consideration */
5310 testcase( pTo->rCost==rCost );
5311 continue;
5313 testcase( pTo->rCost==rCost+1 );
5314 /* Control reaches here if the candidate path is better than the
5315 ** pTo path. Replace pTo with the candidate. */
5316 #ifdef WHERETRACE_ENABLED /* 0x4 */
5317 if( sqlite3WhereTrace&0x4 ){
5318 sqlite3DebugPrintf(
5319 "Update %s cost=%-3d,%3d,%3d order=%c",
5320 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5321 isOrdered>=0 ? isOrdered+'0' : '?');
5322 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
5323 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5324 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5326 #endif
5328 /* pWLoop is a winner. Add it to the set of best so far */
5329 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
5330 pTo->revLoop = revMask;
5331 pTo->nRow = nOut;
5332 pTo->rCost = rCost;
5333 pTo->rUnsorted = rUnsorted;
5334 pTo->isOrdered = isOrdered;
5335 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5336 pTo->aLoop[iLoop] = pWLoop;
5337 if( nTo>=mxChoice ){
5338 mxI = 0;
5339 mxCost = aTo[0].rCost;
5340 mxUnsorted = aTo[0].nRow;
5341 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5342 if( pTo->rCost>mxCost
5343 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
5345 mxCost = pTo->rCost;
5346 mxUnsorted = pTo->rUnsorted;
5347 mxI = jj;
5354 #ifdef WHERETRACE_ENABLED /* >=2 */
5355 if( sqlite3WhereTrace & 0x02 ){
5356 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
5357 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
5358 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
5359 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5360 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
5361 if( pTo->isOrdered>0 ){
5362 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5363 }else{
5364 sqlite3DebugPrintf("\n");
5368 #endif
5370 /* Swap the roles of aFrom and aTo for the next generation */
5371 pFrom = aTo;
5372 aTo = aFrom;
5373 aFrom = pFrom;
5374 nFrom = nTo;
5377 if( nFrom==0 ){
5378 sqlite3ErrorMsg(pParse, "no query solution");
5379 sqlite3StackFreeNN(pParse->db, pSpace);
5380 return SQLITE_ERROR;
5383 /* Find the lowest cost path. pFrom will be left pointing to that path */
5384 pFrom = aFrom;
5385 for(ii=1; ii<nFrom; ii++){
5386 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5388 assert( pWInfo->nLevel==nLoop );
5389 /* Load the lowest cost path into pWInfo */
5390 for(iLoop=0; iLoop<nLoop; iLoop++){
5391 WhereLevel *pLevel = pWInfo->a + iLoop;
5392 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
5393 pLevel->iFrom = pWLoop->iTab;
5394 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
5396 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5397 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5398 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
5399 && nRowEst
5401 Bitmask notUsed;
5402 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
5403 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
5404 if( rc==pWInfo->pResultSet->nExpr ){
5405 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5408 pWInfo->bOrderedInnerLoop = 0;
5409 if( pWInfo->pOrderBy ){
5410 pWInfo->nOBSat = pFrom->isOrdered;
5411 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5412 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
5413 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5415 if( pWInfo->pSelect->pOrderBy
5416 && pWInfo->nOBSat > pWInfo->pSelect->pOrderBy->nExpr ){
5417 pWInfo->nOBSat = pWInfo->pSelect->pOrderBy->nExpr;
5419 }else{
5420 pWInfo->revMask = pFrom->revLoop;
5421 if( pWInfo->nOBSat<=0 ){
5422 pWInfo->nOBSat = 0;
5423 if( nLoop>0 ){
5424 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
5425 if( (wsFlags & WHERE_ONEROW)==0
5426 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
5428 Bitmask m = 0;
5429 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
5430 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
5431 testcase( wsFlags & WHERE_IPK );
5432 testcase( wsFlags & WHERE_COLUMN_IN );
5433 if( rc==pWInfo->pOrderBy->nExpr ){
5434 pWInfo->bOrderedInnerLoop = 1;
5435 pWInfo->revMask = m;
5439 }else if( nLoop
5440 && pWInfo->nOBSat==1
5441 && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
5443 pWInfo->bOrderedInnerLoop = 1;
5446 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
5447 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
5449 Bitmask revMask = 0;
5450 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
5451 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
5453 assert( pWInfo->sorted==0 );
5454 if( nOrder==pWInfo->pOrderBy->nExpr ){
5455 pWInfo->sorted = 1;
5456 pWInfo->revMask = revMask;
5462 pWInfo->nRowOut = pFrom->nRow;
5464 /* Free temporary memory and return success */
5465 sqlite3StackFreeNN(pParse->db, pSpace);
5466 return SQLITE_OK;
5470 ** Most queries use only a single table (they are not joins) and have
5471 ** simple == constraints against indexed fields. This routine attempts
5472 ** to plan those simple cases using much less ceremony than the
5473 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5474 ** times for the common case.
5476 ** Return non-zero on success, if this query can be handled by this
5477 ** no-frills query planner. Return zero if this query needs the
5478 ** general-purpose query planner.
5480 static int whereShortCut(WhereLoopBuilder *pBuilder){
5481 WhereInfo *pWInfo;
5482 SrcItem *pItem;
5483 WhereClause *pWC;
5484 WhereTerm *pTerm;
5485 WhereLoop *pLoop;
5486 int iCur;
5487 int j;
5488 Table *pTab;
5489 Index *pIdx;
5490 WhereScan scan;
5492 pWInfo = pBuilder->pWInfo;
5493 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
5494 assert( pWInfo->pTabList->nSrc>=1 );
5495 pItem = pWInfo->pTabList->a;
5496 pTab = pItem->pTab;
5497 if( IsVirtual(pTab) ) return 0;
5498 if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){
5499 testcase( pItem->fg.isIndexedBy );
5500 testcase( pItem->fg.notIndexed );
5501 return 0;
5503 iCur = pItem->iCursor;
5504 pWC = &pWInfo->sWC;
5505 pLoop = pBuilder->pNew;
5506 pLoop->wsFlags = 0;
5507 pLoop->nSkip = 0;
5508 pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
5509 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5510 if( pTerm ){
5511 testcase( pTerm->eOperator & WO_IS );
5512 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5513 pLoop->aLTerm[0] = pTerm;
5514 pLoop->nLTerm = 1;
5515 pLoop->u.btree.nEq = 1;
5516 /* TUNING: Cost of a rowid lookup is 10 */
5517 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
5518 }else{
5519 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5520 int opMask;
5521 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5522 if( !IsUniqueIndex(pIdx)
5523 || pIdx->pPartIdxWhere!=0
5524 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
5525 ) continue;
5526 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
5527 for(j=0; j<pIdx->nKeyCol; j++){
5528 pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx);
5529 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5530 if( pTerm==0 ) break;
5531 testcase( pTerm->eOperator & WO_IS );
5532 pLoop->aLTerm[j] = pTerm;
5534 if( j!=pIdx->nKeyCol ) continue;
5535 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
5536 if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
5537 pLoop->wsFlags |= WHERE_IDX_ONLY;
5539 pLoop->nLTerm = j;
5540 pLoop->u.btree.nEq = j;
5541 pLoop->u.btree.pIndex = pIdx;
5542 /* TUNING: Cost of a unique index lookup is 15 */
5543 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
5544 break;
5547 if( pLoop->wsFlags ){
5548 pLoop->nOut = (LogEst)1;
5549 pWInfo->a[0].pWLoop = pLoop;
5550 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
5551 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
5552 pWInfo->a[0].iTabCur = iCur;
5553 pWInfo->nRowOut = 1;
5554 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
5555 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5556 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5558 if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
5559 #ifdef SQLITE_DEBUG
5560 pLoop->cId = '0';
5561 #endif
5562 #ifdef WHERETRACE_ENABLED
5563 if( sqlite3WhereTrace & 0x02 ){
5564 sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
5566 #endif
5567 return 1;
5569 return 0;
5573 ** Helper function for exprIsDeterministic().
5575 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
5576 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
5577 pWalker->eCode = 0;
5578 return WRC_Abort;
5580 return WRC_Continue;
5584 ** Return true if the expression contains no non-deterministic SQL
5585 ** functions. Do not consider non-deterministic SQL functions that are
5586 ** part of sub-select statements.
5588 static int exprIsDeterministic(Expr *p){
5589 Walker w;
5590 memset(&w, 0, sizeof(w));
5591 w.eCode = 1;
5592 w.xExprCallback = exprNodeIsDeterministic;
5593 w.xSelectCallback = sqlite3SelectWalkFail;
5594 sqlite3WalkExpr(&w, p);
5595 return w.eCode;
5599 #ifdef WHERETRACE_ENABLED
5601 ** Display all WhereLoops in pWInfo
5603 static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
5604 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
5605 WhereLoop *p;
5606 int i;
5607 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5608 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5609 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5610 p->cId = zLabel[i%(sizeof(zLabel)-1)];
5611 sqlite3WhereLoopPrint(p, pWC);
5615 # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
5616 #else
5617 # define WHERETRACE_ALL_LOOPS(W,C)
5618 #endif
5620 /* Attempt to omit tables from a join that do not affect the result.
5621 ** For a table to not affect the result, the following must be true:
5623 ** 1) The query must not be an aggregate.
5624 ** 2) The table must be the RHS of a LEFT JOIN.
5625 ** 3) Either the query must be DISTINCT, or else the ON or USING clause
5626 ** must contain a constraint that limits the scan of the table to
5627 ** at most a single row.
5628 ** 4) The table must not be referenced by any part of the query apart
5629 ** from its own USING or ON clause.
5630 ** 5) The table must not have an inner-join ON or USING clause if there is
5631 ** a RIGHT JOIN anywhere in the query. Otherwise the ON/USING clause
5632 ** might move from the right side to the left side of the RIGHT JOIN.
5633 ** Note: Due to (2), this condition can only arise if the table is
5634 ** the right-most table of a subquery that was flattened into the
5635 ** main query and that subquery was the right-hand operand of an
5636 ** inner join that held an ON or USING clause.
5638 ** For example, given:
5640 ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
5641 ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
5642 ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
5644 ** then table t2 can be omitted from the following:
5646 ** SELECT v1, v3 FROM t1
5647 ** LEFT JOIN t2 ON (t1.ipk=t2.ipk)
5648 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5650 ** or from:
5652 ** SELECT DISTINCT v1, v3 FROM t1
5653 ** LEFT JOIN t2
5654 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5656 static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
5657 WhereInfo *pWInfo,
5658 Bitmask notReady
5660 int i;
5661 Bitmask tabUsed;
5662 int hasRightJoin;
5664 /* Preconditions checked by the caller */
5665 assert( pWInfo->nLevel>=2 );
5666 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
5668 /* These two preconditions checked by the caller combine to guarantee
5669 ** condition (1) of the header comment */
5670 assert( pWInfo->pResultSet!=0 );
5671 assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
5673 tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
5674 if( pWInfo->pOrderBy ){
5675 tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
5677 hasRightJoin = (pWInfo->pTabList->a[0].fg.jointype & JT_LTORJ)!=0;
5678 for(i=pWInfo->nLevel-1; i>=1; i--){
5679 WhereTerm *pTerm, *pEnd;
5680 SrcItem *pItem;
5681 WhereLoop *pLoop;
5682 pLoop = pWInfo->a[i].pWLoop;
5683 pItem = &pWInfo->pTabList->a[pLoop->iTab];
5684 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
5685 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
5686 && (pLoop->wsFlags & WHERE_ONEROW)==0
5688 continue;
5690 if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
5691 pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
5692 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5693 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5694 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
5695 || pTerm->pExpr->w.iJoin!=pItem->iCursor
5697 break;
5700 if( hasRightJoin
5701 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
5702 && pTerm->pExpr->w.iJoin==pItem->iCursor
5704 break; /* restriction (5) */
5707 if( pTerm<pEnd ) continue;
5708 WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop->cId));
5709 notReady &= ~pLoop->maskSelf;
5710 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5711 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5712 pTerm->wtFlags |= TERM_CODED;
5715 if( i!=pWInfo->nLevel-1 ){
5716 int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
5717 memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
5719 pWInfo->nLevel--;
5720 assert( pWInfo->nLevel>0 );
5722 return notReady;
5726 ** Check to see if there are any SEARCH loops that might benefit from
5727 ** using a Bloom filter. Consider a Bloom filter if:
5729 ** (1) The SEARCH happens more than N times where N is the number
5730 ** of rows in the table that is being considered for the Bloom
5731 ** filter.
5732 ** (2) Some searches are expected to find zero rows. (This is determined
5733 ** by the WHERE_SELFCULL flag on the term.)
5734 ** (3) Bloom-filter processing is not disabled. (Checked by the
5735 ** caller.)
5736 ** (4) The size of the table being searched is known by ANALYZE.
5738 ** This block of code merely checks to see if a Bloom filter would be
5739 ** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
5740 ** WhereLoop. The implementation of the Bloom filter comes further
5741 ** down where the code for each WhereLoop is generated.
5743 static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
5744 const WhereInfo *pWInfo
5746 int i;
5747 LogEst nSearch = 0;
5749 assert( pWInfo->nLevel>=2 );
5750 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
5751 for(i=0; i<pWInfo->nLevel; i++){
5752 WhereLoop *pLoop = pWInfo->a[i].pWLoop;
5753 const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ);
5754 SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
5755 Table *pTab = pItem->pTab;
5756 if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
5757 pTab->tabFlags |= TF_StatsUsed;
5758 if( i>=1
5759 && (pLoop->wsFlags & reqFlags)==reqFlags
5760 /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
5761 && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
5763 if( nSearch > pTab->nRowLogEst ){
5764 testcase( pItem->fg.jointype & JT_LEFT );
5765 pLoop->wsFlags |= WHERE_BLOOMFILTER;
5766 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
5767 WHERETRACE(0xffffffff, (
5768 "-> use Bloom-filter on loop %c because there are ~%.1e "
5769 "lookups into %s which has only ~%.1e rows\n",
5770 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
5771 (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
5774 nSearch += pLoop->nOut;
5779 ** The index pIdx is used by a query and contains one or more expressions.
5780 ** In other words pIdx is an index on an expression. iIdxCur is the cursor
5781 ** number for the index and iDataCur is the cursor number for the corresponding
5782 ** table.
5784 ** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for
5785 ** each of the expressions in the index so that the expression code generator
5786 ** will know to replace occurrences of the indexed expression with
5787 ** references to the corresponding column of the index.
5789 static SQLITE_NOINLINE void whereAddIndexedExpr(
5790 Parse *pParse, /* Add IndexedExpr entries to pParse->pIdxEpr */
5791 Index *pIdx, /* The index-on-expression that contains the expressions */
5792 int iIdxCur, /* Cursor number for pIdx */
5793 SrcItem *pTabItem /* The FROM clause entry for the table */
5795 int i;
5796 IndexedExpr *p;
5797 Table *pTab;
5798 assert( pIdx->bHasExpr );
5799 pTab = pIdx->pTable;
5800 for(i=0; i<pIdx->nColumn; i++){
5801 Expr *pExpr;
5802 int j = pIdx->aiColumn[i];
5803 int bMaybeNullRow;
5804 if( j==XN_EXPR ){
5805 pExpr = pIdx->aColExpr->a[i].pExpr;
5806 testcase( pTabItem->fg.jointype & JT_LEFT );
5807 testcase( pTabItem->fg.jointype & JT_RIGHT );
5808 testcase( pTabItem->fg.jointype & JT_LTORJ );
5809 bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0;
5810 }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
5811 pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
5812 bMaybeNullRow = 0;
5813 }else{
5814 continue;
5816 if( sqlite3ExprIsConstant(pExpr) ) continue;
5817 p = sqlite3DbMallocRaw(pParse->db, sizeof(IndexedExpr));
5818 if( p==0 ) break;
5819 p->pIENext = pParse->pIdxEpr;
5820 #ifdef WHERETRACE_ENABLED
5821 if( sqlite3WhereTrace & 0x200 ){
5822 sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
5823 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr);
5825 #endif
5826 p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5827 p->iDataCur = pTabItem->iCursor;
5828 p->iIdxCur = iIdxCur;
5829 p->iIdxCol = i;
5830 p->bMaybeNullRow = bMaybeNullRow;
5831 if( sqlite3IndexAffinityStr(pParse->db, pIdx) ){
5832 p->aff = pIdx->zColAff[i];
5834 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
5835 p->zIdxName = pIdx->zName;
5836 #endif
5837 pParse->pIdxEpr = p;
5838 if( p->pIENext==0 ){
5839 void *pArg = (void*)&pParse->pIdxEpr;
5840 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
5846 ** Set the reverse-scan order mask to one for all tables in the query
5847 ** with the exception of MATERIALIZED common table expressions that have
5848 ** their own internal ORDER BY clauses.
5850 ** This implements the PRAGMA reverse_unordered_selects=ON setting.
5851 ** (Also SQLITE_DBCONFIG_REVERSE_SCANORDER).
5853 static SQLITE_NOINLINE void whereReverseScanOrder(WhereInfo *pWInfo){
5854 int ii;
5855 for(ii=0; ii<pWInfo->pTabList->nSrc; ii++){
5856 SrcItem *pItem = &pWInfo->pTabList->a[ii];
5857 if( !pItem->fg.isCte
5858 || pItem->u2.pCteUse->eM10d!=M10d_Yes
5859 || NEVER(pItem->pSelect==0)
5860 || pItem->pSelect->pOrderBy==0
5862 pWInfo->revMask |= MASKBIT(ii);
5868 ** Generate the beginning of the loop used for WHERE clause processing.
5869 ** The return value is a pointer to an opaque structure that contains
5870 ** information needed to terminate the loop. Later, the calling routine
5871 ** should invoke sqlite3WhereEnd() with the return value of this function
5872 ** in order to complete the WHERE clause processing.
5874 ** If an error occurs, this routine returns NULL.
5876 ** The basic idea is to do a nested loop, one loop for each table in
5877 ** the FROM clause of a select. (INSERT and UPDATE statements are the
5878 ** same as a SELECT with only a single table in the FROM clause.) For
5879 ** example, if the SQL is this:
5881 ** SELECT * FROM t1, t2, t3 WHERE ...;
5883 ** Then the code generated is conceptually like the following:
5885 ** foreach row1 in t1 do \ Code generated
5886 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
5887 ** foreach row3 in t3 do /
5888 ** ...
5889 ** end \ Code generated
5890 ** end |-- by sqlite3WhereEnd()
5891 ** end /
5893 ** Note that the loops might not be nested in the order in which they
5894 ** appear in the FROM clause if a different order is better able to make
5895 ** use of indices. Note also that when the IN operator appears in
5896 ** the WHERE clause, it might result in additional nested loops for
5897 ** scanning through all values on the right-hand side of the IN.
5899 ** There are Btree cursors associated with each table. t1 uses cursor
5900 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5901 ** And so forth. This routine generates code to open those VDBE cursors
5902 ** and sqlite3WhereEnd() generates the code to close them.
5904 ** The code that sqlite3WhereBegin() generates leaves the cursors named
5905 ** in pTabList pointing at their appropriate entries. The [...] code
5906 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
5907 ** data from the various tables of the loop.
5909 ** If the WHERE clause is empty, the foreach loops must each scan their
5910 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
5911 ** the tables have indices and there are terms in the WHERE clause that
5912 ** refer to those indices, a complete table scan can be avoided and the
5913 ** code will run much faster. Most of the work of this routine is checking
5914 ** to see if there are indices that can be used to speed up the loop.
5916 ** Terms of the WHERE clause are also used to limit which rows actually
5917 ** make it to the "..." in the middle of the loop. After each "foreach",
5918 ** terms of the WHERE clause that use only terms in that loop and outer
5919 ** loops are evaluated and if false a jump is made around all subsequent
5920 ** inner loops (or around the "..." if the test occurs within the inner-
5921 ** most loop)
5923 ** OUTER JOINS
5925 ** An outer join of tables t1 and t2 is conceptually coded as follows:
5927 ** foreach row1 in t1 do
5928 ** flag = 0
5929 ** foreach row2 in t2 do
5930 ** start:
5931 ** ...
5932 ** flag = 1
5933 ** end
5934 ** if flag==0 then
5935 ** move the row2 cursor to a null row
5936 ** goto start
5937 ** fi
5938 ** end
5940 ** ORDER BY CLAUSE PROCESSING
5942 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5943 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
5944 ** if there is one. If there is no ORDER BY clause or if this routine
5945 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
5947 ** The iIdxCur parameter is the cursor number of an index. If
5948 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
5949 ** to use for OR clause processing. The WHERE clause should use this
5950 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5951 ** the first cursor in an array of cursors for all indices. iIdxCur should
5952 ** be used to compute the appropriate cursor depending on which index is
5953 ** used.
5955 WhereInfo *sqlite3WhereBegin(
5956 Parse *pParse, /* The parser context */
5957 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
5958 Expr *pWhere, /* The WHERE clause */
5959 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
5960 ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
5961 Select *pSelect, /* The entire SELECT statement */
5962 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
5963 int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
5964 ** If WHERE_USE_LIMIT, then the limit amount */
5966 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
5967 int nTabList; /* Number of elements in pTabList */
5968 WhereInfo *pWInfo; /* Will become the return value of this function */
5969 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
5970 Bitmask notReady; /* Cursors that are not yet positioned */
5971 WhereLoopBuilder sWLB; /* The WhereLoop builder */
5972 WhereMaskSet *pMaskSet; /* The expression mask set */
5973 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
5974 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
5975 int ii; /* Loop counter */
5976 sqlite3 *db; /* Database connection */
5977 int rc; /* Return code */
5978 u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
5980 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
5981 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5982 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
5985 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
5986 assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
5987 || (wctrlFlags & WHERE_USE_LIMIT)==0 );
5989 /* Variable initialization */
5990 db = pParse->db;
5991 memset(&sWLB, 0, sizeof(sWLB));
5993 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
5994 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
5995 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
5997 /* The number of tables in the FROM clause is limited by the number of
5998 ** bits in a Bitmask
6000 testcase( pTabList->nSrc==BMS );
6001 if( pTabList->nSrc>BMS ){
6002 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
6003 return 0;
6006 /* This function normally generates a nested loop for all tables in
6007 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
6008 ** only generate code for the first table in pTabList and assume that
6009 ** any cursors associated with subsequent tables are uninitialized.
6011 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
6013 /* Allocate and initialize the WhereInfo structure that will become the
6014 ** return value. A single allocation is used to store the WhereInfo
6015 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6016 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6017 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6018 ** some architectures. Hence the ROUND8() below.
6020 nByteWInfo = ROUND8P(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
6021 pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
6022 if( db->mallocFailed ){
6023 sqlite3DbFree(db, pWInfo);
6024 pWInfo = 0;
6025 goto whereBeginError;
6027 pWInfo->pParse = pParse;
6028 pWInfo->pTabList = pTabList;
6029 pWInfo->pOrderBy = pOrderBy;
6030 #if WHERETRACE_ENABLED
6031 pWInfo->pWhere = pWhere;
6032 #endif
6033 pWInfo->pResultSet = pResultSet;
6034 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
6035 pWInfo->nLevel = nTabList;
6036 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
6037 pWInfo->wctrlFlags = wctrlFlags;
6038 pWInfo->iLimit = iAuxArg;
6039 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
6040 pWInfo->pSelect = pSelect;
6041 memset(&pWInfo->nOBSat, 0,
6042 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
6043 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
6044 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
6045 pMaskSet = &pWInfo->sMaskSet;
6046 pMaskSet->n = 0;
6047 pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
6048 ** a valid cursor number, to avoid an initial
6049 ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
6050 sWLB.pWInfo = pWInfo;
6051 sWLB.pWC = &pWInfo->sWC;
6052 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
6053 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
6054 whereLoopInit(sWLB.pNew);
6055 #ifdef SQLITE_DEBUG
6056 sWLB.pNew->cId = '*';
6057 #endif
6059 /* Split the WHERE clause into separate subexpressions where each
6060 ** subexpression is separated by an AND operator.
6062 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
6063 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
6065 /* Special case: No FROM clause
6067 if( nTabList==0 ){
6068 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
6069 if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0
6070 && OptimizationEnabled(db, SQLITE_DistinctOpt)
6072 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6074 ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
6075 }else{
6076 /* Assign a bit from the bitmask to every term in the FROM clause.
6078 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
6080 ** The rule of the previous sentence ensures that if X is the bitmask for
6081 ** a table T, then X-1 is the bitmask for all other tables to the left of T.
6082 ** Knowing the bitmask for all tables to the left of a left join is
6083 ** important. Ticket #3015.
6085 ** Note that bitmasks are created for all pTabList->nSrc tables in
6086 ** pTabList, not just the first nTabList tables. nTabList is normally
6087 ** equal to pTabList->nSrc but might be shortened to 1 if the
6088 ** WHERE_OR_SUBCLAUSE flag is set.
6090 ii = 0;
6092 createMask(pMaskSet, pTabList->a[ii].iCursor);
6093 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
6094 }while( (++ii)<pTabList->nSrc );
6095 #ifdef SQLITE_DEBUG
6097 Bitmask mx = 0;
6098 for(ii=0; ii<pTabList->nSrc; ii++){
6099 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
6100 assert( m>=mx );
6101 mx = m;
6104 #endif
6107 /* Analyze all of the subexpressions. */
6108 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
6109 if( pSelect && pSelect->pLimit ){
6110 sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
6112 if( pParse->nErr ) goto whereBeginError;
6114 /* The False-WHERE-Term-Bypass optimization:
6116 ** If there are WHERE terms that are false, then no rows will be output,
6117 ** so skip over all of the code generated here.
6119 ** Conditions:
6121 ** (1) The WHERE term must not refer to any tables in the join.
6122 ** (2) The term must not come from an ON clause on the
6123 ** right-hand side of a LEFT or FULL JOIN.
6124 ** (3) The term must not come from an ON clause, or there must be
6125 ** no RIGHT or FULL OUTER joins in pTabList.
6126 ** (4) If the expression contains non-deterministic functions
6127 ** that are not within a sub-select. This is not required
6128 ** for correctness but rather to preserves SQLite's legacy
6129 ** behaviour in the following two cases:
6131 ** WHERE random()>0; -- eval random() once per row
6132 ** WHERE (SELECT random())>0; -- eval random() just once overall
6134 ** Note that the Where term need not be a constant in order for this
6135 ** optimization to apply, though it does need to be constant relative to
6136 ** the current subquery (condition 1). The term might include variables
6137 ** from outer queries so that the value of the term changes from one
6138 ** invocation of the current subquery to the next.
6140 for(ii=0; ii<sWLB.pWC->nBase; ii++){
6141 WhereTerm *pT = &sWLB.pWC->a[ii]; /* A term of the WHERE clause */
6142 Expr *pX; /* The expression of pT */
6143 if( pT->wtFlags & TERM_VIRTUAL ) continue;
6144 pX = pT->pExpr;
6145 assert( pX!=0 );
6146 assert( pT->prereqAll!=0 || !ExprHasProperty(pX, EP_OuterON) );
6147 if( pT->prereqAll==0 /* Conditions (1) and (2) */
6148 && (nTabList==0 || exprIsDeterministic(pX)) /* Condition (4) */
6149 && !(ExprHasProperty(pX, EP_InnerON) /* Condition (3) */
6150 && (pTabList->a[0].fg.jointype & JT_LTORJ)!=0 )
6152 sqlite3ExprIfFalse(pParse, pX, pWInfo->iBreak, SQLITE_JUMPIFNULL);
6153 pT->wtFlags |= TERM_CODED;
6157 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6158 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6159 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6160 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6161 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6162 pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
6163 }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6164 /* The DISTINCT marking is pointless. Ignore it. */
6165 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6166 }else if( pOrderBy==0 ){
6167 /* Try to ORDER BY the result set to make distinct processing easier */
6168 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
6169 pWInfo->pOrderBy = pResultSet;
6173 /* Construct the WhereLoop objects */
6174 #if defined(WHERETRACE_ENABLED)
6175 if( sqlite3WhereTrace & 0xffffffff ){
6176 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
6177 if( wctrlFlags & WHERE_USE_LIMIT ){
6178 sqlite3DebugPrintf(", limit: %d", iAuxArg);
6180 sqlite3DebugPrintf(")\n");
6181 if( sqlite3WhereTrace & 0x8000 ){
6182 Select sSelect;
6183 memset(&sSelect, 0, sizeof(sSelect));
6184 sSelect.selFlags = SF_WhereBegin;
6185 sSelect.pSrc = pTabList;
6186 sSelect.pWhere = pWhere;
6187 sSelect.pOrderBy = pOrderBy;
6188 sSelect.pEList = pResultSet;
6189 sqlite3TreeViewSelect(0, &sSelect, 0);
6191 if( sqlite3WhereTrace & 0x4000 ){ /* Display all WHERE clause terms */
6192 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
6193 sqlite3WhereClausePrint(sWLB.pWC);
6196 #endif
6198 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
6199 rc = whereLoopAddAll(&sWLB);
6200 if( rc ) goto whereBeginError;
6202 #ifdef SQLITE_ENABLE_STAT4
6203 /* If one or more WhereTerm.truthProb values were used in estimating
6204 ** loop parameters, but then those truthProb values were subsequently
6205 ** changed based on STAT4 information while computing subsequent loops,
6206 ** then we need to rerun the whole loop building process so that all
6207 ** loops will be built using the revised truthProb values. */
6208 if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
6209 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6210 WHERETRACE(0xffffffff,
6211 ("**** Redo all loop computations due to"
6212 " TERM_HIGHTRUTH changes ****\n"));
6213 while( pWInfo->pLoops ){
6214 WhereLoop *p = pWInfo->pLoops;
6215 pWInfo->pLoops = p->pNextLoop;
6216 whereLoopDelete(db, p);
6218 rc = whereLoopAddAll(&sWLB);
6219 if( rc ) goto whereBeginError;
6221 #endif
6222 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6224 wherePathSolver(pWInfo, 0);
6225 if( db->mallocFailed ) goto whereBeginError;
6226 if( pWInfo->pOrderBy ){
6227 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
6228 if( db->mallocFailed ) goto whereBeginError;
6231 /* TUNING: Assume that a DISTINCT clause on a subquery reduces
6232 ** the output size by a factor of 8 (LogEst -30).
6234 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
6235 WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n",
6236 pWInfo->nRowOut, pWInfo->nRowOut-30));
6237 pWInfo->nRowOut -= 30;
6241 assert( pWInfo->pTabList!=0 );
6242 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
6243 whereReverseScanOrder(pWInfo);
6245 if( pParse->nErr ){
6246 goto whereBeginError;
6248 assert( db->mallocFailed==0 );
6249 #ifdef WHERETRACE_ENABLED
6250 if( sqlite3WhereTrace ){
6251 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
6252 if( pWInfo->nOBSat>0 ){
6253 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
6255 switch( pWInfo->eDistinct ){
6256 case WHERE_DISTINCT_UNIQUE: {
6257 sqlite3DebugPrintf(" DISTINCT=unique");
6258 break;
6260 case WHERE_DISTINCT_ORDERED: {
6261 sqlite3DebugPrintf(" DISTINCT=ordered");
6262 break;
6264 case WHERE_DISTINCT_UNORDERED: {
6265 sqlite3DebugPrintf(" DISTINCT=unordered");
6266 break;
6269 sqlite3DebugPrintf("\n");
6270 for(ii=0; ii<pWInfo->nLevel; ii++){
6271 sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
6274 #endif
6276 /* Attempt to omit tables from a join that do not affect the result.
6277 ** See the comment on whereOmitNoopJoin() for further information.
6279 ** This query optimization is factored out into a separate "no-inline"
6280 ** procedure to keep the sqlite3WhereBegin() procedure from becoming
6281 ** too large. If sqlite3WhereBegin() becomes too large, that prevents
6282 ** some C-compiler optimizers from in-lining the
6283 ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
6284 ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
6286 notReady = ~(Bitmask)0;
6287 if( pWInfo->nLevel>=2
6288 && pResultSet!=0 /* these two combine to guarantee */
6289 && 0==(wctrlFlags & WHERE_AGG_DISTINCT) /* condition (1) above */
6290 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6292 notReady = whereOmitNoopJoin(pWInfo, notReady);
6293 nTabList = pWInfo->nLevel;
6294 assert( nTabList>0 );
6297 /* Check to see if there are any SEARCH loops that might benefit from
6298 ** using a Bloom filter.
6300 if( pWInfo->nLevel>=2
6301 && OptimizationEnabled(db, SQLITE_BloomFilter)
6303 whereCheckIfBloomFilterIsUseful(pWInfo);
6306 #if defined(WHERETRACE_ENABLED)
6307 if( sqlite3WhereTrace & 0x4000 ){ /* Display all terms of the WHERE clause */
6308 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
6309 sqlite3WhereClausePrint(sWLB.pWC);
6311 WHERETRACE(0xffffffff,("*** Optimizer Finished ***\n"));
6312 #endif
6313 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
6315 /* If the caller is an UPDATE or DELETE statement that is requesting
6316 ** to use a one-pass algorithm, determine if this is appropriate.
6318 ** A one-pass approach can be used if the caller has requested one
6319 ** and either (a) the scan visits at most one row or (b) each
6320 ** of the following are true:
6322 ** * the caller has indicated that a one-pass approach can be used
6323 ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
6324 ** * the table is not a virtual table, and
6325 ** * either the scan does not use the OR optimization or the caller
6326 ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
6327 ** for DELETE).
6329 ** The last qualification is because an UPDATE statement uses
6330 ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
6331 ** use a one-pass approach, and this is not set accurately for scans
6332 ** that use the OR optimization.
6334 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
6335 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
6336 int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
6337 int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
6338 assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
6339 if( bOnerow || (
6340 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
6341 && !IsVirtual(pTabList->a[0].pTab)
6342 && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
6343 && OptimizationEnabled(db, SQLITE_OnePass)
6345 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
6346 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
6347 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
6348 bFordelete = OPFLAG_FORDELETE;
6350 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
6355 /* Open all tables in the pTabList and any indices selected for
6356 ** searching those tables.
6358 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
6359 Table *pTab; /* Table to open */
6360 int iDb; /* Index of database containing table/index */
6361 SrcItem *pTabItem;
6363 pTabItem = &pTabList->a[pLevel->iFrom];
6364 pTab = pTabItem->pTab;
6365 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6366 pLoop = pLevel->pWLoop;
6367 if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
6368 /* Do nothing */
6369 }else
6370 #ifndef SQLITE_OMIT_VIRTUALTABLE
6371 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
6372 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
6373 int iCur = pTabItem->iCursor;
6374 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
6375 }else if( IsVirtual(pTab) ){
6376 /* noop */
6377 }else
6378 #endif
6379 if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0
6380 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0)
6381 || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0
6383 int op = OP_OpenRead;
6384 if( pWInfo->eOnePass!=ONEPASS_OFF ){
6385 op = OP_OpenWrite;
6386 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6388 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
6389 assert( pTabItem->iCursor==pLevel->iTabCur );
6390 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
6391 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
6392 if( pWInfo->eOnePass==ONEPASS_OFF
6393 && pTab->nCol<BMS
6394 && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
6395 && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
6397 /* If we know that only a prefix of the record will be used,
6398 ** it is advantageous to reduce the "column count" field in
6399 ** the P4 operand of the OP_OpenRead/Write opcode. */
6400 Bitmask b = pTabItem->colUsed;
6401 int n = 0;
6402 for(; b; b=b>>1, n++){}
6403 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
6404 assert( n<=pTab->nCol );
6406 #ifdef SQLITE_ENABLE_CURSOR_HINTS
6407 if( pLoop->u.btree.pIndex!=0 && (pTab->tabFlags & TF_WithoutRowid)==0 ){
6408 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
6409 }else
6410 #endif
6412 sqlite3VdbeChangeP5(v, bFordelete);
6414 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6415 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
6416 (const u8*)&pTabItem->colUsed, P4_INT64);
6417 #endif
6418 }else{
6419 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
6421 if( pLoop->wsFlags & WHERE_INDEXED ){
6422 Index *pIx = pLoop->u.btree.pIndex;
6423 int iIndexCur;
6424 int op = OP_OpenRead;
6425 /* iAuxArg is always set to a positive value if ONEPASS is possible */
6426 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
6427 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
6428 && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
6430 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6431 ** WITHOUT ROWID table. No need for a separate index */
6432 iIndexCur = pLevel->iTabCur;
6433 op = 0;
6434 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
6435 Index *pJ = pTabItem->pTab->pIndex;
6436 iIndexCur = iAuxArg;
6437 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6438 while( ALWAYS(pJ) && pJ!=pIx ){
6439 iIndexCur++;
6440 pJ = pJ->pNext;
6442 op = OP_OpenWrite;
6443 pWInfo->aiCurOnePass[1] = iIndexCur;
6444 }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
6445 iIndexCur = iAuxArg;
6446 op = OP_ReopenIdx;
6447 }else{
6448 iIndexCur = pParse->nTab++;
6449 if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
6450 whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem);
6452 if( pIx->pPartIdxWhere && (pTabItem->fg.jointype & JT_RIGHT)==0 ){
6453 wherePartIdxExpr(
6454 pParse, pIx, pIx->pPartIdxWhere, 0, iIndexCur, pTabItem
6458 pLevel->iIdxCur = iIndexCur;
6459 assert( pIx!=0 );
6460 assert( pIx->pSchema==pTab->pSchema );
6461 assert( iIndexCur>=0 );
6462 if( op ){
6463 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6464 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6465 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
6466 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
6467 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
6468 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
6469 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
6470 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
6472 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
6474 VdbeComment((v, "%s", pIx->zName));
6475 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6477 u64 colUsed = 0;
6478 int ii, jj;
6479 for(ii=0; ii<pIx->nColumn; ii++){
6480 jj = pIx->aiColumn[ii];
6481 if( jj<0 ) continue;
6482 if( jj>63 ) jj = 63;
6483 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
6484 colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
6486 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
6487 (u8*)&colUsed, P4_INT64);
6489 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
6492 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
6493 if( (pTabItem->fg.jointype & JT_RIGHT)!=0
6494 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
6496 WhereRightJoin *pRJ = pLevel->pRJ;
6497 pRJ->iMatch = pParse->nTab++;
6498 pRJ->regBloom = ++pParse->nMem;
6499 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
6500 pRJ->regReturn = ++pParse->nMem;
6501 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
6502 assert( pTab==pTabItem->pTab );
6503 if( HasRowid(pTab) ){
6504 KeyInfo *pInfo;
6505 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
6506 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
6507 if( pInfo ){
6508 pInfo->aColl[0] = 0;
6509 pInfo->aSortFlags[0] = 0;
6510 sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
6512 }else{
6513 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6514 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
6515 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
6517 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
6518 /* The nature of RIGHT JOIN processing is such that it messes up
6519 ** the output order. So omit any ORDER BY/GROUP BY elimination
6520 ** optimizations. We need to do an actual sort for RIGHT JOIN. */
6521 pWInfo->nOBSat = 0;
6522 pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED;
6525 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
6526 if( db->mallocFailed ) goto whereBeginError;
6528 /* Generate the code to do the search. Each iteration of the for
6529 ** loop below generates code for a single nested loop of the VM
6530 ** program.
6532 for(ii=0; ii<nTabList; ii++){
6533 int addrExplain;
6534 int wsFlags;
6535 SrcItem *pSrc;
6536 if( pParse->nErr ) goto whereBeginError;
6537 pLevel = &pWInfo->a[ii];
6538 wsFlags = pLevel->pWLoop->wsFlags;
6539 pSrc = &pTabList->a[pLevel->iFrom];
6540 if( pSrc->fg.isMaterialized ){
6541 if( pSrc->fg.isCorrelated ){
6542 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6543 }else{
6544 int iOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
6545 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6546 sqlite3VdbeJumpHere(v, iOnce);
6549 assert( pTabList == pWInfo->pTabList );
6550 if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
6551 if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
6552 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6553 constructAutomaticIndex(pParse, &pWInfo->sWC, notReady, pLevel);
6554 #endif
6555 }else{
6556 sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
6558 if( db->mallocFailed ) goto whereBeginError;
6560 addrExplain = sqlite3WhereExplainOneScan(
6561 pParse, pTabList, pLevel, wctrlFlags
6563 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
6564 notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
6565 pWInfo->iContinue = pLevel->addrCont;
6566 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
6567 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
6571 /* Done. */
6572 VdbeModuleComment((v, "Begin WHERE-core"));
6573 pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
6574 return pWInfo;
6576 /* Jump here if malloc fails */
6577 whereBeginError:
6578 if( pWInfo ){
6579 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6580 whereInfoFree(db, pWInfo);
6582 return 0;
6586 ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
6587 ** index rather than the main table. In SQLITE_DEBUG mode, we want
6588 ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
6589 ** does that.
6591 #ifndef SQLITE_DEBUG
6592 # define OpcodeRewriteTrace(D,K,P) /* no-op */
6593 #else
6594 # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
6595 static void sqlite3WhereOpcodeRewriteTrace(
6596 sqlite3 *db,
6597 int pc,
6598 VdbeOp *pOp
6600 if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
6601 sqlite3VdbePrintOp(0, pc, pOp);
6603 #endif
6605 #ifdef SQLITE_DEBUG
6607 ** Return true if cursor iCur is opened by instruction k of the
6608 ** bytecode. Used inside of assert() only.
6610 static int cursorIsOpen(Vdbe *v, int iCur, int k){
6611 while( k>=0 ){
6612 VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
6613 if( pOp->p1!=iCur ) continue;
6614 if( pOp->opcode==OP_Close ) return 0;
6615 if( pOp->opcode==OP_OpenRead ) return 1;
6616 if( pOp->opcode==OP_OpenWrite ) return 1;
6617 if( pOp->opcode==OP_OpenDup ) return 1;
6618 if( pOp->opcode==OP_OpenAutoindex ) return 1;
6619 if( pOp->opcode==OP_OpenEphemeral ) return 1;
6621 return 0;
6623 #endif /* SQLITE_DEBUG */
6626 ** Generate the end of the WHERE loop. See comments on
6627 ** sqlite3WhereBegin() for additional information.
6629 void sqlite3WhereEnd(WhereInfo *pWInfo){
6630 Parse *pParse = pWInfo->pParse;
6631 Vdbe *v = pParse->pVdbe;
6632 int i;
6633 WhereLevel *pLevel;
6634 WhereLoop *pLoop;
6635 SrcList *pTabList = pWInfo->pTabList;
6636 sqlite3 *db = pParse->db;
6637 int iEnd = sqlite3VdbeCurrentAddr(v);
6638 int nRJ = 0;
6640 /* Generate loop termination code.
6642 VdbeModuleComment((v, "End WHERE-core"));
6643 for(i=pWInfo->nLevel-1; i>=0; i--){
6644 int addr;
6645 pLevel = &pWInfo->a[i];
6646 if( pLevel->pRJ ){
6647 /* Terminate the subroutine that forms the interior of the loop of
6648 ** the RIGHT JOIN table */
6649 WhereRightJoin *pRJ = pLevel->pRJ;
6650 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6651 pLevel->addrCont = 0;
6652 pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);
6653 sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);
6654 VdbeCoverage(v);
6655 nRJ++;
6657 pLoop = pLevel->pWLoop;
6658 if( pLevel->op!=OP_Noop ){
6659 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6660 int addrSeek = 0;
6661 Index *pIdx;
6662 int n;
6663 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
6664 && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
6665 && (pLoop->wsFlags & WHERE_INDEXED)!=0
6666 && (pIdx = pLoop->u.btree.pIndex)->hasStat1
6667 && (n = pLoop->u.btree.nDistinctCol)>0
6668 && pIdx->aiRowLogEst[n]>=36
6670 int r1 = pParse->nMem+1;
6671 int j, op;
6672 for(j=0; j<n; j++){
6673 sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
6675 pParse->nMem += n+1;
6676 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
6677 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
6678 VdbeCoverageIf(v, op==OP_SeekLT);
6679 VdbeCoverageIf(v, op==OP_SeekGT);
6680 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
6682 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
6683 /* The common case: Advance to the next row */
6684 if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6685 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
6686 sqlite3VdbeChangeP5(v, pLevel->p5);
6687 VdbeCoverage(v);
6688 VdbeCoverageIf(v, pLevel->op==OP_Next);
6689 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6690 VdbeCoverageIf(v, pLevel->op==OP_VNext);
6691 if( pLevel->regBignull ){
6692 sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
6693 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
6694 VdbeCoverage(v);
6696 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6697 if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
6698 #endif
6699 }else if( pLevel->addrCont ){
6700 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6702 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
6703 struct InLoop *pIn;
6704 int j;
6705 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
6706 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
6707 assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
6708 || pParse->db->mallocFailed );
6709 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6710 if( pIn->eEndLoopOp!=OP_Noop ){
6711 if( pIn->nPrefix ){
6712 int bEarlyOut =
6713 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
6714 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
6715 if( pLevel->iLeftJoin ){
6716 /* For LEFT JOIN queries, cursor pIn->iCur may not have been
6717 ** opened yet. This occurs for WHERE clauses such as
6718 ** "a = ? AND b IN (...)", where the index is on (a, b). If
6719 ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
6720 ** never have been coded, but the body of the loop run to
6721 ** return the null-row. So, if the cursor is not open yet,
6722 ** jump over the OP_Next or OP_Prev instruction about to
6723 ** be coded. */
6724 sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
6725 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
6726 VdbeCoverage(v);
6728 if( bEarlyOut ){
6729 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
6730 sqlite3VdbeCurrentAddr(v)+2,
6731 pIn->iBase, pIn->nPrefix);
6732 VdbeCoverage(v);
6733 /* Retarget the OP_IsNull against the left operand of IN so
6734 ** it jumps past the OP_IfNoHope. This is because the
6735 ** OP_IsNull also bypasses the OP_Affinity opcode that is
6736 ** required by OP_IfNoHope. */
6737 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6740 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
6741 VdbeCoverage(v);
6742 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
6743 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
6745 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
6748 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
6749 if( pLevel->pRJ ){
6750 sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1);
6751 VdbeCoverage(v);
6753 if( pLevel->addrSkip ){
6754 sqlite3VdbeGoto(v, pLevel->addrSkip);
6755 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
6756 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6757 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
6759 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
6760 if( pLevel->addrLikeRep ){
6761 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
6762 pLevel->addrLikeRep);
6763 VdbeCoverage(v);
6765 #endif
6766 if( pLevel->iLeftJoin ){
6767 int ws = pLoop->wsFlags;
6768 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
6769 assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
6770 if( (ws & WHERE_IDX_ONLY)==0 ){
6771 assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
6772 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
6774 if( (ws & WHERE_INDEXED)
6775 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
6777 if( ws & WHERE_MULTI_OR ){
6778 Index *pIx = pLevel->u.pCoveringIdx;
6779 int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
6780 sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
6781 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6783 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
6785 if( pLevel->op==OP_Return ){
6786 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6787 }else{
6788 sqlite3VdbeGoto(v, pLevel->addrFirst);
6790 sqlite3VdbeJumpHere(v, addr);
6792 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
6793 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
6796 assert( pWInfo->nLevel<=pTabList->nSrc );
6797 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
6798 int k, last;
6799 VdbeOp *pOp, *pLastOp;
6800 Index *pIdx = 0;
6801 SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
6802 Table *pTab = pTabItem->pTab;
6803 assert( pTab!=0 );
6804 pLoop = pLevel->pWLoop;
6806 /* Do RIGHT JOIN processing. Generate code that will output the
6807 ** unmatched rows of the right operand of the RIGHT JOIN with
6808 ** all of the columns of the left operand set to NULL.
6810 if( pLevel->pRJ ){
6811 sqlite3WhereRightJoinLoop(pWInfo, i, pLevel);
6812 continue;
6815 /* For a co-routine, change all OP_Column references to the table of
6816 ** the co-routine into OP_Copy of result contained in a register.
6817 ** OP_Rowid becomes OP_Null.
6819 if( pTabItem->fg.viaCoroutine ){
6820 testcase( pParse->db->mallocFailed );
6821 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
6822 pTabItem->regResult, 0);
6823 continue;
6826 /* If this scan uses an index, make VDBE code substitutions to read data
6827 ** from the index instead of from the table where possible. In some cases
6828 ** this optimization prevents the table from ever being read, which can
6829 ** yield a significant performance boost.
6831 ** Calls to the code generator in between sqlite3WhereBegin and
6832 ** sqlite3WhereEnd will have created code that references the table
6833 ** directly. This loop scans all that code looking for opcodes
6834 ** that reference the table and converts them into opcodes that
6835 ** reference the index.
6837 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6838 pIdx = pLoop->u.btree.pIndex;
6839 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
6840 pIdx = pLevel->u.pCoveringIdx;
6842 if( pIdx
6843 && !db->mallocFailed
6845 if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
6846 last = iEnd;
6847 }else{
6848 last = pWInfo->iEndWhere;
6850 if( pIdx->bHasExpr ){
6851 IndexedExpr *p = pParse->pIdxEpr;
6852 while( p ){
6853 if( p->iIdxCur==pLevel->iIdxCur ){
6854 #ifdef WHERETRACE_ENABLED
6855 if( sqlite3WhereTrace & 0x200 ){
6856 sqlite3DebugPrintf("Disable pParse->pIdxEpr term {%d,%d}\n",
6857 p->iIdxCur, p->iIdxCol);
6858 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(p->pExpr);
6860 #endif
6861 p->iDataCur = -1;
6862 p->iIdxCur = -1;
6864 p = p->pIENext;
6867 k = pLevel->addrBody + 1;
6868 #ifdef SQLITE_DEBUG
6869 if( db->flags & SQLITE_VdbeAddopTrace ){
6870 printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n",
6871 pLevel->iTabCur, pLevel->iIdxCur, k, last-1);
6873 /* Proof that the "+1" on the k value above is safe */
6874 pOp = sqlite3VdbeGetOp(v, k - 1);
6875 assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
6876 assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur );
6877 assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
6878 #endif
6879 pOp = sqlite3VdbeGetOp(v, k);
6880 pLastOp = pOp + (last - k);
6881 assert( pOp<=pLastOp );
6883 if( pOp->p1!=pLevel->iTabCur ){
6884 /* no-op */
6885 }else if( pOp->opcode==OP_Column
6886 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6887 || pOp->opcode==OP_Offset
6888 #endif
6890 int x = pOp->p2;
6891 assert( pIdx->pTable==pTab );
6892 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6893 if( pOp->opcode==OP_Offset ){
6894 /* Do not need to translate the column number */
6895 }else
6896 #endif
6897 if( !HasRowid(pTab) ){
6898 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6899 x = pPk->aiColumn[x];
6900 assert( x>=0 );
6901 }else{
6902 testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
6903 x = sqlite3StorageColumnToTable(pTab,x);
6905 x = sqlite3TableColumnToIndex(pIdx, x);
6906 if( x>=0 ){
6907 pOp->p2 = x;
6908 pOp->p1 = pLevel->iIdxCur;
6909 OpcodeRewriteTrace(db, k, pOp);
6910 }else{
6911 /* Unable to translate the table reference into an index
6912 ** reference. Verify that this is harmless - that the
6913 ** table being referenced really is open.
6915 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6916 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6917 || cursorIsOpen(v,pOp->p1,k)
6918 || pOp->opcode==OP_Offset
6920 #else
6921 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6922 || cursorIsOpen(v,pOp->p1,k)
6924 #endif
6926 }else if( pOp->opcode==OP_Rowid ){
6927 pOp->p1 = pLevel->iIdxCur;
6928 pOp->opcode = OP_IdxRowid;
6929 OpcodeRewriteTrace(db, k, pOp);
6930 }else if( pOp->opcode==OP_IfNullRow ){
6931 pOp->p1 = pLevel->iIdxCur;
6932 OpcodeRewriteTrace(db, k, pOp);
6934 #ifdef SQLITE_DEBUG
6935 k++;
6936 #endif
6937 }while( (++pOp)<pLastOp );
6938 #ifdef SQLITE_DEBUG
6939 if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
6940 #endif
6944 /* The "break" point is here, just past the end of the outer loop.
6945 ** Set it.
6947 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
6949 /* Final cleanup
6951 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6952 whereInfoFree(db, pWInfo);
6953 pParse->withinRJSubrtn -= nRJ;
6954 return;