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