downgrade memory unlock failures to info level and fix function name in log output
[sqlcipher.git] / src / where.c
blob8e7b112ac006e4804eddde51f433e30d95b9b9aa
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 #ifdef SQLITE_DEBUG
682 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
683 printf("TRANSLATE OP_Column to OP_Copy at %d\n", iStart);
685 #endif
686 pOp->opcode = OP_Copy;
687 pOp->p1 = pOp->p2 + iRegister;
688 pOp->p2 = pOp->p3;
689 pOp->p3 = 0;
690 pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */
691 }else if( pOp->opcode==OP_Rowid ){
692 #ifdef SQLITE_DEBUG
693 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
694 printf("TRANSLATE OP_Rowid to OP_Sequence at %d\n", iStart);
696 #endif
697 pOp->opcode = OP_Sequence;
698 pOp->p1 = iAutoidxCur;
699 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
700 if( iAutoidxCur==0 ){
701 pOp->opcode = OP_Null;
702 pOp->p3 = 0;
704 #endif
710 ** Two routines for printing the content of an sqlite3_index_info
711 ** structure. Used for testing and debugging only. If neither
712 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
713 ** are no-ops.
715 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
716 static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
717 int i;
718 if( (sqlite3WhereTrace & 0x10)==0 ) return;
719 for(i=0; i<p->nConstraint; i++){
720 sqlite3DebugPrintf(
721 " constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",
723 p->aConstraint[i].iColumn,
724 p->aConstraint[i].iTermOffset,
725 p->aConstraint[i].op,
726 p->aConstraint[i].usable,
727 sqlite3_vtab_collation(p,i));
729 for(i=0; i<p->nOrderBy; i++){
730 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
732 p->aOrderBy[i].iColumn,
733 p->aOrderBy[i].desc);
736 static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
737 int i;
738 if( (sqlite3WhereTrace & 0x10)==0 ) return;
739 for(i=0; i<p->nConstraint; i++){
740 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
742 p->aConstraintUsage[i].argvIndex,
743 p->aConstraintUsage[i].omit);
745 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
746 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
747 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
748 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
749 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
751 #else
752 #define whereTraceIndexInfoInputs(A)
753 #define whereTraceIndexInfoOutputs(A)
754 #endif
757 ** We know that pSrc is an operand of an outer join. Return true if
758 ** pTerm is a constraint that is compatible with that join.
760 ** pTerm must be EP_OuterON if pSrc is the right operand of an
761 ** outer join. pTerm can be either EP_OuterON or EP_InnerON if pSrc
762 ** is the left operand of a RIGHT join.
764 ** See https://sqlite.org/forum/forumpost/206d99a16dd9212f
765 ** for an example of a WHERE clause constraints that may not be used on
766 ** the right table of a RIGHT JOIN because the constraint implies a
767 ** not-NULL condition on the left table of the RIGHT JOIN.
769 static int constraintCompatibleWithOuterJoin(
770 const WhereTerm *pTerm, /* WHERE clause term to check */
771 const SrcItem *pSrc /* Table we are trying to access */
773 assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */
774 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT );
775 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ );
776 testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) )
777 testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) );
778 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON)
779 || pTerm->pExpr->w.iJoin != pSrc->iCursor
781 return 0;
783 if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0
784 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
786 return 0;
788 return 1;
793 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
795 ** Return TRUE if the WHERE clause term pTerm is of a form where it
796 ** could be used with an index to access pSrc, assuming an appropriate
797 ** index existed.
799 static int termCanDriveIndex(
800 const WhereTerm *pTerm, /* WHERE clause term to check */
801 const SrcItem *pSrc, /* Table we are trying to access */
802 const Bitmask notReady /* Tables in outer loops of the join */
804 char aff;
805 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
806 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
807 assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
808 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
809 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
811 return 0; /* See https://sqlite.org/forum/forumpost/51e6959f61 */
813 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
814 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
815 if( pTerm->u.x.leftColumn<0 ) return 0;
816 aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
817 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
818 testcase( pTerm->pExpr->op==TK_IS );
819 return 1;
821 #endif
824 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
826 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
828 ** Argument pIdx represents an automatic index that the current statement
829 ** will create and populate. Add an OP_Explain with text of the form:
831 ** CREATE AUTOMATIC INDEX ON <table>(<cols>) [WHERE <expr>]
833 ** This is only required if sqlite3_stmt_scanstatus() is enabled, to
834 ** associate an SQLITE_SCANSTAT_NCYCLE and SQLITE_SCANSTAT_NLOOP
835 ** values with. In order to avoid breaking legacy code and test cases,
836 ** the OP_Explain is not added if this is an EXPLAIN QUERY PLAN command.
838 static void explainAutomaticIndex(
839 Parse *pParse,
840 Index *pIdx, /* Automatic index to explain */
841 int bPartial, /* True if pIdx is a partial index */
842 int *pAddrExplain /* OUT: Address of OP_Explain */
844 if( IS_STMT_SCANSTATUS(pParse->db) && pParse->explain!=2 ){
845 Table *pTab = pIdx->pTable;
846 const char *zSep = "";
847 char *zText = 0;
848 int ii = 0;
849 sqlite3_str *pStr = sqlite3_str_new(pParse->db);
850 sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName);
851 assert( pIdx->nColumn>1 );
852 assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID );
853 for(ii=0; ii<(pIdx->nColumn-1); ii++){
854 const char *zName = 0;
855 int iCol = pIdx->aiColumn[ii];
857 zName = pTab->aCol[iCol].zCnName;
858 sqlite3_str_appendf(pStr, "%s%s", zSep, zName);
859 zSep = ", ";
861 zText = sqlite3_str_finish(pStr);
862 if( zText==0 ){
863 sqlite3OomFault(pParse->db);
864 }else{
865 *pAddrExplain = sqlite3VdbeExplain(
866 pParse, 0, "%s)%s", zText, (bPartial ? " WHERE <expr>" : "")
868 sqlite3_free(zText);
872 #else
873 # define explainAutomaticIndex(a,b,c,d)
874 #endif
877 ** Generate code to construct the Index object for an automatic index
878 ** and to set up the WhereLevel object pLevel so that the code generator
879 ** makes use of the automatic index.
881 static SQLITE_NOINLINE void constructAutomaticIndex(
882 Parse *pParse, /* The parsing context */
883 WhereClause *pWC, /* The WHERE clause */
884 const Bitmask notReady, /* Mask of cursors that are not available */
885 WhereLevel *pLevel /* Write new index here */
887 int nKeyCol; /* Number of columns in the constructed index */
888 WhereTerm *pTerm; /* A single term of the WHERE clause */
889 WhereTerm *pWCEnd; /* End of pWC->a[] */
890 Index *pIdx; /* Object describing the transient index */
891 Vdbe *v; /* Prepared statement under construction */
892 int addrInit; /* Address of the initialization bypass jump */
893 Table *pTable; /* The table being indexed */
894 int addrTop; /* Top of the index fill loop */
895 int regRecord; /* Register holding an index record */
896 int n; /* Column counter */
897 int i; /* Loop counter */
898 int mxBitCol; /* Maximum column in pSrc->colUsed */
899 CollSeq *pColl; /* Collating sequence to on a column */
900 WhereLoop *pLoop; /* The Loop object */
901 char *zNotUsed; /* Extra space on the end of pIdx */
902 Bitmask idxCols; /* Bitmap of columns used for indexing */
903 Bitmask extraCols; /* Bitmap of additional columns */
904 u8 sentWarning = 0; /* True if a warning has been issued */
905 u8 useBloomFilter = 0; /* True to also add a Bloom filter */
906 Expr *pPartial = 0; /* Partial Index Expression */
907 int iContinue = 0; /* Jump here to skip excluded rows */
908 SrcList *pTabList; /* The complete FROM clause */
909 SrcItem *pSrc; /* The FROM clause term to get the next index */
910 int addrCounter = 0; /* Address where integer counter is initialized */
911 int regBase; /* Array of registers where record is assembled */
912 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
913 int addrExp = 0; /* Address of OP_Explain */
914 #endif
916 /* Generate code to skip over the creation and initialization of the
917 ** transient index on 2nd and subsequent iterations of the loop. */
918 v = pParse->pVdbe;
919 assert( v!=0 );
920 addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
922 /* Count the number of columns that will be added to the index
923 ** and used to match WHERE clause constraints */
924 nKeyCol = 0;
925 pTabList = pWC->pWInfo->pTabList;
926 pSrc = &pTabList->a[pLevel->iFrom];
927 pTable = pSrc->pTab;
928 pWCEnd = &pWC->a[pWC->nTerm];
929 pLoop = pLevel->pWLoop;
930 idxCols = 0;
931 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
932 Expr *pExpr = pTerm->pExpr;
933 /* Make the automatic index a partial index if there are terms in the
934 ** WHERE clause (or the ON clause of a LEFT join) that constrain which
935 ** rows of the target table (pSrc) that can be used. */
936 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
937 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, pLevel->iFrom)
939 pPartial = sqlite3ExprAnd(pParse, pPartial,
940 sqlite3ExprDup(pParse->db, pExpr, 0));
942 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
943 int iCol;
944 Bitmask cMask;
945 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
946 iCol = pTerm->u.x.leftColumn;
947 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
948 testcase( iCol==BMS );
949 testcase( iCol==BMS-1 );
950 if( !sentWarning ){
951 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
952 "automatic index on %s(%s)", pTable->zName,
953 pTable->aCol[iCol].zCnName);
954 sentWarning = 1;
956 if( (idxCols & cMask)==0 ){
957 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
958 goto end_auto_index_create;
960 pLoop->aLTerm[nKeyCol++] = pTerm;
961 idxCols |= cMask;
965 assert( nKeyCol>0 || pParse->db->mallocFailed );
966 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
967 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
968 | WHERE_AUTO_INDEX;
970 /* Count the number of additional columns needed to create a
971 ** covering index. A "covering index" is an index that contains all
972 ** columns that are needed by the query. With a covering index, the
973 ** original table never needs to be accessed. Automatic indices must
974 ** be a covering index because the index will not be updated if the
975 ** original table changes and the index and table cannot both be used
976 ** if they go out of sync.
978 if( IsView(pTable) ){
979 extraCols = ALLBITS;
980 }else{
981 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
983 mxBitCol = MIN(BMS-1,pTable->nCol);
984 testcase( pTable->nCol==BMS-1 );
985 testcase( pTable->nCol==BMS-2 );
986 for(i=0; i<mxBitCol; i++){
987 if( extraCols & MASKBIT(i) ) nKeyCol++;
989 if( pSrc->colUsed & MASKBIT(BMS-1) ){
990 nKeyCol += pTable->nCol - BMS + 1;
993 /* Construct the Index object to describe this index */
994 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
995 if( pIdx==0 ) goto end_auto_index_create;
996 pLoop->u.btree.pIndex = pIdx;
997 pIdx->zName = "auto-index";
998 pIdx->pTable = pTable;
999 n = 0;
1000 idxCols = 0;
1001 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1002 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1003 int iCol;
1004 Bitmask cMask;
1005 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
1006 iCol = pTerm->u.x.leftColumn;
1007 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
1008 testcase( iCol==BMS-1 );
1009 testcase( iCol==BMS );
1010 if( (idxCols & cMask)==0 ){
1011 Expr *pX = pTerm->pExpr;
1012 idxCols |= cMask;
1013 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
1014 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
1015 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
1016 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
1017 n++;
1018 if( ALWAYS(pX->pLeft!=0)
1019 && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT
1021 /* TUNING: only use a Bloom filter on an automatic index
1022 ** if one or more key columns has the ability to hold numeric
1023 ** values, since strings all have the same hash in the Bloom
1024 ** filter implementation and hence a Bloom filter on a text column
1025 ** is not usually helpful. */
1026 useBloomFilter = 1;
1031 assert( (u32)n==pLoop->u.btree.nEq );
1033 /* Add additional columns needed to make the automatic index into
1034 ** a covering index */
1035 for(i=0; i<mxBitCol; i++){
1036 if( extraCols & MASKBIT(i) ){
1037 pIdx->aiColumn[n] = i;
1038 pIdx->azColl[n] = sqlite3StrBINARY;
1039 n++;
1042 if( pSrc->colUsed & MASKBIT(BMS-1) ){
1043 for(i=BMS-1; i<pTable->nCol; i++){
1044 pIdx->aiColumn[n] = i;
1045 pIdx->azColl[n] = sqlite3StrBINARY;
1046 n++;
1049 assert( n==nKeyCol );
1050 pIdx->aiColumn[n] = XN_ROWID;
1051 pIdx->azColl[n] = sqlite3StrBINARY;
1053 /* Create the automatic index */
1054 explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp);
1055 assert( pLevel->iIdxCur>=0 );
1056 pLevel->iIdxCur = pParse->nTab++;
1057 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1058 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1059 VdbeComment((v, "for %s", pTable->zName));
1060 if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) && useBloomFilter ){
1061 sqlite3WhereExplainBloomFilter(pParse, pWC->pWInfo, pLevel);
1062 pLevel->regFilter = ++pParse->nMem;
1063 sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
1066 /* Fill the automatic index with content */
1067 assert( pSrc == &pWC->pWInfo->pTabList->a[pLevel->iFrom] );
1068 if( pSrc->fg.viaCoroutine ){
1069 int regYield = pSrc->regReturn;
1070 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
1071 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSrc->addrFillSub);
1072 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
1073 VdbeCoverage(v);
1074 VdbeComment((v, "next row of %s", pSrc->pTab->zName));
1075 }else{
1076 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
1078 if( pPartial ){
1079 iContinue = sqlite3VdbeMakeLabel(pParse);
1080 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
1081 pLoop->wsFlags |= WHERE_PARTIALIDX;
1083 regRecord = sqlite3GetTempReg(pParse);
1084 regBase = sqlite3GenerateIndexKey(
1085 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
1087 if( pLevel->regFilter ){
1088 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
1089 regBase, pLoop->u.btree.nEq);
1091 sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
1092 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1093 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1094 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
1095 if( pSrc->fg.viaCoroutine ){
1096 sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
1097 testcase( pParse->db->mallocFailed );
1098 assert( pLevel->iIdxCur>0 );
1099 translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
1100 pSrc->regResult, pLevel->iIdxCur);
1101 sqlite3VdbeGoto(v, addrTop);
1102 pSrc->fg.viaCoroutine = 0;
1103 }else{
1104 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
1105 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
1107 sqlite3VdbeJumpHere(v, addrTop);
1108 sqlite3ReleaseTempReg(pParse, regRecord);
1110 /* Jump here when skipping the initialization */
1111 sqlite3VdbeJumpHere(v, addrInit);
1112 sqlite3VdbeScanStatusRange(v, addrExp, addrExp, -1);
1114 end_auto_index_create:
1115 sqlite3ExprDelete(pParse->db, pPartial);
1117 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1120 ** Generate bytecode that will initialize a Bloom filter that is appropriate
1121 ** for pLevel.
1123 ** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER
1124 ** flag set, initialize a Bloomfilter for them as well. Except don't do
1125 ** this recursive initialization if the SQLITE_BloomPulldown optimization has
1126 ** been turned off.
1128 ** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared
1129 ** from the loop, but the regFilter value is set to a register that implements
1130 ** the Bloom filter. When regFilter is positive, the
1131 ** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter
1132 ** and skip the subsequence B-Tree seek if the Bloom filter indicates that
1133 ** no matching rows exist.
1135 ** This routine may only be called if it has previously been determined that
1136 ** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit
1137 ** is set.
1139 static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
1140 WhereInfo *pWInfo, /* The WHERE clause */
1141 int iLevel, /* Index in pWInfo->a[] that is pLevel */
1142 WhereLevel *pLevel, /* Make a Bloom filter for this FROM term */
1143 Bitmask notReady /* Loops that are not ready */
1145 int addrOnce; /* Address of opening OP_Once */
1146 int addrTop; /* Address of OP_Rewind */
1147 int addrCont; /* Jump here to skip a row */
1148 const WhereTerm *pTerm; /* For looping over WHERE clause terms */
1149 const WhereTerm *pWCEnd; /* Last WHERE clause term */
1150 Parse *pParse = pWInfo->pParse; /* Parsing context */
1151 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
1152 WhereLoop *pLoop = pLevel->pWLoop; /* The loop being coded */
1153 int iCur; /* Cursor for table getting the filter */
1154 IndexedExpr *saved_pIdxEpr; /* saved copy of Parse.pIdxEpr */
1155 IndexedExpr *saved_pIdxPartExpr; /* saved copy of Parse.pIdxPartExpr */
1157 saved_pIdxEpr = pParse->pIdxEpr;
1158 saved_pIdxPartExpr = pParse->pIdxPartExpr;
1159 pParse->pIdxEpr = 0;
1160 pParse->pIdxPartExpr = 0;
1162 assert( pLoop!=0 );
1163 assert( v!=0 );
1164 assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
1165 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 );
1167 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
1169 const SrcList *pTabList;
1170 const SrcItem *pItem;
1171 const Table *pTab;
1172 u64 sz;
1173 int iSrc;
1174 sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
1175 addrCont = sqlite3VdbeMakeLabel(pParse);
1176 iCur = pLevel->iTabCur;
1177 pLevel->regFilter = ++pParse->nMem;
1179 /* The Bloom filter is a Blob held in a register. Initialize it
1180 ** to zero-filled blob of at least 80K bits, but maybe more if the
1181 ** estimated size of the table is larger. We could actually
1182 ** measure the size of the table at run-time using OP_Count with
1183 ** P3==1 and use that value to initialize the blob. But that makes
1184 ** testing complicated. By basing the blob size on the value in the
1185 ** sqlite_stat1 table, testing is much easier.
1187 pTabList = pWInfo->pTabList;
1188 iSrc = pLevel->iFrom;
1189 pItem = &pTabList->a[iSrc];
1190 assert( pItem!=0 );
1191 pTab = pItem->pTab;
1192 assert( pTab!=0 );
1193 sz = sqlite3LogEstToInt(pTab->nRowLogEst);
1194 if( sz<10000 ){
1195 sz = 10000;
1196 }else if( sz>10000000 ){
1197 sz = 10000000;
1199 sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
1201 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
1202 pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
1203 for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
1204 Expr *pExpr = pTerm->pExpr;
1205 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
1206 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, iSrc)
1208 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1211 if( pLoop->wsFlags & WHERE_IPK ){
1212 int r1 = sqlite3GetTempReg(pParse);
1213 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
1214 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
1215 sqlite3ReleaseTempReg(pParse, r1);
1216 }else{
1217 Index *pIdx = pLoop->u.btree.pIndex;
1218 int n = pLoop->u.btree.nEq;
1219 int r1 = sqlite3GetTempRange(pParse, n);
1220 int jj;
1221 for(jj=0; jj<n; jj++){
1222 assert( pIdx->pTable==pItem->pTab );
1223 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
1225 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
1226 sqlite3ReleaseTempRange(pParse, r1, n);
1228 sqlite3VdbeResolveLabel(v, addrCont);
1229 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
1230 VdbeCoverage(v);
1231 sqlite3VdbeJumpHere(v, addrTop);
1232 pLoop->wsFlags &= ~WHERE_BLOOMFILTER;
1233 if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break;
1234 while( ++iLevel < pWInfo->nLevel ){
1235 const SrcItem *pTabItem;
1236 pLevel = &pWInfo->a[iLevel];
1237 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
1238 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ) ) continue;
1239 pLoop = pLevel->pWLoop;
1240 if( NEVER(pLoop==0) ) continue;
1241 if( pLoop->prereq & notReady ) continue;
1242 if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN))
1243 ==WHERE_BLOOMFILTER
1245 /* This is a candidate for bloom-filter pull-down (early evaluation).
1246 ** The test that WHERE_COLUMN_IN is omitted is important, as we are
1247 ** not able to do early evaluation of bloom filters that make use of
1248 ** the IN operator */
1249 break;
1252 }while( iLevel < pWInfo->nLevel );
1253 sqlite3VdbeJumpHere(v, addrOnce);
1254 pParse->pIdxEpr = saved_pIdxEpr;
1255 pParse->pIdxPartExpr = saved_pIdxPartExpr;
1259 #ifndef SQLITE_OMIT_VIRTUALTABLE
1261 ** Allocate and populate an sqlite3_index_info structure. It is the
1262 ** responsibility of the caller to eventually release the structure
1263 ** by passing the pointer returned by this function to freeIndexInfo().
1265 static sqlite3_index_info *allocateIndexInfo(
1266 WhereInfo *pWInfo, /* The WHERE clause */
1267 WhereClause *pWC, /* The WHERE clause being analyzed */
1268 Bitmask mUnusable, /* Ignore terms with these prereqs */
1269 SrcItem *pSrc, /* The FROM clause term that is the vtab */
1270 u16 *pmNoOmit /* Mask of terms not to omit */
1272 int i, j;
1273 int nTerm;
1274 Parse *pParse = pWInfo->pParse;
1275 struct sqlite3_index_constraint *pIdxCons;
1276 struct sqlite3_index_orderby *pIdxOrderBy;
1277 struct sqlite3_index_constraint_usage *pUsage;
1278 struct HiddenIndexInfo *pHidden;
1279 WhereTerm *pTerm;
1280 int nOrderBy;
1281 sqlite3_index_info *pIdxInfo;
1282 u16 mNoOmit = 0;
1283 const Table *pTab;
1284 int eDistinct = 0;
1285 ExprList *pOrderBy = pWInfo->pOrderBy;
1287 assert( pSrc!=0 );
1288 pTab = pSrc->pTab;
1289 assert( pTab!=0 );
1290 assert( IsVirtual(pTab) );
1292 /* Find all WHERE clause constraints referring to this virtual table.
1293 ** Mark each term with the TERM_OK flag. Set nTerm to the number of
1294 ** terms found.
1296 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1297 pTerm->wtFlags &= ~TERM_OK;
1298 if( pTerm->leftCursor != pSrc->iCursor ) continue;
1299 if( pTerm->prereqRight & mUnusable ) continue;
1300 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1301 testcase( pTerm->eOperator & WO_IN );
1302 testcase( pTerm->eOperator & WO_ISNULL );
1303 testcase( pTerm->eOperator & WO_IS );
1304 testcase( pTerm->eOperator & WO_ALL );
1305 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
1306 if( pTerm->wtFlags & TERM_VNULL ) continue;
1308 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
1309 assert( pTerm->u.x.leftColumn>=XN_ROWID );
1310 assert( pTerm->u.x.leftColumn<pTab->nCol );
1311 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
1312 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
1314 continue;
1316 nTerm++;
1317 pTerm->wtFlags |= TERM_OK;
1320 /* If the ORDER BY clause contains only columns in the current
1321 ** virtual table then allocate space for the aOrderBy part of
1322 ** the sqlite3_index_info structure.
1324 nOrderBy = 0;
1325 if( pOrderBy ){
1326 int n = pOrderBy->nExpr;
1327 for(i=0; i<n; i++){
1328 Expr *pExpr = pOrderBy->a[i].pExpr;
1329 Expr *pE2;
1331 /* Skip over constant terms in the ORDER BY clause */
1332 if( sqlite3ExprIsConstant(pExpr) ){
1333 continue;
1336 /* Virtual tables are unable to deal with NULLS FIRST */
1337 if( pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) break;
1339 /* First case - a direct column references without a COLLATE operator */
1340 if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){
1341 assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumn<pTab->nCol );
1342 continue;
1345 /* 2nd case - a column reference with a COLLATE operator. Only match
1346 ** of the COLLATE operator matches the collation of the column. */
1347 if( pExpr->op==TK_COLLATE
1348 && (pE2 = pExpr->pLeft)->op==TK_COLUMN
1349 && pE2->iTable==pSrc->iCursor
1351 const char *zColl; /* The collating sequence name */
1352 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1353 assert( pExpr->u.zToken!=0 );
1354 assert( pE2->iColumn>=XN_ROWID && pE2->iColumn<pTab->nCol );
1355 pExpr->iColumn = pE2->iColumn;
1356 if( pE2->iColumn<0 ) continue; /* Collseq does not matter for rowid */
1357 zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]);
1358 if( zColl==0 ) zColl = sqlite3StrBINARY;
1359 if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue;
1362 /* No matches cause a break out of the loop */
1363 break;
1365 if( i==n ){
1366 nOrderBy = n;
1367 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) ){
1368 eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
1369 }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
1370 eDistinct = 1;
1375 /* Allocate the sqlite3_index_info structure
1377 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1378 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1379 + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden)
1380 + sizeof(sqlite3_value*)*nTerm );
1381 if( pIdxInfo==0 ){
1382 sqlite3ErrorMsg(pParse, "out of memory");
1383 return 0;
1385 pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
1386 pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm];
1387 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1388 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1389 pIdxInfo->aConstraint = pIdxCons;
1390 pIdxInfo->aOrderBy = pIdxOrderBy;
1391 pIdxInfo->aConstraintUsage = pUsage;
1392 pHidden->pWC = pWC;
1393 pHidden->pParse = pParse;
1394 pHidden->eDistinct = eDistinct;
1395 pHidden->mIn = 0;
1396 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1397 u16 op;
1398 if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
1399 pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
1400 pIdxCons[j].iTermOffset = i;
1401 op = pTerm->eOperator & WO_ALL;
1402 if( op==WO_IN ){
1403 if( (pTerm->wtFlags & TERM_SLICE)==0 ){
1404 pHidden->mIn |= SMASKBIT32(j);
1406 op = WO_EQ;
1408 if( op==WO_AUX ){
1409 pIdxCons[j].op = pTerm->eMatchOp;
1410 }else if( op & (WO_ISNULL|WO_IS) ){
1411 if( op==WO_ISNULL ){
1412 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
1413 }else{
1414 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
1416 }else{
1417 pIdxCons[j].op = (u8)op;
1418 /* The direct assignment in the previous line is possible only because
1419 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1420 ** following asserts verify this fact. */
1421 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1422 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1423 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1424 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1425 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1426 assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
1428 if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
1429 && sqlite3ExprIsVector(pTerm->pExpr->pRight)
1431 testcase( j!=i );
1432 if( j<16 ) mNoOmit |= (1 << j);
1433 if( op==WO_LT ) pIdxCons[j].op = WO_LE;
1434 if( op==WO_GT ) pIdxCons[j].op = WO_GE;
1438 j++;
1440 assert( j==nTerm );
1441 pIdxInfo->nConstraint = j;
1442 for(i=j=0; i<nOrderBy; i++){
1443 Expr *pExpr = pOrderBy->a[i].pExpr;
1444 if( sqlite3ExprIsConstant(pExpr) ) continue;
1445 assert( pExpr->op==TK_COLUMN
1446 || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
1447 && pExpr->iColumn==pExpr->pLeft->iColumn) );
1448 pIdxOrderBy[j].iColumn = pExpr->iColumn;
1449 pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
1450 j++;
1452 pIdxInfo->nOrderBy = j;
1454 *pmNoOmit = mNoOmit;
1455 return pIdxInfo;
1459 ** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
1460 ** and possibly modified by xBestIndex methods.
1462 static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
1463 HiddenIndexInfo *pHidden;
1464 int i;
1465 assert( pIdxInfo!=0 );
1466 pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
1467 assert( pHidden->pParse!=0 );
1468 assert( pHidden->pParse->db==db );
1469 for(i=0; i<pIdxInfo->nConstraint; i++){
1470 sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
1471 pHidden->aRhs[i] = 0;
1473 sqlite3DbFree(db, pIdxInfo);
1477 ** The table object reference passed as the second argument to this function
1478 ** must represent a virtual table. This function invokes the xBestIndex()
1479 ** method of the virtual table with the sqlite3_index_info object that
1480 ** comes in as the 3rd argument to this function.
1482 ** If an error occurs, pParse is populated with an error message and an
1483 ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
1484 ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
1485 ** the current configuration of "unusable" flags in sqlite3_index_info can
1486 ** not result in a valid plan.
1488 ** Whether or not an error is returned, it is the responsibility of the
1489 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1490 ** that this is required.
1492 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
1493 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
1494 int rc;
1496 whereTraceIndexInfoInputs(p);
1497 pParse->db->nSchemaLock++;
1498 rc = pVtab->pModule->xBestIndex(pVtab, p);
1499 pParse->db->nSchemaLock--;
1500 whereTraceIndexInfoOutputs(p);
1502 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
1503 if( rc==SQLITE_NOMEM ){
1504 sqlite3OomFault(pParse->db);
1505 }else if( !pVtab->zErrMsg ){
1506 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1507 }else{
1508 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1511 if( pTab->u.vtab.p->bAllSchemas ){
1512 sqlite3VtabUsesAllSchemas(pParse);
1514 sqlite3_free(pVtab->zErrMsg);
1515 pVtab->zErrMsg = 0;
1516 return rc;
1518 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
1520 #ifdef SQLITE_ENABLE_STAT4
1522 ** Estimate the location of a particular key among all keys in an
1523 ** index. Store the results in aStat as follows:
1525 ** aStat[0] Est. number of rows less than pRec
1526 ** aStat[1] Est. number of rows equal to pRec
1528 ** Return the index of the sample that is the smallest sample that
1529 ** is greater than or equal to pRec. Note that this index is not an index
1530 ** into the aSample[] array - it is an index into a virtual set of samples
1531 ** based on the contents of aSample[] and the number of fields in record
1532 ** pRec.
1534 static int whereKeyStats(
1535 Parse *pParse, /* Database connection */
1536 Index *pIdx, /* Index to consider domain of */
1537 UnpackedRecord *pRec, /* Vector of values to consider */
1538 int roundUp, /* Round up if true. Round down if false */
1539 tRowcnt *aStat /* OUT: stats written here */
1541 IndexSample *aSample = pIdx->aSample;
1542 int iCol; /* Index of required stats in anEq[] etc. */
1543 int i; /* Index of first sample >= pRec */
1544 int iSample; /* Smallest sample larger than or equal to pRec */
1545 int iMin = 0; /* Smallest sample not yet tested */
1546 int iTest; /* Next sample to test */
1547 int res; /* Result of comparison operation */
1548 int nField; /* Number of fields in pRec */
1549 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
1551 #ifndef SQLITE_DEBUG
1552 UNUSED_PARAMETER( pParse );
1553 #endif
1554 assert( pRec!=0 );
1555 assert( pIdx->nSample>0 );
1556 assert( pRec->nField>0 );
1559 /* Do a binary search to find the first sample greater than or equal
1560 ** to pRec. If pRec contains a single field, the set of samples to search
1561 ** is simply the aSample[] array. If the samples in aSample[] contain more
1562 ** than one fields, all fields following the first are ignored.
1564 ** If pRec contains N fields, where N is more than one, then as well as the
1565 ** samples in aSample[] (truncated to N fields), the search also has to
1566 ** consider prefixes of those samples. For example, if the set of samples
1567 ** in aSample is:
1569 ** aSample[0] = (a, 5)
1570 ** aSample[1] = (a, 10)
1571 ** aSample[2] = (b, 5)
1572 ** aSample[3] = (c, 100)
1573 ** aSample[4] = (c, 105)
1575 ** Then the search space should ideally be the samples above and the
1576 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
1577 ** the code actually searches this set:
1579 ** 0: (a)
1580 ** 1: (a, 5)
1581 ** 2: (a, 10)
1582 ** 3: (a, 10)
1583 ** 4: (b)
1584 ** 5: (b, 5)
1585 ** 6: (c)
1586 ** 7: (c, 100)
1587 ** 8: (c, 105)
1588 ** 9: (c, 105)
1590 ** For each sample in the aSample[] array, N samples are present in the
1591 ** effective sample array. In the above, samples 0 and 1 are based on
1592 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
1594 ** Often, sample i of each block of N effective samples has (i+1) fields.
1595 ** Except, each sample may be extended to ensure that it is greater than or
1596 ** equal to the previous sample in the array. For example, in the above,
1597 ** sample 2 is the first sample of a block of N samples, so at first it
1598 ** appears that it should be 1 field in size. However, that would make it
1599 ** smaller than sample 1, so the binary search would not work. As a result,
1600 ** it is extended to two fields. The duplicates that this creates do not
1601 ** cause any problems.
1603 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
1604 nField = pIdx->nKeyCol;
1605 }else{
1606 nField = pIdx->nColumn;
1608 nField = MIN(pRec->nField, nField);
1609 iCol = 0;
1610 iSample = pIdx->nSample * nField;
1612 int iSamp; /* Index in aSample[] of test sample */
1613 int n; /* Number of fields in test sample */
1615 iTest = (iMin+iSample)/2;
1616 iSamp = iTest / nField;
1617 if( iSamp>0 ){
1618 /* The proposed effective sample is a prefix of sample aSample[iSamp].
1619 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
1620 ** fields that is greater than the previous effective sample. */
1621 for(n=(iTest % nField) + 1; n<nField; n++){
1622 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
1624 }else{
1625 n = iTest + 1;
1628 pRec->nField = n;
1629 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
1630 if( res<0 ){
1631 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
1632 iMin = iTest+1;
1633 }else if( res==0 && n<nField ){
1634 iLower = aSample[iSamp].anLt[n-1];
1635 iMin = iTest+1;
1636 res = -1;
1637 }else{
1638 iSample = iTest;
1639 iCol = n-1;
1641 }while( res && iMin<iSample );
1642 i = iSample / nField;
1644 #ifdef SQLITE_DEBUG
1645 /* The following assert statements check that the binary search code
1646 ** above found the right answer. This block serves no purpose other
1647 ** than to invoke the asserts. */
1648 if( pParse->db->mallocFailed==0 ){
1649 if( res==0 ){
1650 /* If (res==0) is true, then pRec must be equal to sample i. */
1651 assert( i<pIdx->nSample );
1652 assert( iCol==nField-1 );
1653 pRec->nField = nField;
1654 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
1655 || pParse->db->mallocFailed
1657 }else{
1658 /* Unless i==pIdx->nSample, indicating that pRec is larger than
1659 ** all samples in the aSample[] array, pRec must be smaller than the
1660 ** (iCol+1) field prefix of sample i. */
1661 assert( i<=pIdx->nSample && i>=0 );
1662 pRec->nField = iCol+1;
1663 assert( i==pIdx->nSample
1664 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
1665 || pParse->db->mallocFailed );
1667 /* if i==0 and iCol==0, then record pRec is smaller than all samples
1668 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
1669 ** be greater than or equal to the (iCol) field prefix of sample i.
1670 ** If (i>0), then pRec must also be greater than sample (i-1). */
1671 if( iCol>0 ){
1672 pRec->nField = iCol;
1673 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
1674 || pParse->db->mallocFailed || CORRUPT_DB );
1676 if( i>0 ){
1677 pRec->nField = nField;
1678 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
1679 || pParse->db->mallocFailed || CORRUPT_DB );
1683 #endif /* ifdef SQLITE_DEBUG */
1685 if( res==0 ){
1686 /* Record pRec is equal to sample i */
1687 assert( iCol==nField-1 );
1688 aStat[0] = aSample[i].anLt[iCol];
1689 aStat[1] = aSample[i].anEq[iCol];
1690 }else{
1691 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
1692 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
1693 ** is larger than all samples in the array. */
1694 tRowcnt iUpper, iGap;
1695 if( i>=pIdx->nSample ){
1696 iUpper = pIdx->nRowEst0;
1697 }else{
1698 iUpper = aSample[i].anLt[iCol];
1701 if( iLower>=iUpper ){
1702 iGap = 0;
1703 }else{
1704 iGap = iUpper - iLower;
1706 if( roundUp ){
1707 iGap = (iGap*2)/3;
1708 }else{
1709 iGap = iGap/3;
1711 aStat[0] = iLower + iGap;
1712 aStat[1] = pIdx->aAvgEq[nField-1];
1715 /* Restore the pRec->nField value before returning. */
1716 pRec->nField = nField;
1717 return i;
1719 #endif /* SQLITE_ENABLE_STAT4 */
1722 ** If it is not NULL, pTerm is a term that provides an upper or lower
1723 ** bound on a range scan. Without considering pTerm, it is estimated
1724 ** that the scan will visit nNew rows. This function returns the number
1725 ** estimated to be visited after taking pTerm into account.
1727 ** If the user explicitly specified a likelihood() value for this term,
1728 ** then the return value is the likelihood multiplied by the number of
1729 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
1730 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
1732 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
1733 LogEst nRet = nNew;
1734 if( pTerm ){
1735 if( pTerm->truthProb<=0 ){
1736 nRet += pTerm->truthProb;
1737 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
1738 nRet -= 20; assert( 20==sqlite3LogEst(4) );
1741 return nRet;
1745 #ifdef SQLITE_ENABLE_STAT4
1747 ** Return the affinity for a single column of an index.
1749 char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
1750 assert( iCol>=0 && iCol<pIdx->nColumn );
1751 if( !pIdx->zColAff ){
1752 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
1754 assert( pIdx->zColAff[iCol]!=0 );
1755 return pIdx->zColAff[iCol];
1757 #endif
1760 #ifdef SQLITE_ENABLE_STAT4
1762 ** This function is called to estimate the number of rows visited by a
1763 ** range-scan on a skip-scan index. For example:
1765 ** CREATE INDEX i1 ON t1(a, b, c);
1766 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
1768 ** Value pLoop->nOut is currently set to the estimated number of rows
1769 ** visited for scanning (a=? AND b=?). This function reduces that estimate
1770 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
1771 ** on the stat4 data for the index. this scan will be performed multiple
1772 ** times (once for each (a,b) combination that matches a=?) is dealt with
1773 ** by the caller.
1775 ** It does this by scanning through all stat4 samples, comparing values
1776 ** extracted from pLower and pUpper with the corresponding column in each
1777 ** sample. If L and U are the number of samples found to be less than or
1778 ** equal to the values extracted from pLower and pUpper respectively, and
1779 ** N is the total number of samples, the pLoop->nOut value is adjusted
1780 ** as follows:
1782 ** nOut = nOut * ( min(U - L, 1) / N )
1784 ** If pLower is NULL, or a value cannot be extracted from the term, L is
1785 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
1786 ** U is set to N.
1788 ** Normally, this function sets *pbDone to 1 before returning. However,
1789 ** if no value can be extracted from either pLower or pUpper (and so the
1790 ** estimate of the number of rows delivered remains unchanged), *pbDone
1791 ** is left as is.
1793 ** If an error occurs, an SQLite error code is returned. Otherwise,
1794 ** SQLITE_OK.
1796 static int whereRangeSkipScanEst(
1797 Parse *pParse, /* Parsing & code generating context */
1798 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
1799 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
1800 WhereLoop *pLoop, /* Update the .nOut value of this loop */
1801 int *pbDone /* Set to true if at least one expr. value extracted */
1803 Index *p = pLoop->u.btree.pIndex;
1804 int nEq = pLoop->u.btree.nEq;
1805 sqlite3 *db = pParse->db;
1806 int nLower = -1;
1807 int nUpper = p->nSample+1;
1808 int rc = SQLITE_OK;
1809 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
1810 CollSeq *pColl;
1812 sqlite3_value *p1 = 0; /* Value extracted from pLower */
1813 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
1814 sqlite3_value *pVal = 0; /* Value extracted from record */
1816 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
1817 if( pLower ){
1818 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
1819 nLower = 0;
1821 if( pUpper && rc==SQLITE_OK ){
1822 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
1823 nUpper = p2 ? 0 : p->nSample;
1826 if( p1 || p2 ){
1827 int i;
1828 int nDiff;
1829 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
1830 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
1831 if( rc==SQLITE_OK && p1 ){
1832 int res = sqlite3MemCompare(p1, pVal, pColl);
1833 if( res>=0 ) nLower++;
1835 if( rc==SQLITE_OK && p2 ){
1836 int res = sqlite3MemCompare(p2, pVal, pColl);
1837 if( res>=0 ) nUpper++;
1840 nDiff = (nUpper - nLower);
1841 if( nDiff<=0 ) nDiff = 1;
1843 /* If there is both an upper and lower bound specified, and the
1844 ** comparisons indicate that they are close together, use the fallback
1845 ** method (assume that the scan visits 1/64 of the rows) for estimating
1846 ** the number of rows visited. Otherwise, estimate the number of rows
1847 ** using the method described in the header comment for this function. */
1848 if( nDiff!=1 || pUpper==0 || pLower==0 ){
1849 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
1850 pLoop->nOut -= nAdjust;
1851 *pbDone = 1;
1852 WHERETRACE(0x20, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
1853 nLower, nUpper, nAdjust*-1, pLoop->nOut));
1856 }else{
1857 assert( *pbDone==0 );
1860 sqlite3ValueFree(p1);
1861 sqlite3ValueFree(p2);
1862 sqlite3ValueFree(pVal);
1864 return rc;
1866 #endif /* SQLITE_ENABLE_STAT4 */
1869 ** This function is used to estimate the number of rows that will be visited
1870 ** by scanning an index for a range of values. The range may have an upper
1871 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
1872 ** and lower bounds are represented by pLower and pUpper respectively. For
1873 ** example, assuming that index p is on t1(a):
1875 ** ... FROM t1 WHERE a > ? AND a < ? ...
1876 ** |_____| |_____|
1877 ** | |
1878 ** pLower pUpper
1880 ** If either of the upper or lower bound is not present, then NULL is passed in
1881 ** place of the corresponding WhereTerm.
1883 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
1884 ** column subject to the range constraint. Or, equivalently, the number of
1885 ** equality constraints optimized by the proposed index scan. For example,
1886 ** assuming index p is on t1(a, b), and the SQL query is:
1888 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
1890 ** then nEq is set to 1 (as the range restricted column, b, is the second
1891 ** left-most column of the index). Or, if the query is:
1893 ** ... FROM t1 WHERE a > ? AND a < ? ...
1895 ** then nEq is set to 0.
1897 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
1898 ** number of rows that the index scan is expected to visit without
1899 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
1900 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
1901 ** to account for the range constraints pLower and pUpper.
1903 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
1904 ** used, a single range inequality reduces the search space by a factor of 4.
1905 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
1906 ** rows visited by a factor of 64.
1908 static int whereRangeScanEst(
1909 Parse *pParse, /* Parsing & code generating context */
1910 WhereLoopBuilder *pBuilder,
1911 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
1912 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
1913 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
1915 int rc = SQLITE_OK;
1916 int nOut = pLoop->nOut;
1917 LogEst nNew;
1919 #ifdef SQLITE_ENABLE_STAT4
1920 Index *p = pLoop->u.btree.pIndex;
1921 int nEq = pLoop->u.btree.nEq;
1923 if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
1924 && OptimizationEnabled(pParse->db, SQLITE_Stat4)
1926 if( nEq==pBuilder->nRecValid ){
1927 UnpackedRecord *pRec = pBuilder->pRec;
1928 tRowcnt a[2];
1929 int nBtm = pLoop->u.btree.nBtm;
1930 int nTop = pLoop->u.btree.nTop;
1932 /* Variable iLower will be set to the estimate of the number of rows in
1933 ** the index that are less than the lower bound of the range query. The
1934 ** lower bound being the concatenation of $P and $L, where $P is the
1935 ** key-prefix formed by the nEq values matched against the nEq left-most
1936 ** columns of the index, and $L is the value in pLower.
1938 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
1939 ** is not a simple variable or literal value), the lower bound of the
1940 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
1941 ** if $L is available, whereKeyStats() is called for both ($P) and
1942 ** ($P:$L) and the larger of the two returned values is used.
1944 ** Similarly, iUpper is to be set to the estimate of the number of rows
1945 ** less than the upper bound of the range query. Where the upper bound
1946 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
1947 ** of iUpper are requested of whereKeyStats() and the smaller used.
1949 ** The number of rows between the two bounds is then just iUpper-iLower.
1951 tRowcnt iLower; /* Rows less than the lower bound */
1952 tRowcnt iUpper; /* Rows less than the upper bound */
1953 int iLwrIdx = -2; /* aSample[] for the lower bound */
1954 int iUprIdx = -1; /* aSample[] for the upper bound */
1956 if( pRec ){
1957 testcase( pRec->nField!=pBuilder->nRecValid );
1958 pRec->nField = pBuilder->nRecValid;
1960 /* Determine iLower and iUpper using ($P) only. */
1961 if( nEq==0 ){
1962 iLower = 0;
1963 iUpper = p->nRowEst0;
1964 }else{
1965 /* Note: this call could be optimized away - since the same values must
1966 ** have been requested when testing key $P in whereEqualScanEst(). */
1967 whereKeyStats(pParse, p, pRec, 0, a);
1968 iLower = a[0];
1969 iUpper = a[0] + a[1];
1972 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
1973 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
1974 assert( p->aSortOrder!=0 );
1975 if( p->aSortOrder[nEq] ){
1976 /* The roles of pLower and pUpper are swapped for a DESC index */
1977 SWAP(WhereTerm*, pLower, pUpper);
1978 SWAP(int, nBtm, nTop);
1981 /* If possible, improve on the iLower estimate using ($P:$L). */
1982 if( pLower ){
1983 int n; /* Values extracted from pExpr */
1984 Expr *pExpr = pLower->pExpr->pRight;
1985 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
1986 if( rc==SQLITE_OK && n ){
1987 tRowcnt iNew;
1988 u16 mask = WO_GT|WO_LE;
1989 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
1990 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
1991 iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
1992 if( iNew>iLower ) iLower = iNew;
1993 nOut--;
1994 pLower = 0;
1998 /* If possible, improve on the iUpper estimate using ($P:$U). */
1999 if( pUpper ){
2000 int n; /* Values extracted from pExpr */
2001 Expr *pExpr = pUpper->pExpr->pRight;
2002 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
2003 if( rc==SQLITE_OK && n ){
2004 tRowcnt iNew;
2005 u16 mask = WO_GT|WO_LE;
2006 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
2007 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
2008 iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
2009 if( iNew<iUpper ) iUpper = iNew;
2010 nOut--;
2011 pUpper = 0;
2015 pBuilder->pRec = pRec;
2016 if( rc==SQLITE_OK ){
2017 if( iUpper>iLower ){
2018 nNew = sqlite3LogEst(iUpper - iLower);
2019 /* TUNING: If both iUpper and iLower are derived from the same
2020 ** sample, then assume they are 4x more selective. This brings
2021 ** the estimated selectivity more in line with what it would be
2022 ** if estimated without the use of STAT4 tables. */
2023 if( iLwrIdx==iUprIdx ){ nNew -= 20; }
2024 assert( 20==sqlite3LogEst(4) );
2025 }else{
2026 nNew = 10; assert( 10==sqlite3LogEst(2) );
2028 if( nNew<nOut ){
2029 nOut = nNew;
2031 WHERETRACE(0x20, ("STAT4 range scan: %u..%u est=%d\n",
2032 (u32)iLower, (u32)iUpper, nOut));
2034 }else{
2035 int bDone = 0;
2036 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2037 if( bDone ) return rc;
2040 #else
2041 UNUSED_PARAMETER(pParse);
2042 UNUSED_PARAMETER(pBuilder);
2043 assert( pLower || pUpper );
2044 #endif
2045 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 || pParse->nErr>0 );
2046 nNew = whereRangeAdjust(pLower, nOut);
2047 nNew = whereRangeAdjust(pUpper, nNew);
2049 /* TUNING: If there is both an upper and lower limit and neither limit
2050 ** has an application-defined likelihood(), assume the range is
2051 ** reduced by an additional 75%. This means that, by default, an open-ended
2052 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2053 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2054 ** match 1/64 of the index. */
2055 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2056 nNew -= 20;
2059 nOut -= (pLower!=0) + (pUpper!=0);
2060 if( nNew<10 ) nNew = 10;
2061 if( nNew<nOut ) nOut = nNew;
2062 #if defined(WHERETRACE_ENABLED)
2063 if( pLoop->nOut>nOut ){
2064 WHERETRACE(0x20,("Range scan lowers nOut from %d to %d\n",
2065 pLoop->nOut, nOut));
2067 #endif
2068 pLoop->nOut = (LogEst)nOut;
2069 return rc;
2072 #ifdef SQLITE_ENABLE_STAT4
2074 ** Estimate the number of rows that will be returned based on
2075 ** an equality constraint x=VALUE and where that VALUE occurs in
2076 ** the histogram data. This only works when x is the left-most
2077 ** column of an index and sqlite_stat4 histogram data is available
2078 ** for that index. When pExpr==NULL that means the constraint is
2079 ** "x IS NULL" instead of "x=VALUE".
2081 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2082 ** If unable to make an estimate, leave *pnRow unchanged and return
2083 ** non-zero.
2085 ** This routine can fail if it is unable to load a collating sequence
2086 ** required for string comparison, or if unable to allocate memory
2087 ** for a UTF conversion required for comparison. The error is stored
2088 ** in the pParse structure.
2090 static int whereEqualScanEst(
2091 Parse *pParse, /* Parsing & code generating context */
2092 WhereLoopBuilder *pBuilder,
2093 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
2094 tRowcnt *pnRow /* Write the revised row estimate here */
2096 Index *p = pBuilder->pNew->u.btree.pIndex;
2097 int nEq = pBuilder->pNew->u.btree.nEq;
2098 UnpackedRecord *pRec = pBuilder->pRec;
2099 int rc; /* Subfunction return code */
2100 tRowcnt a[2]; /* Statistics */
2101 int bOk;
2103 assert( nEq>=1 );
2104 assert( nEq<=p->nColumn );
2105 assert( p->aSample!=0 );
2106 assert( p->nSample>0 );
2107 assert( pBuilder->nRecValid<nEq );
2109 /* If values are not available for all fields of the index to the left
2110 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2111 if( pBuilder->nRecValid<(nEq-1) ){
2112 return SQLITE_NOTFOUND;
2115 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2116 ** below would return the same value. */
2117 if( nEq>=p->nColumn ){
2118 *pnRow = 1;
2119 return SQLITE_OK;
2122 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
2123 pBuilder->pRec = pRec;
2124 if( rc!=SQLITE_OK ) return rc;
2125 if( bOk==0 ) return SQLITE_NOTFOUND;
2126 pBuilder->nRecValid = nEq;
2128 whereKeyStats(pParse, p, pRec, 0, a);
2129 WHERETRACE(0x20,("equality scan regions %s(%d): %d\n",
2130 p->zName, nEq-1, (int)a[1]));
2131 *pnRow = a[1];
2133 return rc;
2135 #endif /* SQLITE_ENABLE_STAT4 */
2137 #ifdef SQLITE_ENABLE_STAT4
2139 ** Estimate the number of rows that will be returned based on
2140 ** an IN constraint where the right-hand side of the IN operator
2141 ** is a list of values. Example:
2143 ** WHERE x IN (1,2,3,4)
2145 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2146 ** If unable to make an estimate, leave *pnRow unchanged and return
2147 ** non-zero.
2149 ** This routine can fail if it is unable to load a collating sequence
2150 ** required for string comparison, or if unable to allocate memory
2151 ** for a UTF conversion required for comparison. The error is stored
2152 ** in the pParse structure.
2154 static int whereInScanEst(
2155 Parse *pParse, /* Parsing & code generating context */
2156 WhereLoopBuilder *pBuilder,
2157 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
2158 tRowcnt *pnRow /* Write the revised row estimate here */
2160 Index *p = pBuilder->pNew->u.btree.pIndex;
2161 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
2162 int nRecValid = pBuilder->nRecValid;
2163 int rc = SQLITE_OK; /* Subfunction return code */
2164 tRowcnt nEst; /* Number of rows for a single term */
2165 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2166 int i; /* Loop counter */
2168 assert( p->aSample!=0 );
2169 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2170 nEst = nRow0;
2171 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
2172 nRowEst += nEst;
2173 pBuilder->nRecValid = nRecValid;
2176 if( rc==SQLITE_OK ){
2177 if( nRowEst > (tRowcnt)nRow0 ) nRowEst = nRow0;
2178 *pnRow = nRowEst;
2179 WHERETRACE(0x20,("IN row estimate: est=%d\n", nRowEst));
2181 assert( pBuilder->nRecValid==nRecValid );
2182 return rc;
2184 #endif /* SQLITE_ENABLE_STAT4 */
2187 #ifdef WHERETRACE_ENABLED
2189 ** Print the content of a WhereTerm object
2191 void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
2192 if( pTerm==0 ){
2193 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
2194 }else{
2195 char zType[8];
2196 char zLeft[50];
2197 memcpy(zType, "....", 5);
2198 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
2199 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
2200 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) zType[2] = 'L';
2201 if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C';
2202 if( pTerm->eOperator & WO_SINGLE ){
2203 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
2204 sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
2205 pTerm->leftCursor, pTerm->u.x.leftColumn);
2206 }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
2207 sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx",
2208 pTerm->u.pOrInfo->indexable);
2209 }else{
2210 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
2212 sqlite3DebugPrintf(
2213 "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
2214 iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
2215 /* The 0x10000 .wheretrace flag causes extra information to be
2216 ** shown about each Term */
2217 if( sqlite3WhereTrace & 0x10000 ){
2218 sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
2219 pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
2221 if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){
2222 sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
2224 if( pTerm->iParent>=0 ){
2225 sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
2227 sqlite3DebugPrintf("\n");
2228 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
2231 #endif
2233 #ifdef WHERETRACE_ENABLED
2235 ** Show the complete content of a WhereClause
2237 void sqlite3WhereClausePrint(WhereClause *pWC){
2238 int i;
2239 for(i=0; i<pWC->nTerm; i++){
2240 sqlite3WhereTermPrint(&pWC->a[i], i);
2243 #endif
2245 #ifdef WHERETRACE_ENABLED
2247 ** Print a WhereLoop object for debugging purposes
2249 ** Format example:
2251 ** .--- Position in WHERE clause rSetup, rRun, nOut ---.
2252 ** | |
2253 ** | .--- selfMask nTerm ------. |
2254 ** | | | |
2255 ** | | .-- prereq Idx wsFlags----. | |
2256 ** | | | Name | | |
2257 ** | | | __|__ nEq ---. ___|__ | __|__
2258 ** | / \ / \ / \ | / \ / \ / \
2259 ** 1.002.001 t2.t2xy 2 f 010241 N 2 cost 0,56,31
2261 void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause *pWC){
2262 if( pWC ){
2263 WhereInfo *pWInfo = pWC->pWInfo;
2264 int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
2265 SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
2266 Table *pTab = pItem->pTab;
2267 Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
2268 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
2269 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
2270 sqlite3DebugPrintf(" %12s",
2271 pItem->zAlias ? pItem->zAlias : pTab->zName);
2272 }else{
2273 sqlite3DebugPrintf("%c%2d.%03llx.%03llx %c%d",
2274 p->cId, p->iTab, p->maskSelf, p->prereq & 0xfff, p->cId, p->iTab);
2276 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2277 const char *zName;
2278 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
2279 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
2280 int i = sqlite3Strlen30(zName) - 1;
2281 while( zName[i]!='_' ) i--;
2282 zName += i;
2284 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
2285 }else{
2286 sqlite3DebugPrintf("%20s","");
2288 }else{
2289 char *z;
2290 if( p->u.vtab.idxStr ){
2291 z = sqlite3_mprintf("(%d,\"%s\",%#x)",
2292 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
2293 }else{
2294 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
2296 sqlite3DebugPrintf(" %-19s", z);
2297 sqlite3_free(z);
2299 if( p->wsFlags & WHERE_SKIPSCAN ){
2300 sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
2301 }else{
2302 sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm);
2304 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
2305 if( p->nLTerm && (sqlite3WhereTrace & 0x4000)!=0 ){
2306 int i;
2307 for(i=0; i<p->nLTerm; i++){
2308 sqlite3WhereTermPrint(p->aLTerm[i], i);
2312 void sqlite3ShowWhereLoop(const WhereLoop *p){
2313 if( p ) sqlite3WhereLoopPrint(p, 0);
2315 void sqlite3ShowWhereLoopList(const WhereLoop *p){
2316 while( p ){
2317 sqlite3ShowWhereLoop(p);
2318 p = p->pNextLoop;
2321 #endif
2324 ** Convert bulk memory into a valid WhereLoop that can be passed
2325 ** to whereLoopClear harmlessly.
2327 static void whereLoopInit(WhereLoop *p){
2328 p->aLTerm = p->aLTermSpace;
2329 p->nLTerm = 0;
2330 p->nLSlot = ArraySize(p->aLTermSpace);
2331 p->wsFlags = 0;
2335 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
2337 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
2338 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
2339 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
2340 sqlite3_free(p->u.vtab.idxStr);
2341 p->u.vtab.needFree = 0;
2342 p->u.vtab.idxStr = 0;
2343 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
2344 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
2345 sqlite3DbFreeNN(db, p->u.btree.pIndex);
2346 p->u.btree.pIndex = 0;
2352 ** Deallocate internal memory used by a WhereLoop object. Leave the
2353 ** object in an initialized state, as if it had been newly allocated.
2355 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
2356 if( p->aLTerm!=p->aLTermSpace ){
2357 sqlite3DbFreeNN(db, p->aLTerm);
2358 p->aLTerm = p->aLTermSpace;
2359 p->nLSlot = ArraySize(p->aLTermSpace);
2361 whereLoopClearUnion(db, p);
2362 p->nLTerm = 0;
2363 p->wsFlags = 0;
2367 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
2369 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
2370 WhereTerm **paNew;
2371 if( p->nLSlot>=n ) return SQLITE_OK;
2372 n = (n+7)&~7;
2373 paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
2374 if( paNew==0 ) return SQLITE_NOMEM_BKPT;
2375 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
2376 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
2377 p->aLTerm = paNew;
2378 p->nLSlot = n;
2379 return SQLITE_OK;
2383 ** Transfer content from the second pLoop into the first.
2385 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
2386 whereLoopClearUnion(db, pTo);
2387 if( pFrom->nLTerm > pTo->nLSlot
2388 && whereLoopResize(db, pTo, pFrom->nLTerm)
2390 memset(pTo, 0, WHERE_LOOP_XFER_SZ);
2391 return SQLITE_NOMEM_BKPT;
2393 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
2394 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
2395 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
2396 pFrom->u.vtab.needFree = 0;
2397 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
2398 pFrom->u.btree.pIndex = 0;
2400 return SQLITE_OK;
2404 ** Delete a WhereLoop object
2406 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
2407 assert( db!=0 );
2408 whereLoopClear(db, p);
2409 sqlite3DbNNFreeNN(db, p);
2413 ** Free a WhereInfo structure
2415 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
2416 assert( pWInfo!=0 );
2417 assert( db!=0 );
2418 sqlite3WhereClauseClear(&pWInfo->sWC);
2419 while( pWInfo->pLoops ){
2420 WhereLoop *p = pWInfo->pLoops;
2421 pWInfo->pLoops = p->pNextLoop;
2422 whereLoopDelete(db, p);
2424 while( pWInfo->pMemToFree ){
2425 WhereMemBlock *pNext = pWInfo->pMemToFree->pNext;
2426 sqlite3DbNNFreeNN(db, pWInfo->pMemToFree);
2427 pWInfo->pMemToFree = pNext;
2429 sqlite3DbNNFreeNN(db, pWInfo);
2433 ** Return TRUE if X is a proper subset of Y but is of equal or less cost.
2434 ** In other words, return true if all constraints of X are also part of Y
2435 ** and Y has additional constraints that might speed the search that X lacks
2436 ** but the cost of running X is not more than the cost of running Y.
2438 ** In other words, return true if the cost relationwship between X and Y
2439 ** is inverted and needs to be adjusted.
2441 ** Case 1:
2443 ** (1a) X and Y use the same index.
2444 ** (1b) X has fewer == terms than Y
2445 ** (1c) Neither X nor Y use skip-scan
2446 ** (1d) X does not have a a greater cost than Y
2448 ** Case 2:
2450 ** (2a) X has the same or lower cost, or returns the same or fewer rows,
2451 ** than Y.
2452 ** (2b) X uses fewer WHERE clause terms than Y
2453 ** (2c) Every WHERE clause term used by X is also used by Y
2454 ** (2d) X skips at least as many columns as Y
2455 ** (2e) If X is a covering index, than Y is too
2457 static int whereLoopCheaperProperSubset(
2458 const WhereLoop *pX, /* First WhereLoop to compare */
2459 const WhereLoop *pY /* Compare against this WhereLoop */
2461 int i, j;
2462 if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0; /* (1d) and (2a) */
2463 assert( (pX->wsFlags & WHERE_VIRTUALTABLE)==0 );
2464 assert( (pY->wsFlags & WHERE_VIRTUALTABLE)==0 );
2465 if( pX->u.btree.nEq < pY->u.btree.nEq /* (1b) */
2466 && pX->u.btree.pIndex==pY->u.btree.pIndex /* (1a) */
2467 && pX->nSkip==0 && pY->nSkip==0 /* (1c) */
2469 return 1; /* Case 1 is true */
2471 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
2472 return 0; /* (2b) */
2474 if( pY->nSkip > pX->nSkip ) return 0; /* (2d) */
2475 for(i=pX->nLTerm-1; i>=0; i--){
2476 if( pX->aLTerm[i]==0 ) continue;
2477 for(j=pY->nLTerm-1; j>=0; j--){
2478 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
2480 if( j<0 ) return 0; /* (2c) */
2482 if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
2483 && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
2484 return 0; /* (2e) */
2486 return 1; /* Case 2 is true */
2490 ** Try to adjust the cost and number of output rows of WhereLoop pTemplate
2491 ** upwards or downwards so that:
2493 ** (1) pTemplate costs less than any other WhereLoops that are a proper
2494 ** subset of pTemplate
2496 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
2497 ** is a proper subset.
2499 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
2500 ** WHERE clause terms than Y and that every WHERE clause term used by X is
2501 ** also used by Y.
2503 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
2504 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
2505 for(; p; p=p->pNextLoop){
2506 if( p->iTab!=pTemplate->iTab ) continue;
2507 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
2508 if( whereLoopCheaperProperSubset(p, pTemplate) ){
2509 /* Adjust pTemplate cost downward so that it is cheaper than its
2510 ** subset p. */
2511 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2512 pTemplate->rRun, pTemplate->nOut,
2513 MIN(p->rRun, pTemplate->rRun),
2514 MIN(p->nOut - 1, pTemplate->nOut)));
2515 pTemplate->rRun = MIN(p->rRun, pTemplate->rRun);
2516 pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut);
2517 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
2518 /* Adjust pTemplate cost upward so that it is costlier than p since
2519 ** pTemplate is a proper subset of p */
2520 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2521 pTemplate->rRun, pTemplate->nOut,
2522 MAX(p->rRun, pTemplate->rRun),
2523 MAX(p->nOut + 1, pTemplate->nOut)));
2524 pTemplate->rRun = MAX(p->rRun, pTemplate->rRun);
2525 pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut);
2531 ** Search the list of WhereLoops in *ppPrev looking for one that can be
2532 ** replaced by pTemplate.
2534 ** Return NULL if pTemplate does not belong on the WhereLoop list.
2535 ** In other words if pTemplate ought to be dropped from further consideration.
2537 ** If pX is a WhereLoop that pTemplate can replace, then return the
2538 ** link that points to pX.
2540 ** If pTemplate cannot replace any existing element of the list but needs
2541 ** to be added to the list as a new entry, then return a pointer to the
2542 ** tail of the list.
2544 static WhereLoop **whereLoopFindLesser(
2545 WhereLoop **ppPrev,
2546 const WhereLoop *pTemplate
2548 WhereLoop *p;
2549 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
2550 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
2551 /* If either the iTab or iSortIdx values for two WhereLoop are different
2552 ** then those WhereLoops need to be considered separately. Neither is
2553 ** a candidate to replace the other. */
2554 continue;
2556 /* In the current implementation, the rSetup value is either zero
2557 ** or the cost of building an automatic index (NlogN) and the NlogN
2558 ** is the same for compatible WhereLoops. */
2559 assert( p->rSetup==0 || pTemplate->rSetup==0
2560 || p->rSetup==pTemplate->rSetup );
2562 /* whereLoopAddBtree() always generates and inserts the automatic index
2563 ** case first. Hence compatible candidate WhereLoops never have a larger
2564 ** rSetup. Call this SETUP-INVARIANT */
2565 assert( p->rSetup>=pTemplate->rSetup );
2567 /* Any loop using an application-defined index (or PRIMARY KEY or
2568 ** UNIQUE constraint) with one or more == constraints is better
2569 ** than an automatic index. Unless it is a skip-scan. */
2570 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
2571 && (pTemplate->nSkip)==0
2572 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
2573 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
2574 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
2576 break;
2579 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
2580 ** discarded. WhereLoop p is better if:
2581 ** (1) p has no more dependencies than pTemplate, and
2582 ** (2) p has an equal or lower cost than pTemplate
2584 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
2585 && p->rSetup<=pTemplate->rSetup /* (2a) */
2586 && p->rRun<=pTemplate->rRun /* (2b) */
2587 && p->nOut<=pTemplate->nOut /* (2c) */
2589 return 0; /* Discard pTemplate */
2592 /* If pTemplate is always better than p, then cause p to be overwritten
2593 ** with pTemplate. pTemplate is better than p if:
2594 ** (1) pTemplate has no more dependencies than p, and
2595 ** (2) pTemplate has an equal or lower cost than p.
2597 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
2598 && p->rRun>=pTemplate->rRun /* (2a) */
2599 && p->nOut>=pTemplate->nOut /* (2b) */
2601 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
2602 break; /* Cause p to be overwritten by pTemplate */
2605 return ppPrev;
2609 ** Insert or replace a WhereLoop entry using the template supplied.
2611 ** An existing WhereLoop entry might be overwritten if the new template
2612 ** is better and has fewer dependencies. Or the template will be ignored
2613 ** and no insert will occur if an existing WhereLoop is faster and has
2614 ** fewer dependencies than the template. Otherwise a new WhereLoop is
2615 ** added based on the template.
2617 ** If pBuilder->pOrSet is not NULL then we care about only the
2618 ** prerequisites and rRun and nOut costs of the N best loops. That
2619 ** information is gathered in the pBuilder->pOrSet object. This special
2620 ** processing mode is used only for OR clause processing.
2622 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
2623 ** still might overwrite similar loops with the new template if the
2624 ** new template is better. Loops may be overwritten if the following
2625 ** conditions are met:
2627 ** (1) They have the same iTab.
2628 ** (2) They have the same iSortIdx.
2629 ** (3) The template has same or fewer dependencies than the current loop
2630 ** (4) The template has the same or lower cost than the current loop
2632 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
2633 WhereLoop **ppPrev, *p;
2634 WhereInfo *pWInfo = pBuilder->pWInfo;
2635 sqlite3 *db = pWInfo->pParse->db;
2636 int rc;
2638 /* Stop the search once we hit the query planner search limit */
2639 if( pBuilder->iPlanLimit==0 ){
2640 WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
2641 if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
2642 return SQLITE_DONE;
2644 pBuilder->iPlanLimit--;
2646 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
2648 /* If pBuilder->pOrSet is defined, then only keep track of the costs
2649 ** and prereqs.
2651 if( pBuilder->pOrSet!=0 ){
2652 if( pTemplate->nLTerm ){
2653 #if WHERETRACE_ENABLED
2654 u16 n = pBuilder->pOrSet->n;
2655 int x =
2656 #endif
2657 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
2658 pTemplate->nOut);
2659 #if WHERETRACE_ENABLED /* 0x8 */
2660 if( sqlite3WhereTrace & 0x8 ){
2661 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
2662 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2664 #endif
2666 return SQLITE_OK;
2669 /* Look for an existing WhereLoop to replace with pTemplate
2671 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
2673 if( ppPrev==0 ){
2674 /* There already exists a WhereLoop on the list that is better
2675 ** than pTemplate, so just ignore pTemplate */
2676 #if WHERETRACE_ENABLED /* 0x8 */
2677 if( sqlite3WhereTrace & 0x8 ){
2678 sqlite3DebugPrintf(" skip: ");
2679 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2681 #endif
2682 return SQLITE_OK;
2683 }else{
2684 p = *ppPrev;
2687 /* If we reach this point it means that either p[] should be overwritten
2688 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
2689 ** WhereLoop and insert it.
2691 #if WHERETRACE_ENABLED /* 0x8 */
2692 if( sqlite3WhereTrace & 0x8 ){
2693 if( p!=0 ){
2694 sqlite3DebugPrintf("replace: ");
2695 sqlite3WhereLoopPrint(p, pBuilder->pWC);
2696 sqlite3DebugPrintf(" with: ");
2697 }else{
2698 sqlite3DebugPrintf(" add: ");
2700 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2702 #endif
2703 if( p==0 ){
2704 /* Allocate a new WhereLoop to add to the end of the list */
2705 *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
2706 if( p==0 ) return SQLITE_NOMEM_BKPT;
2707 whereLoopInit(p);
2708 p->pNextLoop = 0;
2709 }else{
2710 /* We will be overwriting WhereLoop p[]. But before we do, first
2711 ** go through the rest of the list and delete any other entries besides
2712 ** p[] that are also supplanted by pTemplate */
2713 WhereLoop **ppTail = &p->pNextLoop;
2714 WhereLoop *pToDel;
2715 while( *ppTail ){
2716 ppTail = whereLoopFindLesser(ppTail, pTemplate);
2717 if( ppTail==0 ) break;
2718 pToDel = *ppTail;
2719 if( pToDel==0 ) break;
2720 *ppTail = pToDel->pNextLoop;
2721 #if WHERETRACE_ENABLED /* 0x8 */
2722 if( sqlite3WhereTrace & 0x8 ){
2723 sqlite3DebugPrintf(" delete: ");
2724 sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
2726 #endif
2727 whereLoopDelete(db, pToDel);
2730 rc = whereLoopXfer(db, p, pTemplate);
2731 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2732 Index *pIndex = p->u.btree.pIndex;
2733 if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
2734 p->u.btree.pIndex = 0;
2737 return rc;
2741 ** Adjust the WhereLoop.nOut value downward to account for terms of the
2742 ** WHERE clause that reference the loop but which are not used by an
2743 ** index.
2745 ** For every WHERE clause term that is not used by the index
2746 ** and which has a truth probability assigned by one of the likelihood(),
2747 ** likely(), or unlikely() SQL functions, reduce the estimated number
2748 ** of output rows by the probability specified.
2750 ** TUNING: For every WHERE clause term that is not used by the index
2751 ** and which does not have an assigned truth probability, heuristics
2752 ** described below are used to try to estimate the truth probability.
2753 ** TODO --> Perhaps this is something that could be improved by better
2754 ** table statistics.
2756 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
2757 ** value corresponds to -1 in LogEst notation, so this means decrement
2758 ** the WhereLoop.nOut field for every such WHERE clause term.
2760 ** Heuristic 2: If there exists one or more WHERE clause terms of the
2761 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
2762 ** final output row estimate is no greater than 1/4 of the total number
2763 ** of rows in the table. In other words, assume that x==EXPR will filter
2764 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
2765 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
2766 ** on the "x" column and so in that case only cap the output row estimate
2767 ** at 1/2 instead of 1/4.
2769 static void whereLoopOutputAdjust(
2770 WhereClause *pWC, /* The WHERE clause */
2771 WhereLoop *pLoop, /* The loop to adjust downward */
2772 LogEst nRow /* Number of rows in the entire table */
2774 WhereTerm *pTerm, *pX;
2775 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
2776 int i, j;
2777 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
2779 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
2780 for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){
2781 assert( pTerm!=0 );
2782 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
2783 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
2784 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue;
2785 for(j=pLoop->nLTerm-1; j>=0; j--){
2786 pX = pLoop->aLTerm[j];
2787 if( pX==0 ) continue;
2788 if( pX==pTerm ) break;
2789 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
2791 if( j<0 ){
2792 sqlite3ProgressCheck(pWC->pWInfo->pParse);
2793 if( pLoop->maskSelf==pTerm->prereqAll ){
2794 /* If there are extra terms in the WHERE clause not used by an index
2795 ** that depend only on the table being scanned, and that will tend to
2796 ** cause many rows to be omitted, then mark that table as
2797 ** "self-culling".
2799 ** 2022-03-24: Self-culling only applies if either the extra terms
2800 ** are straight comparison operators that are non-true with NULL
2801 ** operand, or if the loop is not an OUTER JOIN.
2803 if( (pTerm->eOperator & 0x3f)!=0
2804 || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype
2805 & (JT_LEFT|JT_LTORJ))==0
2807 pLoop->wsFlags |= WHERE_SELFCULL;
2810 if( pTerm->truthProb<=0 ){
2811 /* If a truth probability is specified using the likelihood() hints,
2812 ** then use the probability provided by the application. */
2813 pLoop->nOut += pTerm->truthProb;
2814 }else{
2815 /* In the absence of explicit truth probabilities, use heuristics to
2816 ** guess a reasonable truth probability. */
2817 pLoop->nOut--;
2818 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
2819 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */
2821 Expr *pRight = pTerm->pExpr->pRight;
2822 int k = 0;
2823 testcase( pTerm->pExpr->op==TK_IS );
2824 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
2825 k = 10;
2826 }else{
2827 k = 20;
2829 if( iReduce<k ){
2830 pTerm->wtFlags |= TERM_HEURTRUTH;
2831 iReduce = k;
2837 if( pLoop->nOut > nRow-iReduce ){
2838 pLoop->nOut = nRow - iReduce;
2843 ** Term pTerm is a vector range comparison operation. The first comparison
2844 ** in the vector can be optimized using column nEq of the index. This
2845 ** function returns the total number of vector elements that can be used
2846 ** as part of the range comparison.
2848 ** For example, if the query is:
2850 ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
2852 ** and the index:
2854 ** CREATE INDEX ... ON (a, b, c, d, e)
2856 ** then this function would be invoked with nEq=1. The value returned in
2857 ** this case is 3.
2859 static int whereRangeVectorLen(
2860 Parse *pParse, /* Parsing context */
2861 int iCur, /* Cursor open on pIdx */
2862 Index *pIdx, /* The index to be used for a inequality constraint */
2863 int nEq, /* Number of prior equality constraints on same index */
2864 WhereTerm *pTerm /* The vector inequality constraint */
2866 int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
2867 int i;
2869 nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
2870 for(i=1; i<nCmp; i++){
2871 /* Test if comparison i of pTerm is compatible with column (i+nEq)
2872 ** of the index. If not, exit the loop. */
2873 char aff; /* Comparison affinity */
2874 char idxaff = 0; /* Indexed columns affinity */
2875 CollSeq *pColl; /* Comparison collation sequence */
2876 Expr *pLhs, *pRhs;
2878 assert( ExprUseXList(pTerm->pExpr->pLeft) );
2879 pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
2880 pRhs = pTerm->pExpr->pRight;
2881 if( ExprUseXSelect(pRhs) ){
2882 pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
2883 }else{
2884 pRhs = pRhs->x.pList->a[i].pExpr;
2887 /* Check that the LHS of the comparison is a column reference to
2888 ** the right column of the right source table. And that the sort
2889 ** order of the index column is the same as the sort order of the
2890 ** leftmost index column. */
2891 if( pLhs->op!=TK_COLUMN
2892 || pLhs->iTable!=iCur
2893 || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
2894 || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
2896 break;
2899 testcase( pLhs->iColumn==XN_ROWID );
2900 aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
2901 idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
2902 if( aff!=idxaff ) break;
2904 pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2905 if( pColl==0 ) break;
2906 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
2908 return i;
2912 ** Adjust the cost C by the costMult factor T. This only occurs if
2913 ** compiled with -DSQLITE_ENABLE_COSTMULT
2915 #ifdef SQLITE_ENABLE_COSTMULT
2916 # define ApplyCostMultiplier(C,T) C += T
2917 #else
2918 # define ApplyCostMultiplier(C,T)
2919 #endif
2922 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
2923 ** index pIndex. Try to match one more.
2925 ** When this function is called, pBuilder->pNew->nOut contains the
2926 ** number of rows expected to be visited by filtering using the nEq
2927 ** terms only. If it is modified, this value is restored before this
2928 ** function returns.
2930 ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
2931 ** a fake index used for the INTEGER PRIMARY KEY.
2933 static int whereLoopAddBtreeIndex(
2934 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
2935 SrcItem *pSrc, /* FROM clause term being analyzed */
2936 Index *pProbe, /* An index on pSrc */
2937 LogEst nInMul /* log(Number of iterations due to IN) */
2939 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyze context */
2940 Parse *pParse = pWInfo->pParse; /* Parsing context */
2941 sqlite3 *db = pParse->db; /* Database connection malloc context */
2942 WhereLoop *pNew; /* Template WhereLoop under construction */
2943 WhereTerm *pTerm; /* A WhereTerm under consideration */
2944 int opMask; /* Valid operators for constraints */
2945 WhereScan scan; /* Iterator for WHERE terms */
2946 Bitmask saved_prereq; /* Original value of pNew->prereq */
2947 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
2948 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
2949 u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
2950 u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
2951 u16 saved_nSkip; /* Original value of pNew->nSkip */
2952 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
2953 LogEst saved_nOut; /* Original value of pNew->nOut */
2954 int rc = SQLITE_OK; /* Return code */
2955 LogEst rSize; /* Number of rows in the table */
2956 LogEst rLogSize; /* Logarithm of table size */
2957 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
2959 pNew = pBuilder->pNew;
2960 assert( db->mallocFailed==0 || pParse->nErr>0 );
2961 if( pParse->nErr ){
2962 return pParse->rc;
2964 WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n",
2965 pProbe->pTable->zName,pProbe->zName,
2966 pNew->u.btree.nEq, pNew->nSkip, pNew->rRun));
2968 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
2969 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
2970 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
2971 opMask = WO_LT|WO_LE;
2972 }else{
2973 assert( pNew->u.btree.nBtm==0 );
2974 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
2976 if( pProbe->bUnordered || pProbe->bLowQual ){
2977 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
2978 if( pProbe->bLowQual ) opMask &= ~(WO_EQ|WO_IN|WO_IS);
2981 assert( pNew->u.btree.nEq<pProbe->nColumn );
2982 assert( pNew->u.btree.nEq<pProbe->nKeyCol
2983 || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
2985 saved_nEq = pNew->u.btree.nEq;
2986 saved_nBtm = pNew->u.btree.nBtm;
2987 saved_nTop = pNew->u.btree.nTop;
2988 saved_nSkip = pNew->nSkip;
2989 saved_nLTerm = pNew->nLTerm;
2990 saved_wsFlags = pNew->wsFlags;
2991 saved_prereq = pNew->prereq;
2992 saved_nOut = pNew->nOut;
2993 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
2994 opMask, pProbe);
2995 pNew->rSetup = 0;
2996 rSize = pProbe->aiRowLogEst[0];
2997 rLogSize = estLog(rSize);
2998 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
2999 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
3000 LogEst rCostIdx;
3001 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
3002 int nIn = 0;
3003 #ifdef SQLITE_ENABLE_STAT4
3004 int nRecValid = pBuilder->nRecValid;
3005 #endif
3006 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
3007 && indexColumnNotNull(pProbe, saved_nEq)
3009 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
3011 if( pTerm->prereqRight & pNew->maskSelf ) continue;
3013 /* Do not allow the upper bound of a LIKE optimization range constraint
3014 ** to mix with a lower range bound from some other source */
3015 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
3017 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
3018 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
3020 continue;
3022 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
3023 pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
3024 }else{
3025 pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
3027 pNew->wsFlags = saved_wsFlags;
3028 pNew->u.btree.nEq = saved_nEq;
3029 pNew->u.btree.nBtm = saved_nBtm;
3030 pNew->u.btree.nTop = saved_nTop;
3031 pNew->nLTerm = saved_nLTerm;
3032 if( pNew->nLTerm>=pNew->nLSlot
3033 && whereLoopResize(db, pNew, pNew->nLTerm+1)
3035 break; /* OOM while trying to enlarge the pNew->aLTerm array */
3037 pNew->aLTerm[pNew->nLTerm++] = pTerm;
3038 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
3040 assert( nInMul==0
3041 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
3042 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
3043 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
3046 if( eOp & WO_IN ){
3047 Expr *pExpr = pTerm->pExpr;
3048 if( ExprUseXSelect(pExpr) ){
3049 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
3050 int i;
3051 nIn = 46; assert( 46==sqlite3LogEst(25) );
3053 /* The expression may actually be of the form (x, y) IN (SELECT...).
3054 ** In this case there is a separate term for each of (x) and (y).
3055 ** However, the nIn multiplier should only be applied once, not once
3056 ** for each such term. The following loop checks that pTerm is the
3057 ** first such term in use, and sets nIn back to 0 if it is not. */
3058 for(i=0; i<pNew->nLTerm-1; i++){
3059 if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
3061 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3062 /* "x IN (value, value, ...)" */
3063 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
3065 if( pProbe->hasStat1 && rLogSize>=10 ){
3066 LogEst M, logK, x;
3067 /* Let:
3068 ** N = the total number of rows in the table
3069 ** K = the number of entries on the RHS of the IN operator
3070 ** M = the number of rows in the table that match terms to the
3071 ** to the left in the same index. If the IN operator is on
3072 ** the left-most index column, M==N.
3074 ** Given the definitions above, it is better to omit the IN operator
3075 ** from the index lookup and instead do a scan of the M elements,
3076 ** testing each scanned row against the IN operator separately, if:
3078 ** M*log(K) < K*log(N)
3080 ** Our estimates for M, K, and N might be inaccurate, so we build in
3081 ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
3082 ** with the index, as using an index has better worst-case behavior.
3083 ** If we do not have real sqlite_stat1 data, always prefer to use
3084 ** the index. Do not bother with this optimization on very small
3085 ** tables (less than 2 rows) as it is pointless in that case.
3087 M = pProbe->aiRowLogEst[saved_nEq];
3088 logK = estLog(nIn);
3089 /* TUNING v----- 10 to bias toward indexed IN */
3090 x = M + logK + 10 - (nIn + rLogSize);
3091 if( x>=0 ){
3092 WHERETRACE(0x40,
3093 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) "
3094 "prefers indexed lookup\n",
3095 saved_nEq, M, logK, nIn, rLogSize, x));
3096 }else if( nInMul<2 && OptimizationEnabled(db, SQLITE_SeekScan) ){
3097 WHERETRACE(0x40,
3098 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3099 " nInMul=%d) prefers skip-scan\n",
3100 saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
3101 pNew->wsFlags |= WHERE_IN_SEEKSCAN;
3102 }else{
3103 WHERETRACE(0x40,
3104 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3105 " nInMul=%d) prefers normal scan\n",
3106 saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
3107 continue;
3110 pNew->wsFlags |= WHERE_COLUMN_IN;
3111 }else if( eOp & (WO_EQ|WO_IS) ){
3112 int iCol = pProbe->aiColumn[saved_nEq];
3113 pNew->wsFlags |= WHERE_COLUMN_EQ;
3114 assert( saved_nEq==pNew->u.btree.nEq );
3115 if( iCol==XN_ROWID
3116 || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
3118 if( iCol==XN_ROWID || pProbe->uniqNotNull
3119 || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
3121 pNew->wsFlags |= WHERE_ONEROW;
3122 }else{
3123 pNew->wsFlags |= WHERE_UNQ_WANTED;
3126 if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
3127 }else if( eOp & WO_ISNULL ){
3128 pNew->wsFlags |= WHERE_COLUMN_NULL;
3129 }else{
3130 int nVecLen = whereRangeVectorLen(
3131 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
3133 if( eOp & (WO_GT|WO_GE) ){
3134 testcase( eOp & WO_GT );
3135 testcase( eOp & WO_GE );
3136 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
3137 pNew->u.btree.nBtm = nVecLen;
3138 pBtm = pTerm;
3139 pTop = 0;
3140 if( pTerm->wtFlags & TERM_LIKEOPT ){
3141 /* Range constraints that come from the LIKE optimization are
3142 ** always used in pairs. */
3143 pTop = &pTerm[1];
3144 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
3145 assert( pTop->wtFlags & TERM_LIKEOPT );
3146 assert( pTop->eOperator==WO_LT );
3147 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3148 pNew->aLTerm[pNew->nLTerm++] = pTop;
3149 pNew->wsFlags |= WHERE_TOP_LIMIT;
3150 pNew->u.btree.nTop = 1;
3152 }else{
3153 assert( eOp & (WO_LT|WO_LE) );
3154 testcase( eOp & WO_LT );
3155 testcase( eOp & WO_LE );
3156 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
3157 pNew->u.btree.nTop = nVecLen;
3158 pTop = pTerm;
3159 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
3160 pNew->aLTerm[pNew->nLTerm-2] : 0;
3164 /* At this point pNew->nOut is set to the number of rows expected to
3165 ** be visited by the index scan before considering term pTerm, or the
3166 ** values of nIn and nInMul. In other words, assuming that all
3167 ** "x IN(...)" terms are replaced with "x = ?". This block updates
3168 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
3169 assert( pNew->nOut==saved_nOut );
3170 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3171 /* Adjust nOut using stat4 data. Or, if there is no stat4
3172 ** data, using some other estimate. */
3173 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
3174 }else{
3175 int nEq = ++pNew->u.btree.nEq;
3176 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
3178 assert( pNew->nOut==saved_nOut );
3179 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
3180 assert( (eOp & WO_IN) || nIn==0 );
3181 testcase( eOp & WO_IN );
3182 pNew->nOut += pTerm->truthProb;
3183 pNew->nOut -= nIn;
3184 }else{
3185 #ifdef SQLITE_ENABLE_STAT4
3186 tRowcnt nOut = 0;
3187 if( nInMul==0
3188 && pProbe->nSample
3189 && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol)
3190 && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr))
3191 && OptimizationEnabled(db, SQLITE_Stat4)
3193 Expr *pExpr = pTerm->pExpr;
3194 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
3195 testcase( eOp & WO_EQ );
3196 testcase( eOp & WO_IS );
3197 testcase( eOp & WO_ISNULL );
3198 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
3199 }else{
3200 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
3202 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
3203 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
3204 if( nOut ){
3205 pNew->nOut = sqlite3LogEst(nOut);
3206 if( nEq==1
3207 /* TUNING: Mark terms as "low selectivity" if they seem likely
3208 ** to be true for half or more of the rows in the table.
3209 ** See tag-202002240-1 */
3210 && pNew->nOut+10 > pProbe->aiRowLogEst[0]
3212 #if WHERETRACE_ENABLED /* 0x01 */
3213 if( sqlite3WhereTrace & 0x20 ){
3214 sqlite3DebugPrintf(
3215 "STAT4 determines term has low selectivity:\n");
3216 sqlite3WhereTermPrint(pTerm, 999);
3218 #endif
3219 pTerm->wtFlags |= TERM_HIGHTRUTH;
3220 if( pTerm->wtFlags & TERM_HEURTRUTH ){
3221 /* If the term has previously been used with an assumption of
3222 ** higher selectivity, then set the flag to rerun the
3223 ** loop computations. */
3224 pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
3227 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
3228 pNew->nOut -= nIn;
3231 if( nOut==0 )
3232 #endif
3234 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
3235 if( eOp & WO_ISNULL ){
3236 /* TUNING: If there is no likelihood() value, assume that a
3237 ** "col IS NULL" expression matches twice as many rows
3238 ** as (col=?). */
3239 pNew->nOut += 10;
3245 /* Set rCostIdx to the cost of visiting selected rows in index. Add
3246 ** it to pNew->rRun, which is currently set to the cost of the index
3247 ** seek only. Then, if this is a non-covering index, add the cost of
3248 ** visiting the rows in the main table. */
3249 assert( pSrc->pTab->szTabRow>0 );
3250 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
3251 /* The pProbe->szIdxRow is low for an IPK table since the interior
3252 ** pages are small. Thus szIdxRow gives a good estimate of seek cost.
3253 ** But the leaf pages are full-size, so pProbe->szIdxRow would badly
3254 ** under-estimate the scanning cost. */
3255 rCostIdx = pNew->nOut + 16;
3256 }else{
3257 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
3259 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
3260 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK|WHERE_EXPRIDX))==0 ){
3261 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
3263 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
3265 nOutUnadjusted = pNew->nOut;
3266 pNew->rRun += nInMul + nIn;
3267 pNew->nOut += nInMul + nIn;
3268 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
3269 rc = whereLoopInsert(pBuilder, pNew);
3271 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3272 pNew->nOut = saved_nOut;
3273 }else{
3274 pNew->nOut = nOutUnadjusted;
3277 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
3278 && pNew->u.btree.nEq<pProbe->nColumn
3279 && (pNew->u.btree.nEq<pProbe->nKeyCol ||
3280 pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)
3282 if( pNew->u.btree.nEq>3 ){
3283 sqlite3ProgressCheck(pParse);
3285 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
3287 pNew->nOut = saved_nOut;
3288 #ifdef SQLITE_ENABLE_STAT4
3289 pBuilder->nRecValid = nRecValid;
3290 #endif
3292 pNew->prereq = saved_prereq;
3293 pNew->u.btree.nEq = saved_nEq;
3294 pNew->u.btree.nBtm = saved_nBtm;
3295 pNew->u.btree.nTop = saved_nTop;
3296 pNew->nSkip = saved_nSkip;
3297 pNew->wsFlags = saved_wsFlags;
3298 pNew->nOut = saved_nOut;
3299 pNew->nLTerm = saved_nLTerm;
3301 /* Consider using a skip-scan if there are no WHERE clause constraints
3302 ** available for the left-most terms of the index, and if the average
3303 ** number of repeats in the left-most terms is at least 18.
3305 ** The magic number 18 is selected on the basis that scanning 17 rows
3306 ** is almost always quicker than an index seek (even though if the index
3307 ** contains fewer than 2^17 rows we assume otherwise in other parts of
3308 ** the code). And, even if it is not, it should not be too much slower.
3309 ** On the other hand, the extra seeks could end up being significantly
3310 ** more expensive. */
3311 assert( 42==sqlite3LogEst(18) );
3312 if( saved_nEq==saved_nSkip
3313 && saved_nEq+1<pProbe->nKeyCol
3314 && saved_nEq==pNew->nLTerm
3315 && pProbe->noSkipScan==0
3316 && pProbe->hasStat1!=0
3317 && OptimizationEnabled(db, SQLITE_SkipScan)
3318 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
3319 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
3321 LogEst nIter;
3322 pNew->u.btree.nEq++;
3323 pNew->nSkip++;
3324 pNew->aLTerm[pNew->nLTerm++] = 0;
3325 pNew->wsFlags |= WHERE_SKIPSCAN;
3326 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
3327 pNew->nOut -= nIter;
3328 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
3329 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
3330 nIter += 5;
3331 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
3332 pNew->nOut = saved_nOut;
3333 pNew->u.btree.nEq = saved_nEq;
3334 pNew->nSkip = saved_nSkip;
3335 pNew->wsFlags = saved_wsFlags;
3338 WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
3339 pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
3340 return rc;
3344 ** Return True if it is possible that pIndex might be useful in
3345 ** implementing the ORDER BY clause in pBuilder.
3347 ** Return False if pBuilder does not contain an ORDER BY clause or
3348 ** if there is no way for pIndex to be useful in implementing that
3349 ** ORDER BY clause.
3351 static int indexMightHelpWithOrderBy(
3352 WhereLoopBuilder *pBuilder,
3353 Index *pIndex,
3354 int iCursor
3356 ExprList *pOB;
3357 ExprList *aColExpr;
3358 int ii, jj;
3360 if( pIndex->bUnordered ) return 0;
3361 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
3362 for(ii=0; ii<pOB->nExpr; ii++){
3363 Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
3364 if( NEVER(pExpr==0) ) continue;
3365 if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
3366 if( pExpr->iColumn<0 ) return 1;
3367 for(jj=0; jj<pIndex->nKeyCol; jj++){
3368 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
3370 }else if( (aColExpr = pIndex->aColExpr)!=0 ){
3371 for(jj=0; jj<pIndex->nKeyCol; jj++){
3372 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
3373 if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
3374 return 1;
3379 return 0;
3382 /* Check to see if a partial index with pPartIndexWhere can be used
3383 ** in the current query. Return true if it can be and false if not.
3385 static int whereUsablePartialIndex(
3386 int iTab, /* The table for which we want an index */
3387 u8 jointype, /* The JT_* flags on the join */
3388 WhereClause *pWC, /* The WHERE clause of the query */
3389 Expr *pWhere /* The WHERE clause from the partial index */
3391 int i;
3392 WhereTerm *pTerm;
3393 Parse *pParse;
3395 if( jointype & JT_LTORJ ) return 0;
3396 pParse = pWC->pWInfo->pParse;
3397 while( pWhere->op==TK_AND ){
3398 if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0;
3399 pWhere = pWhere->pRight;
3401 if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
3402 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
3403 Expr *pExpr;
3404 pExpr = pTerm->pExpr;
3405 if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab)
3406 && ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON))
3407 && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
3408 && (pTerm->wtFlags & TERM_VNULL)==0
3410 return 1;
3413 return 0;
3417 ** pIdx is an index containing expressions. Check it see if any of the
3418 ** expressions in the index match the pExpr expression.
3420 static int exprIsCoveredByIndex(
3421 const Expr *pExpr,
3422 const Index *pIdx,
3423 int iTabCur
3425 int i;
3426 for(i=0; i<pIdx->nColumn; i++){
3427 if( pIdx->aiColumn[i]==XN_EXPR
3428 && sqlite3ExprCompare(0, pExpr, pIdx->aColExpr->a[i].pExpr, iTabCur)==0
3430 return 1;
3433 return 0;
3437 ** Structure passed to the whereIsCoveringIndex Walker callback.
3439 typedef struct CoveringIndexCheck CoveringIndexCheck;
3440 struct CoveringIndexCheck {
3441 Index *pIdx; /* The index */
3442 int iTabCur; /* Cursor number for the corresponding table */
3443 u8 bExpr; /* Uses an indexed expression */
3444 u8 bUnidx; /* Uses an unindexed column not within an indexed expr */
3448 ** Information passed in is pWalk->u.pCovIdxCk. Call it pCk.
3450 ** If the Expr node references the table with cursor pCk->iTabCur, then
3451 ** make sure that column is covered by the index pCk->pIdx. We know that
3452 ** all columns less than 63 (really BMS-1) are covered, so we don't need
3453 ** to check them. But we do need to check any column at 63 or greater.
3455 ** If the index does not cover the column, then set pWalk->eCode to
3456 ** non-zero and return WRC_Abort to stop the search.
3458 ** If this node does not disprove that the index can be a covering index,
3459 ** then just return WRC_Continue, to continue the search.
3461 ** If pCk->pIdx contains indexed expressions and one of those expressions
3462 ** matches pExpr, then prune the search.
3464 static int whereIsCoveringIndexWalkCallback(Walker *pWalk, Expr *pExpr){
3465 int i; /* Loop counter */
3466 const Index *pIdx; /* The index of interest */
3467 const i16 *aiColumn; /* Columns contained in the index */
3468 u16 nColumn; /* Number of columns in the index */
3469 CoveringIndexCheck *pCk; /* Info about this search */
3471 pCk = pWalk->u.pCovIdxCk;
3472 pIdx = pCk->pIdx;
3473 if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){
3474 /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
3475 if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue;
3476 pIdx = pWalk->u.pCovIdxCk->pIdx;
3477 aiColumn = pIdx->aiColumn;
3478 nColumn = pIdx->nColumn;
3479 for(i=0; i<nColumn; i++){
3480 if( aiColumn[i]==pExpr->iColumn ) return WRC_Continue;
3482 pCk->bUnidx = 1;
3483 return WRC_Abort;
3484 }else if( pIdx->bHasExpr
3485 && exprIsCoveredByIndex(pExpr, pIdx, pWalk->u.pCovIdxCk->iTabCur) ){
3486 pCk->bExpr = 1;
3487 return WRC_Prune;
3489 return WRC_Continue;
3494 ** pIdx is an index that covers all of the low-number columns used by
3495 ** pWInfo->pSelect (columns from 0 through 62) or an index that has
3496 ** expressions terms. Hence, we cannot determine whether or not it is
3497 ** a covering index by using the colUsed bitmasks. We have to do a search
3498 ** to see if the index is covering. This routine does that search.
3500 ** The return value is one of these:
3502 ** 0 The index is definitely not a covering index
3504 ** WHERE_IDX_ONLY The index is definitely a covering index
3506 ** WHERE_EXPRIDX The index is likely a covering index, but it is
3507 ** difficult to determine precisely because of the
3508 ** expressions that are indexed. Score it as a
3509 ** covering index, but still keep the main table open
3510 ** just in case we need it.
3512 ** This routine is an optimization. It is always safe to return zero.
3513 ** But returning one of the other two values when zero should have been
3514 ** returned can lead to incorrect bytecode and assertion faults.
3516 static SQLITE_NOINLINE u32 whereIsCoveringIndex(
3517 WhereInfo *pWInfo, /* The WHERE clause context */
3518 Index *pIdx, /* Index that is being tested */
3519 int iTabCur /* Cursor for the table being indexed */
3521 int i, rc;
3522 struct CoveringIndexCheck ck;
3523 Walker w;
3524 if( pWInfo->pSelect==0 ){
3525 /* We don't have access to the full query, so we cannot check to see
3526 ** if pIdx is covering. Assume it is not. */
3527 return 0;
3529 if( pIdx->bHasExpr==0 ){
3530 for(i=0; i<pIdx->nColumn; i++){
3531 if( pIdx->aiColumn[i]>=BMS-1 ) break;
3533 if( i>=pIdx->nColumn ){
3534 /* pIdx does not index any columns greater than 62, but we know from
3535 ** colMask that columns greater than 62 are used, so this is not a
3536 ** covering index */
3537 return 0;
3540 ck.pIdx = pIdx;
3541 ck.iTabCur = iTabCur;
3542 ck.bExpr = 0;
3543 ck.bUnidx = 0;
3544 memset(&w, 0, sizeof(w));
3545 w.xExprCallback = whereIsCoveringIndexWalkCallback;
3546 w.xSelectCallback = sqlite3SelectWalkNoop;
3547 w.u.pCovIdxCk = &ck;
3548 sqlite3WalkSelect(&w, pWInfo->pSelect);
3549 if( ck.bUnidx ){
3550 rc = 0;
3551 }else if( ck.bExpr ){
3552 rc = WHERE_EXPRIDX;
3553 }else{
3554 rc = WHERE_IDX_ONLY;
3556 return rc;
3560 ** This is an sqlite3ParserAddCleanup() callback that is invoked to
3561 ** free the Parse->pIdxEpr list when the Parse object is destroyed.
3563 static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){
3564 IndexedExpr **pp = (IndexedExpr**)pObject;
3565 while( *pp!=0 ){
3566 IndexedExpr *p = *pp;
3567 *pp = p->pIENext;
3568 sqlite3ExprDelete(db, p->pExpr);
3569 sqlite3DbFreeNN(db, p);
3574 ** This function is called for a partial index - one with a WHERE clause - in
3575 ** two scenarios. In both cases, it determines whether or not the WHERE
3576 ** clause on the index implies that a column of the table may be safely
3577 ** replaced by a constant expression. For example, in the following
3578 ** SELECT:
3580 ** CREATE INDEX i1 ON t1(b, c) WHERE a=<expr>;
3581 ** SELECT a, b, c FROM t1 WHERE a=<expr> AND b=?;
3583 ** The "a" in the select-list may be replaced by <expr>, iff:
3585 ** (a) <expr> is a constant expression, and
3586 ** (b) The (a=<expr>) comparison uses the BINARY collation sequence, and
3587 ** (c) Column "a" has an affinity other than NONE or BLOB.
3589 ** If argument pItem is NULL, then pMask must not be NULL. In this case this
3590 ** function is being called as part of determining whether or not pIdx
3591 ** is a covering index. This function clears any bits in (*pMask)
3592 ** corresponding to columns that may be replaced by constants as described
3593 ** above.
3595 ** Otherwise, if pItem is not NULL, then this function is being called
3596 ** as part of coding a loop that uses index pIdx. In this case, add entries
3597 ** to the Parse.pIdxPartExpr list for each column that can be replaced
3598 ** by a constant.
3600 static void wherePartIdxExpr(
3601 Parse *pParse, /* Parse context */
3602 Index *pIdx, /* Partial index being processed */
3603 Expr *pPart, /* WHERE clause being processed */
3604 Bitmask *pMask, /* Mask to clear bits in */
3605 int iIdxCur, /* Cursor number for index */
3606 SrcItem *pItem /* The FROM clause entry for the table */
3608 assert( pItem==0 || (pItem->fg.jointype & JT_RIGHT)==0 );
3609 assert( (pItem==0 || pMask==0) && (pMask!=0 || pItem!=0) );
3611 if( pPart->op==TK_AND ){
3612 wherePartIdxExpr(pParse, pIdx, pPart->pRight, pMask, iIdxCur, pItem);
3613 pPart = pPart->pLeft;
3616 if( (pPart->op==TK_EQ || pPart->op==TK_IS) ){
3617 Expr *pLeft = pPart->pLeft;
3618 Expr *pRight = pPart->pRight;
3619 u8 aff;
3621 if( pLeft->op!=TK_COLUMN ) return;
3622 if( !sqlite3ExprIsConstant(pRight) ) return;
3623 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pParse, pPart)) ) return;
3624 if( pLeft->iColumn<0 ) return;
3625 aff = pIdx->pTable->aCol[pLeft->iColumn].affinity;
3626 if( aff>=SQLITE_AFF_TEXT ){
3627 if( pItem ){
3628 sqlite3 *db = pParse->db;
3629 IndexedExpr *p = (IndexedExpr*)sqlite3DbMallocRaw(db, sizeof(*p));
3630 if( p ){
3631 int bNullRow = (pItem->fg.jointype&(JT_LEFT|JT_LTORJ))!=0;
3632 p->pExpr = sqlite3ExprDup(db, pRight, 0);
3633 p->iDataCur = pItem->iCursor;
3634 p->iIdxCur = iIdxCur;
3635 p->iIdxCol = pLeft->iColumn;
3636 p->bMaybeNullRow = bNullRow;
3637 p->pIENext = pParse->pIdxPartExpr;
3638 p->aff = aff;
3639 pParse->pIdxPartExpr = p;
3640 if( p->pIENext==0 ){
3641 void *pArg = (void*)&pParse->pIdxPartExpr;
3642 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
3645 }else if( pLeft->iColumn<(BMS-1) ){
3646 *pMask &= ~((Bitmask)1 << pLeft->iColumn);
3654 ** Add all WhereLoop objects for a single table of the join where the table
3655 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
3656 ** a b-tree table, not a virtual table.
3658 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
3659 ** are calculated as follows:
3661 ** For a full scan, assuming the table (or index) contains nRow rows:
3663 ** cost = nRow * 3.0 // full-table scan
3664 ** cost = nRow * K // scan of covering index
3665 ** cost = nRow * (K+3.0) // scan of non-covering index
3667 ** where K is a value between 1.1 and 3.0 set based on the relative
3668 ** estimated average size of the index and table records.
3670 ** For an index scan, where nVisit is the number of index rows visited
3671 ** by the scan, and nSeek is the number of seek operations required on
3672 ** the index b-tree:
3674 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
3675 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
3677 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
3678 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
3679 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
3681 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
3682 ** of uncertainty. For this reason, scoring is designed to pick plans that
3683 ** "do the least harm" if the estimates are inaccurate. For example, a
3684 ** log(nRow) factor is omitted from a non-covering index scan in order to
3685 ** bias the scoring in favor of using an index, since the worst-case
3686 ** performance of using an index is far better than the worst-case performance
3687 ** of a full table scan.
3689 static int whereLoopAddBtree(
3690 WhereLoopBuilder *pBuilder, /* WHERE clause information */
3691 Bitmask mPrereq /* Extra prerequisites for using this table */
3693 WhereInfo *pWInfo; /* WHERE analysis context */
3694 Index *pProbe; /* An index we are evaluating */
3695 Index sPk; /* A fake index object for the primary key */
3696 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
3697 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
3698 SrcList *pTabList; /* The FROM clause */
3699 SrcItem *pSrc; /* The FROM clause btree term to add */
3700 WhereLoop *pNew; /* Template WhereLoop object */
3701 int rc = SQLITE_OK; /* Return code */
3702 int iSortIdx = 1; /* Index number */
3703 int b; /* A boolean value */
3704 LogEst rSize; /* number of rows in the table */
3705 WhereClause *pWC; /* The parsed WHERE clause */
3706 Table *pTab; /* Table being queried */
3708 pNew = pBuilder->pNew;
3709 pWInfo = pBuilder->pWInfo;
3710 pTabList = pWInfo->pTabList;
3711 pSrc = pTabList->a + pNew->iTab;
3712 pTab = pSrc->pTab;
3713 pWC = pBuilder->pWC;
3714 assert( !IsVirtual(pSrc->pTab) );
3716 if( pSrc->fg.isIndexedBy ){
3717 assert( pSrc->fg.isCte==0 );
3718 /* An INDEXED BY clause specifies a particular index to use */
3719 pProbe = pSrc->u2.pIBIndex;
3720 }else if( !HasRowid(pTab) ){
3721 pProbe = pTab->pIndex;
3722 }else{
3723 /* There is no INDEXED BY clause. Create a fake Index object in local
3724 ** variable sPk to represent the rowid primary key index. Make this
3725 ** fake index the first in a chain of Index objects with all of the real
3726 ** indices to follow */
3727 Index *pFirst; /* First of real indices on the table */
3728 memset(&sPk, 0, sizeof(Index));
3729 sPk.nKeyCol = 1;
3730 sPk.nColumn = 1;
3731 sPk.aiColumn = &aiColumnPk;
3732 sPk.aiRowLogEst = aiRowEstPk;
3733 sPk.onError = OE_Replace;
3734 sPk.pTable = pTab;
3735 sPk.szIdxRow = 3; /* TUNING: Interior rows of IPK table are very small */
3736 sPk.idxType = SQLITE_IDXTYPE_IPK;
3737 aiRowEstPk[0] = pTab->nRowLogEst;
3738 aiRowEstPk[1] = 0;
3739 pFirst = pSrc->pTab->pIndex;
3740 if( pSrc->fg.notIndexed==0 ){
3741 /* The real indices of the table are only considered if the
3742 ** NOT INDEXED qualifier is omitted from the FROM clause */
3743 sPk.pNext = pFirst;
3745 pProbe = &sPk;
3747 rSize = pTab->nRowLogEst;
3749 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
3750 /* Automatic indexes */
3751 if( !pBuilder->pOrSet /* Not part of an OR optimization */
3752 && (pWInfo->wctrlFlags & (WHERE_RIGHT_JOIN|WHERE_OR_SUBCLAUSE))==0
3753 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
3754 && !pSrc->fg.isIndexedBy /* Has no INDEXED BY clause */
3755 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
3756 && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
3757 && !pSrc->fg.isCorrelated /* Not a correlated subquery */
3758 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
3759 && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */
3761 /* Generate auto-index WhereLoops */
3762 LogEst rLogSize; /* Logarithm of the number of rows in the table */
3763 WhereTerm *pTerm;
3764 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
3765 rLogSize = estLog(rSize);
3766 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
3767 if( pTerm->prereqRight & pNew->maskSelf ) continue;
3768 if( termCanDriveIndex(pTerm, pSrc, 0) ){
3769 pNew->u.btree.nEq = 1;
3770 pNew->nSkip = 0;
3771 pNew->u.btree.pIndex = 0;
3772 pNew->nLTerm = 1;
3773 pNew->aLTerm[0] = pTerm;
3774 /* TUNING: One-time cost for computing the automatic index is
3775 ** estimated to be X*N*log2(N) where N is the number of rows in
3776 ** the table being indexed and where X is 7 (LogEst=28) for normal
3777 ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
3778 ** of X is smaller for views and subqueries so that the query planner
3779 ** will be more aggressive about generating automatic indexes for
3780 ** those objects, since there is no opportunity to add schema
3781 ** indexes on subqueries and views. */
3782 pNew->rSetup = rLogSize + rSize;
3783 if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){
3784 pNew->rSetup += 28;
3785 }else{
3786 pNew->rSetup -= 25; /* Greatly reduced setup cost for auto indexes
3787 ** on ephemeral materializations of views */
3789 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
3790 if( pNew->rSetup<0 ) pNew->rSetup = 0;
3791 /* TUNING: Each index lookup yields 20 rows in the table. This
3792 ** is more than the usual guess of 10 rows, since we have no way
3793 ** of knowing how selective the index will ultimately be. It would
3794 ** not be unreasonable to make this value much larger. */
3795 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
3796 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
3797 pNew->wsFlags = WHERE_AUTO_INDEX;
3798 pNew->prereq = mPrereq | pTerm->prereqRight;
3799 rc = whereLoopInsert(pBuilder, pNew);
3803 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
3805 /* Loop over all indices. If there was an INDEXED BY clause, then only
3806 ** consider index pProbe. */
3807 for(; rc==SQLITE_OK && pProbe;
3808 pProbe=(pSrc->fg.isIndexedBy ? 0 : pProbe->pNext), iSortIdx++
3810 if( pProbe->pPartIdxWhere!=0
3811 && !whereUsablePartialIndex(pSrc->iCursor, pSrc->fg.jointype, pWC,
3812 pProbe->pPartIdxWhere)
3814 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
3815 continue; /* Partial index inappropriate for this query */
3817 if( pProbe->bNoQuery ) continue;
3818 rSize = pProbe->aiRowLogEst[0];
3819 pNew->u.btree.nEq = 0;
3820 pNew->u.btree.nBtm = 0;
3821 pNew->u.btree.nTop = 0;
3822 pNew->nSkip = 0;
3823 pNew->nLTerm = 0;
3824 pNew->iSortIdx = 0;
3825 pNew->rSetup = 0;
3826 pNew->prereq = mPrereq;
3827 pNew->nOut = rSize;
3828 pNew->u.btree.pIndex = pProbe;
3829 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
3831 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
3832 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
3833 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
3834 /* Integer primary key index */
3835 pNew->wsFlags = WHERE_IPK;
3837 /* Full table scan */
3838 pNew->iSortIdx = b ? iSortIdx : 0;
3839 /* TUNING: Cost of full table scan is 3.0*N. The 3.0 factor is an
3840 ** extra cost designed to discourage the use of full table scans,
3841 ** since index lookups have better worst-case performance if our
3842 ** stat guesses are wrong. Reduce the 3.0 penalty slightly
3843 ** (to 2.75) if we have valid STAT4 information for the table.
3844 ** At 2.75, a full table scan is preferred over using an index on
3845 ** a column with just two distinct values where each value has about
3846 ** an equal number of appearances. Without STAT4 data, we still want
3847 ** to use an index in that case, since the constraint might be for
3848 ** the scarcer of the two values, and in that case an index lookup is
3849 ** better.
3851 #ifdef SQLITE_ENABLE_STAT4
3852 pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
3853 #else
3854 pNew->rRun = rSize + 16;
3855 #endif
3856 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3857 whereLoopOutputAdjust(pWC, pNew, rSize);
3858 rc = whereLoopInsert(pBuilder, pNew);
3859 pNew->nOut = rSize;
3860 if( rc ) break;
3861 }else{
3862 Bitmask m;
3863 if( pProbe->isCovering ){
3864 m = 0;
3865 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3866 }else{
3867 m = pSrc->colUsed & pProbe->colNotIdxed;
3868 if( pProbe->pPartIdxWhere ){
3869 wherePartIdxExpr(
3870 pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0
3873 pNew->wsFlags = WHERE_INDEXED;
3874 if( m==TOPBIT || (pProbe->bHasExpr && !pProbe->bHasVCol && m!=0) ){
3875 u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
3876 if( isCov==0 ){
3877 WHERETRACE(0x200,
3878 ("-> %s is not a covering index"
3879 " according to whereIsCoveringIndex()\n", pProbe->zName));
3880 assert( m!=0 );
3881 }else{
3882 m = 0;
3883 pNew->wsFlags |= isCov;
3884 if( isCov & WHERE_IDX_ONLY ){
3885 WHERETRACE(0x200,
3886 ("-> %s is a covering expression index"
3887 " according to whereIsCoveringIndex()\n", pProbe->zName));
3888 }else{
3889 assert( isCov==WHERE_EXPRIDX );
3890 WHERETRACE(0x200,
3891 ("-> %s might be a covering expression index"
3892 " according to whereIsCoveringIndex()\n", pProbe->zName));
3895 }else if( m==0 ){
3896 WHERETRACE(0x200,
3897 ("-> %s a covering index according to bitmasks\n",
3898 pProbe->zName, m==0 ? "is" : "is not"));
3899 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3903 /* Full scan via index */
3904 if( b
3905 || !HasRowid(pTab)
3906 || pProbe->pPartIdxWhere!=0
3907 || pSrc->fg.isIndexedBy
3908 || ( m==0
3909 && pProbe->bUnordered==0
3910 && (pProbe->szIdxRow<pTab->szTabRow)
3911 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3912 && sqlite3GlobalConfig.bUseCis
3913 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
3916 pNew->iSortIdx = b ? iSortIdx : 0;
3918 /* The cost of visiting the index rows is N*K, where K is
3919 ** between 1.1 and 3.0, depending on the relative sizes of the
3920 ** index and table rows. */
3921 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
3922 if( m!=0 ){
3923 /* If this is a non-covering index scan, add in the cost of
3924 ** doing table lookups. The cost will be 3x the number of
3925 ** lookups. Take into account WHERE clause terms that can be
3926 ** satisfied using just the index, and that do not require a
3927 ** table lookup. */
3928 LogEst nLookup = rSize + 16; /* Base cost: N*3 */
3929 int ii;
3930 int iCur = pSrc->iCursor;
3931 WhereClause *pWC2 = &pWInfo->sWC;
3932 for(ii=0; ii<pWC2->nTerm; ii++){
3933 WhereTerm *pTerm = &pWC2->a[ii];
3934 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
3935 break;
3937 /* pTerm can be evaluated using just the index. So reduce
3938 ** the expected number of table lookups accordingly */
3939 if( pTerm->truthProb<=0 ){
3940 nLookup += pTerm->truthProb;
3941 }else{
3942 nLookup--;
3943 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
3947 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
3949 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3950 whereLoopOutputAdjust(pWC, pNew, rSize);
3951 if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){
3952 /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
3953 ** because the cursor used to access the index might not be
3954 ** positioned to the correct row during the right-join no-match
3955 ** loop. */
3956 }else{
3957 rc = whereLoopInsert(pBuilder, pNew);
3959 pNew->nOut = rSize;
3960 if( rc ) break;
3964 pBuilder->bldFlags1 = 0;
3965 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
3966 if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
3967 /* If a non-unique index is used, or if a prefix of the key for
3968 ** unique index is used (making the index functionally non-unique)
3969 ** then the sqlite_stat1 data becomes important for scoring the
3970 ** plan */
3971 pTab->tabFlags |= TF_StatsUsed;
3973 #ifdef SQLITE_ENABLE_STAT4
3974 sqlite3Stat4ProbeFree(pBuilder->pRec);
3975 pBuilder->nRecValid = 0;
3976 pBuilder->pRec = 0;
3977 #endif
3979 return rc;
3982 #ifndef SQLITE_OMIT_VIRTUALTABLE
3985 ** Return true if pTerm is a virtual table LIMIT or OFFSET term.
3987 static int isLimitTerm(WhereTerm *pTerm){
3988 assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
3989 return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
3990 && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
3994 ** Argument pIdxInfo is already populated with all constraints that may
3995 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
3996 ** function marks a subset of those constraints usable, invokes the
3997 ** xBestIndex method and adds the returned plan to pBuilder.
3999 ** A constraint is marked usable if:
4001 ** * Argument mUsable indicates that its prerequisites are available, and
4003 ** * It is not one of the operators specified in the mExclude mask passed
4004 ** as the fourth argument (which in practice is either WO_IN or 0).
4006 ** Argument mPrereq is a mask of tables that must be scanned before the
4007 ** virtual table in question. These are added to the plans prerequisites
4008 ** before it is added to pBuilder.
4010 ** Output parameter *pbIn is set to true if the plan added to pBuilder
4011 ** uses one or more WO_IN terms, or false otherwise.
4013 static int whereLoopAddVirtualOne(
4014 WhereLoopBuilder *pBuilder,
4015 Bitmask mPrereq, /* Mask of tables that must be used. */
4016 Bitmask mUsable, /* Mask of usable tables */
4017 u16 mExclude, /* Exclude terms using these operators */
4018 sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
4019 u16 mNoOmit, /* Do not omit these constraints */
4020 int *pbIn, /* OUT: True if plan uses an IN(...) op */
4021 int *pbRetryLimit /* OUT: Retry without LIMIT/OFFSET */
4023 WhereClause *pWC = pBuilder->pWC;
4024 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4025 struct sqlite3_index_constraint *pIdxCons;
4026 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
4027 int i;
4028 int mxTerm;
4029 int rc = SQLITE_OK;
4030 WhereLoop *pNew = pBuilder->pNew;
4031 Parse *pParse = pBuilder->pWInfo->pParse;
4032 SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
4033 int nConstraint = pIdxInfo->nConstraint;
4035 assert( (mUsable & mPrereq)==mPrereq );
4036 *pbIn = 0;
4037 pNew->prereq = mPrereq;
4039 /* Set the usable flag on the subset of constraints identified by
4040 ** arguments mUsable and mExclude. */
4041 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4042 for(i=0; i<nConstraint; i++, pIdxCons++){
4043 WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
4044 pIdxCons->usable = 0;
4045 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
4046 && (pTerm->eOperator & mExclude)==0
4047 && (pbRetryLimit || !isLimitTerm(pTerm))
4049 pIdxCons->usable = 1;
4053 /* Initialize the output fields of the sqlite3_index_info structure */
4054 memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
4055 assert( pIdxInfo->needToFreeIdxStr==0 );
4056 pIdxInfo->idxStr = 0;
4057 pIdxInfo->idxNum = 0;
4058 pIdxInfo->orderByConsumed = 0;
4059 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
4060 pIdxInfo->estimatedRows = 25;
4061 pIdxInfo->idxFlags = 0;
4062 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
4063 pHidden->mHandleIn = 0;
4065 /* Invoke the virtual table xBestIndex() method */
4066 rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
4067 if( rc ){
4068 if( rc==SQLITE_CONSTRAINT ){
4069 /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
4070 ** that the particular combination of parameters provided is unusable.
4071 ** Make no entries in the loop table.
4073 WHERETRACE(0xffffffff, (" ^^^^--- non-viable plan rejected!\n"));
4074 return SQLITE_OK;
4076 return rc;
4079 mxTerm = -1;
4080 assert( pNew->nLSlot>=nConstraint );
4081 memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
4082 memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
4083 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4084 for(i=0; i<nConstraint; i++, pIdxCons++){
4085 int iTerm;
4086 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4087 WhereTerm *pTerm;
4088 int j = pIdxCons->iTermOffset;
4089 if( iTerm>=nConstraint
4090 || j<0
4091 || j>=pWC->nTerm
4092 || pNew->aLTerm[iTerm]!=0
4093 || pIdxCons->usable==0
4095 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
4096 testcase( pIdxInfo->needToFreeIdxStr );
4097 return SQLITE_ERROR;
4099 testcase( iTerm==nConstraint-1 );
4100 testcase( j==0 );
4101 testcase( j==pWC->nTerm-1 );
4102 pTerm = &pWC->a[j];
4103 pNew->prereq |= pTerm->prereqRight;
4104 assert( iTerm<pNew->nLSlot );
4105 pNew->aLTerm[iTerm] = pTerm;
4106 if( iTerm>mxTerm ) mxTerm = iTerm;
4107 testcase( iTerm==15 );
4108 testcase( iTerm==16 );
4109 if( pUsage[i].omit ){
4110 if( i<16 && ((1<<i)&mNoOmit)==0 ){
4111 testcase( i!=iTerm );
4112 pNew->u.vtab.omitMask |= 1<<iTerm;
4113 }else{
4114 testcase( i!=iTerm );
4116 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
4117 pNew->u.vtab.bOmitOffset = 1;
4120 if( SMASKBIT32(i) & pHidden->mHandleIn ){
4121 pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
4122 }else if( (pTerm->eOperator & WO_IN)!=0 ){
4123 /* A virtual table that is constrained by an IN clause may not
4124 ** consume the ORDER BY clause because (1) the order of IN terms
4125 ** is not necessarily related to the order of output terms and
4126 ** (2) Multiple outputs from a single IN value will not merge
4127 ** together. */
4128 pIdxInfo->orderByConsumed = 0;
4129 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
4130 *pbIn = 1; assert( (mExclude & WO_IN)==0 );
4133 assert( pbRetryLimit || !isLimitTerm(pTerm) );
4134 if( isLimitTerm(pTerm) && *pbIn ){
4135 /* If there is an IN(...) term handled as an == (separate call to
4136 ** xFilter for each value on the RHS of the IN) and a LIMIT or
4137 ** OFFSET term handled as well, the plan is unusable. Set output
4138 ** variable *pbRetryLimit to true to tell the caller to retry with
4139 ** LIMIT and OFFSET disabled. */
4140 if( pIdxInfo->needToFreeIdxStr ){
4141 sqlite3_free(pIdxInfo->idxStr);
4142 pIdxInfo->idxStr = 0;
4143 pIdxInfo->needToFreeIdxStr = 0;
4145 *pbRetryLimit = 1;
4146 return SQLITE_OK;
4151 pNew->nLTerm = mxTerm+1;
4152 for(i=0; i<=mxTerm; i++){
4153 if( pNew->aLTerm[i]==0 ){
4154 /* The non-zero argvIdx values must be contiguous. Raise an
4155 ** error if they are not */
4156 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
4157 testcase( pIdxInfo->needToFreeIdxStr );
4158 return SQLITE_ERROR;
4161 assert( pNew->nLTerm<=pNew->nLSlot );
4162 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4163 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4164 pIdxInfo->needToFreeIdxStr = 0;
4165 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
4166 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
4167 pIdxInfo->nOrderBy : 0);
4168 pNew->rSetup = 0;
4169 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
4170 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
4172 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
4173 ** that the scan will visit at most one row. Clear it otherwise. */
4174 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
4175 pNew->wsFlags |= WHERE_ONEROW;
4176 }else{
4177 pNew->wsFlags &= ~WHERE_ONEROW;
4179 rc = whereLoopInsert(pBuilder, pNew);
4180 if( pNew->u.vtab.needFree ){
4181 sqlite3_free(pNew->u.vtab.idxStr);
4182 pNew->u.vtab.needFree = 0;
4184 WHERETRACE(0xffffffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
4185 *pbIn, (sqlite3_uint64)mPrereq,
4186 (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
4188 return rc;
4192 ** Return the collating sequence for a constraint passed into xBestIndex.
4194 ** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
4195 ** This routine depends on there being a HiddenIndexInfo structure immediately
4196 ** following the sqlite3_index_info structure.
4198 ** Return a pointer to the collation name:
4200 ** 1. If there is an explicit COLLATE operator on the constraint, return it.
4202 ** 2. Else, if the column has an alternative collation, return that.
4204 ** 3. Otherwise, return "BINARY".
4206 const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
4207 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4208 const char *zRet = 0;
4209 if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
4210 CollSeq *pC = 0;
4211 int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
4212 Expr *pX = pHidden->pWC->a[iTerm].pExpr;
4213 if( pX->pLeft ){
4214 pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
4216 zRet = (pC ? pC->zName : sqlite3StrBINARY);
4218 return zRet;
4222 ** Return true if constraint iCons is really an IN(...) constraint, or
4223 ** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
4224 ** or clear (if bHandle==0) the flag to handle it using an iterator.
4226 int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){
4227 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4228 u32 m = SMASKBIT32(iCons);
4229 if( m & pHidden->mIn ){
4230 if( bHandle==0 ){
4231 pHidden->mHandleIn &= ~m;
4232 }else if( bHandle>0 ){
4233 pHidden->mHandleIn |= m;
4235 return 1;
4237 return 0;
4241 ** This interface is callable from within the xBestIndex callback only.
4243 ** If possible, set (*ppVal) to point to an object containing the value
4244 ** on the right-hand-side of constraint iCons.
4246 int sqlite3_vtab_rhs_value(
4247 sqlite3_index_info *pIdxInfo, /* Copy of first argument to xBestIndex */
4248 int iCons, /* Constraint for which RHS is wanted */
4249 sqlite3_value **ppVal /* Write value extracted here */
4251 HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
4252 sqlite3_value *pVal = 0;
4253 int rc = SQLITE_OK;
4254 if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
4255 rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */
4256 }else{
4257 if( pH->aRhs[iCons]==0 ){
4258 WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
4259 rc = sqlite3ValueFromExpr(
4260 pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
4261 SQLITE_AFF_BLOB, &pH->aRhs[iCons]
4263 testcase( rc!=SQLITE_OK );
4265 pVal = pH->aRhs[iCons];
4267 *ppVal = pVal;
4269 if( rc==SQLITE_OK && pVal==0 ){ /* IMP: R-19933-32160 */
4270 rc = SQLITE_NOTFOUND; /* IMP: R-36424-56542 */
4273 return rc;
4277 ** Return true if ORDER BY clause may be handled as DISTINCT.
4279 int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
4280 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4281 assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
4282 return pHidden->eDistinct;
4286 ** Cause the prepared statement that is associated with a call to
4287 ** xBestIndex to potentially use all schemas. If the statement being
4288 ** prepared is read-only, then just start read transactions on all
4289 ** schemas. But if this is a write operation, start writes on all
4290 ** schemas.
4292 ** This is used by the (built-in) sqlite_dbpage virtual table.
4294 void sqlite3VtabUsesAllSchemas(Parse *pParse){
4295 int nDb = pParse->db->nDb;
4296 int i;
4297 for(i=0; i<nDb; i++){
4298 sqlite3CodeVerifySchema(pParse, i);
4300 if( DbMaskNonZero(pParse->writeMask) ){
4301 for(i=0; i<nDb; i++){
4302 sqlite3BeginWriteOperation(pParse, 0, i);
4308 ** Add all WhereLoop objects for a table of the join identified by
4309 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
4311 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
4312 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
4313 ** entries that occur before the virtual table in the FROM clause and are
4314 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
4315 ** mUnusable mask contains all FROM clause entries that occur after the
4316 ** virtual table and are separated from it by at least one LEFT or
4317 ** CROSS JOIN.
4319 ** For example, if the query were:
4321 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
4323 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
4325 ** All the tables in mPrereq must be scanned before the current virtual
4326 ** table. So any terms for which all prerequisites are satisfied by
4327 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
4328 ** Conversely, all tables in mUnusable must be scanned after the current
4329 ** virtual table, so any terms for which the prerequisites overlap with
4330 ** mUnusable should always be configured as "not-usable" for xBestIndex.
4332 static int whereLoopAddVirtual(
4333 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4334 Bitmask mPrereq, /* Tables that must be scanned before this one */
4335 Bitmask mUnusable /* Tables that must be scanned after this one */
4337 int rc = SQLITE_OK; /* Return code */
4338 WhereInfo *pWInfo; /* WHERE analysis context */
4339 Parse *pParse; /* The parsing context */
4340 WhereClause *pWC; /* The WHERE clause */
4341 SrcItem *pSrc; /* The FROM clause term to search */
4342 sqlite3_index_info *p; /* Object to pass to xBestIndex() */
4343 int nConstraint; /* Number of constraints in p */
4344 int bIn; /* True if plan uses IN(...) operator */
4345 WhereLoop *pNew;
4346 Bitmask mBest; /* Tables used by best possible plan */
4347 u16 mNoOmit;
4348 int bRetry = 0; /* True to retry with LIMIT/OFFSET disabled */
4350 assert( (mPrereq & mUnusable)==0 );
4351 pWInfo = pBuilder->pWInfo;
4352 pParse = pWInfo->pParse;
4353 pWC = pBuilder->pWC;
4354 pNew = pBuilder->pNew;
4355 pSrc = &pWInfo->pTabList->a[pNew->iTab];
4356 assert( IsVirtual(pSrc->pTab) );
4357 p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit);
4358 if( p==0 ) return SQLITE_NOMEM_BKPT;
4359 pNew->rSetup = 0;
4360 pNew->wsFlags = WHERE_VIRTUALTABLE;
4361 pNew->nLTerm = 0;
4362 pNew->u.vtab.needFree = 0;
4363 nConstraint = p->nConstraint;
4364 if( whereLoopResize(pParse->db, pNew, nConstraint) ){
4365 freeIndexInfo(pParse->db, p);
4366 return SQLITE_NOMEM_BKPT;
4369 /* First call xBestIndex() with all constraints usable. */
4370 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
4371 WHERETRACE(0x800, (" VirtualOne: all usable\n"));
4372 rc = whereLoopAddVirtualOne(
4373 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry
4375 if( bRetry ){
4376 assert( rc==SQLITE_OK );
4377 rc = whereLoopAddVirtualOne(
4378 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0
4382 /* If the call to xBestIndex() with all terms enabled produced a plan
4383 ** that does not require any source tables (IOW: a plan with mBest==0)
4384 ** and does not use an IN(...) operator, then there is no point in making
4385 ** any further calls to xBestIndex() since they will all return the same
4386 ** result (if the xBestIndex() implementation is sane). */
4387 if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
4388 int seenZero = 0; /* True if a plan with no prereqs seen */
4389 int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
4390 Bitmask mPrev = 0;
4391 Bitmask mBestNoIn = 0;
4393 /* If the plan produced by the earlier call uses an IN(...) term, call
4394 ** xBestIndex again, this time with IN(...) terms disabled. */
4395 if( bIn ){
4396 WHERETRACE(0x800, (" VirtualOne: all usable w/o IN\n"));
4397 rc = whereLoopAddVirtualOne(
4398 pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0);
4399 assert( bIn==0 );
4400 mBestNoIn = pNew->prereq & ~mPrereq;
4401 if( mBestNoIn==0 ){
4402 seenZero = 1;
4403 seenZeroNoIN = 1;
4407 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
4408 ** in the set of terms that apply to the current virtual table. */
4409 while( rc==SQLITE_OK ){
4410 int i;
4411 Bitmask mNext = ALLBITS;
4412 assert( mNext>0 );
4413 for(i=0; i<nConstraint; i++){
4414 Bitmask mThis = (
4415 pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
4417 if( mThis>mPrev && mThis<mNext ) mNext = mThis;
4419 mPrev = mNext;
4420 if( mNext==ALLBITS ) break;
4421 if( mNext==mBest || mNext==mBestNoIn ) continue;
4422 WHERETRACE(0x800, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
4423 (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
4424 rc = whereLoopAddVirtualOne(
4425 pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn, 0);
4426 if( pNew->prereq==mPrereq ){
4427 seenZero = 1;
4428 if( bIn==0 ) seenZeroNoIN = 1;
4432 /* If the calls to xBestIndex() in the above loop did not find a plan
4433 ** that requires no source tables at all (i.e. one guaranteed to be
4434 ** usable), make a call here with all source tables disabled */
4435 if( rc==SQLITE_OK && seenZero==0 ){
4436 WHERETRACE(0x800, (" VirtualOne: all disabled\n"));
4437 rc = whereLoopAddVirtualOne(
4438 pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0);
4439 if( bIn==0 ) seenZeroNoIN = 1;
4442 /* If the calls to xBestIndex() have so far failed to find a plan
4443 ** that requires no source tables at all and does not use an IN(...)
4444 ** operator, make a final call to obtain one here. */
4445 if( rc==SQLITE_OK && seenZeroNoIN==0 ){
4446 WHERETRACE(0x800, (" VirtualOne: all disabled and w/o IN\n"));
4447 rc = whereLoopAddVirtualOne(
4448 pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
4452 if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
4453 freeIndexInfo(pParse->db, p);
4454 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
4455 return rc;
4457 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4460 ** Add WhereLoop entries to handle OR terms. This works for either
4461 ** btrees or virtual tables.
4463 static int whereLoopAddOr(
4464 WhereLoopBuilder *pBuilder,
4465 Bitmask mPrereq,
4466 Bitmask mUnusable
4468 WhereInfo *pWInfo = pBuilder->pWInfo;
4469 WhereClause *pWC;
4470 WhereLoop *pNew;
4471 WhereTerm *pTerm, *pWCEnd;
4472 int rc = SQLITE_OK;
4473 int iCur;
4474 WhereClause tempWC;
4475 WhereLoopBuilder sSubBuild;
4476 WhereOrSet sSum, sCur;
4477 SrcItem *pItem;
4479 pWC = pBuilder->pWC;
4480 pWCEnd = pWC->a + pWC->nTerm;
4481 pNew = pBuilder->pNew;
4482 memset(&sSum, 0, sizeof(sSum));
4483 pItem = pWInfo->pTabList->a + pNew->iTab;
4484 iCur = pItem->iCursor;
4486 /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
4487 if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK;
4489 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4490 if( (pTerm->eOperator & WO_OR)!=0
4491 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4493 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4494 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4495 WhereTerm *pOrTerm;
4496 int once = 1;
4497 int i, j;
4499 sSubBuild = *pBuilder;
4500 sSubBuild.pOrSet = &sCur;
4502 WHERETRACE(0x400, ("Begin processing OR-clause %p\n", pTerm));
4503 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
4504 if( (pOrTerm->eOperator & WO_AND)!=0 ){
4505 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4506 }else if( pOrTerm->leftCursor==iCur ){
4507 tempWC.pWInfo = pWC->pWInfo;
4508 tempWC.pOuter = pWC;
4509 tempWC.op = TK_AND;
4510 tempWC.nTerm = 1;
4511 tempWC.nBase = 1;
4512 tempWC.a = pOrTerm;
4513 sSubBuild.pWC = &tempWC;
4514 }else{
4515 continue;
4517 sCur.n = 0;
4518 #ifdef WHERETRACE_ENABLED
4519 WHERETRACE(0x400, ("OR-term %d of %p has %d subterms:\n",
4520 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
4521 if( sqlite3WhereTrace & 0x20000 ){
4522 sqlite3WhereClausePrint(sSubBuild.pWC);
4524 #endif
4525 #ifndef SQLITE_OMIT_VIRTUALTABLE
4526 if( IsVirtual(pItem->pTab) ){
4527 rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
4528 }else
4529 #endif
4531 rc = whereLoopAddBtree(&sSubBuild, mPrereq);
4533 if( rc==SQLITE_OK ){
4534 rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
4536 testcase( rc==SQLITE_NOMEM && sCur.n>0 );
4537 testcase( rc==SQLITE_DONE );
4538 if( sCur.n==0 ){
4539 sSum.n = 0;
4540 break;
4541 }else if( once ){
4542 whereOrMove(&sSum, &sCur);
4543 once = 0;
4544 }else{
4545 WhereOrSet sPrev;
4546 whereOrMove(&sPrev, &sSum);
4547 sSum.n = 0;
4548 for(i=0; i<sPrev.n; i++){
4549 for(j=0; j<sCur.n; j++){
4550 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4551 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4552 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4557 pNew->nLTerm = 1;
4558 pNew->aLTerm[0] = pTerm;
4559 pNew->wsFlags = WHERE_MULTI_OR;
4560 pNew->rSetup = 0;
4561 pNew->iSortIdx = 0;
4562 memset(&pNew->u, 0, sizeof(pNew->u));
4563 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
4564 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
4565 ** of all sub-scans required by the OR-scan. However, due to rounding
4566 ** errors, it may be that the cost of the OR-scan is equal to its
4567 ** most expensive sub-scan. Add the smallest possible penalty
4568 ** (equivalent to multiplying the cost by 1.07) to ensure that
4569 ** this does not happen. Otherwise, for WHERE clauses such as the
4570 ** following where there is an index on "y":
4572 ** WHERE likelihood(x=?, 0.99) OR y=?
4574 ** the planner may elect to "OR" together a full-table scan and an
4575 ** index lookup. And other similarly odd results. */
4576 pNew->rRun = sSum.a[i].rRun + 1;
4577 pNew->nOut = sSum.a[i].nOut;
4578 pNew->prereq = sSum.a[i].prereq;
4579 rc = whereLoopInsert(pBuilder, pNew);
4581 WHERETRACE(0x400, ("End processing OR-clause %p\n", pTerm));
4584 return rc;
4588 ** Add all WhereLoop objects for all tables
4590 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
4591 WhereInfo *pWInfo = pBuilder->pWInfo;
4592 Bitmask mPrereq = 0;
4593 Bitmask mPrior = 0;
4594 int iTab;
4595 SrcList *pTabList = pWInfo->pTabList;
4596 SrcItem *pItem;
4597 SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
4598 sqlite3 *db = pWInfo->pParse->db;
4599 int rc = SQLITE_OK;
4600 int bFirstPastRJ = 0;
4601 int hasRightJoin = 0;
4602 WhereLoop *pNew;
4605 /* Loop over the tables in the join, from left to right */
4606 pNew = pBuilder->pNew;
4608 /* Verify that pNew has already been initialized */
4609 assert( pNew->nLTerm==0 );
4610 assert( pNew->wsFlags==0 );
4611 assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) );
4612 assert( pNew->aLTerm!=0 );
4614 pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
4615 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
4616 Bitmask mUnusable = 0;
4617 pNew->iTab = iTab;
4618 pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
4619 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
4620 if( bFirstPastRJ
4621 || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0
4623 /* Add prerequisites to prevent reordering of FROM clause terms
4624 ** across CROSS joins and outer joins. The bFirstPastRJ boolean
4625 ** prevents the right operand of a RIGHT JOIN from being swapped with
4626 ** other elements even further to the right.
4628 ** The JT_LTORJ case and the hasRightJoin flag work together to
4629 ** prevent FROM-clause terms from moving from the right side of
4630 ** a LEFT JOIN over to the left side of that join if the LEFT JOIN
4631 ** is itself on the left side of a RIGHT JOIN.
4633 if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1;
4634 mPrereq |= mPrior;
4635 bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0;
4636 }else if( !hasRightJoin ){
4637 mPrereq = 0;
4639 #ifndef SQLITE_OMIT_VIRTUALTABLE
4640 if( IsVirtual(pItem->pTab) ){
4641 SrcItem *p;
4642 for(p=&pItem[1]; p<pEnd; p++){
4643 if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
4644 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
4647 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
4648 }else
4649 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4651 rc = whereLoopAddBtree(pBuilder, mPrereq);
4653 if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
4654 rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
4656 mPrior |= pNew->maskSelf;
4657 if( rc || db->mallocFailed ){
4658 if( rc==SQLITE_DONE ){
4659 /* We hit the query planner search limit set by iPlanLimit */
4660 sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
4661 rc = SQLITE_OK;
4662 }else{
4663 break;
4668 whereLoopClear(db, pNew);
4669 return rc;
4673 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
4674 ** parameters) to see if it outputs rows in the requested ORDER BY
4675 ** (or GROUP BY) without requiring a separate sort operation. Return N:
4677 ** N>0: N terms of the ORDER BY clause are satisfied
4678 ** N==0: No terms of the ORDER BY clause are satisfied
4679 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
4681 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4682 ** strict. With GROUP BY and DISTINCT the only requirement is that
4683 ** equivalent rows appear immediately adjacent to one another. GROUP BY
4684 ** and DISTINCT do not require rows to appear in any particular order as long
4685 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
4686 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
4687 ** pOrderBy terms must be matched in strict left-to-right order.
4689 static i8 wherePathSatisfiesOrderBy(
4690 WhereInfo *pWInfo, /* The WHERE clause */
4691 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
4692 WherePath *pPath, /* The WherePath to check */
4693 u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
4694 u16 nLoop, /* Number of entries in pPath->aLoop[] */
4695 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
4696 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
4698 u8 revSet; /* True if rev is known */
4699 u8 rev; /* Composite sort order */
4700 u8 revIdx; /* Index sort order */
4701 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4702 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4703 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
4704 u16 eqOpMask; /* Allowed equality operators */
4705 u16 nKeyCol; /* Number of key columns in pIndex */
4706 u16 nColumn; /* Total number of ordered columns in the index */
4707 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4708 int iLoop; /* Index of WhereLoop in pPath being processed */
4709 int i, j; /* Loop counters */
4710 int iCur; /* Cursor number for current WhereLoop */
4711 int iColumn; /* A column number within table iCur */
4712 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
4713 WhereTerm *pTerm; /* A single term of the WHERE clause */
4714 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4715 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4716 Index *pIndex; /* The index associated with pLoop */
4717 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4718 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4719 Bitmask obDone; /* Mask of all ORDER BY terms */
4720 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
4721 Bitmask ready; /* Mask of inner loops */
4724 ** We say the WhereLoop is "one-row" if it generates no more than one
4725 ** row of output. A WhereLoop is one-row if all of the following are true:
4726 ** (a) All index columns match with WHERE_COLUMN_EQ.
4727 ** (b) The index is unique
4728 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4729 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
4731 ** We say the WhereLoop is "order-distinct" if the set of columns from
4732 ** that WhereLoop that are in the ORDER BY clause are different for every
4733 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4734 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4735 ** is not order-distinct. To be order-distinct is not quite the same as being
4736 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4737 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4738 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4740 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4741 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4742 ** automatically order-distinct.
4745 assert( pOrderBy!=0 );
4746 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
4748 nOrderBy = pOrderBy->nExpr;
4749 testcase( nOrderBy==BMS-1 );
4750 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4751 isOrderDistinct = 1;
4752 obDone = MASKBIT(nOrderBy)-1;
4753 orderDistinctMask = 0;
4754 ready = 0;
4755 eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
4756 if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
4757 eqOpMask |= WO_IN;
4759 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
4760 if( iLoop>0 ) ready |= pLoop->maskSelf;
4761 if( iLoop<nLoop ){
4762 pLoop = pPath->aLoop[iLoop];
4763 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
4764 }else{
4765 pLoop = pLast;
4767 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
4768 if( pLoop->u.vtab.isOrdered
4769 && ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY)
4771 obSat = obDone;
4773 break;
4774 }else if( wctrlFlags & WHERE_DISTINCTBY ){
4775 pLoop->u.btree.nDistinctCol = 0;
4777 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
4779 /* Mark off any ORDER BY term X that is a column in the table of
4780 ** the current loop for which there is term in the WHERE
4781 ** clause of the form X IS NULL or X=? that reference only outer
4782 ** loops.
4784 for(i=0; i<nOrderBy; i++){
4785 if( MASKBIT(i) & obSat ) continue;
4786 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4787 if( NEVER(pOBExpr==0) ) continue;
4788 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4789 if( pOBExpr->iTable!=iCur ) continue;
4790 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4791 ~ready, eqOpMask, 0);
4792 if( pTerm==0 ) continue;
4793 if( pTerm->eOperator==WO_IN ){
4794 /* IN terms are only valid for sorting in the ORDER BY LIMIT
4795 ** optimization, and then only if they are actually used
4796 ** by the query plan */
4797 assert( wctrlFlags &
4798 (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
4799 for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
4800 if( j>=pLoop->nLTerm ) continue;
4802 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
4803 Parse *pParse = pWInfo->pParse;
4804 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
4805 CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
4806 assert( pColl1 );
4807 if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
4808 continue;
4810 testcase( pTerm->pExpr->op==TK_IS );
4812 obSat |= MASKBIT(i);
4815 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4816 if( pLoop->wsFlags & WHERE_IPK ){
4817 pIndex = 0;
4818 nKeyCol = 0;
4819 nColumn = 1;
4820 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
4821 return 0;
4822 }else{
4823 nKeyCol = pIndex->nKeyCol;
4824 nColumn = pIndex->nColumn;
4825 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4826 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
4827 || !HasRowid(pIndex->pTable));
4828 /* All relevant terms of the index must also be non-NULL in order
4829 ** for isOrderDistinct to be true. So the isOrderDistint value
4830 ** computed here might be a false positive. Corrections will be
4831 ** made at tag-20210426-1 below */
4832 isOrderDistinct = IsUniqueIndex(pIndex)
4833 && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
4836 /* Loop through all columns of the index and deal with the ones
4837 ** that are not constrained by == or IN.
4839 rev = revSet = 0;
4840 distinctColumns = 0;
4841 for(j=0; j<nColumn; j++){
4842 u8 bOnce = 1; /* True to run the ORDER BY search loop */
4844 assert( j>=pLoop->u.btree.nEq
4845 || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
4847 if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
4848 u16 eOp = pLoop->aLTerm[j]->eOperator;
4850 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
4851 ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL
4852 ** terms imply that the index is not UNIQUE NOT NULL in which case
4853 ** the loop need to be marked as not order-distinct because it can
4854 ** have repeated NULL rows.
4856 ** If the current term is a column of an ((?,?) IN (SELECT...))
4857 ** expression for which the SELECT returns more than one column,
4858 ** check that it is the only column used by this loop. Otherwise,
4859 ** if it is one of two or more, none of the columns can be
4860 ** considered to match an ORDER BY term.
4862 if( (eOp & eqOpMask)!=0 ){
4863 if( eOp & (WO_ISNULL|WO_IS) ){
4864 testcase( eOp & WO_ISNULL );
4865 testcase( eOp & WO_IS );
4866 testcase( isOrderDistinct );
4867 isOrderDistinct = 0;
4869 continue;
4870 }else if( ALWAYS(eOp & WO_IN) ){
4871 /* ALWAYS() justification: eOp is an equality operator due to the
4872 ** j<pLoop->u.btree.nEq constraint above. Any equality other
4873 ** than WO_IN is captured by the previous "if". So this one
4874 ** always has to be WO_IN. */
4875 Expr *pX = pLoop->aLTerm[j]->pExpr;
4876 for(i=j+1; i<pLoop->u.btree.nEq; i++){
4877 if( pLoop->aLTerm[i]->pExpr==pX ){
4878 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
4879 bOnce = 0;
4880 break;
4886 /* Get the column number in the table (iColumn) and sort order
4887 ** (revIdx) for the j-th column of the index.
4889 if( pIndex ){
4890 iColumn = pIndex->aiColumn[j];
4891 revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
4892 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
4893 }else{
4894 iColumn = XN_ROWID;
4895 revIdx = 0;
4898 /* An unconstrained column that might be NULL means that this
4899 ** WhereLoop is not well-ordered. tag-20210426-1
4901 if( isOrderDistinct ){
4902 if( iColumn>=0
4903 && j>=pLoop->u.btree.nEq
4904 && pIndex->pTable->aCol[iColumn].notNull==0
4906 isOrderDistinct = 0;
4908 if( iColumn==XN_EXPR ){
4909 isOrderDistinct = 0;
4913 /* Find the ORDER BY term that corresponds to the j-th column
4914 ** of the index and mark that ORDER BY term off
4916 isMatch = 0;
4917 for(i=0; bOnce && i<nOrderBy; i++){
4918 if( MASKBIT(i) & obSat ) continue;
4919 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4920 testcase( wctrlFlags & WHERE_GROUPBY );
4921 testcase( wctrlFlags & WHERE_DISTINCTBY );
4922 if( NEVER(pOBExpr==0) ) continue;
4923 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
4924 if( iColumn>=XN_ROWID ){
4925 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4926 if( pOBExpr->iTable!=iCur ) continue;
4927 if( pOBExpr->iColumn!=iColumn ) continue;
4928 }else{
4929 Expr *pIxExpr = pIndex->aColExpr->a[j].pExpr;
4930 if( sqlite3ExprCompareSkip(pOBExpr, pIxExpr, iCur) ){
4931 continue;
4934 if( iColumn!=XN_ROWID ){
4935 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4936 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4938 if( wctrlFlags & WHERE_DISTINCTBY ){
4939 pLoop->u.btree.nDistinctCol = j+1;
4941 isMatch = 1;
4942 break;
4944 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
4945 /* Make sure the sort order is compatible in an ORDER BY clause.
4946 ** Sort order is irrelevant for a GROUP BY clause. */
4947 if( revSet ){
4948 if( (rev ^ revIdx)
4949 != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC)
4951 isMatch = 0;
4953 }else{
4954 rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC);
4955 if( rev ) *pRevMask |= MASKBIT(iLoop);
4956 revSet = 1;
4959 if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){
4960 if( j==pLoop->u.btree.nEq ){
4961 pLoop->wsFlags |= WHERE_BIGNULL_SORT;
4962 }else{
4963 isMatch = 0;
4966 if( isMatch ){
4967 if( iColumn==XN_ROWID ){
4968 testcase( distinctColumns==0 );
4969 distinctColumns = 1;
4971 obSat |= MASKBIT(i);
4972 }else{
4973 /* No match found */
4974 if( j==0 || j<nKeyCol ){
4975 testcase( isOrderDistinct!=0 );
4976 isOrderDistinct = 0;
4978 break;
4980 } /* end Loop over all index columns */
4981 if( distinctColumns ){
4982 testcase( isOrderDistinct==0 );
4983 isOrderDistinct = 1;
4985 } /* end-if not one-row */
4987 /* Mark off any other ORDER BY terms that reference pLoop */
4988 if( isOrderDistinct ){
4989 orderDistinctMask |= pLoop->maskSelf;
4990 for(i=0; i<nOrderBy; i++){
4991 Expr *p;
4992 Bitmask mTerm;
4993 if( MASKBIT(i) & obSat ) continue;
4994 p = pOrderBy->a[i].pExpr;
4995 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
4996 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
4997 if( (mTerm&~orderDistinctMask)==0 ){
4998 obSat |= MASKBIT(i);
5002 } /* End the loop over all WhereLoops from outer-most down to inner-most */
5003 if( obSat==obDone ) return (i8)nOrderBy;
5004 if( !isOrderDistinct ){
5005 for(i=nOrderBy-1; i>0; i--){
5006 Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
5007 if( (obSat&m)==m ) return i;
5009 return 0;
5011 return -1;
5016 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5017 ** the planner assumes that the specified pOrderBy list is actually a GROUP
5018 ** BY clause - and so any order that groups rows as required satisfies the
5019 ** request.
5021 ** Normally, in this case it is not possible for the caller to determine
5022 ** whether or not the rows are really being delivered in sorted order, or
5023 ** just in some other order that provides the required grouping. However,
5024 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5025 ** this function may be called on the returned WhereInfo object. It returns
5026 ** true if the rows really will be sorted in the specified order, or false
5027 ** otherwise.
5029 ** For example, assuming:
5031 ** CREATE INDEX i1 ON t1(x, Y);
5033 ** then
5035 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5036 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5038 int sqlite3WhereIsSorted(WhereInfo *pWInfo){
5039 assert( pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) );
5040 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
5041 return pWInfo->sorted;
5044 #ifdef WHERETRACE_ENABLED
5045 /* For debugging use only: */
5046 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5047 static char zName[65];
5048 int i;
5049 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5050 if( pLast ) zName[i++] = pLast->cId;
5051 zName[i] = 0;
5052 return zName;
5054 #endif
5057 ** Return the cost of sorting nRow rows, assuming that the keys have
5058 ** nOrderby columns and that the first nSorted columns are already in
5059 ** order.
5061 static LogEst whereSortingCost(
5062 WhereInfo *pWInfo, /* Query planning context */
5063 LogEst nRow, /* Estimated number of rows to sort */
5064 int nOrderBy, /* Number of ORDER BY clause terms */
5065 int nSorted /* Number of initial ORDER BY terms naturally in order */
5067 /* Estimated cost of a full external sort, where N is
5068 ** the number of rows to sort is:
5070 ** cost = (K * N * log(N)).
5072 ** Or, if the order-by clause has X terms but only the last Y
5073 ** terms are out of order, then block-sorting will reduce the
5074 ** sorting cost to:
5076 ** cost = (K * N * log(N)) * (Y/X)
5078 ** The constant K is at least 2.0 but will be larger if there are a
5079 ** large number of columns to be sorted, as the sorting time is
5080 ** proportional to the amount of content to be sorted. The algorithm
5081 ** does not currently distinguish between fat columns (BLOBs and TEXTs)
5082 ** and skinny columns (INTs). It just uses the number of columns as
5083 ** an approximation for the row width.
5085 ** And extra factor of 2.0 or 3.0 is added to the sorting cost if the sort
5086 ** is built using OP_IdxInsert and OP_Sort rather than with OP_SorterInsert.
5088 LogEst rSortCost, nCol;
5089 assert( pWInfo->pSelect!=0 );
5090 assert( pWInfo->pSelect->pEList!=0 );
5091 /* TUNING: sorting cost proportional to the number of output columns: */
5092 nCol = sqlite3LogEst((pWInfo->pSelect->pEList->nExpr+59)/30);
5093 rSortCost = nRow + nCol;
5094 if( nSorted>0 ){
5095 /* Scale the result by (Y/X) */
5096 rSortCost += sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
5099 /* Multiple by log(M) where M is the number of output rows.
5100 ** Use the LIMIT for M if it is smaller. Or if this sort is for
5101 ** a DISTINCT operator, M will be the number of distinct output
5102 ** rows, so fudge it downwards a bit.
5104 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 ){
5105 rSortCost += 10; /* TUNING: Extra 2.0x if using LIMIT */
5106 if( nSorted!=0 ){
5107 rSortCost += 6; /* TUNING: Extra 1.5x if also using partial sort */
5109 if( pWInfo->iLimit<nRow ){
5110 nRow = pWInfo->iLimit;
5112 }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
5113 /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
5114 ** reduces the number of output rows by a factor of 2 */
5115 if( nRow>10 ){ nRow -= 10; assert( 10==sqlite3LogEst(2) ); }
5117 rSortCost += estLog(nRow);
5118 return rSortCost;
5122 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
5123 ** attempts to find the lowest cost path that visits each WhereLoop
5124 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5126 ** Assume that the total number of output rows that will need to be sorted
5127 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5128 ** costs if nRowEst==0.
5130 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5131 ** error occurs.
5133 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
5134 int mxChoice; /* Maximum number of simultaneous paths tracked */
5135 int nLoop; /* Number of terms in the join */
5136 Parse *pParse; /* Parsing context */
5137 int iLoop; /* Loop counter over the terms of the join */
5138 int ii, jj; /* Loop counters */
5139 int mxI = 0; /* Index of next entry to replace */
5140 int nOrderBy; /* Number of ORDER BY clause terms */
5141 LogEst mxCost = 0; /* Maximum cost of a set of paths */
5142 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
5143 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5144 WherePath *aFrom; /* All nFrom paths at the previous level */
5145 WherePath *aTo; /* The nTo best paths at the current level */
5146 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5147 WherePath *pTo; /* An element of aTo[] that we are working on */
5148 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5149 WhereLoop **pX; /* Used to divy up the pSpace memory */
5150 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
5151 char *pSpace; /* Temporary memory used by this routine */
5152 int nSpace; /* Bytes of space allocated at pSpace */
5154 pParse = pWInfo->pParse;
5155 nLoop = pWInfo->nLevel;
5156 /* TUNING: For simple queries, only the best path is tracked.
5157 ** For 2-way joins, the 5 best paths are followed.
5158 ** For joins of 3 or more tables, track the 10 best paths */
5159 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
5160 assert( nLoop<=pWInfo->pTabList->nSrc );
5161 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d, nQueryLoop=%d)\n",
5162 nRowEst, pParse->nQueryLoop));
5164 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5165 ** case the purpose of this call is to estimate the number of rows returned
5166 ** by the overall query. Once this estimate has been obtained, the caller
5167 ** will invoke this function a second time, passing the estimate as the
5168 ** nRowEst parameter. */
5169 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5170 nOrderBy = 0;
5171 }else{
5172 nOrderBy = pWInfo->pOrderBy->nExpr;
5175 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
5176 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5177 nSpace += sizeof(LogEst) * nOrderBy;
5178 pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace);
5179 if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
5180 aTo = (WherePath*)pSpace;
5181 aFrom = aTo+mxChoice;
5182 memset(aFrom, 0, sizeof(aFrom[0]));
5183 pX = (WhereLoop**)(aFrom+mxChoice);
5184 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
5185 pFrom->aLoop = pX;
5187 if( nOrderBy ){
5188 /* If there is an ORDER BY clause and it is not being ignored, set up
5189 ** space for the aSortCost[] array. Each element of the aSortCost array
5190 ** is either zero - meaning it has not yet been initialized - or the
5191 ** cost of sorting nRowEst rows of data where the first X terms of
5192 ** the ORDER BY clause are already in order, where X is the array
5193 ** index. */
5194 aSortCost = (LogEst*)pX;
5195 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
5197 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
5198 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
5200 /* Seed the search with a single WherePath containing zero WhereLoops.
5202 ** TUNING: Do not let the number of iterations go above 28. If the cost
5203 ** of computing an automatic index is not paid back within the first 28
5204 ** rows, then do not use the automatic index. */
5205 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
5206 nFrom = 1;
5207 assert( aFrom[0].isOrdered==0 );
5208 if( nOrderBy ){
5209 /* If nLoop is zero, then there are no FROM terms in the query. Since
5210 ** in this case the query may return a maximum of one row, the results
5211 ** are already in the requested order. Set isOrdered to nOrderBy to
5212 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
5213 ** -1, indicating that the result set may or may not be ordered,
5214 ** depending on the loops added to the current plan. */
5215 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
5218 /* Compute successively longer WherePaths using the previous generation
5219 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5220 ** best paths at each generation */
5221 for(iLoop=0; iLoop<nLoop; iLoop++){
5222 nTo = 0;
5223 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5224 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5225 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
5226 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
5227 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
5228 i8 isOrdered; /* isOrdered for (pFrom+pWLoop) */
5229 Bitmask maskNew; /* Mask of src visited by (..) */
5230 Bitmask revMask; /* Mask of rev-order loops for (..) */
5232 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5233 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
5234 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
5235 /* Do not use an automatic index if the this loop is expected
5236 ** to run less than 1.25 times. It is tempting to also exclude
5237 ** automatic index usage on an outer loop, but sometimes an automatic
5238 ** index is useful in the outer loop of a correlated subquery. */
5239 assert( 10==sqlite3LogEst(2) );
5240 continue;
5243 /* At this point, pWLoop is a candidate to be the next loop.
5244 ** Compute its cost */
5245 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5246 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
5247 nOut = pFrom->nRow + pWLoop->nOut;
5248 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
5249 isOrdered = pFrom->isOrdered;
5250 if( isOrdered<0 ){
5251 revMask = 0;
5252 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
5253 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
5254 iLoop, pWLoop, &revMask);
5255 }else{
5256 revMask = pFrom->revLoop;
5258 if( isOrdered>=0 && isOrdered<nOrderBy ){
5259 if( aSortCost[isOrdered]==0 ){
5260 aSortCost[isOrdered] = whereSortingCost(
5261 pWInfo, nRowEst, nOrderBy, isOrdered
5264 /* TUNING: Add a small extra penalty (3) to sorting as an
5265 ** extra encouragement to the query planner to select a plan
5266 ** where the rows emerge in the correct order without any sorting
5267 ** required. */
5268 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 3;
5270 WHERETRACE(0x002,
5271 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5272 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
5273 rUnsorted, rCost));
5274 }else{
5275 rCost = rUnsorted;
5276 rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
5279 /* Check to see if pWLoop should be added to the set of
5280 ** mxChoice best-so-far paths.
5282 ** First look for an existing path among best-so-far paths
5283 ** that covers the same set of loops and has the same isOrdered
5284 ** setting as the current path candidate.
5286 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
5287 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
5288 ** of legal values for isOrdered, -1..64.
5290 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5291 if( pTo->maskLoop==maskNew
5292 && ((pTo->isOrdered^isOrdered)&0x80)==0
5294 testcase( jj==nTo-1 );
5295 break;
5298 if( jj>=nTo ){
5299 /* None of the existing best-so-far paths match the candidate. */
5300 if( nTo>=mxChoice
5301 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
5303 /* The current candidate is no better than any of the mxChoice
5304 ** paths currently in the best-so-far buffer. So discard
5305 ** this candidate as not viable. */
5306 #ifdef WHERETRACE_ENABLED /* 0x4 */
5307 if( sqlite3WhereTrace&0x4 ){
5308 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
5309 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5310 isOrdered>=0 ? isOrdered+'0' : '?');
5312 #endif
5313 continue;
5315 /* If we reach this points it means that the new candidate path
5316 ** needs to be added to the set of best-so-far paths. */
5317 if( nTo<mxChoice ){
5318 /* Increase the size of the aTo set by one */
5319 jj = nTo++;
5320 }else{
5321 /* New path replaces the prior worst to keep count below mxChoice */
5322 jj = mxI;
5324 pTo = &aTo[jj];
5325 #ifdef WHERETRACE_ENABLED /* 0x4 */
5326 if( sqlite3WhereTrace&0x4 ){
5327 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
5328 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5329 isOrdered>=0 ? isOrdered+'0' : '?');
5331 #endif
5332 }else{
5333 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
5334 ** same set of loops and has the same isOrdered setting as the
5335 ** candidate path. Check to see if the candidate should replace
5336 ** pTo or if the candidate should be skipped.
5338 ** The conditional is an expanded vector comparison equivalent to:
5339 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
5341 if( pTo->rCost<rCost
5342 || (pTo->rCost==rCost
5343 && (pTo->nRow<nOut
5344 || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
5348 #ifdef WHERETRACE_ENABLED /* 0x4 */
5349 if( sqlite3WhereTrace&0x4 ){
5350 sqlite3DebugPrintf(
5351 "Skip %s cost=%-3d,%3d,%3d order=%c",
5352 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5353 isOrdered>=0 ? isOrdered+'0' : '?');
5354 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
5355 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5356 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5358 #endif
5359 /* Discard the candidate path from further consideration */
5360 testcase( pTo->rCost==rCost );
5361 continue;
5363 testcase( pTo->rCost==rCost+1 );
5364 /* Control reaches here if the candidate path is better than the
5365 ** pTo path. Replace pTo with the candidate. */
5366 #ifdef WHERETRACE_ENABLED /* 0x4 */
5367 if( sqlite3WhereTrace&0x4 ){
5368 sqlite3DebugPrintf(
5369 "Update %s cost=%-3d,%3d,%3d order=%c",
5370 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5371 isOrdered>=0 ? isOrdered+'0' : '?');
5372 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
5373 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5374 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5376 #endif
5378 /* pWLoop is a winner. Add it to the set of best so far */
5379 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
5380 pTo->revLoop = revMask;
5381 pTo->nRow = nOut;
5382 pTo->rCost = rCost;
5383 pTo->rUnsorted = rUnsorted;
5384 pTo->isOrdered = isOrdered;
5385 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5386 pTo->aLoop[iLoop] = pWLoop;
5387 if( nTo>=mxChoice ){
5388 mxI = 0;
5389 mxCost = aTo[0].rCost;
5390 mxUnsorted = aTo[0].nRow;
5391 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5392 if( pTo->rCost>mxCost
5393 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
5395 mxCost = pTo->rCost;
5396 mxUnsorted = pTo->rUnsorted;
5397 mxI = jj;
5404 #ifdef WHERETRACE_ENABLED /* >=2 */
5405 if( sqlite3WhereTrace & 0x02 ){
5406 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
5407 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
5408 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
5409 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5410 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
5411 if( pTo->isOrdered>0 ){
5412 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5413 }else{
5414 sqlite3DebugPrintf("\n");
5418 #endif
5420 /* Swap the roles of aFrom and aTo for the next generation */
5421 pFrom = aTo;
5422 aTo = aFrom;
5423 aFrom = pFrom;
5424 nFrom = nTo;
5427 if( nFrom==0 ){
5428 sqlite3ErrorMsg(pParse, "no query solution");
5429 sqlite3StackFreeNN(pParse->db, pSpace);
5430 return SQLITE_ERROR;
5433 /* Find the lowest cost path. pFrom will be left pointing to that path */
5434 pFrom = aFrom;
5435 for(ii=1; ii<nFrom; ii++){
5436 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5438 assert( pWInfo->nLevel==nLoop );
5439 /* Load the lowest cost path into pWInfo */
5440 for(iLoop=0; iLoop<nLoop; iLoop++){
5441 WhereLevel *pLevel = pWInfo->a + iLoop;
5442 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
5443 pLevel->iFrom = pWLoop->iTab;
5444 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
5446 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5447 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5448 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
5449 && nRowEst
5451 Bitmask notUsed;
5452 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
5453 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
5454 if( rc==pWInfo->pResultSet->nExpr ){
5455 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5458 pWInfo->bOrderedInnerLoop = 0;
5459 if( pWInfo->pOrderBy ){
5460 pWInfo->nOBSat = pFrom->isOrdered;
5461 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5462 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
5463 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5465 if( pWInfo->pSelect->pOrderBy
5466 && pWInfo->nOBSat > pWInfo->pSelect->pOrderBy->nExpr ){
5467 pWInfo->nOBSat = pWInfo->pSelect->pOrderBy->nExpr;
5469 }else{
5470 pWInfo->revMask = pFrom->revLoop;
5471 if( pWInfo->nOBSat<=0 ){
5472 pWInfo->nOBSat = 0;
5473 if( nLoop>0 ){
5474 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
5475 if( (wsFlags & WHERE_ONEROW)==0
5476 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
5478 Bitmask m = 0;
5479 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
5480 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
5481 testcase( wsFlags & WHERE_IPK );
5482 testcase( wsFlags & WHERE_COLUMN_IN );
5483 if( rc==pWInfo->pOrderBy->nExpr ){
5484 pWInfo->bOrderedInnerLoop = 1;
5485 pWInfo->revMask = m;
5489 }else if( nLoop
5490 && pWInfo->nOBSat==1
5491 && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
5493 pWInfo->bOrderedInnerLoop = 1;
5496 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
5497 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
5499 Bitmask revMask = 0;
5500 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
5501 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
5503 assert( pWInfo->sorted==0 );
5504 if( nOrder==pWInfo->pOrderBy->nExpr ){
5505 pWInfo->sorted = 1;
5506 pWInfo->revMask = revMask;
5512 pWInfo->nRowOut = pFrom->nRow;
5514 /* Free temporary memory and return success */
5515 sqlite3StackFreeNN(pParse->db, pSpace);
5516 return SQLITE_OK;
5520 ** Most queries use only a single table (they are not joins) and have
5521 ** simple == constraints against indexed fields. This routine attempts
5522 ** to plan those simple cases using much less ceremony than the
5523 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5524 ** times for the common case.
5526 ** Return non-zero on success, if this query can be handled by this
5527 ** no-frills query planner. Return zero if this query needs the
5528 ** general-purpose query planner.
5530 static int whereShortCut(WhereLoopBuilder *pBuilder){
5531 WhereInfo *pWInfo;
5532 SrcItem *pItem;
5533 WhereClause *pWC;
5534 WhereTerm *pTerm;
5535 WhereLoop *pLoop;
5536 int iCur;
5537 int j;
5538 Table *pTab;
5539 Index *pIdx;
5540 WhereScan scan;
5542 pWInfo = pBuilder->pWInfo;
5543 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
5544 assert( pWInfo->pTabList->nSrc>=1 );
5545 pItem = pWInfo->pTabList->a;
5546 pTab = pItem->pTab;
5547 if( IsVirtual(pTab) ) return 0;
5548 if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){
5549 testcase( pItem->fg.isIndexedBy );
5550 testcase( pItem->fg.notIndexed );
5551 return 0;
5553 iCur = pItem->iCursor;
5554 pWC = &pWInfo->sWC;
5555 pLoop = pBuilder->pNew;
5556 pLoop->wsFlags = 0;
5557 pLoop->nSkip = 0;
5558 pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
5559 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5560 if( pTerm ){
5561 testcase( pTerm->eOperator & WO_IS );
5562 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5563 pLoop->aLTerm[0] = pTerm;
5564 pLoop->nLTerm = 1;
5565 pLoop->u.btree.nEq = 1;
5566 /* TUNING: Cost of a rowid lookup is 10 */
5567 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
5568 }else{
5569 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5570 int opMask;
5571 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5572 if( !IsUniqueIndex(pIdx)
5573 || pIdx->pPartIdxWhere!=0
5574 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
5575 ) continue;
5576 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
5577 for(j=0; j<pIdx->nKeyCol; j++){
5578 pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx);
5579 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5580 if( pTerm==0 ) break;
5581 testcase( pTerm->eOperator & WO_IS );
5582 pLoop->aLTerm[j] = pTerm;
5584 if( j!=pIdx->nKeyCol ) continue;
5585 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
5586 if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
5587 pLoop->wsFlags |= WHERE_IDX_ONLY;
5589 pLoop->nLTerm = j;
5590 pLoop->u.btree.nEq = j;
5591 pLoop->u.btree.pIndex = pIdx;
5592 /* TUNING: Cost of a unique index lookup is 15 */
5593 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
5594 break;
5597 if( pLoop->wsFlags ){
5598 pLoop->nOut = (LogEst)1;
5599 pWInfo->a[0].pWLoop = pLoop;
5600 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
5601 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
5602 pWInfo->a[0].iTabCur = iCur;
5603 pWInfo->nRowOut = 1;
5604 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
5605 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5606 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5608 if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
5609 #ifdef SQLITE_DEBUG
5610 pLoop->cId = '0';
5611 #endif
5612 #ifdef WHERETRACE_ENABLED
5613 if( sqlite3WhereTrace & 0x02 ){
5614 sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
5616 #endif
5617 return 1;
5619 return 0;
5623 ** Helper function for exprIsDeterministic().
5625 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
5626 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
5627 pWalker->eCode = 0;
5628 return WRC_Abort;
5630 return WRC_Continue;
5634 ** Return true if the expression contains no non-deterministic SQL
5635 ** functions. Do not consider non-deterministic SQL functions that are
5636 ** part of sub-select statements.
5638 static int exprIsDeterministic(Expr *p){
5639 Walker w;
5640 memset(&w, 0, sizeof(w));
5641 w.eCode = 1;
5642 w.xExprCallback = exprNodeIsDeterministic;
5643 w.xSelectCallback = sqlite3SelectWalkFail;
5644 sqlite3WalkExpr(&w, p);
5645 return w.eCode;
5649 #ifdef WHERETRACE_ENABLED
5651 ** Display all WhereLoops in pWInfo
5653 static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
5654 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
5655 WhereLoop *p;
5656 int i;
5657 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5658 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5659 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5660 p->cId = zLabel[i%(sizeof(zLabel)-1)];
5661 sqlite3WhereLoopPrint(p, pWC);
5665 # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
5666 #else
5667 # define WHERETRACE_ALL_LOOPS(W,C)
5668 #endif
5670 /* Attempt to omit tables from a join that do not affect the result.
5671 ** For a table to not affect the result, the following must be true:
5673 ** 1) The query must not be an aggregate.
5674 ** 2) The table must be the RHS of a LEFT JOIN.
5675 ** 3) Either the query must be DISTINCT, or else the ON or USING clause
5676 ** must contain a constraint that limits the scan of the table to
5677 ** at most a single row.
5678 ** 4) The table must not be referenced by any part of the query apart
5679 ** from its own USING or ON clause.
5680 ** 5) The table must not have an inner-join ON or USING clause if there is
5681 ** a RIGHT JOIN anywhere in the query. Otherwise the ON/USING clause
5682 ** might move from the right side to the left side of the RIGHT JOIN.
5683 ** Note: Due to (2), this condition can only arise if the table is
5684 ** the right-most table of a subquery that was flattened into the
5685 ** main query and that subquery was the right-hand operand of an
5686 ** inner join that held an ON or USING clause.
5688 ** For example, given:
5690 ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
5691 ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
5692 ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
5694 ** then table t2 can be omitted from the following:
5696 ** SELECT v1, v3 FROM t1
5697 ** LEFT JOIN t2 ON (t1.ipk=t2.ipk)
5698 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5700 ** or from:
5702 ** SELECT DISTINCT v1, v3 FROM t1
5703 ** LEFT JOIN t2
5704 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5706 static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
5707 WhereInfo *pWInfo,
5708 Bitmask notReady
5710 int i;
5711 Bitmask tabUsed;
5712 int hasRightJoin;
5714 /* Preconditions checked by the caller */
5715 assert( pWInfo->nLevel>=2 );
5716 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
5718 /* These two preconditions checked by the caller combine to guarantee
5719 ** condition (1) of the header comment */
5720 assert( pWInfo->pResultSet!=0 );
5721 assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
5723 tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
5724 if( pWInfo->pOrderBy ){
5725 tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
5727 hasRightJoin = (pWInfo->pTabList->a[0].fg.jointype & JT_LTORJ)!=0;
5728 for(i=pWInfo->nLevel-1; i>=1; i--){
5729 WhereTerm *pTerm, *pEnd;
5730 SrcItem *pItem;
5731 WhereLoop *pLoop;
5732 pLoop = pWInfo->a[i].pWLoop;
5733 pItem = &pWInfo->pTabList->a[pLoop->iTab];
5734 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
5735 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
5736 && (pLoop->wsFlags & WHERE_ONEROW)==0
5738 continue;
5740 if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
5741 pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
5742 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5743 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5744 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
5745 || pTerm->pExpr->w.iJoin!=pItem->iCursor
5747 break;
5750 if( hasRightJoin
5751 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
5752 && pTerm->pExpr->w.iJoin==pItem->iCursor
5754 break; /* restriction (5) */
5757 if( pTerm<pEnd ) continue;
5758 WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop->cId));
5759 notReady &= ~pLoop->maskSelf;
5760 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5761 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5762 pTerm->wtFlags |= TERM_CODED;
5765 if( i!=pWInfo->nLevel-1 ){
5766 int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
5767 memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
5769 pWInfo->nLevel--;
5770 assert( pWInfo->nLevel>0 );
5772 return notReady;
5776 ** Check to see if there are any SEARCH loops that might benefit from
5777 ** using a Bloom filter. Consider a Bloom filter if:
5779 ** (1) The SEARCH happens more than N times where N is the number
5780 ** of rows in the table that is being considered for the Bloom
5781 ** filter.
5782 ** (2) Some searches are expected to find zero rows. (This is determined
5783 ** by the WHERE_SELFCULL flag on the term.)
5784 ** (3) Bloom-filter processing is not disabled. (Checked by the
5785 ** caller.)
5786 ** (4) The size of the table being searched is known by ANALYZE.
5788 ** This block of code merely checks to see if a Bloom filter would be
5789 ** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
5790 ** WhereLoop. The implementation of the Bloom filter comes further
5791 ** down where the code for each WhereLoop is generated.
5793 static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
5794 const WhereInfo *pWInfo
5796 int i;
5797 LogEst nSearch = 0;
5799 assert( pWInfo->nLevel>=2 );
5800 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
5801 for(i=0; i<pWInfo->nLevel; i++){
5802 WhereLoop *pLoop = pWInfo->a[i].pWLoop;
5803 const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ);
5804 SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
5805 Table *pTab = pItem->pTab;
5806 if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
5807 pTab->tabFlags |= TF_StatsUsed;
5808 if( i>=1
5809 && (pLoop->wsFlags & reqFlags)==reqFlags
5810 /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
5811 && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
5813 if( nSearch > pTab->nRowLogEst ){
5814 testcase( pItem->fg.jointype & JT_LEFT );
5815 pLoop->wsFlags |= WHERE_BLOOMFILTER;
5816 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
5817 WHERETRACE(0xffffffff, (
5818 "-> use Bloom-filter on loop %c because there are ~%.1e "
5819 "lookups into %s which has only ~%.1e rows\n",
5820 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
5821 (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
5824 nSearch += pLoop->nOut;
5829 ** The index pIdx is used by a query and contains one or more expressions.
5830 ** In other words pIdx is an index on an expression. iIdxCur is the cursor
5831 ** number for the index and iDataCur is the cursor number for the corresponding
5832 ** table.
5834 ** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for
5835 ** each of the expressions in the index so that the expression code generator
5836 ** will know to replace occurrences of the indexed expression with
5837 ** references to the corresponding column of the index.
5839 static SQLITE_NOINLINE void whereAddIndexedExpr(
5840 Parse *pParse, /* Add IndexedExpr entries to pParse->pIdxEpr */
5841 Index *pIdx, /* The index-on-expression that contains the expressions */
5842 int iIdxCur, /* Cursor number for pIdx */
5843 SrcItem *pTabItem /* The FROM clause entry for the table */
5845 int i;
5846 IndexedExpr *p;
5847 Table *pTab;
5848 assert( pIdx->bHasExpr );
5849 pTab = pIdx->pTable;
5850 for(i=0; i<pIdx->nColumn; i++){
5851 Expr *pExpr;
5852 int j = pIdx->aiColumn[i];
5853 if( j==XN_EXPR ){
5854 pExpr = pIdx->aColExpr->a[i].pExpr;
5855 }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
5856 pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
5857 }else{
5858 continue;
5860 if( sqlite3ExprIsConstant(pExpr) ) continue;
5861 if( pExpr->op==TK_FUNCTION ){
5862 /* Functions that might set a subtype should not be replaced by the
5863 ** value taken from an expression index since the index omits the
5864 ** subtype. https://sqlite.org/forum/forumpost/68d284c86b082c3e */
5865 int n;
5866 FuncDef *pDef;
5867 sqlite3 *db = pParse->db;
5868 assert( ExprUseXList(pExpr) );
5869 n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
5870 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
5871 if( pDef==0 || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
5872 continue;
5875 p = sqlite3DbMallocRaw(pParse->db, sizeof(IndexedExpr));
5876 if( p==0 ) break;
5877 p->pIENext = pParse->pIdxEpr;
5878 #ifdef WHERETRACE_ENABLED
5879 if( sqlite3WhereTrace & 0x200 ){
5880 sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
5881 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr);
5883 #endif
5884 p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5885 p->iDataCur = pTabItem->iCursor;
5886 p->iIdxCur = iIdxCur;
5887 p->iIdxCol = i;
5888 p->bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0;
5889 if( sqlite3IndexAffinityStr(pParse->db, pIdx) ){
5890 p->aff = pIdx->zColAff[i];
5892 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
5893 p->zIdxName = pIdx->zName;
5894 #endif
5895 pParse->pIdxEpr = p;
5896 if( p->pIENext==0 ){
5897 void *pArg = (void*)&pParse->pIdxEpr;
5898 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
5904 ** Set the reverse-scan order mask to one for all tables in the query
5905 ** with the exception of MATERIALIZED common table expressions that have
5906 ** their own internal ORDER BY clauses.
5908 ** This implements the PRAGMA reverse_unordered_selects=ON setting.
5909 ** (Also SQLITE_DBCONFIG_REVERSE_SCANORDER).
5911 static SQLITE_NOINLINE void whereReverseScanOrder(WhereInfo *pWInfo){
5912 int ii;
5913 for(ii=0; ii<pWInfo->pTabList->nSrc; ii++){
5914 SrcItem *pItem = &pWInfo->pTabList->a[ii];
5915 if( !pItem->fg.isCte
5916 || pItem->u2.pCteUse->eM10d!=M10d_Yes
5917 || NEVER(pItem->pSelect==0)
5918 || pItem->pSelect->pOrderBy==0
5920 pWInfo->revMask |= MASKBIT(ii);
5926 ** Generate the beginning of the loop used for WHERE clause processing.
5927 ** The return value is a pointer to an opaque structure that contains
5928 ** information needed to terminate the loop. Later, the calling routine
5929 ** should invoke sqlite3WhereEnd() with the return value of this function
5930 ** in order to complete the WHERE clause processing.
5932 ** If an error occurs, this routine returns NULL.
5934 ** The basic idea is to do a nested loop, one loop for each table in
5935 ** the FROM clause of a select. (INSERT and UPDATE statements are the
5936 ** same as a SELECT with only a single table in the FROM clause.) For
5937 ** example, if the SQL is this:
5939 ** SELECT * FROM t1, t2, t3 WHERE ...;
5941 ** Then the code generated is conceptually like the following:
5943 ** foreach row1 in t1 do \ Code generated
5944 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
5945 ** foreach row3 in t3 do /
5946 ** ...
5947 ** end \ Code generated
5948 ** end |-- by sqlite3WhereEnd()
5949 ** end /
5951 ** Note that the loops might not be nested in the order in which they
5952 ** appear in the FROM clause if a different order is better able to make
5953 ** use of indices. Note also that when the IN operator appears in
5954 ** the WHERE clause, it might result in additional nested loops for
5955 ** scanning through all values on the right-hand side of the IN.
5957 ** There are Btree cursors associated with each table. t1 uses cursor
5958 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5959 ** And so forth. This routine generates code to open those VDBE cursors
5960 ** and sqlite3WhereEnd() generates the code to close them.
5962 ** The code that sqlite3WhereBegin() generates leaves the cursors named
5963 ** in pTabList pointing at their appropriate entries. The [...] code
5964 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
5965 ** data from the various tables of the loop.
5967 ** If the WHERE clause is empty, the foreach loops must each scan their
5968 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
5969 ** the tables have indices and there are terms in the WHERE clause that
5970 ** refer to those indices, a complete table scan can be avoided and the
5971 ** code will run much faster. Most of the work of this routine is checking
5972 ** to see if there are indices that can be used to speed up the loop.
5974 ** Terms of the WHERE clause are also used to limit which rows actually
5975 ** make it to the "..." in the middle of the loop. After each "foreach",
5976 ** terms of the WHERE clause that use only terms in that loop and outer
5977 ** loops are evaluated and if false a jump is made around all subsequent
5978 ** inner loops (or around the "..." if the test occurs within the inner-
5979 ** most loop)
5981 ** OUTER JOINS
5983 ** An outer join of tables t1 and t2 is conceptually coded as follows:
5985 ** foreach row1 in t1 do
5986 ** flag = 0
5987 ** foreach row2 in t2 do
5988 ** start:
5989 ** ...
5990 ** flag = 1
5991 ** end
5992 ** if flag==0 then
5993 ** move the row2 cursor to a null row
5994 ** goto start
5995 ** fi
5996 ** end
5998 ** ORDER BY CLAUSE PROCESSING
6000 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
6001 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
6002 ** if there is one. If there is no ORDER BY clause or if this routine
6003 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
6005 ** The iIdxCur parameter is the cursor number of an index. If
6006 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
6007 ** to use for OR clause processing. The WHERE clause should use this
6008 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
6009 ** the first cursor in an array of cursors for all indices. iIdxCur should
6010 ** be used to compute the appropriate cursor depending on which index is
6011 ** used.
6013 WhereInfo *sqlite3WhereBegin(
6014 Parse *pParse, /* The parser context */
6015 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
6016 Expr *pWhere, /* The WHERE clause */
6017 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
6018 ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
6019 Select *pSelect, /* The entire SELECT statement */
6020 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
6021 int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
6022 ** If WHERE_USE_LIMIT, then the limit amount */
6024 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
6025 int nTabList; /* Number of elements in pTabList */
6026 WhereInfo *pWInfo; /* Will become the return value of this function */
6027 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
6028 Bitmask notReady; /* Cursors that are not yet positioned */
6029 WhereLoopBuilder sWLB; /* The WhereLoop builder */
6030 WhereMaskSet *pMaskSet; /* The expression mask set */
6031 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
6032 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
6033 int ii; /* Loop counter */
6034 sqlite3 *db; /* Database connection */
6035 int rc; /* Return code */
6036 u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
6038 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
6039 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
6040 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
6043 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
6044 assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
6045 || (wctrlFlags & WHERE_USE_LIMIT)==0 );
6047 /* Variable initialization */
6048 db = pParse->db;
6049 memset(&sWLB, 0, sizeof(sWLB));
6051 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
6052 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
6053 if( pOrderBy && pOrderBy->nExpr>=BMS ){
6054 pOrderBy = 0;
6055 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6058 /* The number of tables in the FROM clause is limited by the number of
6059 ** bits in a Bitmask
6061 testcase( pTabList->nSrc==BMS );
6062 if( pTabList->nSrc>BMS ){
6063 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
6064 return 0;
6067 /* This function normally generates a nested loop for all tables in
6068 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
6069 ** only generate code for the first table in pTabList and assume that
6070 ** any cursors associated with subsequent tables are uninitialized.
6072 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
6074 /* Allocate and initialize the WhereInfo structure that will become the
6075 ** return value. A single allocation is used to store the WhereInfo
6076 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6077 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6078 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6079 ** some architectures. Hence the ROUND8() below.
6081 nByteWInfo = ROUND8P(sizeof(WhereInfo));
6082 if( nTabList>1 ){
6083 nByteWInfo = ROUND8P(nByteWInfo + (nTabList-1)*sizeof(WhereLevel));
6085 pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
6086 if( db->mallocFailed ){
6087 sqlite3DbFree(db, pWInfo);
6088 pWInfo = 0;
6089 goto whereBeginError;
6091 pWInfo->pParse = pParse;
6092 pWInfo->pTabList = pTabList;
6093 pWInfo->pOrderBy = pOrderBy;
6094 #if WHERETRACE_ENABLED
6095 pWInfo->pWhere = pWhere;
6096 #endif
6097 pWInfo->pResultSet = pResultSet;
6098 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
6099 pWInfo->nLevel = nTabList;
6100 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
6101 pWInfo->wctrlFlags = wctrlFlags;
6102 pWInfo->iLimit = iAuxArg;
6103 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
6104 pWInfo->pSelect = pSelect;
6105 memset(&pWInfo->nOBSat, 0,
6106 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
6107 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
6108 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
6109 pMaskSet = &pWInfo->sMaskSet;
6110 pMaskSet->n = 0;
6111 pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
6112 ** a valid cursor number, to avoid an initial
6113 ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
6114 sWLB.pWInfo = pWInfo;
6115 sWLB.pWC = &pWInfo->sWC;
6116 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
6117 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
6118 whereLoopInit(sWLB.pNew);
6119 #ifdef SQLITE_DEBUG
6120 sWLB.pNew->cId = '*';
6121 #endif
6123 /* Split the WHERE clause into separate subexpressions where each
6124 ** subexpression is separated by an AND operator.
6126 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
6127 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
6129 /* Special case: No FROM clause
6131 if( nTabList==0 ){
6132 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
6133 if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0
6134 && OptimizationEnabled(db, SQLITE_DistinctOpt)
6136 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6138 ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
6139 }else{
6140 /* Assign a bit from the bitmask to every term in the FROM clause.
6142 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
6144 ** The rule of the previous sentence ensures that if X is the bitmask for
6145 ** a table T, then X-1 is the bitmask for all other tables to the left of T.
6146 ** Knowing the bitmask for all tables to the left of a left join is
6147 ** important. Ticket #3015.
6149 ** Note that bitmasks are created for all pTabList->nSrc tables in
6150 ** pTabList, not just the first nTabList tables. nTabList is normally
6151 ** equal to pTabList->nSrc but might be shortened to 1 if the
6152 ** WHERE_OR_SUBCLAUSE flag is set.
6154 ii = 0;
6156 createMask(pMaskSet, pTabList->a[ii].iCursor);
6157 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
6158 }while( (++ii)<pTabList->nSrc );
6159 #ifdef SQLITE_DEBUG
6161 Bitmask mx = 0;
6162 for(ii=0; ii<pTabList->nSrc; ii++){
6163 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
6164 assert( m>=mx );
6165 mx = m;
6168 #endif
6171 /* Analyze all of the subexpressions. */
6172 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
6173 if( pSelect && pSelect->pLimit ){
6174 sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
6176 if( pParse->nErr ) goto whereBeginError;
6178 /* The False-WHERE-Term-Bypass optimization:
6180 ** If there are WHERE terms that are false, then no rows will be output,
6181 ** so skip over all of the code generated here.
6183 ** Conditions:
6185 ** (1) The WHERE term must not refer to any tables in the join.
6186 ** (2) The term must not come from an ON clause on the
6187 ** right-hand side of a LEFT or FULL JOIN.
6188 ** (3) The term must not come from an ON clause, or there must be
6189 ** no RIGHT or FULL OUTER joins in pTabList.
6190 ** (4) If the expression contains non-deterministic functions
6191 ** that are not within a sub-select. This is not required
6192 ** for correctness but rather to preserves SQLite's legacy
6193 ** behaviour in the following two cases:
6195 ** WHERE random()>0; -- eval random() once per row
6196 ** WHERE (SELECT random())>0; -- eval random() just once overall
6198 ** Note that the Where term need not be a constant in order for this
6199 ** optimization to apply, though it does need to be constant relative to
6200 ** the current subquery (condition 1). The term might include variables
6201 ** from outer queries so that the value of the term changes from one
6202 ** invocation of the current subquery to the next.
6204 for(ii=0; ii<sWLB.pWC->nBase; ii++){
6205 WhereTerm *pT = &sWLB.pWC->a[ii]; /* A term of the WHERE clause */
6206 Expr *pX; /* The expression of pT */
6207 if( pT->wtFlags & TERM_VIRTUAL ) continue;
6208 pX = pT->pExpr;
6209 assert( pX!=0 );
6210 assert( pT->prereqAll!=0 || !ExprHasProperty(pX, EP_OuterON) );
6211 if( pT->prereqAll==0 /* Conditions (1) and (2) */
6212 && (nTabList==0 || exprIsDeterministic(pX)) /* Condition (4) */
6213 && !(ExprHasProperty(pX, EP_InnerON) /* Condition (3) */
6214 && (pTabList->a[0].fg.jointype & JT_LTORJ)!=0 )
6216 sqlite3ExprIfFalse(pParse, pX, pWInfo->iBreak, SQLITE_JUMPIFNULL);
6217 pT->wtFlags |= TERM_CODED;
6221 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6222 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6223 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6224 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6225 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6226 pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
6227 }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6228 /* The DISTINCT marking is pointless. Ignore it. */
6229 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6230 }else if( pOrderBy==0 ){
6231 /* Try to ORDER BY the result set to make distinct processing easier */
6232 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
6233 pWInfo->pOrderBy = pResultSet;
6237 /* Construct the WhereLoop objects */
6238 #if defined(WHERETRACE_ENABLED)
6239 if( sqlite3WhereTrace & 0xffffffff ){
6240 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
6241 if( wctrlFlags & WHERE_USE_LIMIT ){
6242 sqlite3DebugPrintf(", limit: %d", iAuxArg);
6244 sqlite3DebugPrintf(")\n");
6245 if( sqlite3WhereTrace & 0x8000 ){
6246 Select sSelect;
6247 memset(&sSelect, 0, sizeof(sSelect));
6248 sSelect.selFlags = SF_WhereBegin;
6249 sSelect.pSrc = pTabList;
6250 sSelect.pWhere = pWhere;
6251 sSelect.pOrderBy = pOrderBy;
6252 sSelect.pEList = pResultSet;
6253 sqlite3TreeViewSelect(0, &sSelect, 0);
6255 if( sqlite3WhereTrace & 0x4000 ){ /* Display all WHERE clause terms */
6256 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
6257 sqlite3WhereClausePrint(sWLB.pWC);
6260 #endif
6262 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
6263 rc = whereLoopAddAll(&sWLB);
6264 if( rc ) goto whereBeginError;
6266 #ifdef SQLITE_ENABLE_STAT4
6267 /* If one or more WhereTerm.truthProb values were used in estimating
6268 ** loop parameters, but then those truthProb values were subsequently
6269 ** changed based on STAT4 information while computing subsequent loops,
6270 ** then we need to rerun the whole loop building process so that all
6271 ** loops will be built using the revised truthProb values. */
6272 if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
6273 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6274 WHERETRACE(0xffffffff,
6275 ("**** Redo all loop computations due to"
6276 " TERM_HIGHTRUTH changes ****\n"));
6277 while( pWInfo->pLoops ){
6278 WhereLoop *p = pWInfo->pLoops;
6279 pWInfo->pLoops = p->pNextLoop;
6280 whereLoopDelete(db, p);
6282 rc = whereLoopAddAll(&sWLB);
6283 if( rc ) goto whereBeginError;
6285 #endif
6286 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6288 wherePathSolver(pWInfo, 0);
6289 if( db->mallocFailed ) goto whereBeginError;
6290 if( pWInfo->pOrderBy ){
6291 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
6292 if( db->mallocFailed ) goto whereBeginError;
6295 /* TUNING: Assume that a DISTINCT clause on a subquery reduces
6296 ** the output size by a factor of 8 (LogEst -30).
6298 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
6299 WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n",
6300 pWInfo->nRowOut, pWInfo->nRowOut-30));
6301 pWInfo->nRowOut -= 30;
6305 assert( pWInfo->pTabList!=0 );
6306 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
6307 whereReverseScanOrder(pWInfo);
6309 if( pParse->nErr ){
6310 goto whereBeginError;
6312 assert( db->mallocFailed==0 );
6313 #ifdef WHERETRACE_ENABLED
6314 if( sqlite3WhereTrace ){
6315 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
6316 if( pWInfo->nOBSat>0 ){
6317 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
6319 switch( pWInfo->eDistinct ){
6320 case WHERE_DISTINCT_UNIQUE: {
6321 sqlite3DebugPrintf(" DISTINCT=unique");
6322 break;
6324 case WHERE_DISTINCT_ORDERED: {
6325 sqlite3DebugPrintf(" DISTINCT=ordered");
6326 break;
6328 case WHERE_DISTINCT_UNORDERED: {
6329 sqlite3DebugPrintf(" DISTINCT=unordered");
6330 break;
6333 sqlite3DebugPrintf("\n");
6334 for(ii=0; ii<pWInfo->nLevel; ii++){
6335 sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
6338 #endif
6340 /* Attempt to omit tables from a join that do not affect the result.
6341 ** See the comment on whereOmitNoopJoin() for further information.
6343 ** This query optimization is factored out into a separate "no-inline"
6344 ** procedure to keep the sqlite3WhereBegin() procedure from becoming
6345 ** too large. If sqlite3WhereBegin() becomes too large, that prevents
6346 ** some C-compiler optimizers from in-lining the
6347 ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
6348 ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
6350 notReady = ~(Bitmask)0;
6351 if( pWInfo->nLevel>=2
6352 && pResultSet!=0 /* these two combine to guarantee */
6353 && 0==(wctrlFlags & WHERE_AGG_DISTINCT) /* condition (1) above */
6354 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6356 notReady = whereOmitNoopJoin(pWInfo, notReady);
6357 nTabList = pWInfo->nLevel;
6358 assert( nTabList>0 );
6361 /* Check to see if there are any SEARCH loops that might benefit from
6362 ** using a Bloom filter.
6364 if( pWInfo->nLevel>=2
6365 && OptimizationEnabled(db, SQLITE_BloomFilter)
6367 whereCheckIfBloomFilterIsUseful(pWInfo);
6370 #if defined(WHERETRACE_ENABLED)
6371 if( sqlite3WhereTrace & 0x4000 ){ /* Display all terms of the WHERE clause */
6372 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
6373 sqlite3WhereClausePrint(sWLB.pWC);
6375 WHERETRACE(0xffffffff,("*** Optimizer Finished ***\n"));
6376 #endif
6377 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
6379 /* If the caller is an UPDATE or DELETE statement that is requesting
6380 ** to use a one-pass algorithm, determine if this is appropriate.
6382 ** A one-pass approach can be used if the caller has requested one
6383 ** and either (a) the scan visits at most one row or (b) each
6384 ** of the following are true:
6386 ** * the caller has indicated that a one-pass approach can be used
6387 ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
6388 ** * the table is not a virtual table, and
6389 ** * either the scan does not use the OR optimization or the caller
6390 ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
6391 ** for DELETE).
6393 ** The last qualification is because an UPDATE statement uses
6394 ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
6395 ** use a one-pass approach, and this is not set accurately for scans
6396 ** that use the OR optimization.
6398 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
6399 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
6400 int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
6401 int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
6402 assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
6403 if( bOnerow || (
6404 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
6405 && !IsVirtual(pTabList->a[0].pTab)
6406 && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
6407 && OptimizationEnabled(db, SQLITE_OnePass)
6409 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
6410 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
6411 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
6412 bFordelete = OPFLAG_FORDELETE;
6414 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
6419 /* Open all tables in the pTabList and any indices selected for
6420 ** searching those tables.
6422 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
6423 Table *pTab; /* Table to open */
6424 int iDb; /* Index of database containing table/index */
6425 SrcItem *pTabItem;
6427 pTabItem = &pTabList->a[pLevel->iFrom];
6428 pTab = pTabItem->pTab;
6429 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6430 pLoop = pLevel->pWLoop;
6431 if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
6432 /* Do nothing */
6433 }else
6434 #ifndef SQLITE_OMIT_VIRTUALTABLE
6435 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
6436 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
6437 int iCur = pTabItem->iCursor;
6438 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
6439 }else if( IsVirtual(pTab) ){
6440 /* noop */
6441 }else
6442 #endif
6443 if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0
6444 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0)
6445 || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0
6447 int op = OP_OpenRead;
6448 if( pWInfo->eOnePass!=ONEPASS_OFF ){
6449 op = OP_OpenWrite;
6450 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6452 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
6453 assert( pTabItem->iCursor==pLevel->iTabCur );
6454 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
6455 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
6456 if( pWInfo->eOnePass==ONEPASS_OFF
6457 && pTab->nCol<BMS
6458 && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
6459 && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
6461 /* If we know that only a prefix of the record will be used,
6462 ** it is advantageous to reduce the "column count" field in
6463 ** the P4 operand of the OP_OpenRead/Write opcode. */
6464 Bitmask b = pTabItem->colUsed;
6465 int n = 0;
6466 for(; b; b=b>>1, n++){}
6467 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
6468 assert( n<=pTab->nCol );
6470 #ifdef SQLITE_ENABLE_CURSOR_HINTS
6471 if( pLoop->u.btree.pIndex!=0 && (pTab->tabFlags & TF_WithoutRowid)==0 ){
6472 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
6473 }else
6474 #endif
6476 sqlite3VdbeChangeP5(v, bFordelete);
6478 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6479 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
6480 (const u8*)&pTabItem->colUsed, P4_INT64);
6481 #endif
6482 }else{
6483 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
6485 if( pLoop->wsFlags & WHERE_INDEXED ){
6486 Index *pIx = pLoop->u.btree.pIndex;
6487 int iIndexCur;
6488 int op = OP_OpenRead;
6489 /* iAuxArg is always set to a positive value if ONEPASS is possible */
6490 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
6491 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
6492 && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
6494 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6495 ** WITHOUT ROWID table. No need for a separate index */
6496 iIndexCur = pLevel->iTabCur;
6497 op = 0;
6498 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
6499 Index *pJ = pTabItem->pTab->pIndex;
6500 iIndexCur = iAuxArg;
6501 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6502 while( ALWAYS(pJ) && pJ!=pIx ){
6503 iIndexCur++;
6504 pJ = pJ->pNext;
6506 op = OP_OpenWrite;
6507 pWInfo->aiCurOnePass[1] = iIndexCur;
6508 }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
6509 iIndexCur = iAuxArg;
6510 op = OP_ReopenIdx;
6511 }else{
6512 iIndexCur = pParse->nTab++;
6513 if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
6514 whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem);
6516 if( pIx->pPartIdxWhere && (pTabItem->fg.jointype & JT_RIGHT)==0 ){
6517 wherePartIdxExpr(
6518 pParse, pIx, pIx->pPartIdxWhere, 0, iIndexCur, pTabItem
6522 pLevel->iIdxCur = iIndexCur;
6523 assert( pIx!=0 );
6524 assert( pIx->pSchema==pTab->pSchema );
6525 assert( iIndexCur>=0 );
6526 if( op ){
6527 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6528 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6529 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
6530 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
6531 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
6532 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
6533 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
6534 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
6536 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
6538 VdbeComment((v, "%s", pIx->zName));
6539 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6541 u64 colUsed = 0;
6542 int ii, jj;
6543 for(ii=0; ii<pIx->nColumn; ii++){
6544 jj = pIx->aiColumn[ii];
6545 if( jj<0 ) continue;
6546 if( jj>63 ) jj = 63;
6547 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
6548 colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
6550 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
6551 (u8*)&colUsed, P4_INT64);
6553 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
6556 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
6557 if( (pTabItem->fg.jointype & JT_RIGHT)!=0
6558 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
6560 WhereRightJoin *pRJ = pLevel->pRJ;
6561 pRJ->iMatch = pParse->nTab++;
6562 pRJ->regBloom = ++pParse->nMem;
6563 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
6564 pRJ->regReturn = ++pParse->nMem;
6565 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
6566 assert( pTab==pTabItem->pTab );
6567 if( HasRowid(pTab) ){
6568 KeyInfo *pInfo;
6569 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
6570 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
6571 if( pInfo ){
6572 pInfo->aColl[0] = 0;
6573 pInfo->aSortFlags[0] = 0;
6574 sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
6576 }else{
6577 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6578 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
6579 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
6581 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
6582 /* The nature of RIGHT JOIN processing is such that it messes up
6583 ** the output order. So omit any ORDER BY/GROUP BY elimination
6584 ** optimizations. We need to do an actual sort for RIGHT JOIN. */
6585 pWInfo->nOBSat = 0;
6586 pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED;
6589 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
6590 if( db->mallocFailed ) goto whereBeginError;
6592 /* Generate the code to do the search. Each iteration of the for
6593 ** loop below generates code for a single nested loop of the VM
6594 ** program.
6596 for(ii=0; ii<nTabList; ii++){
6597 int addrExplain;
6598 int wsFlags;
6599 SrcItem *pSrc;
6600 if( pParse->nErr ) goto whereBeginError;
6601 pLevel = &pWInfo->a[ii];
6602 wsFlags = pLevel->pWLoop->wsFlags;
6603 pSrc = &pTabList->a[pLevel->iFrom];
6604 if( pSrc->fg.isMaterialized ){
6605 if( pSrc->fg.isCorrelated ){
6606 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6607 }else{
6608 int iOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
6609 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6610 sqlite3VdbeJumpHere(v, iOnce);
6613 assert( pTabList == pWInfo->pTabList );
6614 if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
6615 if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
6616 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6617 constructAutomaticIndex(pParse, &pWInfo->sWC, notReady, pLevel);
6618 #endif
6619 }else{
6620 sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
6622 if( db->mallocFailed ) goto whereBeginError;
6624 addrExplain = sqlite3WhereExplainOneScan(
6625 pParse, pTabList, pLevel, wctrlFlags
6627 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
6628 notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
6629 pWInfo->iContinue = pLevel->addrCont;
6630 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
6631 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
6635 /* Done. */
6636 VdbeModuleComment((v, "Begin WHERE-core"));
6637 pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
6638 return pWInfo;
6640 /* Jump here if malloc fails */
6641 whereBeginError:
6642 if( pWInfo ){
6643 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6644 whereInfoFree(db, pWInfo);
6646 #ifdef WHERETRACE_ENABLED
6647 /* Prevent harmless compiler warnings about debugging routines
6648 ** being declared but never used */
6649 sqlite3ShowWhereLoopList(0);
6650 #endif /* WHERETRACE_ENABLED */
6651 return 0;
6655 ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
6656 ** index rather than the main table. In SQLITE_DEBUG mode, we want
6657 ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
6658 ** does that.
6660 #ifndef SQLITE_DEBUG
6661 # define OpcodeRewriteTrace(D,K,P) /* no-op */
6662 #else
6663 # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
6664 static void sqlite3WhereOpcodeRewriteTrace(
6665 sqlite3 *db,
6666 int pc,
6667 VdbeOp *pOp
6669 if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
6670 sqlite3VdbePrintOp(0, pc, pOp);
6672 #endif
6674 #ifdef SQLITE_DEBUG
6676 ** Return true if cursor iCur is opened by instruction k of the
6677 ** bytecode. Used inside of assert() only.
6679 static int cursorIsOpen(Vdbe *v, int iCur, int k){
6680 while( k>=0 ){
6681 VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
6682 if( pOp->p1!=iCur ) continue;
6683 if( pOp->opcode==OP_Close ) return 0;
6684 if( pOp->opcode==OP_OpenRead ) return 1;
6685 if( pOp->opcode==OP_OpenWrite ) return 1;
6686 if( pOp->opcode==OP_OpenDup ) return 1;
6687 if( pOp->opcode==OP_OpenAutoindex ) return 1;
6688 if( pOp->opcode==OP_OpenEphemeral ) return 1;
6690 return 0;
6692 #endif /* SQLITE_DEBUG */
6695 ** Generate the end of the WHERE loop. See comments on
6696 ** sqlite3WhereBegin() for additional information.
6698 void sqlite3WhereEnd(WhereInfo *pWInfo){
6699 Parse *pParse = pWInfo->pParse;
6700 Vdbe *v = pParse->pVdbe;
6701 int i;
6702 WhereLevel *pLevel;
6703 WhereLoop *pLoop;
6704 SrcList *pTabList = pWInfo->pTabList;
6705 sqlite3 *db = pParse->db;
6706 int iEnd = sqlite3VdbeCurrentAddr(v);
6707 int nRJ = 0;
6709 /* Generate loop termination code.
6711 VdbeModuleComment((v, "End WHERE-core"));
6712 for(i=pWInfo->nLevel-1; i>=0; i--){
6713 int addr;
6714 pLevel = &pWInfo->a[i];
6715 if( pLevel->pRJ ){
6716 /* Terminate the subroutine that forms the interior of the loop of
6717 ** the RIGHT JOIN table */
6718 WhereRightJoin *pRJ = pLevel->pRJ;
6719 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6720 pLevel->addrCont = 0;
6721 pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);
6722 sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);
6723 VdbeCoverage(v);
6724 nRJ++;
6726 pLoop = pLevel->pWLoop;
6727 if( pLevel->op!=OP_Noop ){
6728 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6729 int addrSeek = 0;
6730 Index *pIdx;
6731 int n;
6732 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
6733 && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
6734 && (pLoop->wsFlags & WHERE_INDEXED)!=0
6735 && (pIdx = pLoop->u.btree.pIndex)->hasStat1
6736 && (n = pLoop->u.btree.nDistinctCol)>0
6737 && pIdx->aiRowLogEst[n]>=36
6739 int r1 = pParse->nMem+1;
6740 int j, op;
6741 for(j=0; j<n; j++){
6742 sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
6744 pParse->nMem += n+1;
6745 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
6746 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
6747 VdbeCoverageIf(v, op==OP_SeekLT);
6748 VdbeCoverageIf(v, op==OP_SeekGT);
6749 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
6751 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
6752 /* The common case: Advance to the next row */
6753 if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6754 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
6755 sqlite3VdbeChangeP5(v, pLevel->p5);
6756 VdbeCoverage(v);
6757 VdbeCoverageIf(v, pLevel->op==OP_Next);
6758 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6759 VdbeCoverageIf(v, pLevel->op==OP_VNext);
6760 if( pLevel->regBignull ){
6761 sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
6762 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
6763 VdbeCoverage(v);
6765 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6766 if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
6767 #endif
6768 }else if( pLevel->addrCont ){
6769 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6771 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
6772 struct InLoop *pIn;
6773 int j;
6774 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
6775 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
6776 assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
6777 || pParse->db->mallocFailed );
6778 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6779 if( pIn->eEndLoopOp!=OP_Noop ){
6780 if( pIn->nPrefix ){
6781 int bEarlyOut =
6782 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
6783 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
6784 if( pLevel->iLeftJoin ){
6785 /* For LEFT JOIN queries, cursor pIn->iCur may not have been
6786 ** opened yet. This occurs for WHERE clauses such as
6787 ** "a = ? AND b IN (...)", where the index is on (a, b). If
6788 ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
6789 ** never have been coded, but the body of the loop run to
6790 ** return the null-row. So, if the cursor is not open yet,
6791 ** jump over the OP_Next or OP_Prev instruction about to
6792 ** be coded. */
6793 sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
6794 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
6795 VdbeCoverage(v);
6797 if( bEarlyOut ){
6798 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
6799 sqlite3VdbeCurrentAddr(v)+2,
6800 pIn->iBase, pIn->nPrefix);
6801 VdbeCoverage(v);
6802 /* Retarget the OP_IsNull against the left operand of IN so
6803 ** it jumps past the OP_IfNoHope. This is because the
6804 ** OP_IsNull also bypasses the OP_Affinity opcode that is
6805 ** required by OP_IfNoHope. */
6806 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6809 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
6810 VdbeCoverage(v);
6811 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
6812 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
6814 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
6817 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
6818 if( pLevel->pRJ ){
6819 sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1);
6820 VdbeCoverage(v);
6822 if( pLevel->addrSkip ){
6823 sqlite3VdbeGoto(v, pLevel->addrSkip);
6824 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
6825 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6826 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
6828 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
6829 if( pLevel->addrLikeRep ){
6830 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
6831 pLevel->addrLikeRep);
6832 VdbeCoverage(v);
6834 #endif
6835 if( pLevel->iLeftJoin ){
6836 int ws = pLoop->wsFlags;
6837 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
6838 assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
6839 if( (ws & WHERE_IDX_ONLY)==0 ){
6840 assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
6841 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
6843 if( (ws & WHERE_INDEXED)
6844 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
6846 if( ws & WHERE_MULTI_OR ){
6847 Index *pIx = pLevel->u.pCoveringIdx;
6848 int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
6849 sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
6850 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6852 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
6854 if( pLevel->op==OP_Return ){
6855 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6856 }else{
6857 sqlite3VdbeGoto(v, pLevel->addrFirst);
6859 sqlite3VdbeJumpHere(v, addr);
6861 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
6862 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
6865 assert( pWInfo->nLevel<=pTabList->nSrc );
6866 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
6867 int k, last;
6868 VdbeOp *pOp, *pLastOp;
6869 Index *pIdx = 0;
6870 SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
6871 Table *pTab = pTabItem->pTab;
6872 assert( pTab!=0 );
6873 pLoop = pLevel->pWLoop;
6875 /* Do RIGHT JOIN processing. Generate code that will output the
6876 ** unmatched rows of the right operand of the RIGHT JOIN with
6877 ** all of the columns of the left operand set to NULL.
6879 if( pLevel->pRJ ){
6880 sqlite3WhereRightJoinLoop(pWInfo, i, pLevel);
6881 continue;
6884 /* For a co-routine, change all OP_Column references to the table of
6885 ** the co-routine into OP_Copy of result contained in a register.
6886 ** OP_Rowid becomes OP_Null.
6888 if( pTabItem->fg.viaCoroutine ){
6889 testcase( pParse->db->mallocFailed );
6890 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
6891 pTabItem->regResult, 0);
6892 continue;
6895 /* If this scan uses an index, make VDBE code substitutions to read data
6896 ** from the index instead of from the table where possible. In some cases
6897 ** this optimization prevents the table from ever being read, which can
6898 ** yield a significant performance boost.
6900 ** Calls to the code generator in between sqlite3WhereBegin and
6901 ** sqlite3WhereEnd will have created code that references the table
6902 ** directly. This loop scans all that code looking for opcodes
6903 ** that reference the table and converts them into opcodes that
6904 ** reference the index.
6906 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6907 pIdx = pLoop->u.btree.pIndex;
6908 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
6909 pIdx = pLevel->u.pCoveringIdx;
6911 if( pIdx
6912 && !db->mallocFailed
6914 if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
6915 last = iEnd;
6916 }else{
6917 last = pWInfo->iEndWhere;
6919 if( pIdx->bHasExpr ){
6920 IndexedExpr *p = pParse->pIdxEpr;
6921 while( p ){
6922 if( p->iIdxCur==pLevel->iIdxCur ){
6923 #ifdef WHERETRACE_ENABLED
6924 if( sqlite3WhereTrace & 0x200 ){
6925 sqlite3DebugPrintf("Disable pParse->pIdxEpr term {%d,%d}\n",
6926 p->iIdxCur, p->iIdxCol);
6927 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(p->pExpr);
6929 #endif
6930 p->iDataCur = -1;
6931 p->iIdxCur = -1;
6933 p = p->pIENext;
6936 k = pLevel->addrBody + 1;
6937 #ifdef SQLITE_DEBUG
6938 if( db->flags & SQLITE_VdbeAddopTrace ){
6939 printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n",
6940 pLevel->iTabCur, pLevel->iIdxCur, k, last-1);
6942 /* Proof that the "+1" on the k value above is safe */
6943 pOp = sqlite3VdbeGetOp(v, k - 1);
6944 assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
6945 assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur );
6946 assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
6947 #endif
6948 pOp = sqlite3VdbeGetOp(v, k);
6949 pLastOp = pOp + (last - k);
6950 assert( pOp<=pLastOp );
6952 if( pOp->p1!=pLevel->iTabCur ){
6953 /* no-op */
6954 }else if( pOp->opcode==OP_Column
6955 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6956 || pOp->opcode==OP_Offset
6957 #endif
6959 int x = pOp->p2;
6960 assert( pIdx->pTable==pTab );
6961 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6962 if( pOp->opcode==OP_Offset ){
6963 /* Do not need to translate the column number */
6964 }else
6965 #endif
6966 if( !HasRowid(pTab) ){
6967 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6968 x = pPk->aiColumn[x];
6969 assert( x>=0 );
6970 }else{
6971 testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
6972 x = sqlite3StorageColumnToTable(pTab,x);
6974 x = sqlite3TableColumnToIndex(pIdx, x);
6975 if( x>=0 ){
6976 pOp->p2 = x;
6977 pOp->p1 = pLevel->iIdxCur;
6978 OpcodeRewriteTrace(db, k, pOp);
6979 }else{
6980 /* Unable to translate the table reference into an index
6981 ** reference. Verify that this is harmless - that the
6982 ** table being referenced really is open.
6984 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6985 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6986 || cursorIsOpen(v,pOp->p1,k)
6987 || pOp->opcode==OP_Offset
6989 #else
6990 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6991 || cursorIsOpen(v,pOp->p1,k)
6993 #endif
6995 }else if( pOp->opcode==OP_Rowid ){
6996 pOp->p1 = pLevel->iIdxCur;
6997 pOp->opcode = OP_IdxRowid;
6998 OpcodeRewriteTrace(db, k, pOp);
6999 }else if( pOp->opcode==OP_IfNullRow ){
7000 pOp->p1 = pLevel->iIdxCur;
7001 OpcodeRewriteTrace(db, k, pOp);
7003 #ifdef SQLITE_DEBUG
7004 k++;
7005 #endif
7006 }while( (++pOp)<pLastOp );
7007 #ifdef SQLITE_DEBUG
7008 if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
7009 #endif
7013 /* The "break" point is here, just past the end of the outer loop.
7014 ** Set it.
7016 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
7018 /* Final cleanup
7020 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
7021 whereInfoFree(db, pWInfo);
7022 pParse->withinRJSubrtn -= nRJ;
7023 return;