4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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"
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
96 int sqlite3WhereOrderByLimitOptLabel(WhereInfo
*pWInfo
){
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
){
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
);
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",
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
){
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 */
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
){
219 if( pSet
->n
<N_OR_COST
){
220 p
= &pSet
->a
[pSet
->n
++];
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;
232 if( p
->nOut
>nOut
) p
->nOut
= nOut
;
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
){
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
){
248 for(i
=1; i
<pMaskSet
->n
; i
++){
249 if( pMaskSet
->ix
[i
]==iCursor
){
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
));
262 pBlock
->pNext
= pWInfo
->pMemToFree
;
264 pWInfo
->pMemToFree
= pBlock
;
267 return (void*)pBlock
;
269 void *sqlite3WhereRealloc(WhereInfo
*pWInfo
, void *pOld
, u64 nByte
){
270 void *pNew
= sqlite3WhereMalloc(pWInfo
, nByte
);
272 WhereMemBlock
*pOldBlk
= (WhereMemBlock
*)pOld
;
274 assert( pOldBlk
->sz
<nByte
);
275 memcpy(pNew
, pOld
, pOldBlk
->sz
);
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
) ){
306 ** Term pTerm is guaranteed to be a WO_IN term. It may be a component term
307 ** of a vector IN expression of the form "(x, y, ...) IN (SELECT ...)".
308 ** This function checks to see if the term is compatible with an index
309 ** column with affinity idxaff (one of the SQLITE_AFF_XYZ values). If so,
310 ** it returns a pointer to the name of the collation sequence (e.g. "BINARY"
311 ** or "NOCASE") used by the comparison in pTerm. If it is not compatible
312 ** with affinity idxaff, NULL is returned.
314 static SQLITE_NOINLINE
const char *indexInAffinityOk(
319 Expr
*pX
= pTerm
->pExpr
;
322 assert( pTerm
->eOperator
& WO_IN
);
324 if( sqlite3ExprIsVector(pX
->pLeft
) ){
325 int iField
= pTerm
->u
.x
.iField
- 1;
328 inexpr
.pLeft
= pX
->pLeft
->x
.pList
->a
[iField
].pExpr
;
329 assert( ExprUseXSelect(pX
) );
330 inexpr
.pRight
= pX
->x
.pSelect
->pEList
->a
[iField
].pExpr
;
334 if( sqlite3IndexAffinityOk(pX
, idxaff
) ){
335 CollSeq
*pRet
= sqlite3ExprCompareCollSeq(pParse
, pX
);
336 return pRet
? pRet
->zName
: sqlite3StrBINARY
;
342 ** Advance to the next WhereTerm that matches according to the criteria
343 ** established when the pScan object was initialized by whereScanInit().
344 ** Return NULL if there are no more matching WhereTerms.
346 static WhereTerm
*whereScanNext(WhereScan
*pScan
){
347 int iCur
; /* The cursor on the LHS of the term */
348 i16 iColumn
; /* The column on the LHS of the term. -1 for IPK */
349 Expr
*pX
; /* An expression being tested */
350 WhereClause
*pWC
; /* Shorthand for pScan->pWC */
351 WhereTerm
*pTerm
; /* The term being tested */
352 int k
= pScan
->k
; /* Where to start scanning */
354 assert( pScan
->iEquiv
<=pScan
->nEquiv
);
357 iColumn
= pScan
->aiColumn
[pScan
->iEquiv
-1];
358 iCur
= pScan
->aiCur
[pScan
->iEquiv
-1];
362 for(pTerm
=pWC
->a
+k
; k
<pWC
->nTerm
; k
++, pTerm
++){
363 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 || pTerm
->leftCursor
<0 );
364 if( pTerm
->leftCursor
==iCur
365 && pTerm
->u
.x
.leftColumn
==iColumn
367 || sqlite3ExprCompareSkip(pTerm
->pExpr
->pLeft
,
368 pScan
->pIdxExpr
,iCur
)==0)
369 && (pScan
->iEquiv
<=1 || !ExprHasProperty(pTerm
->pExpr
, EP_OuterON
))
371 if( (pTerm
->eOperator
& WO_EQUIV
)!=0
372 && pScan
->nEquiv
<ArraySize(pScan
->aiCur
)
373 && (pX
= whereRightSubexprIsColumn(pTerm
->pExpr
))!=0
376 for(j
=0; j
<pScan
->nEquiv
; j
++){
377 if( pScan
->aiCur
[j
]==pX
->iTable
378 && pScan
->aiColumn
[j
]==pX
->iColumn
){
382 if( j
==pScan
->nEquiv
){
383 pScan
->aiCur
[j
] = pX
->iTable
;
384 pScan
->aiColumn
[j
] = pX
->iColumn
;
388 if( (pTerm
->eOperator
& pScan
->opMask
)!=0 ){
389 /* Verify the affinity and collating sequence match */
390 if( pScan
->zCollName
&& (pTerm
->eOperator
& WO_ISNULL
)==0 ){
391 const char *zCollName
;
392 Parse
*pParse
= pWC
->pWInfo
->pParse
;
395 if( (pTerm
->eOperator
& WO_IN
) ){
396 zCollName
= indexInAffinityOk(pParse
, pTerm
, pScan
->idxaff
);
397 if( !zCollName
) continue;
400 if( !sqlite3IndexAffinityOk(pX
, pScan
->idxaff
) ){
404 pColl
= sqlite3ExprCompareCollSeq(pParse
, pX
);
405 zCollName
= pColl
? pColl
->zName
: sqlite3StrBINARY
;
408 if( sqlite3StrICmp(zCollName
, pScan
->zCollName
) ){
412 if( (pTerm
->eOperator
& (WO_EQ
|WO_IS
))!=0
413 && (pX
= pTerm
->pExpr
->pRight
, ALWAYS(pX
!=0))
415 && pX
->iTable
==pScan
->aiCur
[0]
416 && pX
->iColumn
==pScan
->aiColumn
[0]
418 testcase( pTerm
->eOperator
& WO_IS
);
423 #ifdef WHERETRACE_ENABLED
424 if( sqlite3WhereTrace
& 0x20000 ){
426 sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d",
427 pTerm
, pScan
->nEquiv
);
428 for(ii
=0; ii
<pScan
->nEquiv
; ii
++){
429 sqlite3DebugPrintf(" {%d:%d}",
430 pScan
->aiCur
[ii
], pScan
->aiColumn
[ii
]);
432 sqlite3DebugPrintf("\n");
442 if( pScan
->iEquiv
>=pScan
->nEquiv
) break;
443 pWC
= pScan
->pOrigWC
;
451 ** This is whereScanInit() for the case of an index on an expression.
452 ** It is factored out into a separate tail-recursion subroutine so that
453 ** the normal whereScanInit() routine, which is a high-runner, does not
454 ** need to push registers onto the stack as part of its prologue.
456 static SQLITE_NOINLINE WhereTerm
*whereScanInitIndexExpr(WhereScan
*pScan
){
457 pScan
->idxaff
= sqlite3ExprAffinity(pScan
->pIdxExpr
);
458 return whereScanNext(pScan
);
462 ** Initialize a WHERE clause scanner object. Return a pointer to the
463 ** first match. Return NULL if there are no matches.
465 ** The scanner will be searching the WHERE clause pWC. It will look
466 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
467 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
468 ** must be one of the indexes of table iCur.
470 ** The <op> must be one of the operators described by opMask.
472 ** If the search is for X and the WHERE clause contains terms of the
473 ** form X=Y then this routine might also return terms of the form
474 ** "Y <op> <expr>". The number of levels of transitivity is limited,
475 ** but is enough to handle most commonly occurring SQL statements.
477 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
480 static WhereTerm
*whereScanInit(
481 WhereScan
*pScan
, /* The WhereScan object being initialized */
482 WhereClause
*pWC
, /* The WHERE clause to be scanned */
483 int iCur
, /* Cursor to scan for */
484 int iColumn
, /* Column to scan for */
485 u32 opMask
, /* Operator(s) to scan for */
486 Index
*pIdx
/* Must be compatible with this index */
488 pScan
->pOrigWC
= pWC
;
492 pScan
->zCollName
= 0;
493 pScan
->opMask
= opMask
;
495 pScan
->aiCur
[0] = iCur
;
500 iColumn
= pIdx
->aiColumn
[j
];
501 if( iColumn
==pIdx
->pTable
->iPKey
){
503 }else if( iColumn
>=0 ){
504 pScan
->idxaff
= pIdx
->pTable
->aCol
[iColumn
].affinity
;
505 pScan
->zCollName
= pIdx
->azColl
[j
];
506 }else if( iColumn
==XN_EXPR
){
507 pScan
->pIdxExpr
= pIdx
->aColExpr
->a
[j
].pExpr
;
508 pScan
->zCollName
= pIdx
->azColl
[j
];
509 pScan
->aiColumn
[0] = XN_EXPR
;
510 return whereScanInitIndexExpr(pScan
);
512 }else if( iColumn
==XN_EXPR
){
515 pScan
->aiColumn
[0] = iColumn
;
516 return whereScanNext(pScan
);
520 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
521 ** where X is a reference to the iColumn of table iCur or of index pIdx
522 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
523 ** the op parameter. Return a pointer to the term. Return 0 if not found.
525 ** If pIdx!=0 then it must be one of the indexes of table iCur.
526 ** Search for terms matching the iColumn-th column of pIdx
527 ** rather than the iColumn-th column of table iCur.
529 ** The term returned might by Y=<expr> if there is another constraint in
530 ** the WHERE clause that specifies that X=Y. Any such constraints will be
531 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
532 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
533 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
534 ** other equivalent values. Hence a search for X will return <expr> if X=A1
535 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
537 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
538 ** then try for the one with no dependencies on <expr> - in other words where
539 ** <expr> is a constant expression of some kind. Only return entries of
540 ** the form "X <op> Y" where Y is a column in another table if no terms of
541 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
542 ** exist, try to return a term that does not use WO_EQUIV.
544 WhereTerm
*sqlite3WhereFindTerm(
545 WhereClause
*pWC
, /* The WHERE clause to be searched */
546 int iCur
, /* Cursor number of LHS */
547 int iColumn
, /* Column number of LHS */
548 Bitmask notReady
, /* RHS must not overlap with this mask */
549 u32 op
, /* Mask of WO_xx values describing operator */
550 Index
*pIdx
/* Must be compatible with this index, if not NULL */
552 WhereTerm
*pResult
= 0;
556 p
= whereScanInit(&scan
, pWC
, iCur
, iColumn
, op
, pIdx
);
559 if( (p
->prereqRight
& notReady
)==0 ){
560 if( p
->prereqRight
==0 && (p
->eOperator
&op
)!=0 ){
561 testcase( p
->eOperator
& WO_IS
);
564 if( pResult
==0 ) pResult
= p
;
566 p
= whereScanNext(&scan
);
572 ** This function searches pList for an entry that matches the iCol-th column
575 ** If such an expression is found, its index in pList->a[] is returned. If
576 ** no expression is found, -1 is returned.
578 static int findIndexCol(
579 Parse
*pParse
, /* Parse context */
580 ExprList
*pList
, /* Expression list to search */
581 int iBase
, /* Cursor for table associated with pIdx */
582 Index
*pIdx
, /* Index to match column of */
583 int iCol
/* Column of index to match */
586 const char *zColl
= pIdx
->azColl
[iCol
];
588 for(i
=0; i
<pList
->nExpr
; i
++){
589 Expr
*p
= sqlite3ExprSkipCollateAndLikely(pList
->a
[i
].pExpr
);
591 && (p
->op
==TK_COLUMN
|| p
->op
==TK_AGG_COLUMN
)
592 && p
->iColumn
==pIdx
->aiColumn
[iCol
]
595 CollSeq
*pColl
= sqlite3ExprNNCollSeq(pParse
, pList
->a
[i
].pExpr
);
596 if( 0==sqlite3StrICmp(pColl
->zName
, zColl
) ){
606 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
608 static int indexColumnNotNull(Index
*pIdx
, int iCol
){
611 assert( iCol
>=0 && iCol
<pIdx
->nColumn
);
612 j
= pIdx
->aiColumn
[iCol
];
614 return pIdx
->pTable
->aCol
[j
].notNull
;
619 return 0; /* Assume an indexed expression can always yield a NULL */
625 ** Return true if the DISTINCT expression-list passed as the third argument
628 ** A DISTINCT list is redundant if any subset of the columns in the
629 ** DISTINCT list are collectively unique and individually non-null.
631 static int isDistinctRedundant(
632 Parse
*pParse
, /* Parsing context */
633 SrcList
*pTabList
, /* The FROM clause */
634 WhereClause
*pWC
, /* The WHERE clause */
635 ExprList
*pDistinct
/* The result set that needs to be DISTINCT */
642 /* If there is more than one table or sub-select in the FROM clause of
643 ** this query, then it will not be possible to show that the DISTINCT
644 ** clause is redundant. */
645 if( pTabList
->nSrc
!=1 ) return 0;
646 iBase
= pTabList
->a
[0].iCursor
;
647 pTab
= pTabList
->a
[0].pTab
;
649 /* If any of the expressions is an IPK column on table iBase, then return
650 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
651 ** current SELECT is a correlated sub-query.
653 for(i
=0; i
<pDistinct
->nExpr
; i
++){
654 Expr
*p
= sqlite3ExprSkipCollateAndLikely(pDistinct
->a
[i
].pExpr
);
655 if( NEVER(p
==0) ) continue;
656 if( p
->op
!=TK_COLUMN
&& p
->op
!=TK_AGG_COLUMN
) continue;
657 if( p
->iTable
==iBase
&& p
->iColumn
<0 ) return 1;
660 /* Loop through all indices on the table, checking each to see if it makes
661 ** the DISTINCT qualifier redundant. It does so if:
663 ** 1. The index is itself UNIQUE, and
665 ** 2. All of the columns in the index are either part of the pDistinct
666 ** list, or else the WHERE clause contains a term of the form "col=X",
667 ** where X is a constant value. The collation sequences of the
668 ** comparison and select-list expressions must match those of the index.
670 ** 3. All of those index columns for which the WHERE clause does not
671 ** contain a "col=X" term are subject to a NOT NULL constraint.
673 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
674 if( !IsUniqueIndex(pIdx
) ) continue;
675 if( pIdx
->pPartIdxWhere
) continue;
676 for(i
=0; i
<pIdx
->nKeyCol
; i
++){
677 if( 0==sqlite3WhereFindTerm(pWC
, iBase
, i
, ~(Bitmask
)0, WO_EQ
, pIdx
) ){
678 if( findIndexCol(pParse
, pDistinct
, iBase
, pIdx
, i
)<0 ) break;
679 if( indexColumnNotNull(pIdx
, i
)==0 ) break;
682 if( i
==pIdx
->nKeyCol
){
683 /* This index implies that the DISTINCT qualifier is redundant. */
693 ** Estimate the logarithm of the input value to base 2.
695 static LogEst
estLog(LogEst N
){
696 return N
<=10 ? 0 : sqlite3LogEst(N
) - 33;
700 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
702 ** This routine runs over generated VDBE code and translates OP_Column
703 ** opcodes into OP_Copy when the table is being accessed via co-routine
704 ** instead of via table lookup.
706 ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
707 ** cursor iTabCur are transformed into OP_Sequence opcode for the
708 ** iAutoidxCur cursor, in order to generate unique rowids for the
709 ** automatic index being generated.
711 static void translateColumnToCopy(
712 Parse
*pParse
, /* Parsing context */
713 int iStart
, /* Translate from this opcode to the end */
714 int iTabCur
, /* OP_Column/OP_Rowid references to this table */
715 int iRegister
, /* The first column is in this register */
716 int iAutoidxCur
/* If non-zero, cursor of autoindex being generated */
718 Vdbe
*v
= pParse
->pVdbe
;
719 VdbeOp
*pOp
= sqlite3VdbeGetOp(v
, iStart
);
720 int iEnd
= sqlite3VdbeCurrentAddr(v
);
721 if( pParse
->db
->mallocFailed
) return;
722 for(; iStart
<iEnd
; iStart
++, pOp
++){
723 if( pOp
->p1
!=iTabCur
) continue;
724 if( pOp
->opcode
==OP_Column
){
726 if( pParse
->db
->flags
& SQLITE_VdbeAddopTrace
){
727 printf("TRANSLATE OP_Column to OP_Copy at %d\n", iStart
);
730 pOp
->opcode
= OP_Copy
;
731 pOp
->p1
= pOp
->p2
+ iRegister
;
734 pOp
->p5
= 2; /* Cause the MEM_Subtype flag to be cleared */
735 }else if( pOp
->opcode
==OP_Rowid
){
737 if( pParse
->db
->flags
& SQLITE_VdbeAddopTrace
){
738 printf("TRANSLATE OP_Rowid to OP_Sequence at %d\n", iStart
);
741 pOp
->opcode
= OP_Sequence
;
742 pOp
->p1
= iAutoidxCur
;
743 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
744 if( iAutoidxCur
==0 ){
745 pOp
->opcode
= OP_Null
;
754 ** Two routines for printing the content of an sqlite3_index_info
755 ** structure. Used for testing and debugging only. If neither
756 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
759 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
760 static void whereTraceIndexInfoInputs(
761 sqlite3_index_info
*p
, /* The IndexInfo object */
762 Table
*pTab
/* The TABLE that is the virtual table */
765 if( (sqlite3WhereTrace
& 0x10)==0 ) return;
766 sqlite3DebugPrintf("sqlite3_index_info inputs for %s:\n", pTab
->zName
);
767 for(i
=0; i
<p
->nConstraint
; i
++){
769 " constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",
771 p
->aConstraint
[i
].iColumn
,
772 p
->aConstraint
[i
].iTermOffset
,
773 p
->aConstraint
[i
].op
,
774 p
->aConstraint
[i
].usable
,
775 sqlite3_vtab_collation(p
,i
));
777 for(i
=0; i
<p
->nOrderBy
; i
++){
778 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
780 p
->aOrderBy
[i
].iColumn
,
781 p
->aOrderBy
[i
].desc
);
784 static void whereTraceIndexInfoOutputs(
785 sqlite3_index_info
*p
, /* The IndexInfo object */
786 Table
*pTab
/* The TABLE that is the virtual table */
789 if( (sqlite3WhereTrace
& 0x10)==0 ) return;
790 sqlite3DebugPrintf("sqlite3_index_info outputs for %s:\n", pTab
->zName
);
791 for(i
=0; i
<p
->nConstraint
; i
++){
792 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
794 p
->aConstraintUsage
[i
].argvIndex
,
795 p
->aConstraintUsage
[i
].omit
);
797 sqlite3DebugPrintf(" idxNum=%d\n", p
->idxNum
);
798 sqlite3DebugPrintf(" idxStr=%s\n", p
->idxStr
);
799 sqlite3DebugPrintf(" orderByConsumed=%d\n", p
->orderByConsumed
);
800 sqlite3DebugPrintf(" estimatedCost=%g\n", p
->estimatedCost
);
801 sqlite3DebugPrintf(" estimatedRows=%lld\n", p
->estimatedRows
);
804 #define whereTraceIndexInfoInputs(A,B)
805 #define whereTraceIndexInfoOutputs(A,B)
809 ** We know that pSrc is an operand of an outer join. Return true if
810 ** pTerm is a constraint that is compatible with that join.
812 ** pTerm must be EP_OuterON if pSrc is the right operand of an
813 ** outer join. pTerm can be either EP_OuterON or EP_InnerON if pSrc
814 ** is the left operand of a RIGHT join.
816 ** See https://sqlite.org/forum/forumpost/206d99a16dd9212f
817 ** for an example of a WHERE clause constraints that may not be used on
818 ** the right table of a RIGHT JOIN because the constraint implies a
819 ** not-NULL condition on the left table of the RIGHT JOIN.
821 static int constraintCompatibleWithOuterJoin(
822 const WhereTerm
*pTerm
, /* WHERE clause term to check */
823 const SrcItem
*pSrc
/* Table we are trying to access */
825 assert( (pSrc
->fg
.jointype
&(JT_LEFT
|JT_LTORJ
|JT_RIGHT
))!=0 ); /* By caller */
826 testcase( (pSrc
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
))==JT_LEFT
);
827 testcase( (pSrc
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
))==JT_LTORJ
);
828 testcase( ExprHasProperty(pTerm
->pExpr
, EP_OuterON
) )
829 testcase( ExprHasProperty(pTerm
->pExpr
, EP_InnerON
) );
830 if( !ExprHasProperty(pTerm
->pExpr
, EP_OuterON
|EP_InnerON
)
831 || pTerm
->pExpr
->w
.iJoin
!= pSrc
->iCursor
835 if( (pSrc
->fg
.jointype
& (JT_LEFT
|JT_RIGHT
))!=0
836 && ExprHasProperty(pTerm
->pExpr
, EP_InnerON
)
845 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
847 ** Return TRUE if the WHERE clause term pTerm is of a form where it
848 ** could be used with an index to access pSrc, assuming an appropriate
851 static int termCanDriveIndex(
852 const WhereTerm
*pTerm
, /* WHERE clause term to check */
853 const SrcItem
*pSrc
, /* Table we are trying to access */
854 const Bitmask notReady
/* Tables in outer loops of the join */
857 if( pTerm
->leftCursor
!=pSrc
->iCursor
) return 0;
858 if( (pTerm
->eOperator
& (WO_EQ
|WO_IS
))==0 ) return 0;
859 assert( (pSrc
->fg
.jointype
& JT_RIGHT
)==0 );
860 if( (pSrc
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
))!=0
861 && !constraintCompatibleWithOuterJoin(pTerm
,pSrc
)
863 return 0; /* See https://sqlite.org/forum/forumpost/51e6959f61 */
865 if( (pTerm
->prereqRight
& notReady
)!=0 ) return 0;
866 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 );
867 if( pTerm
->u
.x
.leftColumn
<0 ) return 0;
868 aff
= pSrc
->pTab
->aCol
[pTerm
->u
.x
.leftColumn
].affinity
;
869 if( !sqlite3IndexAffinityOk(pTerm
->pExpr
, aff
) ) return 0;
870 testcase( pTerm
->pExpr
->op
==TK_IS
);
876 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
878 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
880 ** Argument pIdx represents an automatic index that the current statement
881 ** will create and populate. Add an OP_Explain with text of the form:
883 ** CREATE AUTOMATIC INDEX ON <table>(<cols>) [WHERE <expr>]
885 ** This is only required if sqlite3_stmt_scanstatus() is enabled, to
886 ** associate an SQLITE_SCANSTAT_NCYCLE and SQLITE_SCANSTAT_NLOOP
887 ** values with. In order to avoid breaking legacy code and test cases,
888 ** the OP_Explain is not added if this is an EXPLAIN QUERY PLAN command.
890 static void explainAutomaticIndex(
892 Index
*pIdx
, /* Automatic index to explain */
893 int bPartial
, /* True if pIdx is a partial index */
894 int *pAddrExplain
/* OUT: Address of OP_Explain */
896 if( IS_STMT_SCANSTATUS(pParse
->db
) && pParse
->explain
!=2 ){
897 Table
*pTab
= pIdx
->pTable
;
898 const char *zSep
= "";
901 sqlite3_str
*pStr
= sqlite3_str_new(pParse
->db
);
902 sqlite3_str_appendf(pStr
,"CREATE AUTOMATIC INDEX ON %s(", pTab
->zName
);
903 assert( pIdx
->nColumn
>1 );
904 assert( pIdx
->aiColumn
[pIdx
->nColumn
-1]==XN_ROWID
);
905 for(ii
=0; ii
<(pIdx
->nColumn
-1); ii
++){
906 const char *zName
= 0;
907 int iCol
= pIdx
->aiColumn
[ii
];
909 zName
= pTab
->aCol
[iCol
].zCnName
;
910 sqlite3_str_appendf(pStr
, "%s%s", zSep
, zName
);
913 zText
= sqlite3_str_finish(pStr
);
915 sqlite3OomFault(pParse
->db
);
917 *pAddrExplain
= sqlite3VdbeExplain(
918 pParse
, 0, "%s)%s", zText
, (bPartial
? " WHERE <expr>" : "")
925 # define explainAutomaticIndex(a,b,c,d)
929 ** Generate code to construct the Index object for an automatic index
930 ** and to set up the WhereLevel object pLevel so that the code generator
931 ** makes use of the automatic index.
933 static SQLITE_NOINLINE
void constructAutomaticIndex(
934 Parse
*pParse
, /* The parsing context */
935 WhereClause
*pWC
, /* The WHERE clause */
936 const Bitmask notReady
, /* Mask of cursors that are not available */
937 WhereLevel
*pLevel
/* Write new index here */
939 int nKeyCol
; /* Number of columns in the constructed index */
940 WhereTerm
*pTerm
; /* A single term of the WHERE clause */
941 WhereTerm
*pWCEnd
; /* End of pWC->a[] */
942 Index
*pIdx
; /* Object describing the transient index */
943 Vdbe
*v
; /* Prepared statement under construction */
944 int addrInit
; /* Address of the initialization bypass jump */
945 Table
*pTable
; /* The table being indexed */
946 int addrTop
; /* Top of the index fill loop */
947 int regRecord
; /* Register holding an index record */
948 int n
; /* Column counter */
949 int i
; /* Loop counter */
950 int mxBitCol
; /* Maximum column in pSrc->colUsed */
951 CollSeq
*pColl
; /* Collating sequence to on a column */
952 WhereLoop
*pLoop
; /* The Loop object */
953 char *zNotUsed
; /* Extra space on the end of pIdx */
954 Bitmask idxCols
; /* Bitmap of columns used for indexing */
955 Bitmask extraCols
; /* Bitmap of additional columns */
956 u8 sentWarning
= 0; /* True if a warning has been issued */
957 u8 useBloomFilter
= 0; /* True to also add a Bloom filter */
958 Expr
*pPartial
= 0; /* Partial Index Expression */
959 int iContinue
= 0; /* Jump here to skip excluded rows */
960 SrcList
*pTabList
; /* The complete FROM clause */
961 SrcItem
*pSrc
; /* The FROM clause term to get the next index */
962 int addrCounter
= 0; /* Address where integer counter is initialized */
963 int regBase
; /* Array of registers where record is assembled */
964 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
965 int addrExp
= 0; /* Address of OP_Explain */
968 /* Generate code to skip over the creation and initialization of the
969 ** transient index on 2nd and subsequent iterations of the loop. */
972 addrInit
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
974 /* Count the number of columns that will be added to the index
975 ** and used to match WHERE clause constraints */
977 pTabList
= pWC
->pWInfo
->pTabList
;
978 pSrc
= &pTabList
->a
[pLevel
->iFrom
];
980 pWCEnd
= &pWC
->a
[pWC
->nTerm
];
981 pLoop
= pLevel
->pWLoop
;
983 for(pTerm
=pWC
->a
; pTerm
<pWCEnd
; pTerm
++){
984 Expr
*pExpr
= pTerm
->pExpr
;
985 /* Make the automatic index a partial index if there are terms in the
986 ** WHERE clause (or the ON clause of a LEFT join) that constrain which
987 ** rows of the target table (pSrc) that can be used. */
988 if( (pTerm
->wtFlags
& TERM_VIRTUAL
)==0
989 && sqlite3ExprIsSingleTableConstraint(pExpr
, pTabList
, pLevel
->iFrom
, 0)
991 pPartial
= sqlite3ExprAnd(pParse
, pPartial
,
992 sqlite3ExprDup(pParse
->db
, pExpr
, 0));
994 if( termCanDriveIndex(pTerm
, pSrc
, notReady
) ){
997 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 );
998 iCol
= pTerm
->u
.x
.leftColumn
;
999 cMask
= iCol
>=BMS
? MASKBIT(BMS
-1) : MASKBIT(iCol
);
1000 testcase( iCol
==BMS
);
1001 testcase( iCol
==BMS
-1 );
1003 sqlite3_log(SQLITE_WARNING_AUTOINDEX
,
1004 "automatic index on %s(%s)", pTable
->zName
,
1005 pTable
->aCol
[iCol
].zCnName
);
1008 if( (idxCols
& cMask
)==0 ){
1009 if( whereLoopResize(pParse
->db
, pLoop
, nKeyCol
+1) ){
1010 goto end_auto_index_create
;
1012 pLoop
->aLTerm
[nKeyCol
++] = pTerm
;
1017 assert( nKeyCol
>0 || pParse
->db
->mallocFailed
);
1018 pLoop
->u
.btree
.nEq
= pLoop
->nLTerm
= nKeyCol
;
1019 pLoop
->wsFlags
= WHERE_COLUMN_EQ
| WHERE_IDX_ONLY
| WHERE_INDEXED
1022 /* Count the number of additional columns needed to create a
1023 ** covering index. A "covering index" is an index that contains all
1024 ** columns that are needed by the query. With a covering index, the
1025 ** original table never needs to be accessed. Automatic indices must
1026 ** be a covering index because the index will not be updated if the
1027 ** original table changes and the index and table cannot both be used
1028 ** if they go out of sync.
1030 if( IsView(pTable
) ){
1031 extraCols
= ALLBITS
& ~idxCols
;
1033 extraCols
= pSrc
->colUsed
& (~idxCols
| MASKBIT(BMS
-1));
1035 mxBitCol
= MIN(BMS
-1,pTable
->nCol
);
1036 testcase( pTable
->nCol
==BMS
-1 );
1037 testcase( pTable
->nCol
==BMS
-2 );
1038 for(i
=0; i
<mxBitCol
; i
++){
1039 if( extraCols
& MASKBIT(i
) ) nKeyCol
++;
1041 if( pSrc
->colUsed
& MASKBIT(BMS
-1) ){
1042 nKeyCol
+= pTable
->nCol
- BMS
+ 1;
1045 /* Construct the Index object to describe this index */
1046 pIdx
= sqlite3AllocateIndexObject(pParse
->db
, nKeyCol
+1, 0, &zNotUsed
);
1047 if( pIdx
==0 ) goto end_auto_index_create
;
1048 pLoop
->u
.btree
.pIndex
= pIdx
;
1049 pIdx
->zName
= "auto-index";
1050 pIdx
->pTable
= pTable
;
1053 for(pTerm
=pWC
->a
; pTerm
<pWCEnd
; pTerm
++){
1054 if( termCanDriveIndex(pTerm
, pSrc
, notReady
) ){
1057 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 );
1058 iCol
= pTerm
->u
.x
.leftColumn
;
1059 cMask
= iCol
>=BMS
? MASKBIT(BMS
-1) : MASKBIT(iCol
);
1060 testcase( iCol
==BMS
-1 );
1061 testcase( iCol
==BMS
);
1062 if( (idxCols
& cMask
)==0 ){
1063 Expr
*pX
= pTerm
->pExpr
;
1065 pIdx
->aiColumn
[n
] = pTerm
->u
.x
.leftColumn
;
1066 pColl
= sqlite3ExprCompareCollSeq(pParse
, pX
);
1067 assert( pColl
!=0 || pParse
->nErr
>0 ); /* TH3 collate01.800 */
1068 pIdx
->azColl
[n
] = pColl
? pColl
->zName
: sqlite3StrBINARY
;
1070 if( ALWAYS(pX
->pLeft
!=0)
1071 && sqlite3ExprAffinity(pX
->pLeft
)!=SQLITE_AFF_TEXT
1073 /* TUNING: only use a Bloom filter on an automatic index
1074 ** if one or more key columns has the ability to hold numeric
1075 ** values, since strings all have the same hash in the Bloom
1076 ** filter implementation and hence a Bloom filter on a text column
1077 ** is not usually helpful. */
1083 assert( (u32
)n
==pLoop
->u
.btree
.nEq
);
1085 /* Add additional columns needed to make the automatic index into
1086 ** a covering index */
1087 for(i
=0; i
<mxBitCol
; i
++){
1088 if( extraCols
& MASKBIT(i
) ){
1089 pIdx
->aiColumn
[n
] = i
;
1090 pIdx
->azColl
[n
] = sqlite3StrBINARY
;
1094 if( pSrc
->colUsed
& MASKBIT(BMS
-1) ){
1095 for(i
=BMS
-1; i
<pTable
->nCol
; i
++){
1096 pIdx
->aiColumn
[n
] = i
;
1097 pIdx
->azColl
[n
] = sqlite3StrBINARY
;
1101 assert( n
==nKeyCol
);
1102 pIdx
->aiColumn
[n
] = XN_ROWID
;
1103 pIdx
->azColl
[n
] = sqlite3StrBINARY
;
1105 /* Create the automatic index */
1106 explainAutomaticIndex(pParse
, pIdx
, pPartial
!=0, &addrExp
);
1107 assert( pLevel
->iIdxCur
>=0 );
1108 pLevel
->iIdxCur
= pParse
->nTab
++;
1109 sqlite3VdbeAddOp2(v
, OP_OpenAutoindex
, pLevel
->iIdxCur
, nKeyCol
+1);
1110 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
1111 VdbeComment((v
, "for %s", pTable
->zName
));
1112 if( OptimizationEnabled(pParse
->db
, SQLITE_BloomFilter
) && useBloomFilter
){
1113 sqlite3WhereExplainBloomFilter(pParse
, pWC
->pWInfo
, pLevel
);
1114 pLevel
->regFilter
= ++pParse
->nMem
;
1115 sqlite3VdbeAddOp2(v
, OP_Blob
, 10000, pLevel
->regFilter
);
1118 /* Fill the automatic index with content */
1119 assert( pSrc
== &pWC
->pWInfo
->pTabList
->a
[pLevel
->iFrom
] );
1120 if( pSrc
->fg
.viaCoroutine
){
1121 int regYield
= pSrc
->regReturn
;
1122 addrCounter
= sqlite3VdbeAddOp2(v
, OP_Integer
, 0, 0);
1123 sqlite3VdbeAddOp3(v
, OP_InitCoroutine
, regYield
, 0, pSrc
->addrFillSub
);
1124 addrTop
= sqlite3VdbeAddOp1(v
, OP_Yield
, regYield
);
1126 VdbeComment((v
, "next row of %s", pSrc
->pTab
->zName
));
1128 addrTop
= sqlite3VdbeAddOp1(v
, OP_Rewind
, pLevel
->iTabCur
); VdbeCoverage(v
);
1131 iContinue
= sqlite3VdbeMakeLabel(pParse
);
1132 sqlite3ExprIfFalse(pParse
, pPartial
, iContinue
, SQLITE_JUMPIFNULL
);
1133 pLoop
->wsFlags
|= WHERE_PARTIALIDX
;
1135 regRecord
= sqlite3GetTempReg(pParse
);
1136 regBase
= sqlite3GenerateIndexKey(
1137 pParse
, pIdx
, pLevel
->iTabCur
, regRecord
, 0, 0, 0, 0
1139 if( pLevel
->regFilter
){
1140 sqlite3VdbeAddOp4Int(v
, OP_FilterAdd
, pLevel
->regFilter
, 0,
1141 regBase
, pLoop
->u
.btree
.nEq
);
1143 sqlite3VdbeScanStatusCounters(v
, addrExp
, addrExp
, sqlite3VdbeCurrentAddr(v
));
1144 sqlite3VdbeAddOp2(v
, OP_IdxInsert
, pLevel
->iIdxCur
, regRecord
);
1145 sqlite3VdbeChangeP5(v
, OPFLAG_USESEEKRESULT
);
1146 if( pPartial
) sqlite3VdbeResolveLabel(v
, iContinue
);
1147 if( pSrc
->fg
.viaCoroutine
){
1148 sqlite3VdbeChangeP2(v
, addrCounter
, regBase
+n
);
1149 testcase( pParse
->db
->mallocFailed
);
1150 assert( pLevel
->iIdxCur
>0 );
1151 translateColumnToCopy(pParse
, addrTop
, pLevel
->iTabCur
,
1152 pSrc
->regResult
, pLevel
->iIdxCur
);
1153 sqlite3VdbeGoto(v
, addrTop
);
1154 pSrc
->fg
.viaCoroutine
= 0;
1156 sqlite3VdbeAddOp2(v
, OP_Next
, pLevel
->iTabCur
, addrTop
+1); VdbeCoverage(v
);
1157 sqlite3VdbeChangeP5(v
, SQLITE_STMTSTATUS_AUTOINDEX
);
1159 sqlite3VdbeJumpHere(v
, addrTop
);
1160 sqlite3ReleaseTempReg(pParse
, regRecord
);
1162 /* Jump here when skipping the initialization */
1163 sqlite3VdbeJumpHere(v
, addrInit
);
1164 sqlite3VdbeScanStatusRange(v
, addrExp
, addrExp
, -1);
1166 end_auto_index_create
:
1167 sqlite3ExprDelete(pParse
->db
, pPartial
);
1169 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1172 ** Generate bytecode that will initialize a Bloom filter that is appropriate
1175 ** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER
1176 ** flag set, initialize a Bloomfilter for them as well. Except don't do
1177 ** this recursive initialization if the SQLITE_BloomPulldown optimization has
1180 ** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared
1181 ** from the loop, but the regFilter value is set to a register that implements
1182 ** the Bloom filter. When regFilter is positive, the
1183 ** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter
1184 ** and skip the subsequence B-Tree seek if the Bloom filter indicates that
1185 ** no matching rows exist.
1187 ** This routine may only be called if it has previously been determined that
1188 ** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit
1191 static SQLITE_NOINLINE
void sqlite3ConstructBloomFilter(
1192 WhereInfo
*pWInfo
, /* The WHERE clause */
1193 int iLevel
, /* Index in pWInfo->a[] that is pLevel */
1194 WhereLevel
*pLevel
, /* Make a Bloom filter for this FROM term */
1195 Bitmask notReady
/* Loops that are not ready */
1197 int addrOnce
; /* Address of opening OP_Once */
1198 int addrTop
; /* Address of OP_Rewind */
1199 int addrCont
; /* Jump here to skip a row */
1200 const WhereTerm
*pTerm
; /* For looping over WHERE clause terms */
1201 const WhereTerm
*pWCEnd
; /* Last WHERE clause term */
1202 Parse
*pParse
= pWInfo
->pParse
; /* Parsing context */
1203 Vdbe
*v
= pParse
->pVdbe
; /* VDBE under construction */
1204 WhereLoop
*pLoop
= pLevel
->pWLoop
; /* The loop being coded */
1205 int iCur
; /* Cursor for table getting the filter */
1206 IndexedExpr
*saved_pIdxEpr
; /* saved copy of Parse.pIdxEpr */
1207 IndexedExpr
*saved_pIdxPartExpr
; /* saved copy of Parse.pIdxPartExpr */
1209 saved_pIdxEpr
= pParse
->pIdxEpr
;
1210 saved_pIdxPartExpr
= pParse
->pIdxPartExpr
;
1211 pParse
->pIdxEpr
= 0;
1212 pParse
->pIdxPartExpr
= 0;
1216 assert( pLoop
->wsFlags
& WHERE_BLOOMFILTER
);
1217 assert( (pLoop
->wsFlags
& WHERE_IDX_ONLY
)==0 );
1219 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
1221 const SrcList
*pTabList
;
1222 const SrcItem
*pItem
;
1226 sqlite3WhereExplainBloomFilter(pParse
, pWInfo
, pLevel
);
1227 addrCont
= sqlite3VdbeMakeLabel(pParse
);
1228 iCur
= pLevel
->iTabCur
;
1229 pLevel
->regFilter
= ++pParse
->nMem
;
1231 /* The Bloom filter is a Blob held in a register. Initialize it
1232 ** to zero-filled blob of at least 80K bits, but maybe more if the
1233 ** estimated size of the table is larger. We could actually
1234 ** measure the size of the table at run-time using OP_Count with
1235 ** P3==1 and use that value to initialize the blob. But that makes
1236 ** testing complicated. By basing the blob size on the value in the
1237 ** sqlite_stat1 table, testing is much easier.
1239 pTabList
= pWInfo
->pTabList
;
1240 iSrc
= pLevel
->iFrom
;
1241 pItem
= &pTabList
->a
[iSrc
];
1245 sz
= sqlite3LogEstToInt(pTab
->nRowLogEst
);
1248 }else if( sz
>10000000 ){
1251 sqlite3VdbeAddOp2(v
, OP_Blob
, (int)sz
, pLevel
->regFilter
);
1253 addrTop
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
1254 pWCEnd
= &pWInfo
->sWC
.a
[pWInfo
->sWC
.nTerm
];
1255 for(pTerm
=pWInfo
->sWC
.a
; pTerm
<pWCEnd
; pTerm
++){
1256 Expr
*pExpr
= pTerm
->pExpr
;
1257 if( (pTerm
->wtFlags
& TERM_VIRTUAL
)==0
1258 && sqlite3ExprIsSingleTableConstraint(pExpr
, pTabList
, iSrc
, 0)
1260 sqlite3ExprIfFalse(pParse
, pTerm
->pExpr
, addrCont
, SQLITE_JUMPIFNULL
);
1263 if( pLoop
->wsFlags
& WHERE_IPK
){
1264 int r1
= sqlite3GetTempReg(pParse
);
1265 sqlite3VdbeAddOp2(v
, OP_Rowid
, iCur
, r1
);
1266 sqlite3VdbeAddOp4Int(v
, OP_FilterAdd
, pLevel
->regFilter
, 0, r1
, 1);
1267 sqlite3ReleaseTempReg(pParse
, r1
);
1269 Index
*pIdx
= pLoop
->u
.btree
.pIndex
;
1270 int n
= pLoop
->u
.btree
.nEq
;
1271 int r1
= sqlite3GetTempRange(pParse
, n
);
1273 for(jj
=0; jj
<n
; jj
++){
1274 assert( pIdx
->pTable
==pItem
->pTab
);
1275 sqlite3ExprCodeLoadIndexColumn(pParse
, pIdx
, iCur
, jj
, r1
+jj
);
1277 sqlite3VdbeAddOp4Int(v
, OP_FilterAdd
, pLevel
->regFilter
, 0, r1
, n
);
1278 sqlite3ReleaseTempRange(pParse
, r1
, n
);
1280 sqlite3VdbeResolveLabel(v
, addrCont
);
1281 sqlite3VdbeAddOp2(v
, OP_Next
, pLevel
->iTabCur
, addrTop
+1);
1283 sqlite3VdbeJumpHere(v
, addrTop
);
1284 pLoop
->wsFlags
&= ~WHERE_BLOOMFILTER
;
1285 if( OptimizationDisabled(pParse
->db
, SQLITE_BloomPulldown
) ) break;
1286 while( ++iLevel
< pWInfo
->nLevel
){
1287 const SrcItem
*pTabItem
;
1288 pLevel
= &pWInfo
->a
[iLevel
];
1289 pTabItem
= &pWInfo
->pTabList
->a
[pLevel
->iFrom
];
1290 if( pTabItem
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
) ) continue;
1291 pLoop
= pLevel
->pWLoop
;
1292 if( NEVER(pLoop
==0) ) continue;
1293 if( pLoop
->prereq
& notReady
) continue;
1294 if( (pLoop
->wsFlags
& (WHERE_BLOOMFILTER
|WHERE_COLUMN_IN
))
1297 /* This is a candidate for bloom-filter pull-down (early evaluation).
1298 ** The test that WHERE_COLUMN_IN is omitted is important, as we are
1299 ** not able to do early evaluation of bloom filters that make use of
1300 ** the IN operator */
1304 }while( iLevel
< pWInfo
->nLevel
);
1305 sqlite3VdbeJumpHere(v
, addrOnce
);
1306 pParse
->pIdxEpr
= saved_pIdxEpr
;
1307 pParse
->pIdxPartExpr
= saved_pIdxPartExpr
;
1311 #ifndef SQLITE_OMIT_VIRTUALTABLE
1313 ** Allocate and populate an sqlite3_index_info structure. It is the
1314 ** responsibility of the caller to eventually release the structure
1315 ** by passing the pointer returned by this function to freeIndexInfo().
1317 static sqlite3_index_info
*allocateIndexInfo(
1318 WhereInfo
*pWInfo
, /* The WHERE clause */
1319 WhereClause
*pWC
, /* The WHERE clause being analyzed */
1320 Bitmask mUnusable
, /* Ignore terms with these prereqs */
1321 SrcItem
*pSrc
, /* The FROM clause term that is the vtab */
1322 u16
*pmNoOmit
/* Mask of terms not to omit */
1326 Parse
*pParse
= pWInfo
->pParse
;
1327 struct sqlite3_index_constraint
*pIdxCons
;
1328 struct sqlite3_index_orderby
*pIdxOrderBy
;
1329 struct sqlite3_index_constraint_usage
*pUsage
;
1330 struct HiddenIndexInfo
*pHidden
;
1333 sqlite3_index_info
*pIdxInfo
;
1337 ExprList
*pOrderBy
= pWInfo
->pOrderBy
;
1342 assert( IsVirtual(pTab
) );
1344 /* Find all WHERE clause constraints referring to this virtual table.
1345 ** Mark each term with the TERM_OK flag. Set nTerm to the number of
1348 for(i
=nTerm
=0, pTerm
=pWC
->a
; i
<pWC
->nTerm
; i
++, pTerm
++){
1349 pTerm
->wtFlags
&= ~TERM_OK
;
1350 if( pTerm
->leftCursor
!= pSrc
->iCursor
) continue;
1351 if( pTerm
->prereqRight
& mUnusable
) continue;
1352 assert( IsPowerOfTwo(pTerm
->eOperator
& ~WO_EQUIV
) );
1353 testcase( pTerm
->eOperator
& WO_IN
);
1354 testcase( pTerm
->eOperator
& WO_ISNULL
);
1355 testcase( pTerm
->eOperator
& WO_IS
);
1356 testcase( pTerm
->eOperator
& WO_ALL
);
1357 if( (pTerm
->eOperator
& ~(WO_EQUIV
))==0 ) continue;
1358 if( pTerm
->wtFlags
& TERM_VNULL
) continue;
1360 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 );
1361 assert( pTerm
->u
.x
.leftColumn
>=XN_ROWID
);
1362 assert( pTerm
->u
.x
.leftColumn
<pTab
->nCol
);
1363 if( (pSrc
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
))!=0
1364 && !constraintCompatibleWithOuterJoin(pTerm
,pSrc
)
1369 pTerm
->wtFlags
|= TERM_OK
;
1372 /* If the ORDER BY clause contains only columns in the current
1373 ** virtual table then allocate space for the aOrderBy part of
1374 ** the sqlite3_index_info structure.
1378 int n
= pOrderBy
->nExpr
;
1380 Expr
*pExpr
= pOrderBy
->a
[i
].pExpr
;
1383 /* Skip over constant terms in the ORDER BY clause */
1384 if( sqlite3ExprIsConstant(0, pExpr
) ){
1388 /* Virtual tables are unable to deal with NULLS FIRST */
1389 if( pOrderBy
->a
[i
].fg
.sortFlags
& KEYINFO_ORDER_BIGNULL
) break;
1391 /* First case - a direct column references without a COLLATE operator */
1392 if( pExpr
->op
==TK_COLUMN
&& pExpr
->iTable
==pSrc
->iCursor
){
1393 assert( pExpr
->iColumn
>=XN_ROWID
&& pExpr
->iColumn
<pTab
->nCol
);
1397 /* 2nd case - a column reference with a COLLATE operator. Only match
1398 ** of the COLLATE operator matches the collation of the column. */
1399 if( pExpr
->op
==TK_COLLATE
1400 && (pE2
= pExpr
->pLeft
)->op
==TK_COLUMN
1401 && pE2
->iTable
==pSrc
->iCursor
1403 const char *zColl
; /* The collating sequence name */
1404 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
1405 assert( pExpr
->u
.zToken
!=0 );
1406 assert( pE2
->iColumn
>=XN_ROWID
&& pE2
->iColumn
<pTab
->nCol
);
1407 pExpr
->iColumn
= pE2
->iColumn
;
1408 if( pE2
->iColumn
<0 ) continue; /* Collseq does not matter for rowid */
1409 zColl
= sqlite3ColumnColl(&pTab
->aCol
[pE2
->iColumn
]);
1410 if( zColl
==0 ) zColl
= sqlite3StrBINARY
;
1411 if( sqlite3_stricmp(pExpr
->u
.zToken
, zColl
)==0 ) continue;
1414 /* No matches cause a break out of the loop */
1419 if( (pWInfo
->wctrlFlags
& WHERE_DISTINCTBY
) && !pSrc
->fg
.rowidUsed
){
1420 eDistinct
= 2 + ((pWInfo
->wctrlFlags
& WHERE_SORTBYGROUP
)!=0);
1421 }else if( pWInfo
->wctrlFlags
& WHERE_GROUPBY
){
1427 /* Allocate the sqlite3_index_info structure
1429 pIdxInfo
= sqlite3DbMallocZero(pParse
->db
, sizeof(*pIdxInfo
)
1430 + (sizeof(*pIdxCons
) + sizeof(*pUsage
))*nTerm
1431 + sizeof(*pIdxOrderBy
)*nOrderBy
+ sizeof(*pHidden
)
1432 + sizeof(sqlite3_value
*)*nTerm
);
1434 sqlite3ErrorMsg(pParse
, "out of memory");
1437 pHidden
= (struct HiddenIndexInfo
*)&pIdxInfo
[1];
1438 pIdxCons
= (struct sqlite3_index_constraint
*)&pHidden
->aRhs
[nTerm
];
1439 pIdxOrderBy
= (struct sqlite3_index_orderby
*)&pIdxCons
[nTerm
];
1440 pUsage
= (struct sqlite3_index_constraint_usage
*)&pIdxOrderBy
[nOrderBy
];
1441 pIdxInfo
->aConstraint
= pIdxCons
;
1442 pIdxInfo
->aOrderBy
= pIdxOrderBy
;
1443 pIdxInfo
->aConstraintUsage
= pUsage
;
1445 pHidden
->pParse
= pParse
;
1446 pHidden
->eDistinct
= eDistinct
;
1448 for(i
=j
=0, pTerm
=pWC
->a
; i
<pWC
->nTerm
; i
++, pTerm
++){
1450 if( (pTerm
->wtFlags
& TERM_OK
)==0 ) continue;
1451 pIdxCons
[j
].iColumn
= pTerm
->u
.x
.leftColumn
;
1452 pIdxCons
[j
].iTermOffset
= i
;
1453 op
= pTerm
->eOperator
& WO_ALL
;
1455 if( (pTerm
->wtFlags
& TERM_SLICE
)==0 ){
1456 pHidden
->mIn
|= SMASKBIT32(j
);
1461 pIdxCons
[j
].op
= pTerm
->eMatchOp
;
1462 }else if( op
& (WO_ISNULL
|WO_IS
) ){
1463 if( op
==WO_ISNULL
){
1464 pIdxCons
[j
].op
= SQLITE_INDEX_CONSTRAINT_ISNULL
;
1466 pIdxCons
[j
].op
= SQLITE_INDEX_CONSTRAINT_IS
;
1469 pIdxCons
[j
].op
= (u8
)op
;
1470 /* The direct assignment in the previous line is possible only because
1471 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1472 ** following asserts verify this fact. */
1473 assert( WO_EQ
==SQLITE_INDEX_CONSTRAINT_EQ
);
1474 assert( WO_LT
==SQLITE_INDEX_CONSTRAINT_LT
);
1475 assert( WO_LE
==SQLITE_INDEX_CONSTRAINT_LE
);
1476 assert( WO_GT
==SQLITE_INDEX_CONSTRAINT_GT
);
1477 assert( WO_GE
==SQLITE_INDEX_CONSTRAINT_GE
);
1478 assert( pTerm
->eOperator
&(WO_IN
|WO_EQ
|WO_LT
|WO_LE
|WO_GT
|WO_GE
|WO_AUX
) );
1480 if( op
& (WO_LT
|WO_LE
|WO_GT
|WO_GE
)
1481 && sqlite3ExprIsVector(pTerm
->pExpr
->pRight
)
1484 if( j
<16 ) mNoOmit
|= (1 << j
);
1485 if( op
==WO_LT
) pIdxCons
[j
].op
= WO_LE
;
1486 if( op
==WO_GT
) pIdxCons
[j
].op
= WO_GE
;
1493 pIdxInfo
->nConstraint
= j
;
1494 for(i
=j
=0; i
<nOrderBy
; i
++){
1495 Expr
*pExpr
= pOrderBy
->a
[i
].pExpr
;
1496 if( sqlite3ExprIsConstant(0, pExpr
) ) continue;
1497 assert( pExpr
->op
==TK_COLUMN
1498 || (pExpr
->op
==TK_COLLATE
&& pExpr
->pLeft
->op
==TK_COLUMN
1499 && pExpr
->iColumn
==pExpr
->pLeft
->iColumn
) );
1500 pIdxOrderBy
[j
].iColumn
= pExpr
->iColumn
;
1501 pIdxOrderBy
[j
].desc
= pOrderBy
->a
[i
].fg
.sortFlags
& KEYINFO_ORDER_DESC
;
1504 pIdxInfo
->nOrderBy
= j
;
1506 *pmNoOmit
= mNoOmit
;
1511 ** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
1512 ** and possibly modified by xBestIndex methods.
1514 static void freeIndexInfo(sqlite3
*db
, sqlite3_index_info
*pIdxInfo
){
1515 HiddenIndexInfo
*pHidden
;
1517 assert( pIdxInfo
!=0 );
1518 pHidden
= (HiddenIndexInfo
*)&pIdxInfo
[1];
1519 assert( pHidden
->pParse
!=0 );
1520 assert( pHidden
->pParse
->db
==db
);
1521 for(i
=0; i
<pIdxInfo
->nConstraint
; i
++){
1522 sqlite3ValueFree(pHidden
->aRhs
[i
]); /* IMP: R-14553-25174 */
1523 pHidden
->aRhs
[i
] = 0;
1525 sqlite3DbFree(db
, pIdxInfo
);
1529 ** The table object reference passed as the second argument to this function
1530 ** must represent a virtual table. This function invokes the xBestIndex()
1531 ** method of the virtual table with the sqlite3_index_info object that
1532 ** comes in as the 3rd argument to this function.
1534 ** If an error occurs, pParse is populated with an error message and an
1535 ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
1536 ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
1537 ** the current configuration of "unusable" flags in sqlite3_index_info can
1538 ** not result in a valid plan.
1540 ** Whether or not an error is returned, it is the responsibility of the
1541 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1542 ** that this is required.
1544 static int vtabBestIndex(Parse
*pParse
, Table
*pTab
, sqlite3_index_info
*p
){
1545 sqlite3_vtab
*pVtab
= sqlite3GetVTable(pParse
->db
, pTab
)->pVtab
;
1548 whereTraceIndexInfoInputs(p
, pTab
);
1549 pParse
->db
->nSchemaLock
++;
1550 rc
= pVtab
->pModule
->xBestIndex(pVtab
, p
);
1551 pParse
->db
->nSchemaLock
--;
1552 whereTraceIndexInfoOutputs(p
, pTab
);
1554 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_CONSTRAINT
){
1555 if( rc
==SQLITE_NOMEM
){
1556 sqlite3OomFault(pParse
->db
);
1557 }else if( !pVtab
->zErrMsg
){
1558 sqlite3ErrorMsg(pParse
, "%s", sqlite3ErrStr(rc
));
1560 sqlite3ErrorMsg(pParse
, "%s", pVtab
->zErrMsg
);
1563 if( pTab
->u
.vtab
.p
->bAllSchemas
){
1564 sqlite3VtabUsesAllSchemas(pParse
);
1566 sqlite3_free(pVtab
->zErrMsg
);
1570 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
1572 #ifdef SQLITE_ENABLE_STAT4
1574 ** Estimate the location of a particular key among all keys in an
1575 ** index. Store the results in aStat as follows:
1577 ** aStat[0] Est. number of rows less than pRec
1578 ** aStat[1] Est. number of rows equal to pRec
1580 ** Return the index of the sample that is the smallest sample that
1581 ** is greater than or equal to pRec. Note that this index is not an index
1582 ** into the aSample[] array - it is an index into a virtual set of samples
1583 ** based on the contents of aSample[] and the number of fields in record
1586 static int whereKeyStats(
1587 Parse
*pParse
, /* Database connection */
1588 Index
*pIdx
, /* Index to consider domain of */
1589 UnpackedRecord
*pRec
, /* Vector of values to consider */
1590 int roundUp
, /* Round up if true. Round down if false */
1591 tRowcnt
*aStat
/* OUT: stats written here */
1593 IndexSample
*aSample
= pIdx
->aSample
;
1594 int iCol
; /* Index of required stats in anEq[] etc. */
1595 int i
; /* Index of first sample >= pRec */
1596 int iSample
; /* Smallest sample larger than or equal to pRec */
1597 int iMin
= 0; /* Smallest sample not yet tested */
1598 int iTest
; /* Next sample to test */
1599 int res
; /* Result of comparison operation */
1600 int nField
; /* Number of fields in pRec */
1601 tRowcnt iLower
= 0; /* anLt[] + anEq[] of largest sample pRec is > */
1603 #ifndef SQLITE_DEBUG
1604 UNUSED_PARAMETER( pParse
);
1607 assert( pIdx
->nSample
>0 );
1608 assert( pRec
->nField
>0 );
1611 /* Do a binary search to find the first sample greater than or equal
1612 ** to pRec. If pRec contains a single field, the set of samples to search
1613 ** is simply the aSample[] array. If the samples in aSample[] contain more
1614 ** than one fields, all fields following the first are ignored.
1616 ** If pRec contains N fields, where N is more than one, then as well as the
1617 ** samples in aSample[] (truncated to N fields), the search also has to
1618 ** consider prefixes of those samples. For example, if the set of samples
1621 ** aSample[0] = (a, 5)
1622 ** aSample[1] = (a, 10)
1623 ** aSample[2] = (b, 5)
1624 ** aSample[3] = (c, 100)
1625 ** aSample[4] = (c, 105)
1627 ** Then the search space should ideally be the samples above and the
1628 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
1629 ** the code actually searches this set:
1642 ** For each sample in the aSample[] array, N samples are present in the
1643 ** effective sample array. In the above, samples 0 and 1 are based on
1644 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
1646 ** Often, sample i of each block of N effective samples has (i+1) fields.
1647 ** Except, each sample may be extended to ensure that it is greater than or
1648 ** equal to the previous sample in the array. For example, in the above,
1649 ** sample 2 is the first sample of a block of N samples, so at first it
1650 ** appears that it should be 1 field in size. However, that would make it
1651 ** smaller than sample 1, so the binary search would not work. As a result,
1652 ** it is extended to two fields. The duplicates that this creates do not
1653 ** cause any problems.
1655 if( !HasRowid(pIdx
->pTable
) && IsPrimaryKeyIndex(pIdx
) ){
1656 nField
= pIdx
->nKeyCol
;
1658 nField
= pIdx
->nColumn
;
1660 nField
= MIN(pRec
->nField
, nField
);
1662 iSample
= pIdx
->nSample
* nField
;
1664 int iSamp
; /* Index in aSample[] of test sample */
1665 int n
; /* Number of fields in test sample */
1667 iTest
= (iMin
+iSample
)/2;
1668 iSamp
= iTest
/ nField
;
1670 /* The proposed effective sample is a prefix of sample aSample[iSamp].
1671 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
1672 ** fields that is greater than the previous effective sample. */
1673 for(n
=(iTest
% nField
) + 1; n
<nField
; n
++){
1674 if( aSample
[iSamp
-1].anLt
[n
-1]!=aSample
[iSamp
].anLt
[n
-1] ) break;
1681 res
= sqlite3VdbeRecordCompare(aSample
[iSamp
].n
, aSample
[iSamp
].p
, pRec
);
1683 iLower
= aSample
[iSamp
].anLt
[n
-1] + aSample
[iSamp
].anEq
[n
-1];
1685 }else if( res
==0 && n
<nField
){
1686 iLower
= aSample
[iSamp
].anLt
[n
-1];
1693 }while( res
&& iMin
<iSample
);
1694 i
= iSample
/ nField
;
1697 /* The following assert statements check that the binary search code
1698 ** above found the right answer. This block serves no purpose other
1699 ** than to invoke the asserts. */
1700 if( pParse
->db
->mallocFailed
==0 ){
1702 /* If (res==0) is true, then pRec must be equal to sample i. */
1703 assert( i
<pIdx
->nSample
);
1704 assert( iCol
==nField
-1 );
1705 pRec
->nField
= nField
;
1706 assert( 0==sqlite3VdbeRecordCompare(aSample
[i
].n
, aSample
[i
].p
, pRec
)
1707 || pParse
->db
->mallocFailed
1710 /* Unless i==pIdx->nSample, indicating that pRec is larger than
1711 ** all samples in the aSample[] array, pRec must be smaller than the
1712 ** (iCol+1) field prefix of sample i. */
1713 assert( i
<=pIdx
->nSample
&& i
>=0 );
1714 pRec
->nField
= iCol
+1;
1715 assert( i
==pIdx
->nSample
1716 || sqlite3VdbeRecordCompare(aSample
[i
].n
, aSample
[i
].p
, pRec
)>0
1717 || pParse
->db
->mallocFailed
);
1719 /* if i==0 and iCol==0, then record pRec is smaller than all samples
1720 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
1721 ** be greater than or equal to the (iCol) field prefix of sample i.
1722 ** If (i>0), then pRec must also be greater than sample (i-1). */
1724 pRec
->nField
= iCol
;
1725 assert( sqlite3VdbeRecordCompare(aSample
[i
].n
, aSample
[i
].p
, pRec
)<=0
1726 || pParse
->db
->mallocFailed
|| CORRUPT_DB
);
1729 pRec
->nField
= nField
;
1730 assert( sqlite3VdbeRecordCompare(aSample
[i
-1].n
, aSample
[i
-1].p
, pRec
)<0
1731 || pParse
->db
->mallocFailed
|| CORRUPT_DB
);
1735 #endif /* ifdef SQLITE_DEBUG */
1738 /* Record pRec is equal to sample i */
1739 assert( iCol
==nField
-1 );
1740 aStat
[0] = aSample
[i
].anLt
[iCol
];
1741 aStat
[1] = aSample
[i
].anEq
[iCol
];
1743 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
1744 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
1745 ** is larger than all samples in the array. */
1746 tRowcnt iUpper
, iGap
;
1747 if( i
>=pIdx
->nSample
){
1748 iUpper
= pIdx
->nRowEst0
;
1750 iUpper
= aSample
[i
].anLt
[iCol
];
1753 if( iLower
>=iUpper
){
1756 iGap
= iUpper
- iLower
;
1763 aStat
[0] = iLower
+ iGap
;
1764 aStat
[1] = pIdx
->aAvgEq
[nField
-1];
1767 /* Restore the pRec->nField value before returning. */
1768 pRec
->nField
= nField
;
1771 #endif /* SQLITE_ENABLE_STAT4 */
1774 ** If it is not NULL, pTerm is a term that provides an upper or lower
1775 ** bound on a range scan. Without considering pTerm, it is estimated
1776 ** that the scan will visit nNew rows. This function returns the number
1777 ** estimated to be visited after taking pTerm into account.
1779 ** If the user explicitly specified a likelihood() value for this term,
1780 ** then the return value is the likelihood multiplied by the number of
1781 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
1782 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
1784 static LogEst
whereRangeAdjust(WhereTerm
*pTerm
, LogEst nNew
){
1787 if( pTerm
->truthProb
<=0 ){
1788 nRet
+= pTerm
->truthProb
;
1789 }else if( (pTerm
->wtFlags
& TERM_VNULL
)==0 ){
1790 nRet
-= 20; assert( 20==sqlite3LogEst(4) );
1797 #ifdef SQLITE_ENABLE_STAT4
1799 ** Return the affinity for a single column of an index.
1801 char sqlite3IndexColumnAffinity(sqlite3
*db
, Index
*pIdx
, int iCol
){
1802 assert( iCol
>=0 && iCol
<pIdx
->nColumn
);
1803 if( !pIdx
->zColAff
){
1804 if( sqlite3IndexAffinityStr(db
, pIdx
)==0 ) return SQLITE_AFF_BLOB
;
1806 assert( pIdx
->zColAff
[iCol
]!=0 );
1807 return pIdx
->zColAff
[iCol
];
1812 #ifdef SQLITE_ENABLE_STAT4
1814 ** This function is called to estimate the number of rows visited by a
1815 ** range-scan on a skip-scan index. For example:
1817 ** CREATE INDEX i1 ON t1(a, b, c);
1818 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
1820 ** Value pLoop->nOut is currently set to the estimated number of rows
1821 ** visited for scanning (a=? AND b=?). This function reduces that estimate
1822 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
1823 ** on the stat4 data for the index. this scan will be performed multiple
1824 ** times (once for each (a,b) combination that matches a=?) is dealt with
1827 ** It does this by scanning through all stat4 samples, comparing values
1828 ** extracted from pLower and pUpper with the corresponding column in each
1829 ** sample. If L and U are the number of samples found to be less than or
1830 ** equal to the values extracted from pLower and pUpper respectively, and
1831 ** N is the total number of samples, the pLoop->nOut value is adjusted
1834 ** nOut = nOut * ( min(U - L, 1) / N )
1836 ** If pLower is NULL, or a value cannot be extracted from the term, L is
1837 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
1840 ** Normally, this function sets *pbDone to 1 before returning. However,
1841 ** if no value can be extracted from either pLower or pUpper (and so the
1842 ** estimate of the number of rows delivered remains unchanged), *pbDone
1845 ** If an error occurs, an SQLite error code is returned. Otherwise,
1848 static int whereRangeSkipScanEst(
1849 Parse
*pParse
, /* Parsing & code generating context */
1850 WhereTerm
*pLower
, /* Lower bound on the range. ex: "x>123" Might be NULL */
1851 WhereTerm
*pUpper
, /* Upper bound on the range. ex: "x<455" Might be NULL */
1852 WhereLoop
*pLoop
, /* Update the .nOut value of this loop */
1853 int *pbDone
/* Set to true if at least one expr. value extracted */
1855 Index
*p
= pLoop
->u
.btree
.pIndex
;
1856 int nEq
= pLoop
->u
.btree
.nEq
;
1857 sqlite3
*db
= pParse
->db
;
1859 int nUpper
= p
->nSample
+1;
1861 u8 aff
= sqlite3IndexColumnAffinity(db
, p
, nEq
);
1864 sqlite3_value
*p1
= 0; /* Value extracted from pLower */
1865 sqlite3_value
*p2
= 0; /* Value extracted from pUpper */
1866 sqlite3_value
*pVal
= 0; /* Value extracted from record */
1868 pColl
= sqlite3LocateCollSeq(pParse
, p
->azColl
[nEq
]);
1870 rc
= sqlite3Stat4ValueFromExpr(pParse
, pLower
->pExpr
->pRight
, aff
, &p1
);
1873 if( pUpper
&& rc
==SQLITE_OK
){
1874 rc
= sqlite3Stat4ValueFromExpr(pParse
, pUpper
->pExpr
->pRight
, aff
, &p2
);
1875 nUpper
= p2
? 0 : p
->nSample
;
1881 for(i
=0; rc
==SQLITE_OK
&& i
<p
->nSample
; i
++){
1882 rc
= sqlite3Stat4Column(db
, p
->aSample
[i
].p
, p
->aSample
[i
].n
, nEq
, &pVal
);
1883 if( rc
==SQLITE_OK
&& p1
){
1884 int res
= sqlite3MemCompare(p1
, pVal
, pColl
);
1885 if( res
>=0 ) nLower
++;
1887 if( rc
==SQLITE_OK
&& p2
){
1888 int res
= sqlite3MemCompare(p2
, pVal
, pColl
);
1889 if( res
>=0 ) nUpper
++;
1892 nDiff
= (nUpper
- nLower
);
1893 if( nDiff
<=0 ) nDiff
= 1;
1895 /* If there is both an upper and lower bound specified, and the
1896 ** comparisons indicate that they are close together, use the fallback
1897 ** method (assume that the scan visits 1/64 of the rows) for estimating
1898 ** the number of rows visited. Otherwise, estimate the number of rows
1899 ** using the method described in the header comment for this function. */
1900 if( nDiff
!=1 || pUpper
==0 || pLower
==0 ){
1901 int nAdjust
= (sqlite3LogEst(p
->nSample
) - sqlite3LogEst(nDiff
));
1902 pLoop
->nOut
-= nAdjust
;
1904 WHERETRACE(0x20, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
1905 nLower
, nUpper
, nAdjust
*-1, pLoop
->nOut
));
1909 assert( *pbDone
==0 );
1912 sqlite3ValueFree(p1
);
1913 sqlite3ValueFree(p2
);
1914 sqlite3ValueFree(pVal
);
1918 #endif /* SQLITE_ENABLE_STAT4 */
1921 ** This function is used to estimate the number of rows that will be visited
1922 ** by scanning an index for a range of values. The range may have an upper
1923 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
1924 ** and lower bounds are represented by pLower and pUpper respectively. For
1925 ** example, assuming that index p is on t1(a):
1927 ** ... FROM t1 WHERE a > ? AND a < ? ...
1932 ** If either of the upper or lower bound is not present, then NULL is passed in
1933 ** place of the corresponding WhereTerm.
1935 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
1936 ** column subject to the range constraint. Or, equivalently, the number of
1937 ** equality constraints optimized by the proposed index scan. For example,
1938 ** assuming index p is on t1(a, b), and the SQL query is:
1940 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
1942 ** then nEq is set to 1 (as the range restricted column, b, is the second
1943 ** left-most column of the index). Or, if the query is:
1945 ** ... FROM t1 WHERE a > ? AND a < ? ...
1947 ** then nEq is set to 0.
1949 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
1950 ** number of rows that the index scan is expected to visit without
1951 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
1952 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
1953 ** to account for the range constraints pLower and pUpper.
1955 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
1956 ** used, a single range inequality reduces the search space by a factor of 4.
1957 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
1958 ** rows visited by a factor of 64.
1960 static int whereRangeScanEst(
1961 Parse
*pParse
, /* Parsing & code generating context */
1962 WhereLoopBuilder
*pBuilder
,
1963 WhereTerm
*pLower
, /* Lower bound on the range. ex: "x>123" Might be NULL */
1964 WhereTerm
*pUpper
, /* Upper bound on the range. ex: "x<455" Might be NULL */
1965 WhereLoop
*pLoop
/* Modify the .nOut and maybe .rRun fields */
1968 int nOut
= pLoop
->nOut
;
1971 #ifdef SQLITE_ENABLE_STAT4
1972 Index
*p
= pLoop
->u
.btree
.pIndex
;
1973 int nEq
= pLoop
->u
.btree
.nEq
;
1975 if( p
->nSample
>0 && ALWAYS(nEq
<p
->nSampleCol
)
1976 && OptimizationEnabled(pParse
->db
, SQLITE_Stat4
)
1978 if( nEq
==pBuilder
->nRecValid
){
1979 UnpackedRecord
*pRec
= pBuilder
->pRec
;
1981 int nBtm
= pLoop
->u
.btree
.nBtm
;
1982 int nTop
= pLoop
->u
.btree
.nTop
;
1984 /* Variable iLower will be set to the estimate of the number of rows in
1985 ** the index that are less than the lower bound of the range query. The
1986 ** lower bound being the concatenation of $P and $L, where $P is the
1987 ** key-prefix formed by the nEq values matched against the nEq left-most
1988 ** columns of the index, and $L is the value in pLower.
1990 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
1991 ** is not a simple variable or literal value), the lower bound of the
1992 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
1993 ** if $L is available, whereKeyStats() is called for both ($P) and
1994 ** ($P:$L) and the larger of the two returned values is used.
1996 ** Similarly, iUpper is to be set to the estimate of the number of rows
1997 ** less than the upper bound of the range query. Where the upper bound
1998 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
1999 ** of iUpper are requested of whereKeyStats() and the smaller used.
2001 ** The number of rows between the two bounds is then just iUpper-iLower.
2003 tRowcnt iLower
; /* Rows less than the lower bound */
2004 tRowcnt iUpper
; /* Rows less than the upper bound */
2005 int iLwrIdx
= -2; /* aSample[] for the lower bound */
2006 int iUprIdx
= -1; /* aSample[] for the upper bound */
2009 testcase( pRec
->nField
!=pBuilder
->nRecValid
);
2010 pRec
->nField
= pBuilder
->nRecValid
;
2012 /* Determine iLower and iUpper using ($P) only. */
2015 iUpper
= p
->nRowEst0
;
2017 /* Note: this call could be optimized away - since the same values must
2018 ** have been requested when testing key $P in whereEqualScanEst(). */
2019 whereKeyStats(pParse
, p
, pRec
, 0, a
);
2021 iUpper
= a
[0] + a
[1];
2024 assert( pLower
==0 || (pLower
->eOperator
& (WO_GT
|WO_GE
))!=0 );
2025 assert( pUpper
==0 || (pUpper
->eOperator
& (WO_LT
|WO_LE
))!=0 );
2026 assert( p
->aSortOrder
!=0 );
2027 if( p
->aSortOrder
[nEq
] ){
2028 /* The roles of pLower and pUpper are swapped for a DESC index */
2029 SWAP(WhereTerm
*, pLower
, pUpper
);
2030 SWAP(int, nBtm
, nTop
);
2033 /* If possible, improve on the iLower estimate using ($P:$L). */
2035 int n
; /* Values extracted from pExpr */
2036 Expr
*pExpr
= pLower
->pExpr
->pRight
;
2037 rc
= sqlite3Stat4ProbeSetValue(pParse
, p
, &pRec
, pExpr
, nBtm
, nEq
, &n
);
2038 if( rc
==SQLITE_OK
&& n
){
2040 u16 mask
= WO_GT
|WO_LE
;
2041 if( sqlite3ExprVectorSize(pExpr
)>n
) mask
= (WO_LE
|WO_LT
);
2042 iLwrIdx
= whereKeyStats(pParse
, p
, pRec
, 0, a
);
2043 iNew
= a
[0] + ((pLower
->eOperator
& mask
) ? a
[1] : 0);
2044 if( iNew
>iLower
) iLower
= iNew
;
2050 /* If possible, improve on the iUpper estimate using ($P:$U). */
2052 int n
; /* Values extracted from pExpr */
2053 Expr
*pExpr
= pUpper
->pExpr
->pRight
;
2054 rc
= sqlite3Stat4ProbeSetValue(pParse
, p
, &pRec
, pExpr
, nTop
, nEq
, &n
);
2055 if( rc
==SQLITE_OK
&& n
){
2057 u16 mask
= WO_GT
|WO_LE
;
2058 if( sqlite3ExprVectorSize(pExpr
)>n
) mask
= (WO_LE
|WO_LT
);
2059 iUprIdx
= whereKeyStats(pParse
, p
, pRec
, 1, a
);
2060 iNew
= a
[0] + ((pUpper
->eOperator
& mask
) ? a
[1] : 0);
2061 if( iNew
<iUpper
) iUpper
= iNew
;
2067 pBuilder
->pRec
= pRec
;
2068 if( rc
==SQLITE_OK
){
2069 if( iUpper
>iLower
){
2070 nNew
= sqlite3LogEst(iUpper
- iLower
);
2071 /* TUNING: If both iUpper and iLower are derived from the same
2072 ** sample, then assume they are 4x more selective. This brings
2073 ** the estimated selectivity more in line with what it would be
2074 ** if estimated without the use of STAT4 tables. */
2075 if( iLwrIdx
==iUprIdx
){ nNew
-= 20; }
2076 assert( 20==sqlite3LogEst(4) );
2078 nNew
= 10; assert( 10==sqlite3LogEst(2) );
2083 WHERETRACE(0x20, ("STAT4 range scan: %u..%u est=%d\n",
2084 (u32
)iLower
, (u32
)iUpper
, nOut
));
2088 rc
= whereRangeSkipScanEst(pParse
, pLower
, pUpper
, pLoop
, &bDone
);
2089 if( bDone
) return rc
;
2093 UNUSED_PARAMETER(pParse
);
2094 UNUSED_PARAMETER(pBuilder
);
2095 assert( pLower
|| pUpper
);
2097 assert( pUpper
==0 || (pUpper
->wtFlags
& TERM_VNULL
)==0 || pParse
->nErr
>0 );
2098 nNew
= whereRangeAdjust(pLower
, nOut
);
2099 nNew
= whereRangeAdjust(pUpper
, nNew
);
2101 /* TUNING: If there is both an upper and lower limit and neither limit
2102 ** has an application-defined likelihood(), assume the range is
2103 ** reduced by an additional 75%. This means that, by default, an open-ended
2104 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2105 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2106 ** match 1/64 of the index. */
2107 if( pLower
&& pLower
->truthProb
>0 && pUpper
&& pUpper
->truthProb
>0 ){
2111 nOut
-= (pLower
!=0) + (pUpper
!=0);
2112 if( nNew
<10 ) nNew
= 10;
2113 if( nNew
<nOut
) nOut
= nNew
;
2114 #if defined(WHERETRACE_ENABLED)
2115 if( pLoop
->nOut
>nOut
){
2116 WHERETRACE(0x20,("Range scan lowers nOut from %d to %d\n",
2117 pLoop
->nOut
, nOut
));
2120 pLoop
->nOut
= (LogEst
)nOut
;
2124 #ifdef SQLITE_ENABLE_STAT4
2126 ** Estimate the number of rows that will be returned based on
2127 ** an equality constraint x=VALUE and where that VALUE occurs in
2128 ** the histogram data. This only works when x is the left-most
2129 ** column of an index and sqlite_stat4 histogram data is available
2130 ** for that index. When pExpr==NULL that means the constraint is
2131 ** "x IS NULL" instead of "x=VALUE".
2133 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2134 ** If unable to make an estimate, leave *pnRow unchanged and return
2137 ** This routine can fail if it is unable to load a collating sequence
2138 ** required for string comparison, or if unable to allocate memory
2139 ** for a UTF conversion required for comparison. The error is stored
2140 ** in the pParse structure.
2142 static int whereEqualScanEst(
2143 Parse
*pParse
, /* Parsing & code generating context */
2144 WhereLoopBuilder
*pBuilder
,
2145 Expr
*pExpr
, /* Expression for VALUE in the x=VALUE constraint */
2146 tRowcnt
*pnRow
/* Write the revised row estimate here */
2148 Index
*p
= pBuilder
->pNew
->u
.btree
.pIndex
;
2149 int nEq
= pBuilder
->pNew
->u
.btree
.nEq
;
2150 UnpackedRecord
*pRec
= pBuilder
->pRec
;
2151 int rc
; /* Subfunction return code */
2152 tRowcnt a
[2]; /* Statistics */
2156 assert( nEq
<=p
->nColumn
);
2157 assert( p
->aSample
!=0 );
2158 assert( p
->nSample
>0 );
2159 assert( pBuilder
->nRecValid
<nEq
);
2161 /* If values are not available for all fields of the index to the left
2162 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2163 if( pBuilder
->nRecValid
<(nEq
-1) ){
2164 return SQLITE_NOTFOUND
;
2167 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2168 ** below would return the same value. */
2169 if( nEq
>=p
->nColumn
){
2174 rc
= sqlite3Stat4ProbeSetValue(pParse
, p
, &pRec
, pExpr
, 1, nEq
-1, &bOk
);
2175 pBuilder
->pRec
= pRec
;
2176 if( rc
!=SQLITE_OK
) return rc
;
2177 if( bOk
==0 ) return SQLITE_NOTFOUND
;
2178 pBuilder
->nRecValid
= nEq
;
2180 whereKeyStats(pParse
, p
, pRec
, 0, a
);
2181 WHERETRACE(0x20,("equality scan regions %s(%d): %d\n",
2182 p
->zName
, nEq
-1, (int)a
[1]));
2187 #endif /* SQLITE_ENABLE_STAT4 */
2189 #ifdef SQLITE_ENABLE_STAT4
2191 ** Estimate the number of rows that will be returned based on
2192 ** an IN constraint where the right-hand side of the IN operator
2193 ** is a list of values. Example:
2195 ** WHERE x IN (1,2,3,4)
2197 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2198 ** If unable to make an estimate, leave *pnRow unchanged and return
2201 ** This routine can fail if it is unable to load a collating sequence
2202 ** required for string comparison, or if unable to allocate memory
2203 ** for a UTF conversion required for comparison. The error is stored
2204 ** in the pParse structure.
2206 static int whereInScanEst(
2207 Parse
*pParse
, /* Parsing & code generating context */
2208 WhereLoopBuilder
*pBuilder
,
2209 ExprList
*pList
, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
2210 tRowcnt
*pnRow
/* Write the revised row estimate here */
2212 Index
*p
= pBuilder
->pNew
->u
.btree
.pIndex
;
2213 i64 nRow0
= sqlite3LogEstToInt(p
->aiRowLogEst
[0]);
2214 int nRecValid
= pBuilder
->nRecValid
;
2215 int rc
= SQLITE_OK
; /* Subfunction return code */
2216 tRowcnt nEst
; /* Number of rows for a single term */
2217 tRowcnt nRowEst
= 0; /* New estimate of the number of rows */
2218 int i
; /* Loop counter */
2220 assert( p
->aSample
!=0 );
2221 for(i
=0; rc
==SQLITE_OK
&& i
<pList
->nExpr
; i
++){
2223 rc
= whereEqualScanEst(pParse
, pBuilder
, pList
->a
[i
].pExpr
, &nEst
);
2225 pBuilder
->nRecValid
= nRecValid
;
2228 if( rc
==SQLITE_OK
){
2229 if( nRowEst
> (tRowcnt
)nRow0
) nRowEst
= nRow0
;
2231 WHERETRACE(0x20,("IN row estimate: est=%d\n", nRowEst
));
2233 assert( pBuilder
->nRecValid
==nRecValid
);
2236 #endif /* SQLITE_ENABLE_STAT4 */
2239 #ifdef WHERETRACE_ENABLED
2241 ** Print the content of a WhereTerm object
2243 void sqlite3WhereTermPrint(WhereTerm
*pTerm
, int iTerm
){
2245 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm
);
2249 memcpy(zType
, "....", 5);
2250 if( pTerm
->wtFlags
& TERM_VIRTUAL
) zType
[0] = 'V';
2251 if( pTerm
->eOperator
& WO_EQUIV
) zType
[1] = 'E';
2252 if( ExprHasProperty(pTerm
->pExpr
, EP_OuterON
) ) zType
[2] = 'L';
2253 if( pTerm
->wtFlags
& TERM_CODED
) zType
[3] = 'C';
2254 if( pTerm
->eOperator
& WO_SINGLE
){
2255 assert( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 );
2256 sqlite3_snprintf(sizeof(zLeft
),zLeft
,"left={%d:%d}",
2257 pTerm
->leftCursor
, pTerm
->u
.x
.leftColumn
);
2258 }else if( (pTerm
->eOperator
& WO_OR
)!=0 && pTerm
->u
.pOrInfo
!=0 ){
2259 sqlite3_snprintf(sizeof(zLeft
),zLeft
,"indexable=0x%llx",
2260 pTerm
->u
.pOrInfo
->indexable
);
2262 sqlite3_snprintf(sizeof(zLeft
),zLeft
,"left=%d", pTerm
->leftCursor
);
2265 "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
2266 iTerm
, pTerm
, zType
, zLeft
, pTerm
->eOperator
, pTerm
->wtFlags
);
2267 /* The 0x10000 .wheretrace flag causes extra information to be
2268 ** shown about each Term */
2269 if( sqlite3WhereTrace
& 0x10000 ){
2270 sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
2271 pTerm
->truthProb
, (u64
)pTerm
->prereqAll
, (u64
)pTerm
->prereqRight
);
2273 if( (pTerm
->eOperator
& (WO_OR
|WO_AND
))==0 && pTerm
->u
.x
.iField
){
2274 sqlite3DebugPrintf(" iField=%d", pTerm
->u
.x
.iField
);
2276 if( pTerm
->iParent
>=0 ){
2277 sqlite3DebugPrintf(" iParent=%d", pTerm
->iParent
);
2279 sqlite3DebugPrintf("\n");
2280 sqlite3TreeViewExpr(0, pTerm
->pExpr
, 0);
2285 #ifdef WHERETRACE_ENABLED
2287 ** Show the complete content of a WhereClause
2289 void sqlite3WhereClausePrint(WhereClause
*pWC
){
2291 for(i
=0; i
<pWC
->nTerm
; i
++){
2292 sqlite3WhereTermPrint(&pWC
->a
[i
], i
);
2297 #ifdef WHERETRACE_ENABLED
2299 ** Print a WhereLoop object for debugging purposes
2303 ** .--- Position in WHERE clause rSetup, rRun, nOut ---.
2305 ** | .--- selfMask nTerm ------. |
2307 ** | | .-- prereq Idx wsFlags----. | |
2309 ** | | | __|__ nEq ---. ___|__ | __|__
2310 ** | / \ / \ / \ | / \ / \ / \
2311 ** 1.002.001 t2.t2xy 2 f 010241 N 2 cost 0,56,31
2313 void sqlite3WhereLoopPrint(const WhereLoop
*p
, const WhereClause
*pWC
){
2315 WhereInfo
*pWInfo
= pWC
->pWInfo
;
2316 int nb
= 1+(pWInfo
->pTabList
->nSrc
+3)/4;
2317 SrcItem
*pItem
= pWInfo
->pTabList
->a
+ p
->iTab
;
2318 Table
*pTab
= pItem
->pTab
;
2319 Bitmask mAll
= (((Bitmask
)1)<<(nb
*4)) - 1;
2320 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p
->cId
,
2321 p
->iTab
, nb
, p
->maskSelf
, nb
, p
->prereq
& mAll
);
2322 sqlite3DebugPrintf(" %12s",
2323 pItem
->zAlias
? pItem
->zAlias
: pTab
->zName
);
2325 sqlite3DebugPrintf("%c%2d.%03llx.%03llx %c%d",
2326 p
->cId
, p
->iTab
, p
->maskSelf
, p
->prereq
& 0xfff, p
->cId
, p
->iTab
);
2328 if( (p
->wsFlags
& WHERE_VIRTUALTABLE
)==0 ){
2330 if( p
->u
.btree
.pIndex
&& (zName
= p
->u
.btree
.pIndex
->zName
)!=0 ){
2331 if( strncmp(zName
, "sqlite_autoindex_", 17)==0 ){
2332 int i
= sqlite3Strlen30(zName
) - 1;
2333 while( zName
[i
]!='_' ) i
--;
2336 sqlite3DebugPrintf(".%-16s %2d", zName
, p
->u
.btree
.nEq
);
2338 sqlite3DebugPrintf("%20s","");
2342 if( p
->u
.vtab
.idxStr
){
2343 z
= sqlite3_mprintf("(%d,\"%s\",%#x)",
2344 p
->u
.vtab
.idxNum
, p
->u
.vtab
.idxStr
, p
->u
.vtab
.omitMask
);
2346 z
= sqlite3_mprintf("(%d,%x)", p
->u
.vtab
.idxNum
, p
->u
.vtab
.omitMask
);
2348 sqlite3DebugPrintf(" %-19s", z
);
2351 if( p
->wsFlags
& WHERE_SKIPSCAN
){
2352 sqlite3DebugPrintf(" f %06x %d-%d", p
->wsFlags
, p
->nLTerm
,p
->nSkip
);
2354 sqlite3DebugPrintf(" f %06x N %d", p
->wsFlags
, p
->nLTerm
);
2356 sqlite3DebugPrintf(" cost %d,%d,%d\n", p
->rSetup
, p
->rRun
, p
->nOut
);
2357 if( p
->nLTerm
&& (sqlite3WhereTrace
& 0x4000)!=0 ){
2359 for(i
=0; i
<p
->nLTerm
; i
++){
2360 sqlite3WhereTermPrint(p
->aLTerm
[i
], i
);
2364 void sqlite3ShowWhereLoop(const WhereLoop
*p
){
2365 if( p
) sqlite3WhereLoopPrint(p
, 0);
2367 void sqlite3ShowWhereLoopList(const WhereLoop
*p
){
2369 sqlite3ShowWhereLoop(p
);
2376 ** Convert bulk memory into a valid WhereLoop that can be passed
2377 ** to whereLoopClear harmlessly.
2379 static void whereLoopInit(WhereLoop
*p
){
2380 p
->aLTerm
= p
->aLTermSpace
;
2382 p
->nLSlot
= ArraySize(p
->aLTermSpace
);
2387 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
2389 static void whereLoopClearUnion(sqlite3
*db
, WhereLoop
*p
){
2390 if( p
->wsFlags
& (WHERE_VIRTUALTABLE
|WHERE_AUTO_INDEX
) ){
2391 if( (p
->wsFlags
& WHERE_VIRTUALTABLE
)!=0 && p
->u
.vtab
.needFree
){
2392 sqlite3_free(p
->u
.vtab
.idxStr
);
2393 p
->u
.vtab
.needFree
= 0;
2394 p
->u
.vtab
.idxStr
= 0;
2395 }else if( (p
->wsFlags
& WHERE_AUTO_INDEX
)!=0 && p
->u
.btree
.pIndex
!=0 ){
2396 sqlite3DbFree(db
, p
->u
.btree
.pIndex
->zColAff
);
2397 sqlite3DbFreeNN(db
, p
->u
.btree
.pIndex
);
2398 p
->u
.btree
.pIndex
= 0;
2404 ** Deallocate internal memory used by a WhereLoop object. Leave the
2405 ** object in an initialized state, as if it had been newly allocated.
2407 static void whereLoopClear(sqlite3
*db
, WhereLoop
*p
){
2408 if( p
->aLTerm
!=p
->aLTermSpace
){
2409 sqlite3DbFreeNN(db
, p
->aLTerm
);
2410 p
->aLTerm
= p
->aLTermSpace
;
2411 p
->nLSlot
= ArraySize(p
->aLTermSpace
);
2413 whereLoopClearUnion(db
, p
);
2419 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
2421 static int whereLoopResize(sqlite3
*db
, WhereLoop
*p
, int n
){
2423 if( p
->nLSlot
>=n
) return SQLITE_OK
;
2425 paNew
= sqlite3DbMallocRawNN(db
, sizeof(p
->aLTerm
[0])*n
);
2426 if( paNew
==0 ) return SQLITE_NOMEM_BKPT
;
2427 memcpy(paNew
, p
->aLTerm
, sizeof(p
->aLTerm
[0])*p
->nLSlot
);
2428 if( p
->aLTerm
!=p
->aLTermSpace
) sqlite3DbFreeNN(db
, p
->aLTerm
);
2435 ** Transfer content from the second pLoop into the first.
2437 static int whereLoopXfer(sqlite3
*db
, WhereLoop
*pTo
, WhereLoop
*pFrom
){
2438 whereLoopClearUnion(db
, pTo
);
2439 if( pFrom
->nLTerm
> pTo
->nLSlot
2440 && whereLoopResize(db
, pTo
, pFrom
->nLTerm
)
2442 memset(pTo
, 0, WHERE_LOOP_XFER_SZ
);
2443 return SQLITE_NOMEM_BKPT
;
2445 memcpy(pTo
, pFrom
, WHERE_LOOP_XFER_SZ
);
2446 memcpy(pTo
->aLTerm
, pFrom
->aLTerm
, pTo
->nLTerm
*sizeof(pTo
->aLTerm
[0]));
2447 if( pFrom
->wsFlags
& WHERE_VIRTUALTABLE
){
2448 pFrom
->u
.vtab
.needFree
= 0;
2449 }else if( (pFrom
->wsFlags
& WHERE_AUTO_INDEX
)!=0 ){
2450 pFrom
->u
.btree
.pIndex
= 0;
2456 ** Delete a WhereLoop object
2458 static void whereLoopDelete(sqlite3
*db
, WhereLoop
*p
){
2460 whereLoopClear(db
, p
);
2461 sqlite3DbNNFreeNN(db
, p
);
2465 ** Free a WhereInfo structure
2467 static void whereInfoFree(sqlite3
*db
, WhereInfo
*pWInfo
){
2468 assert( pWInfo
!=0 );
2470 sqlite3WhereClauseClear(&pWInfo
->sWC
);
2471 while( pWInfo
->pLoops
){
2472 WhereLoop
*p
= pWInfo
->pLoops
;
2473 pWInfo
->pLoops
= p
->pNextLoop
;
2474 whereLoopDelete(db
, p
);
2476 while( pWInfo
->pMemToFree
){
2477 WhereMemBlock
*pNext
= pWInfo
->pMemToFree
->pNext
;
2478 sqlite3DbNNFreeNN(db
, pWInfo
->pMemToFree
);
2479 pWInfo
->pMemToFree
= pNext
;
2481 sqlite3DbNNFreeNN(db
, pWInfo
);
2485 ** Return TRUE if X is a proper subset of Y but is of equal or less cost.
2486 ** In other words, return true if all constraints of X are also part of Y
2487 ** and Y has additional constraints that might speed the search that X lacks
2488 ** but the cost of running X is not more than the cost of running Y.
2490 ** In other words, return true if the cost relationwship between X and Y
2491 ** is inverted and needs to be adjusted.
2495 ** (1a) X and Y use the same index.
2496 ** (1b) X has fewer == terms than Y
2497 ** (1c) Neither X nor Y use skip-scan
2498 ** (1d) X does not have a a greater cost than Y
2502 ** (2a) X has the same or lower cost, or returns the same or fewer rows,
2504 ** (2b) X uses fewer WHERE clause terms than Y
2505 ** (2c) Every WHERE clause term used by X is also used by Y
2506 ** (2d) X skips at least as many columns as Y
2507 ** (2e) If X is a covering index, than Y is too
2509 static int whereLoopCheaperProperSubset(
2510 const WhereLoop
*pX
, /* First WhereLoop to compare */
2511 const WhereLoop
*pY
/* Compare against this WhereLoop */
2514 if( pX
->rRun
>pY
->rRun
&& pX
->nOut
>pY
->nOut
) return 0; /* (1d) and (2a) */
2515 assert( (pX
->wsFlags
& WHERE_VIRTUALTABLE
)==0 );
2516 assert( (pY
->wsFlags
& WHERE_VIRTUALTABLE
)==0 );
2517 if( pX
->u
.btree
.nEq
< pY
->u
.btree
.nEq
/* (1b) */
2518 && pX
->u
.btree
.pIndex
==pY
->u
.btree
.pIndex
/* (1a) */
2519 && pX
->nSkip
==0 && pY
->nSkip
==0 /* (1c) */
2521 return 1; /* Case 1 is true */
2523 if( pX
->nLTerm
-pX
->nSkip
>= pY
->nLTerm
-pY
->nSkip
){
2524 return 0; /* (2b) */
2526 if( pY
->nSkip
> pX
->nSkip
) return 0; /* (2d) */
2527 for(i
=pX
->nLTerm
-1; i
>=0; i
--){
2528 if( pX
->aLTerm
[i
]==0 ) continue;
2529 for(j
=pY
->nLTerm
-1; j
>=0; j
--){
2530 if( pY
->aLTerm
[j
]==pX
->aLTerm
[i
] ) break;
2532 if( j
<0 ) return 0; /* (2c) */
2534 if( (pX
->wsFlags
&WHERE_IDX_ONLY
)!=0
2535 && (pY
->wsFlags
&WHERE_IDX_ONLY
)==0 ){
2536 return 0; /* (2e) */
2538 return 1; /* Case 2 is true */
2542 ** Try to adjust the cost and number of output rows of WhereLoop pTemplate
2543 ** upwards or downwards so that:
2545 ** (1) pTemplate costs less than any other WhereLoops that are a proper
2546 ** subset of pTemplate
2548 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
2549 ** is a proper subset.
2551 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
2552 ** WHERE clause terms than Y and that every WHERE clause term used by X is
2555 static void whereLoopAdjustCost(const WhereLoop
*p
, WhereLoop
*pTemplate
){
2556 if( (pTemplate
->wsFlags
& WHERE_INDEXED
)==0 ) return;
2557 for(; p
; p
=p
->pNextLoop
){
2558 if( p
->iTab
!=pTemplate
->iTab
) continue;
2559 if( (p
->wsFlags
& WHERE_INDEXED
)==0 ) continue;
2560 if( whereLoopCheaperProperSubset(p
, pTemplate
) ){
2561 /* Adjust pTemplate cost downward so that it is cheaper than its
2563 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2564 pTemplate
->rRun
, pTemplate
->nOut
,
2565 MIN(p
->rRun
, pTemplate
->rRun
),
2566 MIN(p
->nOut
- 1, pTemplate
->nOut
)));
2567 pTemplate
->rRun
= MIN(p
->rRun
, pTemplate
->rRun
);
2568 pTemplate
->nOut
= MIN(p
->nOut
- 1, pTemplate
->nOut
);
2569 }else if( whereLoopCheaperProperSubset(pTemplate
, p
) ){
2570 /* Adjust pTemplate cost upward so that it is costlier than p since
2571 ** pTemplate is a proper subset of p */
2572 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2573 pTemplate
->rRun
, pTemplate
->nOut
,
2574 MAX(p
->rRun
, pTemplate
->rRun
),
2575 MAX(p
->nOut
+ 1, pTemplate
->nOut
)));
2576 pTemplate
->rRun
= MAX(p
->rRun
, pTemplate
->rRun
);
2577 pTemplate
->nOut
= MAX(p
->nOut
+ 1, pTemplate
->nOut
);
2583 ** Search the list of WhereLoops in *ppPrev looking for one that can be
2584 ** replaced by pTemplate.
2586 ** Return NULL if pTemplate does not belong on the WhereLoop list.
2587 ** In other words if pTemplate ought to be dropped from further consideration.
2589 ** If pX is a WhereLoop that pTemplate can replace, then return the
2590 ** link that points to pX.
2592 ** If pTemplate cannot replace any existing element of the list but needs
2593 ** to be added to the list as a new entry, then return a pointer to the
2594 ** tail of the list.
2596 static WhereLoop
**whereLoopFindLesser(
2598 const WhereLoop
*pTemplate
2601 for(p
=(*ppPrev
); p
; ppPrev
=&p
->pNextLoop
, p
=*ppPrev
){
2602 if( p
->iTab
!=pTemplate
->iTab
|| p
->iSortIdx
!=pTemplate
->iSortIdx
){
2603 /* If either the iTab or iSortIdx values for two WhereLoop are different
2604 ** then those WhereLoops need to be considered separately. Neither is
2605 ** a candidate to replace the other. */
2608 /* In the current implementation, the rSetup value is either zero
2609 ** or the cost of building an automatic index (NlogN) and the NlogN
2610 ** is the same for compatible WhereLoops. */
2611 assert( p
->rSetup
==0 || pTemplate
->rSetup
==0
2612 || p
->rSetup
==pTemplate
->rSetup
);
2614 /* whereLoopAddBtree() always generates and inserts the automatic index
2615 ** case first. Hence compatible candidate WhereLoops never have a larger
2616 ** rSetup. Call this SETUP-INVARIANT */
2617 assert( p
->rSetup
>=pTemplate
->rSetup
);
2619 /* Any loop using an application-defined index (or PRIMARY KEY or
2620 ** UNIQUE constraint) with one or more == constraints is better
2621 ** than an automatic index. Unless it is a skip-scan. */
2622 if( (p
->wsFlags
& WHERE_AUTO_INDEX
)!=0
2623 && (pTemplate
->nSkip
)==0
2624 && (pTemplate
->wsFlags
& WHERE_INDEXED
)!=0
2625 && (pTemplate
->wsFlags
& WHERE_COLUMN_EQ
)!=0
2626 && (p
->prereq
& pTemplate
->prereq
)==pTemplate
->prereq
2631 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
2632 ** discarded. WhereLoop p is better if:
2633 ** (1) p has no more dependencies than pTemplate, and
2634 ** (2) p has an equal or lower cost than pTemplate
2636 if( (p
->prereq
& pTemplate
->prereq
)==p
->prereq
/* (1) */
2637 && p
->rSetup
<=pTemplate
->rSetup
/* (2a) */
2638 && p
->rRun
<=pTemplate
->rRun
/* (2b) */
2639 && p
->nOut
<=pTemplate
->nOut
/* (2c) */
2641 return 0; /* Discard pTemplate */
2644 /* If pTemplate is always better than p, then cause p to be overwritten
2645 ** with pTemplate. pTemplate is better than p if:
2646 ** (1) pTemplate has no more dependencies than p, and
2647 ** (2) pTemplate has an equal or lower cost than p.
2649 if( (p
->prereq
& pTemplate
->prereq
)==pTemplate
->prereq
/* (1) */
2650 && p
->rRun
>=pTemplate
->rRun
/* (2a) */
2651 && p
->nOut
>=pTemplate
->nOut
/* (2b) */
2653 assert( p
->rSetup
>=pTemplate
->rSetup
); /* SETUP-INVARIANT above */
2654 break; /* Cause p to be overwritten by pTemplate */
2661 ** Insert or replace a WhereLoop entry using the template supplied.
2663 ** An existing WhereLoop entry might be overwritten if the new template
2664 ** is better and has fewer dependencies. Or the template will be ignored
2665 ** and no insert will occur if an existing WhereLoop is faster and has
2666 ** fewer dependencies than the template. Otherwise a new WhereLoop is
2667 ** added based on the template.
2669 ** If pBuilder->pOrSet is not NULL then we care about only the
2670 ** prerequisites and rRun and nOut costs of the N best loops. That
2671 ** information is gathered in the pBuilder->pOrSet object. This special
2672 ** processing mode is used only for OR clause processing.
2674 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
2675 ** still might overwrite similar loops with the new template if the
2676 ** new template is better. Loops may be overwritten if the following
2677 ** conditions are met:
2679 ** (1) They have the same iTab.
2680 ** (2) They have the same iSortIdx.
2681 ** (3) The template has same or fewer dependencies than the current loop
2682 ** (4) The template has the same or lower cost than the current loop
2684 static int whereLoopInsert(WhereLoopBuilder
*pBuilder
, WhereLoop
*pTemplate
){
2685 WhereLoop
**ppPrev
, *p
;
2686 WhereInfo
*pWInfo
= pBuilder
->pWInfo
;
2687 sqlite3
*db
= pWInfo
->pParse
->db
;
2690 /* Stop the search once we hit the query planner search limit */
2691 if( pBuilder
->iPlanLimit
==0 ){
2692 WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
2693 if( pBuilder
->pOrSet
) pBuilder
->pOrSet
->n
= 0;
2696 pBuilder
->iPlanLimit
--;
2698 whereLoopAdjustCost(pWInfo
->pLoops
, pTemplate
);
2700 /* If pBuilder->pOrSet is defined, then only keep track of the costs
2703 if( pBuilder
->pOrSet
!=0 ){
2704 if( pTemplate
->nLTerm
){
2705 #if WHERETRACE_ENABLED
2706 u16 n
= pBuilder
->pOrSet
->n
;
2709 whereOrInsert(pBuilder
->pOrSet
, pTemplate
->prereq
, pTemplate
->rRun
,
2711 #if WHERETRACE_ENABLED /* 0x8 */
2712 if( sqlite3WhereTrace
& 0x8 ){
2713 sqlite3DebugPrintf(x
?" or-%d: ":" or-X: ", n
);
2714 sqlite3WhereLoopPrint(pTemplate
, pBuilder
->pWC
);
2721 /* Look for an existing WhereLoop to replace with pTemplate
2723 ppPrev
= whereLoopFindLesser(&pWInfo
->pLoops
, pTemplate
);
2726 /* There already exists a WhereLoop on the list that is better
2727 ** than pTemplate, so just ignore pTemplate */
2728 #if WHERETRACE_ENABLED /* 0x8 */
2729 if( sqlite3WhereTrace
& 0x8 ){
2730 sqlite3DebugPrintf(" skip: ");
2731 sqlite3WhereLoopPrint(pTemplate
, pBuilder
->pWC
);
2739 /* If we reach this point it means that either p[] should be overwritten
2740 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
2741 ** WhereLoop and insert it.
2743 #if WHERETRACE_ENABLED /* 0x8 */
2744 if( sqlite3WhereTrace
& 0x8 ){
2746 sqlite3DebugPrintf("replace: ");
2747 sqlite3WhereLoopPrint(p
, pBuilder
->pWC
);
2748 sqlite3DebugPrintf(" with: ");
2750 sqlite3DebugPrintf(" add: ");
2752 sqlite3WhereLoopPrint(pTemplate
, pBuilder
->pWC
);
2756 /* Allocate a new WhereLoop to add to the end of the list */
2757 *ppPrev
= p
= sqlite3DbMallocRawNN(db
, sizeof(WhereLoop
));
2758 if( p
==0 ) return SQLITE_NOMEM_BKPT
;
2762 /* We will be overwriting WhereLoop p[]. But before we do, first
2763 ** go through the rest of the list and delete any other entries besides
2764 ** p[] that are also supplanted by pTemplate */
2765 WhereLoop
**ppTail
= &p
->pNextLoop
;
2768 ppTail
= whereLoopFindLesser(ppTail
, pTemplate
);
2769 if( ppTail
==0 ) break;
2771 if( pToDel
==0 ) break;
2772 *ppTail
= pToDel
->pNextLoop
;
2773 #if WHERETRACE_ENABLED /* 0x8 */
2774 if( sqlite3WhereTrace
& 0x8 ){
2775 sqlite3DebugPrintf(" delete: ");
2776 sqlite3WhereLoopPrint(pToDel
, pBuilder
->pWC
);
2779 whereLoopDelete(db
, pToDel
);
2782 rc
= whereLoopXfer(db
, p
, pTemplate
);
2783 if( (p
->wsFlags
& WHERE_VIRTUALTABLE
)==0 ){
2784 Index
*pIndex
= p
->u
.btree
.pIndex
;
2785 if( pIndex
&& pIndex
->idxType
==SQLITE_IDXTYPE_IPK
){
2786 p
->u
.btree
.pIndex
= 0;
2793 ** Adjust the WhereLoop.nOut value downward to account for terms of the
2794 ** WHERE clause that reference the loop but which are not used by an
2797 ** For every WHERE clause term that is not used by the index
2798 ** and which has a truth probability assigned by one of the likelihood(),
2799 ** likely(), or unlikely() SQL functions, reduce the estimated number
2800 ** of output rows by the probability specified.
2802 ** TUNING: For every WHERE clause term that is not used by the index
2803 ** and which does not have an assigned truth probability, heuristics
2804 ** described below are used to try to estimate the truth probability.
2805 ** TODO --> Perhaps this is something that could be improved by better
2806 ** table statistics.
2808 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
2809 ** value corresponds to -1 in LogEst notation, so this means decrement
2810 ** the WhereLoop.nOut field for every such WHERE clause term.
2812 ** Heuristic 2: If there exists one or more WHERE clause terms of the
2813 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
2814 ** final output row estimate is no greater than 1/4 of the total number
2815 ** of rows in the table. In other words, assume that x==EXPR will filter
2816 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
2817 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
2818 ** on the "x" column and so in that case only cap the output row estimate
2819 ** at 1/2 instead of 1/4.
2821 static void whereLoopOutputAdjust(
2822 WhereClause
*pWC
, /* The WHERE clause */
2823 WhereLoop
*pLoop
, /* The loop to adjust downward */
2824 LogEst nRow
/* Number of rows in the entire table */
2826 WhereTerm
*pTerm
, *pX
;
2827 Bitmask notAllowed
= ~(pLoop
->prereq
|pLoop
->maskSelf
);
2829 LogEst iReduce
= 0; /* pLoop->nOut should not exceed nRow-iReduce */
2831 assert( (pLoop
->wsFlags
& WHERE_AUTO_INDEX
)==0 );
2832 for(i
=pWC
->nBase
, pTerm
=pWC
->a
; i
>0; i
--, pTerm
++){
2834 if( (pTerm
->prereqAll
& notAllowed
)!=0 ) continue;
2835 if( (pTerm
->prereqAll
& pLoop
->maskSelf
)==0 ) continue;
2836 if( (pTerm
->wtFlags
& TERM_VIRTUAL
)!=0 ) continue;
2837 for(j
=pLoop
->nLTerm
-1; j
>=0; j
--){
2838 pX
= pLoop
->aLTerm
[j
];
2839 if( pX
==0 ) continue;
2840 if( pX
==pTerm
) break;
2841 if( pX
->iParent
>=0 && (&pWC
->a
[pX
->iParent
])==pTerm
) break;
2844 sqlite3ProgressCheck(pWC
->pWInfo
->pParse
);
2845 if( pLoop
->maskSelf
==pTerm
->prereqAll
){
2846 /* If there are extra terms in the WHERE clause not used by an index
2847 ** that depend only on the table being scanned, and that will tend to
2848 ** cause many rows to be omitted, then mark that table as
2851 ** 2022-03-24: Self-culling only applies if either the extra terms
2852 ** are straight comparison operators that are non-true with NULL
2853 ** operand, or if the loop is not an OUTER JOIN.
2855 if( (pTerm
->eOperator
& 0x3f)!=0
2856 || (pWC
->pWInfo
->pTabList
->a
[pLoop
->iTab
].fg
.jointype
2857 & (JT_LEFT
|JT_LTORJ
))==0
2859 pLoop
->wsFlags
|= WHERE_SELFCULL
;
2862 if( pTerm
->truthProb
<=0 ){
2863 /* If a truth probability is specified using the likelihood() hints,
2864 ** then use the probability provided by the application. */
2865 pLoop
->nOut
+= pTerm
->truthProb
;
2867 /* In the absence of explicit truth probabilities, use heuristics to
2868 ** guess a reasonable truth probability. */
2870 if( (pTerm
->eOperator
&(WO_EQ
|WO_IS
))!=0
2871 && (pTerm
->wtFlags
& TERM_HIGHTRUTH
)==0 /* tag-20200224-1 */
2873 Expr
*pRight
= pTerm
->pExpr
->pRight
;
2875 testcase( pTerm
->pExpr
->op
==TK_IS
);
2876 if( sqlite3ExprIsInteger(pRight
, &k
) && k
>=(-1) && k
<=1 ){
2882 pTerm
->wtFlags
|= TERM_HEURTRUTH
;
2889 if( pLoop
->nOut
> nRow
-iReduce
){
2890 pLoop
->nOut
= nRow
- iReduce
;
2895 ** Term pTerm is a vector range comparison operation. The first comparison
2896 ** in the vector can be optimized using column nEq of the index. This
2897 ** function returns the total number of vector elements that can be used
2898 ** as part of the range comparison.
2900 ** For example, if the query is:
2902 ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
2906 ** CREATE INDEX ... ON (a, b, c, d, e)
2908 ** then this function would be invoked with nEq=1. The value returned in
2911 static int whereRangeVectorLen(
2912 Parse
*pParse
, /* Parsing context */
2913 int iCur
, /* Cursor open on pIdx */
2914 Index
*pIdx
, /* The index to be used for a inequality constraint */
2915 int nEq
, /* Number of prior equality constraints on same index */
2916 WhereTerm
*pTerm
/* The vector inequality constraint */
2918 int nCmp
= sqlite3ExprVectorSize(pTerm
->pExpr
->pLeft
);
2921 nCmp
= MIN(nCmp
, (pIdx
->nColumn
- nEq
));
2922 for(i
=1; i
<nCmp
; i
++){
2923 /* Test if comparison i of pTerm is compatible with column (i+nEq)
2924 ** of the index. If not, exit the loop. */
2925 char aff
; /* Comparison affinity */
2926 char idxaff
= 0; /* Indexed columns affinity */
2927 CollSeq
*pColl
; /* Comparison collation sequence */
2930 assert( ExprUseXList(pTerm
->pExpr
->pLeft
) );
2931 pLhs
= pTerm
->pExpr
->pLeft
->x
.pList
->a
[i
].pExpr
;
2932 pRhs
= pTerm
->pExpr
->pRight
;
2933 if( ExprUseXSelect(pRhs
) ){
2934 pRhs
= pRhs
->x
.pSelect
->pEList
->a
[i
].pExpr
;
2936 pRhs
= pRhs
->x
.pList
->a
[i
].pExpr
;
2939 /* Check that the LHS of the comparison is a column reference to
2940 ** the right column of the right source table. And that the sort
2941 ** order of the index column is the same as the sort order of the
2942 ** leftmost index column. */
2943 if( pLhs
->op
!=TK_COLUMN
2944 || pLhs
->iTable
!=iCur
2945 || pLhs
->iColumn
!=pIdx
->aiColumn
[i
+nEq
]
2946 || pIdx
->aSortOrder
[i
+nEq
]!=pIdx
->aSortOrder
[nEq
]
2951 testcase( pLhs
->iColumn
==XN_ROWID
);
2952 aff
= sqlite3CompareAffinity(pRhs
, sqlite3ExprAffinity(pLhs
));
2953 idxaff
= sqlite3TableColumnAffinity(pIdx
->pTable
, pLhs
->iColumn
);
2954 if( aff
!=idxaff
) break;
2956 pColl
= sqlite3BinaryCompareCollSeq(pParse
, pLhs
, pRhs
);
2957 if( pColl
==0 ) break;
2958 if( sqlite3StrICmp(pColl
->zName
, pIdx
->azColl
[i
+nEq
]) ) break;
2964 ** Adjust the cost C by the costMult factor T. This only occurs if
2965 ** compiled with -DSQLITE_ENABLE_COSTMULT
2967 #ifdef SQLITE_ENABLE_COSTMULT
2968 # define ApplyCostMultiplier(C,T) C += T
2970 # define ApplyCostMultiplier(C,T)
2974 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
2975 ** index pIndex. Try to match one more.
2977 ** When this function is called, pBuilder->pNew->nOut contains the
2978 ** number of rows expected to be visited by filtering using the nEq
2979 ** terms only. If it is modified, this value is restored before this
2980 ** function returns.
2982 ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
2983 ** a fake index used for the INTEGER PRIMARY KEY.
2985 static int whereLoopAddBtreeIndex(
2986 WhereLoopBuilder
*pBuilder
, /* The WhereLoop factory */
2987 SrcItem
*pSrc
, /* FROM clause term being analyzed */
2988 Index
*pProbe
, /* An index on pSrc */
2989 LogEst nInMul
/* log(Number of iterations due to IN) */
2991 WhereInfo
*pWInfo
= pBuilder
->pWInfo
; /* WHERE analyze context */
2992 Parse
*pParse
= pWInfo
->pParse
; /* Parsing context */
2993 sqlite3
*db
= pParse
->db
; /* Database connection malloc context */
2994 WhereLoop
*pNew
; /* Template WhereLoop under construction */
2995 WhereTerm
*pTerm
; /* A WhereTerm under consideration */
2996 int opMask
; /* Valid operators for constraints */
2997 WhereScan scan
; /* Iterator for WHERE terms */
2998 Bitmask saved_prereq
; /* Original value of pNew->prereq */
2999 u16 saved_nLTerm
; /* Original value of pNew->nLTerm */
3000 u16 saved_nEq
; /* Original value of pNew->u.btree.nEq */
3001 u16 saved_nBtm
; /* Original value of pNew->u.btree.nBtm */
3002 u16 saved_nTop
; /* Original value of pNew->u.btree.nTop */
3003 u16 saved_nSkip
; /* Original value of pNew->nSkip */
3004 u32 saved_wsFlags
; /* Original value of pNew->wsFlags */
3005 LogEst saved_nOut
; /* Original value of pNew->nOut */
3006 int rc
= SQLITE_OK
; /* Return code */
3007 LogEst rSize
; /* Number of rows in the table */
3008 LogEst rLogSize
; /* Logarithm of table size */
3009 WhereTerm
*pTop
= 0, *pBtm
= 0; /* Top and bottom range constraints */
3011 pNew
= pBuilder
->pNew
;
3012 assert( db
->mallocFailed
==0 || pParse
->nErr
>0 );
3016 WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n",
3017 pProbe
->pTable
->zName
,pProbe
->zName
,
3018 pNew
->u
.btree
.nEq
, pNew
->nSkip
, pNew
->rRun
));
3020 assert( (pNew
->wsFlags
& WHERE_VIRTUALTABLE
)==0 );
3021 assert( (pNew
->wsFlags
& WHERE_TOP_LIMIT
)==0 );
3022 if( pNew
->wsFlags
& WHERE_BTM_LIMIT
){
3023 opMask
= WO_LT
|WO_LE
;
3025 assert( pNew
->u
.btree
.nBtm
==0 );
3026 opMask
= WO_EQ
|WO_IN
|WO_GT
|WO_GE
|WO_LT
|WO_LE
|WO_ISNULL
|WO_IS
;
3028 if( pProbe
->bUnordered
|| pProbe
->bLowQual
){
3029 if( pProbe
->bUnordered
) opMask
&= ~(WO_GT
|WO_GE
|WO_LT
|WO_LE
);
3030 if( pProbe
->bLowQual
&& pSrc
->fg
.isIndexedBy
==0 ){
3031 opMask
&= ~(WO_EQ
|WO_IN
|WO_IS
);
3035 assert( pNew
->u
.btree
.nEq
<pProbe
->nColumn
);
3036 assert( pNew
->u
.btree
.nEq
<pProbe
->nKeyCol
3037 || pProbe
->idxType
!=SQLITE_IDXTYPE_PRIMARYKEY
);
3039 saved_nEq
= pNew
->u
.btree
.nEq
;
3040 saved_nBtm
= pNew
->u
.btree
.nBtm
;
3041 saved_nTop
= pNew
->u
.btree
.nTop
;
3042 saved_nSkip
= pNew
->nSkip
;
3043 saved_nLTerm
= pNew
->nLTerm
;
3044 saved_wsFlags
= pNew
->wsFlags
;
3045 saved_prereq
= pNew
->prereq
;
3046 saved_nOut
= pNew
->nOut
;
3047 pTerm
= whereScanInit(&scan
, pBuilder
->pWC
, pSrc
->iCursor
, saved_nEq
,
3050 rSize
= pProbe
->aiRowLogEst
[0];
3051 rLogSize
= estLog(rSize
);
3052 for(; rc
==SQLITE_OK
&& pTerm
!=0; pTerm
= whereScanNext(&scan
)){
3053 u16 eOp
= pTerm
->eOperator
; /* Shorthand for pTerm->eOperator */
3055 LogEst nOutUnadjusted
; /* nOut before IN() and WHERE adjustments */
3057 #ifdef SQLITE_ENABLE_STAT4
3058 int nRecValid
= pBuilder
->nRecValid
;
3060 if( (eOp
==WO_ISNULL
|| (pTerm
->wtFlags
&TERM_VNULL
)!=0)
3061 && indexColumnNotNull(pProbe
, saved_nEq
)
3063 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
3065 if( pTerm
->prereqRight
& pNew
->maskSelf
) continue;
3067 /* Do not allow the upper bound of a LIKE optimization range constraint
3068 ** to mix with a lower range bound from some other source */
3069 if( pTerm
->wtFlags
& TERM_LIKEOPT
&& pTerm
->eOperator
==WO_LT
) continue;
3071 if( (pSrc
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
))!=0
3072 && !constraintCompatibleWithOuterJoin(pTerm
,pSrc
)
3076 if( IsUniqueIndex(pProbe
) && saved_nEq
==pProbe
->nKeyCol
-1 ){
3077 pBuilder
->bldFlags1
|= SQLITE_BLDF1_UNIQUE
;
3079 pBuilder
->bldFlags1
|= SQLITE_BLDF1_INDEXED
;
3081 pNew
->wsFlags
= saved_wsFlags
;
3082 pNew
->u
.btree
.nEq
= saved_nEq
;
3083 pNew
->u
.btree
.nBtm
= saved_nBtm
;
3084 pNew
->u
.btree
.nTop
= saved_nTop
;
3085 pNew
->nLTerm
= saved_nLTerm
;
3086 if( pNew
->nLTerm
>=pNew
->nLSlot
3087 && whereLoopResize(db
, pNew
, pNew
->nLTerm
+1)
3089 break; /* OOM while trying to enlarge the pNew->aLTerm array */
3091 pNew
->aLTerm
[pNew
->nLTerm
++] = pTerm
;
3092 pNew
->prereq
= (saved_prereq
| pTerm
->prereqRight
) & ~pNew
->maskSelf
;
3095 || (pNew
->wsFlags
& WHERE_COLUMN_NULL
)!=0
3096 || (pNew
->wsFlags
& WHERE_COLUMN_IN
)!=0
3097 || (pNew
->wsFlags
& WHERE_SKIPSCAN
)!=0
3101 Expr
*pExpr
= pTerm
->pExpr
;
3102 if( ExprUseXSelect(pExpr
) ){
3103 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
3105 nIn
= 46; assert( 46==sqlite3LogEst(25) );
3107 /* The expression may actually be of the form (x, y) IN (SELECT...).
3108 ** In this case there is a separate term for each of (x) and (y).
3109 ** However, the nIn multiplier should only be applied once, not once
3110 ** for each such term. The following loop checks that pTerm is the
3111 ** first such term in use, and sets nIn back to 0 if it is not. */
3112 for(i
=0; i
<pNew
->nLTerm
-1; i
++){
3113 if( pNew
->aLTerm
[i
] && pNew
->aLTerm
[i
]->pExpr
==pExpr
) nIn
= 0;
3115 }else if( ALWAYS(pExpr
->x
.pList
&& pExpr
->x
.pList
->nExpr
) ){
3116 /* "x IN (value, value, ...)" */
3117 nIn
= sqlite3LogEst(pExpr
->x
.pList
->nExpr
);
3119 if( pProbe
->hasStat1
&& rLogSize
>=10 ){
3122 ** N = the total number of rows in the table
3123 ** K = the number of entries on the RHS of the IN operator
3124 ** M = the number of rows in the table that match terms to the
3125 ** to the left in the same index. If the IN operator is on
3126 ** the left-most index column, M==N.
3128 ** Given the definitions above, it is better to omit the IN operator
3129 ** from the index lookup and instead do a scan of the M elements,
3130 ** testing each scanned row against the IN operator separately, if:
3132 ** M*log(K) < K*log(N)
3134 ** Our estimates for M, K, and N might be inaccurate, so we build in
3135 ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
3136 ** with the index, as using an index has better worst-case behavior.
3137 ** If we do not have real sqlite_stat1 data, always prefer to use
3138 ** the index. Do not bother with this optimization on very small
3139 ** tables (less than 2 rows) as it is pointless in that case.
3141 M
= pProbe
->aiRowLogEst
[saved_nEq
];
3143 /* TUNING v----- 10 to bias toward indexed IN */
3144 x
= M
+ logK
+ 10 - (nIn
+ rLogSize
);
3147 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) "
3148 "prefers indexed lookup\n",
3149 saved_nEq
, M
, logK
, nIn
, rLogSize
, x
));
3150 }else if( nInMul
<2 && OptimizationEnabled(db
, SQLITE_SeekScan
) ){
3152 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3153 " nInMul=%d) prefers skip-scan\n",
3154 saved_nEq
, M
, logK
, nIn
, rLogSize
, x
, nInMul
));
3155 pNew
->wsFlags
|= WHERE_IN_SEEKSCAN
;
3158 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3159 " nInMul=%d) prefers normal scan\n",
3160 saved_nEq
, M
, logK
, nIn
, rLogSize
, x
, nInMul
));
3164 pNew
->wsFlags
|= WHERE_COLUMN_IN
;
3165 }else if( eOp
& (WO_EQ
|WO_IS
) ){
3166 int iCol
= pProbe
->aiColumn
[saved_nEq
];
3167 pNew
->wsFlags
|= WHERE_COLUMN_EQ
;
3168 assert( saved_nEq
==pNew
->u
.btree
.nEq
);
3170 || (iCol
>=0 && nInMul
==0 && saved_nEq
==pProbe
->nKeyCol
-1)
3172 if( iCol
==XN_ROWID
|| pProbe
->uniqNotNull
3173 || (pProbe
->nKeyCol
==1 && pProbe
->onError
&& eOp
==WO_EQ
)
3175 pNew
->wsFlags
|= WHERE_ONEROW
;
3177 pNew
->wsFlags
|= WHERE_UNQ_WANTED
;
3180 if( scan
.iEquiv
>1 ) pNew
->wsFlags
|= WHERE_TRANSCONS
;
3181 }else if( eOp
& WO_ISNULL
){
3182 pNew
->wsFlags
|= WHERE_COLUMN_NULL
;
3184 int nVecLen
= whereRangeVectorLen(
3185 pParse
, pSrc
->iCursor
, pProbe
, saved_nEq
, pTerm
3187 if( eOp
& (WO_GT
|WO_GE
) ){
3188 testcase( eOp
& WO_GT
);
3189 testcase( eOp
& WO_GE
);
3190 pNew
->wsFlags
|= WHERE_COLUMN_RANGE
|WHERE_BTM_LIMIT
;
3191 pNew
->u
.btree
.nBtm
= nVecLen
;
3194 if( pTerm
->wtFlags
& TERM_LIKEOPT
){
3195 /* Range constraints that come from the LIKE optimization are
3196 ** always used in pairs. */
3198 assert( (pTop
-(pTerm
->pWC
->a
))<pTerm
->pWC
->nTerm
);
3199 assert( pTop
->wtFlags
& TERM_LIKEOPT
);
3200 assert( pTop
->eOperator
==WO_LT
);
3201 if( whereLoopResize(db
, pNew
, pNew
->nLTerm
+1) ) break; /* OOM */
3202 pNew
->aLTerm
[pNew
->nLTerm
++] = pTop
;
3203 pNew
->wsFlags
|= WHERE_TOP_LIMIT
;
3204 pNew
->u
.btree
.nTop
= 1;
3207 assert( eOp
& (WO_LT
|WO_LE
) );
3208 testcase( eOp
& WO_LT
);
3209 testcase( eOp
& WO_LE
);
3210 pNew
->wsFlags
|= WHERE_COLUMN_RANGE
|WHERE_TOP_LIMIT
;
3211 pNew
->u
.btree
.nTop
= nVecLen
;
3213 pBtm
= (pNew
->wsFlags
& WHERE_BTM_LIMIT
)!=0 ?
3214 pNew
->aLTerm
[pNew
->nLTerm
-2] : 0;
3218 /* At this point pNew->nOut is set to the number of rows expected to
3219 ** be visited by the index scan before considering term pTerm, or the
3220 ** values of nIn and nInMul. In other words, assuming that all
3221 ** "x IN(...)" terms are replaced with "x = ?". This block updates
3222 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
3223 assert( pNew
->nOut
==saved_nOut
);
3224 if( pNew
->wsFlags
& WHERE_COLUMN_RANGE
){
3225 /* Adjust nOut using stat4 data. Or, if there is no stat4
3226 ** data, using some other estimate. */
3227 whereRangeScanEst(pParse
, pBuilder
, pBtm
, pTop
, pNew
);
3229 int nEq
= ++pNew
->u
.btree
.nEq
;
3230 assert( eOp
& (WO_ISNULL
|WO_EQ
|WO_IN
|WO_IS
) );
3232 assert( pNew
->nOut
==saved_nOut
);
3233 if( pTerm
->truthProb
<=0 && pProbe
->aiColumn
[saved_nEq
]>=0 ){
3234 assert( (eOp
& WO_IN
) || nIn
==0 );
3235 testcase( eOp
& WO_IN
);
3236 pNew
->nOut
+= pTerm
->truthProb
;
3239 #ifdef SQLITE_ENABLE_STAT4
3243 && ALWAYS(pNew
->u
.btree
.nEq
<=pProbe
->nSampleCol
)
3244 && ((eOp
& WO_IN
)==0 || ExprUseXList(pTerm
->pExpr
))
3245 && OptimizationEnabled(db
, SQLITE_Stat4
)
3247 Expr
*pExpr
= pTerm
->pExpr
;
3248 if( (eOp
& (WO_EQ
|WO_ISNULL
|WO_IS
))!=0 ){
3249 testcase( eOp
& WO_EQ
);
3250 testcase( eOp
& WO_IS
);
3251 testcase( eOp
& WO_ISNULL
);
3252 rc
= whereEqualScanEst(pParse
, pBuilder
, pExpr
->pRight
, &nOut
);
3254 rc
= whereInScanEst(pParse
, pBuilder
, pExpr
->x
.pList
, &nOut
);
3256 if( rc
==SQLITE_NOTFOUND
) rc
= SQLITE_OK
;
3257 if( rc
!=SQLITE_OK
) break; /* Jump out of the pTerm loop */
3259 pNew
->nOut
= sqlite3LogEst(nOut
);
3261 /* TUNING: Mark terms as "low selectivity" if they seem likely
3262 ** to be true for half or more of the rows in the table.
3263 ** See tag-202002240-1 */
3264 && pNew
->nOut
+10 > pProbe
->aiRowLogEst
[0]
3266 #if WHERETRACE_ENABLED /* 0x01 */
3267 if( sqlite3WhereTrace
& 0x20 ){
3269 "STAT4 determines term has low selectivity:\n");
3270 sqlite3WhereTermPrint(pTerm
, 999);
3273 pTerm
->wtFlags
|= TERM_HIGHTRUTH
;
3274 if( pTerm
->wtFlags
& TERM_HEURTRUTH
){
3275 /* If the term has previously been used with an assumption of
3276 ** higher selectivity, then set the flag to rerun the
3277 ** loop computations. */
3278 pBuilder
->bldFlags2
|= SQLITE_BLDF2_2NDPASS
;
3281 if( pNew
->nOut
>saved_nOut
) pNew
->nOut
= saved_nOut
;
3288 pNew
->nOut
+= (pProbe
->aiRowLogEst
[nEq
] - pProbe
->aiRowLogEst
[nEq
-1]);
3289 if( eOp
& WO_ISNULL
){
3290 /* TUNING: If there is no likelihood() value, assume that a
3291 ** "col IS NULL" expression matches twice as many rows
3299 /* Set rCostIdx to the estimated cost of visiting selected rows in the
3300 ** index. The estimate is the sum of two values:
3301 ** 1. The cost of doing one search-by-key to find the first matching
3303 ** 2. Stepping forward in the index pNew->nOut times to find all
3304 ** additional matching entries.
3306 assert( pSrc
->pTab
->szTabRow
>0 );
3307 if( pProbe
->idxType
==SQLITE_IDXTYPE_IPK
){
3308 /* The pProbe->szIdxRow is low for an IPK table since the interior
3309 ** pages are small. Thus szIdxRow gives a good estimate of seek cost.
3310 ** But the leaf pages are full-size, so pProbe->szIdxRow would badly
3311 ** under-estimate the scanning cost. */
3312 rCostIdx
= pNew
->nOut
+ 16;
3314 rCostIdx
= pNew
->nOut
+ 1 + (15*pProbe
->szIdxRow
)/pSrc
->pTab
->szTabRow
;
3316 rCostIdx
= sqlite3LogEstAdd(rLogSize
, rCostIdx
);
3318 /* Estimate the cost of running the loop. If all data is coming
3319 ** from the index, then this is just the cost of doing the index
3320 ** lookup and scan. But if some data is coming out of the main table,
3321 ** we also have to add in the cost of doing pNew->nOut searches to
3322 ** locate the row in the main table that corresponds to the index entry.
3324 pNew
->rRun
= rCostIdx
;
3325 if( (pNew
->wsFlags
& (WHERE_IDX_ONLY
|WHERE_IPK
|WHERE_EXPRIDX
))==0 ){
3326 pNew
->rRun
= sqlite3LogEstAdd(pNew
->rRun
, pNew
->nOut
+ 16);
3328 ApplyCostMultiplier(pNew
->rRun
, pProbe
->pTable
->costMult
);
3330 nOutUnadjusted
= pNew
->nOut
;
3331 pNew
->rRun
+= nInMul
+ nIn
;
3332 pNew
->nOut
+= nInMul
+ nIn
;
3333 whereLoopOutputAdjust(pBuilder
->pWC
, pNew
, rSize
);
3334 rc
= whereLoopInsert(pBuilder
, pNew
);
3336 if( pNew
->wsFlags
& WHERE_COLUMN_RANGE
){
3337 pNew
->nOut
= saved_nOut
;
3339 pNew
->nOut
= nOutUnadjusted
;
3342 if( (pNew
->wsFlags
& WHERE_TOP_LIMIT
)==0
3343 && pNew
->u
.btree
.nEq
<pProbe
->nColumn
3344 && (pNew
->u
.btree
.nEq
<pProbe
->nKeyCol
||
3345 pProbe
->idxType
!=SQLITE_IDXTYPE_PRIMARYKEY
)
3347 if( pNew
->u
.btree
.nEq
>3 ){
3348 sqlite3ProgressCheck(pParse
);
3350 whereLoopAddBtreeIndex(pBuilder
, pSrc
, pProbe
, nInMul
+nIn
);
3352 pNew
->nOut
= saved_nOut
;
3353 #ifdef SQLITE_ENABLE_STAT4
3354 pBuilder
->nRecValid
= nRecValid
;
3357 pNew
->prereq
= saved_prereq
;
3358 pNew
->u
.btree
.nEq
= saved_nEq
;
3359 pNew
->u
.btree
.nBtm
= saved_nBtm
;
3360 pNew
->u
.btree
.nTop
= saved_nTop
;
3361 pNew
->nSkip
= saved_nSkip
;
3362 pNew
->wsFlags
= saved_wsFlags
;
3363 pNew
->nOut
= saved_nOut
;
3364 pNew
->nLTerm
= saved_nLTerm
;
3366 /* Consider using a skip-scan if there are no WHERE clause constraints
3367 ** available for the left-most terms of the index, and if the average
3368 ** number of repeats in the left-most terms is at least 18.
3370 ** The magic number 18 is selected on the basis that scanning 17 rows
3371 ** is almost always quicker than an index seek (even though if the index
3372 ** contains fewer than 2^17 rows we assume otherwise in other parts of
3373 ** the code). And, even if it is not, it should not be too much slower.
3374 ** On the other hand, the extra seeks could end up being significantly
3375 ** more expensive. */
3376 assert( 42==sqlite3LogEst(18) );
3377 if( saved_nEq
==saved_nSkip
3378 && saved_nEq
+1<pProbe
->nKeyCol
3379 && saved_nEq
==pNew
->nLTerm
3380 && pProbe
->noSkipScan
==0
3381 && pProbe
->hasStat1
!=0
3382 && OptimizationEnabled(db
, SQLITE_SkipScan
)
3383 && pProbe
->aiRowLogEst
[saved_nEq
+1]>=42 /* TUNING: Minimum for skip-scan */
3384 && (rc
= whereLoopResize(db
, pNew
, pNew
->nLTerm
+1))==SQLITE_OK
3387 pNew
->u
.btree
.nEq
++;
3389 pNew
->aLTerm
[pNew
->nLTerm
++] = 0;
3390 pNew
->wsFlags
|= WHERE_SKIPSCAN
;
3391 nIter
= pProbe
->aiRowLogEst
[saved_nEq
] - pProbe
->aiRowLogEst
[saved_nEq
+1];
3392 pNew
->nOut
-= nIter
;
3393 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
3394 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
3396 whereLoopAddBtreeIndex(pBuilder
, pSrc
, pProbe
, nIter
+ nInMul
);
3397 pNew
->nOut
= saved_nOut
;
3398 pNew
->u
.btree
.nEq
= saved_nEq
;
3399 pNew
->nSkip
= saved_nSkip
;
3400 pNew
->wsFlags
= saved_wsFlags
;
3403 WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
3404 pProbe
->pTable
->zName
, pProbe
->zName
, saved_nEq
, rc
));
3409 ** Return True if it is possible that pIndex might be useful in
3410 ** implementing the ORDER BY clause in pBuilder.
3412 ** Return False if pBuilder does not contain an ORDER BY clause or
3413 ** if there is no way for pIndex to be useful in implementing that
3416 static int indexMightHelpWithOrderBy(
3417 WhereLoopBuilder
*pBuilder
,
3425 if( pIndex
->bUnordered
) return 0;
3426 if( (pOB
= pBuilder
->pWInfo
->pOrderBy
)==0 ) return 0;
3427 for(ii
=0; ii
<pOB
->nExpr
; ii
++){
3428 Expr
*pExpr
= sqlite3ExprSkipCollateAndLikely(pOB
->a
[ii
].pExpr
);
3429 if( NEVER(pExpr
==0) ) continue;
3430 if( (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_AGG_COLUMN
)
3431 && pExpr
->iTable
==iCursor
3433 if( pExpr
->iColumn
<0 ) return 1;
3434 for(jj
=0; jj
<pIndex
->nKeyCol
; jj
++){
3435 if( pExpr
->iColumn
==pIndex
->aiColumn
[jj
] ) return 1;
3437 }else if( (aColExpr
= pIndex
->aColExpr
)!=0 ){
3438 for(jj
=0; jj
<pIndex
->nKeyCol
; jj
++){
3439 if( pIndex
->aiColumn
[jj
]!=XN_EXPR
) continue;
3440 if( sqlite3ExprCompareSkip(pExpr
,aColExpr
->a
[jj
].pExpr
,iCursor
)==0 ){
3449 /* Check to see if a partial index with pPartIndexWhere can be used
3450 ** in the current query. Return true if it can be and false if not.
3452 static int whereUsablePartialIndex(
3453 int iTab
, /* The table for which we want an index */
3454 u8 jointype
, /* The JT_* flags on the join */
3455 WhereClause
*pWC
, /* The WHERE clause of the query */
3456 Expr
*pWhere
/* The WHERE clause from the partial index */
3462 if( jointype
& JT_LTORJ
) return 0;
3463 pParse
= pWC
->pWInfo
->pParse
;
3464 while( pWhere
->op
==TK_AND
){
3465 if( !whereUsablePartialIndex(iTab
,jointype
,pWC
,pWhere
->pLeft
) ) return 0;
3466 pWhere
= pWhere
->pRight
;
3468 if( pParse
->db
->flags
& SQLITE_EnableQPSG
) pParse
= 0;
3469 for(i
=0, pTerm
=pWC
->a
; i
<pWC
->nTerm
; i
++, pTerm
++){
3471 pExpr
= pTerm
->pExpr
;
3472 if( (!ExprHasProperty(pExpr
, EP_OuterON
) || pExpr
->w
.iJoin
==iTab
)
3473 && ((jointype
& JT_OUTER
)==0 || ExprHasProperty(pExpr
, EP_OuterON
))
3474 && sqlite3ExprImpliesExpr(pParse
, pExpr
, pWhere
, iTab
)
3475 && (pTerm
->wtFlags
& TERM_VNULL
)==0
3484 ** pIdx is an index containing expressions. Check it see if any of the
3485 ** expressions in the index match the pExpr expression.
3487 static int exprIsCoveredByIndex(
3493 for(i
=0; i
<pIdx
->nColumn
; i
++){
3494 if( pIdx
->aiColumn
[i
]==XN_EXPR
3495 && sqlite3ExprCompare(0, pExpr
, pIdx
->aColExpr
->a
[i
].pExpr
, iTabCur
)==0
3504 ** Structure passed to the whereIsCoveringIndex Walker callback.
3506 typedef struct CoveringIndexCheck CoveringIndexCheck
;
3507 struct CoveringIndexCheck
{
3508 Index
*pIdx
; /* The index */
3509 int iTabCur
; /* Cursor number for the corresponding table */
3510 u8 bExpr
; /* Uses an indexed expression */
3511 u8 bUnidx
; /* Uses an unindexed column not within an indexed expr */
3515 ** Information passed in is pWalk->u.pCovIdxCk. Call it pCk.
3517 ** If the Expr node references the table with cursor pCk->iTabCur, then
3518 ** make sure that column is covered by the index pCk->pIdx. We know that
3519 ** all columns less than 63 (really BMS-1) are covered, so we don't need
3520 ** to check them. But we do need to check any column at 63 or greater.
3522 ** If the index does not cover the column, then set pWalk->eCode to
3523 ** non-zero and return WRC_Abort to stop the search.
3525 ** If this node does not disprove that the index can be a covering index,
3526 ** then just return WRC_Continue, to continue the search.
3528 ** If pCk->pIdx contains indexed expressions and one of those expressions
3529 ** matches pExpr, then prune the search.
3531 static int whereIsCoveringIndexWalkCallback(Walker
*pWalk
, Expr
*pExpr
){
3532 int i
; /* Loop counter */
3533 const Index
*pIdx
; /* The index of interest */
3534 const i16
*aiColumn
; /* Columns contained in the index */
3535 u16 nColumn
; /* Number of columns in the index */
3536 CoveringIndexCheck
*pCk
; /* Info about this search */
3538 pCk
= pWalk
->u
.pCovIdxCk
;
3540 if( (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_AGG_COLUMN
) ){
3541 /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
3542 if( pExpr
->iTable
!=pCk
->iTabCur
) return WRC_Continue
;
3543 pIdx
= pWalk
->u
.pCovIdxCk
->pIdx
;
3544 aiColumn
= pIdx
->aiColumn
;
3545 nColumn
= pIdx
->nColumn
;
3546 for(i
=0; i
<nColumn
; i
++){
3547 if( aiColumn
[i
]==pExpr
->iColumn
) return WRC_Continue
;
3551 }else if( pIdx
->bHasExpr
3552 && exprIsCoveredByIndex(pExpr
, pIdx
, pWalk
->u
.pCovIdxCk
->iTabCur
) ){
3556 return WRC_Continue
;
3561 ** pIdx is an index that covers all of the low-number columns used by
3562 ** pWInfo->pSelect (columns from 0 through 62) or an index that has
3563 ** expressions terms. Hence, we cannot determine whether or not it is
3564 ** a covering index by using the colUsed bitmasks. We have to do a search
3565 ** to see if the index is covering. This routine does that search.
3567 ** The return value is one of these:
3569 ** 0 The index is definitely not a covering index
3571 ** WHERE_IDX_ONLY The index is definitely a covering index
3573 ** WHERE_EXPRIDX The index is likely a covering index, but it is
3574 ** difficult to determine precisely because of the
3575 ** expressions that are indexed. Score it as a
3576 ** covering index, but still keep the main table open
3577 ** just in case we need it.
3579 ** This routine is an optimization. It is always safe to return zero.
3580 ** But returning one of the other two values when zero should have been
3581 ** returned can lead to incorrect bytecode and assertion faults.
3583 static SQLITE_NOINLINE u32
whereIsCoveringIndex(
3584 WhereInfo
*pWInfo
, /* The WHERE clause context */
3585 Index
*pIdx
, /* Index that is being tested */
3586 int iTabCur
/* Cursor for the table being indexed */
3589 struct CoveringIndexCheck ck
;
3591 if( pWInfo
->pSelect
==0 ){
3592 /* We don't have access to the full query, so we cannot check to see
3593 ** if pIdx is covering. Assume it is not. */
3596 if( pIdx
->bHasExpr
==0 ){
3597 for(i
=0; i
<pIdx
->nColumn
; i
++){
3598 if( pIdx
->aiColumn
[i
]>=BMS
-1 ) break;
3600 if( i
>=pIdx
->nColumn
){
3601 /* pIdx does not index any columns greater than 62, but we know from
3602 ** colMask that columns greater than 62 are used, so this is not a
3603 ** covering index */
3608 ck
.iTabCur
= iTabCur
;
3611 memset(&w
, 0, sizeof(w
));
3612 w
.xExprCallback
= whereIsCoveringIndexWalkCallback
;
3613 w
.xSelectCallback
= sqlite3SelectWalkNoop
;
3614 w
.u
.pCovIdxCk
= &ck
;
3615 sqlite3WalkSelect(&w
, pWInfo
->pSelect
);
3618 }else if( ck
.bExpr
){
3621 rc
= WHERE_IDX_ONLY
;
3627 ** This is an sqlite3ParserAddCleanup() callback that is invoked to
3628 ** free the Parse->pIdxEpr list when the Parse object is destroyed.
3630 static void whereIndexedExprCleanup(sqlite3
*db
, void *pObject
){
3631 IndexedExpr
**pp
= (IndexedExpr
**)pObject
;
3633 IndexedExpr
*p
= *pp
;
3635 sqlite3ExprDelete(db
, p
->pExpr
);
3636 sqlite3DbFreeNN(db
, p
);
3641 ** This function is called for a partial index - one with a WHERE clause - in
3642 ** two scenarios. In both cases, it determines whether or not the WHERE
3643 ** clause on the index implies that a column of the table may be safely
3644 ** replaced by a constant expression. For example, in the following
3647 ** CREATE INDEX i1 ON t1(b, c) WHERE a=<expr>;
3648 ** SELECT a, b, c FROM t1 WHERE a=<expr> AND b=?;
3650 ** The "a" in the select-list may be replaced by <expr>, iff:
3652 ** (a) <expr> is a constant expression, and
3653 ** (b) The (a=<expr>) comparison uses the BINARY collation sequence, and
3654 ** (c) Column "a" has an affinity other than NONE or BLOB.
3656 ** If argument pItem is NULL, then pMask must not be NULL. In this case this
3657 ** function is being called as part of determining whether or not pIdx
3658 ** is a covering index. This function clears any bits in (*pMask)
3659 ** corresponding to columns that may be replaced by constants as described
3662 ** Otherwise, if pItem is not NULL, then this function is being called
3663 ** as part of coding a loop that uses index pIdx. In this case, add entries
3664 ** to the Parse.pIdxPartExpr list for each column that can be replaced
3667 static void wherePartIdxExpr(
3668 Parse
*pParse
, /* Parse context */
3669 Index
*pIdx
, /* Partial index being processed */
3670 Expr
*pPart
, /* WHERE clause being processed */
3671 Bitmask
*pMask
, /* Mask to clear bits in */
3672 int iIdxCur
, /* Cursor number for index */
3673 SrcItem
*pItem
/* The FROM clause entry for the table */
3675 assert( pItem
==0 || (pItem
->fg
.jointype
& JT_RIGHT
)==0 );
3676 assert( (pItem
==0 || pMask
==0) && (pMask
!=0 || pItem
!=0) );
3678 if( pPart
->op
==TK_AND
){
3679 wherePartIdxExpr(pParse
, pIdx
, pPart
->pRight
, pMask
, iIdxCur
, pItem
);
3680 pPart
= pPart
->pLeft
;
3683 if( (pPart
->op
==TK_EQ
|| pPart
->op
==TK_IS
) ){
3684 Expr
*pLeft
= pPart
->pLeft
;
3685 Expr
*pRight
= pPart
->pRight
;
3688 if( pLeft
->op
!=TK_COLUMN
) return;
3689 if( !sqlite3ExprIsConstant(0, pRight
) ) return;
3690 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pParse
, pPart
)) ) return;
3691 if( pLeft
->iColumn
<0 ) return;
3692 aff
= pIdx
->pTable
->aCol
[pLeft
->iColumn
].affinity
;
3693 if( aff
>=SQLITE_AFF_TEXT
){
3695 sqlite3
*db
= pParse
->db
;
3696 IndexedExpr
*p
= (IndexedExpr
*)sqlite3DbMallocRaw(db
, sizeof(*p
));
3698 int bNullRow
= (pItem
->fg
.jointype
&(JT_LEFT
|JT_LTORJ
))!=0;
3699 p
->pExpr
= sqlite3ExprDup(db
, pRight
, 0);
3700 p
->iDataCur
= pItem
->iCursor
;
3701 p
->iIdxCur
= iIdxCur
;
3702 p
->iIdxCol
= pLeft
->iColumn
;
3703 p
->bMaybeNullRow
= bNullRow
;
3704 p
->pIENext
= pParse
->pIdxPartExpr
;
3706 pParse
->pIdxPartExpr
= p
;
3707 if( p
->pIENext
==0 ){
3708 void *pArg
= (void*)&pParse
->pIdxPartExpr
;
3709 sqlite3ParserAddCleanup(pParse
, whereIndexedExprCleanup
, pArg
);
3712 }else if( pLeft
->iColumn
<(BMS
-1) ){
3713 *pMask
&= ~((Bitmask
)1 << pLeft
->iColumn
);
3721 ** Add all WhereLoop objects for a single table of the join where the table
3722 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
3723 ** a b-tree table, not a virtual table.
3725 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
3726 ** are calculated as follows:
3728 ** For a full scan, assuming the table (or index) contains nRow rows:
3730 ** cost = nRow * 3.0 // full-table scan
3731 ** cost = nRow * K // scan of covering index
3732 ** cost = nRow * (K+3.0) // scan of non-covering index
3734 ** where K is a value between 1.1 and 3.0 set based on the relative
3735 ** estimated average size of the index and table records.
3737 ** For an index scan, where nVisit is the number of index rows visited
3738 ** by the scan, and nSeek is the number of seek operations required on
3739 ** the index b-tree:
3741 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
3742 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
3744 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
3745 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
3746 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
3748 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
3749 ** of uncertainty. For this reason, scoring is designed to pick plans that
3750 ** "do the least harm" if the estimates are inaccurate. For example, a
3751 ** log(nRow) factor is omitted from a non-covering index scan in order to
3752 ** bias the scoring in favor of using an index, since the worst-case
3753 ** performance of using an index is far better than the worst-case performance
3754 ** of a full table scan.
3756 static int whereLoopAddBtree(
3757 WhereLoopBuilder
*pBuilder
, /* WHERE clause information */
3758 Bitmask mPrereq
/* Extra prerequisites for using this table */
3760 WhereInfo
*pWInfo
; /* WHERE analysis context */
3761 Index
*pProbe
; /* An index we are evaluating */
3762 Index sPk
; /* A fake index object for the primary key */
3763 LogEst aiRowEstPk
[2]; /* The aiRowLogEst[] value for the sPk index */
3764 i16 aiColumnPk
= -1; /* The aColumn[] value for the sPk index */
3765 SrcList
*pTabList
; /* The FROM clause */
3766 SrcItem
*pSrc
; /* The FROM clause btree term to add */
3767 WhereLoop
*pNew
; /* Template WhereLoop object */
3768 int rc
= SQLITE_OK
; /* Return code */
3769 int iSortIdx
= 1; /* Index number */
3770 int b
; /* A boolean value */
3771 LogEst rSize
; /* number of rows in the table */
3772 WhereClause
*pWC
; /* The parsed WHERE clause */
3773 Table
*pTab
; /* Table being queried */
3775 pNew
= pBuilder
->pNew
;
3776 pWInfo
= pBuilder
->pWInfo
;
3777 pTabList
= pWInfo
->pTabList
;
3778 pSrc
= pTabList
->a
+ pNew
->iTab
;
3780 pWC
= pBuilder
->pWC
;
3781 assert( !IsVirtual(pSrc
->pTab
) );
3783 if( pSrc
->fg
.isIndexedBy
){
3784 assert( pSrc
->fg
.isCte
==0 );
3785 /* An INDEXED BY clause specifies a particular index to use */
3786 pProbe
= pSrc
->u2
.pIBIndex
;
3787 }else if( !HasRowid(pTab
) ){
3788 pProbe
= pTab
->pIndex
;
3790 /* There is no INDEXED BY clause. Create a fake Index object in local
3791 ** variable sPk to represent the rowid primary key index. Make this
3792 ** fake index the first in a chain of Index objects with all of the real
3793 ** indices to follow */
3794 Index
*pFirst
; /* First of real indices on the table */
3795 memset(&sPk
, 0, sizeof(Index
));
3798 sPk
.aiColumn
= &aiColumnPk
;
3799 sPk
.aiRowLogEst
= aiRowEstPk
;
3800 sPk
.onError
= OE_Replace
;
3802 sPk
.szIdxRow
= 3; /* TUNING: Interior rows of IPK table are very small */
3803 sPk
.idxType
= SQLITE_IDXTYPE_IPK
;
3804 aiRowEstPk
[0] = pTab
->nRowLogEst
;
3806 pFirst
= pSrc
->pTab
->pIndex
;
3807 if( pSrc
->fg
.notIndexed
==0 ){
3808 /* The real indices of the table are only considered if the
3809 ** NOT INDEXED qualifier is omitted from the FROM clause */
3814 rSize
= pTab
->nRowLogEst
;
3816 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
3817 /* Automatic indexes */
3818 if( !pBuilder
->pOrSet
/* Not part of an OR optimization */
3819 && (pWInfo
->wctrlFlags
& (WHERE_RIGHT_JOIN
|WHERE_OR_SUBCLAUSE
))==0
3820 && (pWInfo
->pParse
->db
->flags
& SQLITE_AutoIndex
)!=0
3821 && !pSrc
->fg
.isIndexedBy
/* Has no INDEXED BY clause */
3822 && !pSrc
->fg
.notIndexed
/* Has no NOT INDEXED clause */
3823 && HasRowid(pTab
) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
3824 && !pSrc
->fg
.isCorrelated
/* Not a correlated subquery */
3825 && !pSrc
->fg
.isRecursive
/* Not a recursive common table expression. */
3826 && (pSrc
->fg
.jointype
& JT_RIGHT
)==0 /* Not the right tab of a RIGHT JOIN */
3828 /* Generate auto-index WhereLoops */
3829 LogEst rLogSize
; /* Logarithm of the number of rows in the table */
3831 WhereTerm
*pWCEnd
= pWC
->a
+ pWC
->nTerm
;
3832 rLogSize
= estLog(rSize
);
3833 for(pTerm
=pWC
->a
; rc
==SQLITE_OK
&& pTerm
<pWCEnd
; pTerm
++){
3834 if( pTerm
->prereqRight
& pNew
->maskSelf
) continue;
3835 if( termCanDriveIndex(pTerm
, pSrc
, 0) ){
3836 pNew
->u
.btree
.nEq
= 1;
3838 pNew
->u
.btree
.pIndex
= 0;
3840 pNew
->aLTerm
[0] = pTerm
;
3841 /* TUNING: One-time cost for computing the automatic index is
3842 ** estimated to be X*N*log2(N) where N is the number of rows in
3843 ** the table being indexed and where X is 7 (LogEst=28) for normal
3844 ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
3845 ** of X is smaller for views and subqueries so that the query planner
3846 ** will be more aggressive about generating automatic indexes for
3847 ** those objects, since there is no opportunity to add schema
3848 ** indexes on subqueries and views. */
3849 pNew
->rSetup
= rLogSize
+ rSize
;
3850 if( !IsView(pTab
) && (pTab
->tabFlags
& TF_Ephemeral
)==0 ){
3853 pNew
->rSetup
-= 25; /* Greatly reduced setup cost for auto indexes
3854 ** on ephemeral materializations of views */
3856 ApplyCostMultiplier(pNew
->rSetup
, pTab
->costMult
);
3857 if( pNew
->rSetup
<0 ) pNew
->rSetup
= 0;
3858 /* TUNING: Each index lookup yields 20 rows in the table. This
3859 ** is more than the usual guess of 10 rows, since we have no way
3860 ** of knowing how selective the index will ultimately be. It would
3861 ** not be unreasonable to make this value much larger. */
3862 pNew
->nOut
= 43; assert( 43==sqlite3LogEst(20) );
3863 pNew
->rRun
= sqlite3LogEstAdd(rLogSize
,pNew
->nOut
);
3864 pNew
->wsFlags
= WHERE_AUTO_INDEX
;
3865 pNew
->prereq
= mPrereq
| pTerm
->prereqRight
;
3866 rc
= whereLoopInsert(pBuilder
, pNew
);
3870 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
3872 /* Loop over all indices. If there was an INDEXED BY clause, then only
3873 ** consider index pProbe. */
3874 for(; rc
==SQLITE_OK
&& pProbe
;
3875 pProbe
=(pSrc
->fg
.isIndexedBy
? 0 : pProbe
->pNext
), iSortIdx
++
3877 if( pProbe
->pPartIdxWhere
!=0
3878 && !whereUsablePartialIndex(pSrc
->iCursor
, pSrc
->fg
.jointype
, pWC
,
3879 pProbe
->pPartIdxWhere
)
3881 testcase( pNew
->iTab
!=pSrc
->iCursor
); /* See ticket [98d973b8f5] */
3882 continue; /* Partial index inappropriate for this query */
3884 if( pProbe
->bNoQuery
) continue;
3885 rSize
= pProbe
->aiRowLogEst
[0];
3886 pNew
->u
.btree
.nEq
= 0;
3887 pNew
->u
.btree
.nBtm
= 0;
3888 pNew
->u
.btree
.nTop
= 0;
3893 pNew
->prereq
= mPrereq
;
3895 pNew
->u
.btree
.pIndex
= pProbe
;
3896 b
= indexMightHelpWithOrderBy(pBuilder
, pProbe
, pSrc
->iCursor
);
3898 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
3899 assert( (pWInfo
->wctrlFlags
& WHERE_ONEPASS_DESIRED
)==0 || b
==0 );
3900 if( pProbe
->idxType
==SQLITE_IDXTYPE_IPK
){
3901 /* Integer primary key index */
3902 pNew
->wsFlags
= WHERE_IPK
;
3904 /* Full table scan */
3905 pNew
->iSortIdx
= b
? iSortIdx
: 0;
3906 /* TUNING: Cost of full table scan is 3.0*N. The 3.0 factor is an
3907 ** extra cost designed to discourage the use of full table scans,
3908 ** since index lookups have better worst-case performance if our
3909 ** stat guesses are wrong. Reduce the 3.0 penalty slightly
3910 ** (to 2.75) if we have valid STAT4 information for the table.
3911 ** At 2.75, a full table scan is preferred over using an index on
3912 ** a column with just two distinct values where each value has about
3913 ** an equal number of appearances. Without STAT4 data, we still want
3914 ** to use an index in that case, since the constraint might be for
3915 ** the scarcer of the two values, and in that case an index lookup is
3918 #ifdef SQLITE_ENABLE_STAT4
3919 pNew
->rRun
= rSize
+ 16 - 2*((pTab
->tabFlags
& TF_HasStat4
)!=0);
3921 pNew
->rRun
= rSize
+ 16;
3923 ApplyCostMultiplier(pNew
->rRun
, pTab
->costMult
);
3924 whereLoopOutputAdjust(pWC
, pNew
, rSize
);
3925 rc
= whereLoopInsert(pBuilder
, pNew
);
3930 if( pProbe
->isCovering
){
3932 pNew
->wsFlags
= WHERE_IDX_ONLY
| WHERE_INDEXED
;
3934 m
= pSrc
->colUsed
& pProbe
->colNotIdxed
;
3935 if( pProbe
->pPartIdxWhere
){
3937 pWInfo
->pParse
, pProbe
, pProbe
->pPartIdxWhere
, &m
, 0, 0
3940 pNew
->wsFlags
= WHERE_INDEXED
;
3941 if( m
==TOPBIT
|| (pProbe
->bHasExpr
&& !pProbe
->bHasVCol
&& m
!=0) ){
3942 u32 isCov
= whereIsCoveringIndex(pWInfo
, pProbe
, pSrc
->iCursor
);
3945 ("-> %s is not a covering index"
3946 " according to whereIsCoveringIndex()\n", pProbe
->zName
));
3950 pNew
->wsFlags
|= isCov
;
3951 if( isCov
& WHERE_IDX_ONLY
){
3953 ("-> %s is a covering expression index"
3954 " according to whereIsCoveringIndex()\n", pProbe
->zName
));
3956 assert( isCov
==WHERE_EXPRIDX
);
3958 ("-> %s might be a covering expression index"
3959 " according to whereIsCoveringIndex()\n", pProbe
->zName
));
3963 && (HasRowid(pTab
) || pWInfo
->pSelect
!=0 || sqlite3FaultSim(700))
3966 ("-> %s a covering index according to bitmasks\n",
3967 pProbe
->zName
, m
==0 ? "is" : "is not"));
3968 pNew
->wsFlags
= WHERE_IDX_ONLY
| WHERE_INDEXED
;
3972 /* Full scan via index */
3975 || pProbe
->pPartIdxWhere
!=0
3976 || pSrc
->fg
.isIndexedBy
3978 && pProbe
->bUnordered
==0
3979 && (pProbe
->szIdxRow
<pTab
->szTabRow
)
3980 && (pWInfo
->wctrlFlags
& WHERE_ONEPASS_DESIRED
)==0
3981 && sqlite3GlobalConfig
.bUseCis
3982 && OptimizationEnabled(pWInfo
->pParse
->db
, SQLITE_CoverIdxScan
)
3985 pNew
->iSortIdx
= b
? iSortIdx
: 0;
3987 /* The cost of visiting the index rows is N*K, where K is
3988 ** between 1.1 and 3.0, depending on the relative sizes of the
3989 ** index and table rows. */
3990 pNew
->rRun
= rSize
+ 1 + (15*pProbe
->szIdxRow
)/pTab
->szTabRow
;
3992 /* If this is a non-covering index scan, add in the cost of
3993 ** doing table lookups. The cost will be 3x the number of
3994 ** lookups. Take into account WHERE clause terms that can be
3995 ** satisfied using just the index, and that do not require a
3997 LogEst nLookup
= rSize
+ 16; /* Base cost: N*3 */
3999 int iCur
= pSrc
->iCursor
;
4000 WhereClause
*pWC2
= &pWInfo
->sWC
;
4001 for(ii
=0; ii
<pWC2
->nTerm
; ii
++){
4002 WhereTerm
*pTerm
= &pWC2
->a
[ii
];
4003 if( !sqlite3ExprCoveredByIndex(pTerm
->pExpr
, iCur
, pProbe
) ){
4006 /* pTerm can be evaluated using just the index. So reduce
4007 ** the expected number of table lookups accordingly */
4008 if( pTerm
->truthProb
<=0 ){
4009 nLookup
+= pTerm
->truthProb
;
4012 if( pTerm
->eOperator
& (WO_EQ
|WO_IS
) ) nLookup
-= 19;
4016 pNew
->rRun
= sqlite3LogEstAdd(pNew
->rRun
, nLookup
);
4018 ApplyCostMultiplier(pNew
->rRun
, pTab
->costMult
);
4019 whereLoopOutputAdjust(pWC
, pNew
, rSize
);
4020 if( (pSrc
->fg
.jointype
& JT_RIGHT
)!=0 && pProbe
->aColExpr
){
4021 /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
4022 ** because the cursor used to access the index might not be
4023 ** positioned to the correct row during the right-join no-match
4026 rc
= whereLoopInsert(pBuilder
, pNew
);
4033 pBuilder
->bldFlags1
= 0;
4034 rc
= whereLoopAddBtreeIndex(pBuilder
, pSrc
, pProbe
, 0);
4035 if( pBuilder
->bldFlags1
==SQLITE_BLDF1_INDEXED
){
4036 /* If a non-unique index is used, or if a prefix of the key for
4037 ** unique index is used (making the index functionally non-unique)
4038 ** then the sqlite_stat1 data becomes important for scoring the
4040 pTab
->tabFlags
|= TF_MaybeReanalyze
;
4042 #ifdef SQLITE_ENABLE_STAT4
4043 sqlite3Stat4ProbeFree(pBuilder
->pRec
);
4044 pBuilder
->nRecValid
= 0;
4051 #ifndef SQLITE_OMIT_VIRTUALTABLE
4054 ** Return true if pTerm is a virtual table LIMIT or OFFSET term.
4056 static int isLimitTerm(WhereTerm
*pTerm
){
4057 assert( pTerm
->eOperator
==WO_AUX
|| pTerm
->eMatchOp
==0 );
4058 return pTerm
->eMatchOp
>=SQLITE_INDEX_CONSTRAINT_LIMIT
4059 && pTerm
->eMatchOp
<=SQLITE_INDEX_CONSTRAINT_OFFSET
;
4063 ** Return true if the first nCons constraints in the pUsage array are
4064 ** marked as in-use (have argvIndex>0). False otherwise.
4066 static int allConstraintsUsed(
4067 struct sqlite3_index_constraint_usage
*aUsage
,
4071 for(ii
=0; ii
<nCons
; ii
++){
4072 if( aUsage
[ii
].argvIndex
<=0 ) return 0;
4078 ** Argument pIdxInfo is already populated with all constraints that may
4079 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
4080 ** function marks a subset of those constraints usable, invokes the
4081 ** xBestIndex method and adds the returned plan to pBuilder.
4083 ** A constraint is marked usable if:
4085 ** * Argument mUsable indicates that its prerequisites are available, and
4087 ** * It is not one of the operators specified in the mExclude mask passed
4088 ** as the fourth argument (which in practice is either WO_IN or 0).
4090 ** Argument mPrereq is a mask of tables that must be scanned before the
4091 ** virtual table in question. These are added to the plans prerequisites
4092 ** before it is added to pBuilder.
4094 ** Output parameter *pbIn is set to true if the plan added to pBuilder
4095 ** uses one or more WO_IN terms, or false otherwise.
4097 static int whereLoopAddVirtualOne(
4098 WhereLoopBuilder
*pBuilder
,
4099 Bitmask mPrereq
, /* Mask of tables that must be used. */
4100 Bitmask mUsable
, /* Mask of usable tables */
4101 u16 mExclude
, /* Exclude terms using these operators */
4102 sqlite3_index_info
*pIdxInfo
, /* Populated object for xBestIndex */
4103 u16 mNoOmit
, /* Do not omit these constraints */
4104 int *pbIn
, /* OUT: True if plan uses an IN(...) op */
4105 int *pbRetryLimit
/* OUT: Retry without LIMIT/OFFSET */
4107 WhereClause
*pWC
= pBuilder
->pWC
;
4108 HiddenIndexInfo
*pHidden
= (HiddenIndexInfo
*)&pIdxInfo
[1];
4109 struct sqlite3_index_constraint
*pIdxCons
;
4110 struct sqlite3_index_constraint_usage
*pUsage
= pIdxInfo
->aConstraintUsage
;
4114 WhereLoop
*pNew
= pBuilder
->pNew
;
4115 Parse
*pParse
= pBuilder
->pWInfo
->pParse
;
4116 SrcItem
*pSrc
= &pBuilder
->pWInfo
->pTabList
->a
[pNew
->iTab
];
4117 int nConstraint
= pIdxInfo
->nConstraint
;
4119 assert( (mUsable
& mPrereq
)==mPrereq
);
4121 pNew
->prereq
= mPrereq
;
4123 /* Set the usable flag on the subset of constraints identified by
4124 ** arguments mUsable and mExclude. */
4125 pIdxCons
= *(struct sqlite3_index_constraint
**)&pIdxInfo
->aConstraint
;
4126 for(i
=0; i
<nConstraint
; i
++, pIdxCons
++){
4127 WhereTerm
*pTerm
= &pWC
->a
[pIdxCons
->iTermOffset
];
4128 pIdxCons
->usable
= 0;
4129 if( (pTerm
->prereqRight
& mUsable
)==pTerm
->prereqRight
4130 && (pTerm
->eOperator
& mExclude
)==0
4131 && (pbRetryLimit
|| !isLimitTerm(pTerm
))
4133 pIdxCons
->usable
= 1;
4137 /* Initialize the output fields of the sqlite3_index_info structure */
4138 memset(pUsage
, 0, sizeof(pUsage
[0])*nConstraint
);
4139 assert( pIdxInfo
->needToFreeIdxStr
==0 );
4140 pIdxInfo
->idxStr
= 0;
4141 pIdxInfo
->idxNum
= 0;
4142 pIdxInfo
->orderByConsumed
= 0;
4143 pIdxInfo
->estimatedCost
= SQLITE_BIG_DBL
/ (double)2;
4144 pIdxInfo
->estimatedRows
= 25;
4145 pIdxInfo
->idxFlags
= 0;
4146 pIdxInfo
->colUsed
= (sqlite3_int64
)pSrc
->colUsed
;
4147 pHidden
->mHandleIn
= 0;
4149 /* Invoke the virtual table xBestIndex() method */
4150 rc
= vtabBestIndex(pParse
, pSrc
->pTab
, pIdxInfo
);
4152 if( rc
==SQLITE_CONSTRAINT
){
4153 /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
4154 ** that the particular combination of parameters provided is unusable.
4155 ** Make no entries in the loop table.
4157 WHERETRACE(0xffffffff, (" ^^^^--- non-viable plan rejected!\n"));
4164 assert( pNew
->nLSlot
>=nConstraint
);
4165 memset(pNew
->aLTerm
, 0, sizeof(pNew
->aLTerm
[0])*nConstraint
);
4166 memset(&pNew
->u
.vtab
, 0, sizeof(pNew
->u
.vtab
));
4167 pIdxCons
= *(struct sqlite3_index_constraint
**)&pIdxInfo
->aConstraint
;
4168 for(i
=0; i
<nConstraint
; i
++, pIdxCons
++){
4170 if( (iTerm
= pUsage
[i
].argvIndex
- 1)>=0 ){
4172 int j
= pIdxCons
->iTermOffset
;
4173 if( iTerm
>=nConstraint
4176 || pNew
->aLTerm
[iTerm
]!=0
4177 || pIdxCons
->usable
==0
4179 sqlite3ErrorMsg(pParse
,"%s.xBestIndex malfunction",pSrc
->pTab
->zName
);
4180 testcase( pIdxInfo
->needToFreeIdxStr
);
4181 return SQLITE_ERROR
;
4183 testcase( iTerm
==nConstraint
-1 );
4185 testcase( j
==pWC
->nTerm
-1 );
4187 pNew
->prereq
|= pTerm
->prereqRight
;
4188 assert( iTerm
<pNew
->nLSlot
);
4189 pNew
->aLTerm
[iTerm
] = pTerm
;
4190 if( iTerm
>mxTerm
) mxTerm
= iTerm
;
4191 testcase( iTerm
==15 );
4192 testcase( iTerm
==16 );
4193 if( pUsage
[i
].omit
){
4194 if( i
<16 && ((1<<i
)&mNoOmit
)==0 ){
4195 testcase( i
!=iTerm
);
4196 pNew
->u
.vtab
.omitMask
|= 1<<iTerm
;
4198 testcase( i
!=iTerm
);
4200 if( pTerm
->eMatchOp
==SQLITE_INDEX_CONSTRAINT_OFFSET
){
4201 pNew
->u
.vtab
.bOmitOffset
= 1;
4204 if( SMASKBIT32(i
) & pHidden
->mHandleIn
){
4205 pNew
->u
.vtab
.mHandleIn
|= MASKBIT32(iTerm
);
4206 }else if( (pTerm
->eOperator
& WO_IN
)!=0 ){
4207 /* A virtual table that is constrained by an IN clause may not
4208 ** consume the ORDER BY clause because (1) the order of IN terms
4209 ** is not necessarily related to the order of output terms and
4210 ** (2) Multiple outputs from a single IN value will not merge
4212 pIdxInfo
->orderByConsumed
= 0;
4213 pIdxInfo
->idxFlags
&= ~SQLITE_INDEX_SCAN_UNIQUE
;
4214 *pbIn
= 1; assert( (mExclude
& WO_IN
)==0 );
4217 /* Unless pbRetryLimit is non-NULL, there should be no LIMIT/OFFSET
4218 ** terms. And if there are any, they should follow all other terms. */
4219 assert( pbRetryLimit
|| !isLimitTerm(pTerm
) );
4220 assert( !isLimitTerm(pTerm
) || i
>=nConstraint
-2 );
4221 assert( !isLimitTerm(pTerm
) || i
==nConstraint
-1 || isLimitTerm(pTerm
+1) );
4223 if( isLimitTerm(pTerm
) && (*pbIn
|| !allConstraintsUsed(pUsage
, i
)) ){
4224 /* If there is an IN(...) term handled as an == (separate call to
4225 ** xFilter for each value on the RHS of the IN) and a LIMIT or
4226 ** OFFSET term handled as well, the plan is unusable. Similarly,
4227 ** if there is a LIMIT/OFFSET and there are other unused terms,
4228 ** the plan cannot be used. In these cases set variable *pbRetryLimit
4229 ** to true to tell the caller to retry with LIMIT and OFFSET
4231 if( pIdxInfo
->needToFreeIdxStr
){
4232 sqlite3_free(pIdxInfo
->idxStr
);
4233 pIdxInfo
->idxStr
= 0;
4234 pIdxInfo
->needToFreeIdxStr
= 0;
4242 pNew
->nLTerm
= mxTerm
+1;
4243 for(i
=0; i
<=mxTerm
; i
++){
4244 if( pNew
->aLTerm
[i
]==0 ){
4245 /* The non-zero argvIdx values must be contiguous. Raise an
4246 ** error if they are not */
4247 sqlite3ErrorMsg(pParse
,"%s.xBestIndex malfunction",pSrc
->pTab
->zName
);
4248 testcase( pIdxInfo
->needToFreeIdxStr
);
4249 return SQLITE_ERROR
;
4252 assert( pNew
->nLTerm
<=pNew
->nLSlot
);
4253 pNew
->u
.vtab
.idxNum
= pIdxInfo
->idxNum
;
4254 pNew
->u
.vtab
.needFree
= pIdxInfo
->needToFreeIdxStr
;
4255 pIdxInfo
->needToFreeIdxStr
= 0;
4256 pNew
->u
.vtab
.idxStr
= pIdxInfo
->idxStr
;
4257 pNew
->u
.vtab
.isOrdered
= (i8
)(pIdxInfo
->orderByConsumed
?
4258 pIdxInfo
->nOrderBy
: 0);
4260 pNew
->rRun
= sqlite3LogEstFromDouble(pIdxInfo
->estimatedCost
);
4261 pNew
->nOut
= sqlite3LogEst(pIdxInfo
->estimatedRows
);
4263 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
4264 ** that the scan will visit at most one row. Clear it otherwise. */
4265 if( pIdxInfo
->idxFlags
& SQLITE_INDEX_SCAN_UNIQUE
){
4266 pNew
->wsFlags
|= WHERE_ONEROW
;
4268 pNew
->wsFlags
&= ~WHERE_ONEROW
;
4270 rc
= whereLoopInsert(pBuilder
, pNew
);
4271 if( pNew
->u
.vtab
.needFree
){
4272 sqlite3_free(pNew
->u
.vtab
.idxStr
);
4273 pNew
->u
.vtab
.needFree
= 0;
4275 WHERETRACE(0xffffffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
4276 *pbIn
, (sqlite3_uint64
)mPrereq
,
4277 (sqlite3_uint64
)(pNew
->prereq
& ~mPrereq
)));
4283 ** Return the collating sequence for a constraint passed into xBestIndex.
4285 ** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
4286 ** This routine depends on there being a HiddenIndexInfo structure immediately
4287 ** following the sqlite3_index_info structure.
4289 ** Return a pointer to the collation name:
4291 ** 1. If there is an explicit COLLATE operator on the constraint, return it.
4293 ** 2. Else, if the column has an alternative collation, return that.
4295 ** 3. Otherwise, return "BINARY".
4297 const char *sqlite3_vtab_collation(sqlite3_index_info
*pIdxInfo
, int iCons
){
4298 HiddenIndexInfo
*pHidden
= (HiddenIndexInfo
*)&pIdxInfo
[1];
4299 const char *zRet
= 0;
4300 if( iCons
>=0 && iCons
<pIdxInfo
->nConstraint
){
4302 int iTerm
= pIdxInfo
->aConstraint
[iCons
].iTermOffset
;
4303 Expr
*pX
= pHidden
->pWC
->a
[iTerm
].pExpr
;
4305 pC
= sqlite3ExprCompareCollSeq(pHidden
->pParse
, pX
);
4307 zRet
= (pC
? pC
->zName
: sqlite3StrBINARY
);
4313 ** Return true if constraint iCons is really an IN(...) constraint, or
4314 ** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
4315 ** or clear (if bHandle==0) the flag to handle it using an iterator.
4317 int sqlite3_vtab_in(sqlite3_index_info
*pIdxInfo
, int iCons
, int bHandle
){
4318 HiddenIndexInfo
*pHidden
= (HiddenIndexInfo
*)&pIdxInfo
[1];
4319 u32 m
= SMASKBIT32(iCons
);
4320 if( m
& pHidden
->mIn
){
4322 pHidden
->mHandleIn
&= ~m
;
4323 }else if( bHandle
>0 ){
4324 pHidden
->mHandleIn
|= m
;
4332 ** This interface is callable from within the xBestIndex callback only.
4334 ** If possible, set (*ppVal) to point to an object containing the value
4335 ** on the right-hand-side of constraint iCons.
4337 int sqlite3_vtab_rhs_value(
4338 sqlite3_index_info
*pIdxInfo
, /* Copy of first argument to xBestIndex */
4339 int iCons
, /* Constraint for which RHS is wanted */
4340 sqlite3_value
**ppVal
/* Write value extracted here */
4342 HiddenIndexInfo
*pH
= (HiddenIndexInfo
*)&pIdxInfo
[1];
4343 sqlite3_value
*pVal
= 0;
4345 if( iCons
<0 || iCons
>=pIdxInfo
->nConstraint
){
4346 rc
= SQLITE_MISUSE_BKPT
; /* EV: R-30545-25046 */
4348 if( pH
->aRhs
[iCons
]==0 ){
4349 WhereTerm
*pTerm
= &pH
->pWC
->a
[pIdxInfo
->aConstraint
[iCons
].iTermOffset
];
4350 rc
= sqlite3ValueFromExpr(
4351 pH
->pParse
->db
, pTerm
->pExpr
->pRight
, ENC(pH
->pParse
->db
),
4352 SQLITE_AFF_BLOB
, &pH
->aRhs
[iCons
]
4354 testcase( rc
!=SQLITE_OK
);
4356 pVal
= pH
->aRhs
[iCons
];
4360 if( rc
==SQLITE_OK
&& pVal
==0 ){ /* IMP: R-19933-32160 */
4361 rc
= SQLITE_NOTFOUND
; /* IMP: R-36424-56542 */
4368 ** Return true if ORDER BY clause may be handled as DISTINCT.
4370 int sqlite3_vtab_distinct(sqlite3_index_info
*pIdxInfo
){
4371 HiddenIndexInfo
*pHidden
= (HiddenIndexInfo
*)&pIdxInfo
[1];
4372 assert( pHidden
->eDistinct
>=0 && pHidden
->eDistinct
<=3 );
4373 return pHidden
->eDistinct
;
4377 ** Cause the prepared statement that is associated with a call to
4378 ** xBestIndex to potentially use all schemas. If the statement being
4379 ** prepared is read-only, then just start read transactions on all
4380 ** schemas. But if this is a write operation, start writes on all
4383 ** This is used by the (built-in) sqlite_dbpage virtual table.
4385 void sqlite3VtabUsesAllSchemas(Parse
*pParse
){
4386 int nDb
= pParse
->db
->nDb
;
4388 for(i
=0; i
<nDb
; i
++){
4389 sqlite3CodeVerifySchema(pParse
, i
);
4391 if( DbMaskNonZero(pParse
->writeMask
) ){
4392 for(i
=0; i
<nDb
; i
++){
4393 sqlite3BeginWriteOperation(pParse
, 0, i
);
4399 ** Add all WhereLoop objects for a table of the join identified by
4400 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
4402 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
4403 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
4404 ** entries that occur before the virtual table in the FROM clause and are
4405 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
4406 ** mUnusable mask contains all FROM clause entries that occur after the
4407 ** virtual table and are separated from it by at least one LEFT or
4410 ** For example, if the query were:
4412 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
4414 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
4416 ** All the tables in mPrereq must be scanned before the current virtual
4417 ** table. So any terms for which all prerequisites are satisfied by
4418 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
4419 ** Conversely, all tables in mUnusable must be scanned after the current
4420 ** virtual table, so any terms for which the prerequisites overlap with
4421 ** mUnusable should always be configured as "not-usable" for xBestIndex.
4423 static int whereLoopAddVirtual(
4424 WhereLoopBuilder
*pBuilder
, /* WHERE clause information */
4425 Bitmask mPrereq
, /* Tables that must be scanned before this one */
4426 Bitmask mUnusable
/* Tables that must be scanned after this one */
4428 int rc
= SQLITE_OK
; /* Return code */
4429 WhereInfo
*pWInfo
; /* WHERE analysis context */
4430 Parse
*pParse
; /* The parsing context */
4431 WhereClause
*pWC
; /* The WHERE clause */
4432 SrcItem
*pSrc
; /* The FROM clause term to search */
4433 sqlite3_index_info
*p
; /* Object to pass to xBestIndex() */
4434 int nConstraint
; /* Number of constraints in p */
4435 int bIn
; /* True if plan uses IN(...) operator */
4437 Bitmask mBest
; /* Tables used by best possible plan */
4439 int bRetry
= 0; /* True to retry with LIMIT/OFFSET disabled */
4441 assert( (mPrereq
& mUnusable
)==0 );
4442 pWInfo
= pBuilder
->pWInfo
;
4443 pParse
= pWInfo
->pParse
;
4444 pWC
= pBuilder
->pWC
;
4445 pNew
= pBuilder
->pNew
;
4446 pSrc
= &pWInfo
->pTabList
->a
[pNew
->iTab
];
4447 assert( IsVirtual(pSrc
->pTab
) );
4448 p
= allocateIndexInfo(pWInfo
, pWC
, mUnusable
, pSrc
, &mNoOmit
);
4449 if( p
==0 ) return SQLITE_NOMEM_BKPT
;
4451 pNew
->wsFlags
= WHERE_VIRTUALTABLE
;
4453 pNew
->u
.vtab
.needFree
= 0;
4454 nConstraint
= p
->nConstraint
;
4455 if( whereLoopResize(pParse
->db
, pNew
, nConstraint
) ){
4456 freeIndexInfo(pParse
->db
, p
);
4457 return SQLITE_NOMEM_BKPT
;
4460 /* First call xBestIndex() with all constraints usable. */
4461 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc
->pTab
->zName
));
4462 WHERETRACE(0x800, (" VirtualOne: all usable\n"));
4463 rc
= whereLoopAddVirtualOne(
4464 pBuilder
, mPrereq
, ALLBITS
, 0, p
, mNoOmit
, &bIn
, &bRetry
4467 assert( rc
==SQLITE_OK
);
4468 rc
= whereLoopAddVirtualOne(
4469 pBuilder
, mPrereq
, ALLBITS
, 0, p
, mNoOmit
, &bIn
, 0
4473 /* If the call to xBestIndex() with all terms enabled produced a plan
4474 ** that does not require any source tables (IOW: a plan with mBest==0)
4475 ** and does not use an IN(...) operator, then there is no point in making
4476 ** any further calls to xBestIndex() since they will all return the same
4477 ** result (if the xBestIndex() implementation is sane). */
4478 if( rc
==SQLITE_OK
&& ((mBest
= (pNew
->prereq
& ~mPrereq
))!=0 || bIn
) ){
4479 int seenZero
= 0; /* True if a plan with no prereqs seen */
4480 int seenZeroNoIN
= 0; /* Plan with no prereqs and no IN(...) seen */
4482 Bitmask mBestNoIn
= 0;
4484 /* If the plan produced by the earlier call uses an IN(...) term, call
4485 ** xBestIndex again, this time with IN(...) terms disabled. */
4487 WHERETRACE(0x800, (" VirtualOne: all usable w/o IN\n"));
4488 rc
= whereLoopAddVirtualOne(
4489 pBuilder
, mPrereq
, ALLBITS
, WO_IN
, p
, mNoOmit
, &bIn
, 0);
4491 mBestNoIn
= pNew
->prereq
& ~mPrereq
;
4498 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
4499 ** in the set of terms that apply to the current virtual table. */
4500 while( rc
==SQLITE_OK
){
4502 Bitmask mNext
= ALLBITS
;
4504 for(i
=0; i
<nConstraint
; i
++){
4506 pWC
->a
[p
->aConstraint
[i
].iTermOffset
].prereqRight
& ~mPrereq
4508 if( mThis
>mPrev
&& mThis
<mNext
) mNext
= mThis
;
4511 if( mNext
==ALLBITS
) break;
4512 if( mNext
==mBest
|| mNext
==mBestNoIn
) continue;
4513 WHERETRACE(0x800, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
4514 (sqlite3_uint64
)mPrev
, (sqlite3_uint64
)mNext
));
4515 rc
= whereLoopAddVirtualOne(
4516 pBuilder
, mPrereq
, mNext
|mPrereq
, 0, p
, mNoOmit
, &bIn
, 0);
4517 if( pNew
->prereq
==mPrereq
){
4519 if( bIn
==0 ) seenZeroNoIN
= 1;
4523 /* If the calls to xBestIndex() in the above loop did not find a plan
4524 ** that requires no source tables at all (i.e. one guaranteed to be
4525 ** usable), make a call here with all source tables disabled */
4526 if( rc
==SQLITE_OK
&& seenZero
==0 ){
4527 WHERETRACE(0x800, (" VirtualOne: all disabled\n"));
4528 rc
= whereLoopAddVirtualOne(
4529 pBuilder
, mPrereq
, mPrereq
, 0, p
, mNoOmit
, &bIn
, 0);
4530 if( bIn
==0 ) seenZeroNoIN
= 1;
4533 /* If the calls to xBestIndex() have so far failed to find a plan
4534 ** that requires no source tables at all and does not use an IN(...)
4535 ** operator, make a final call to obtain one here. */
4536 if( rc
==SQLITE_OK
&& seenZeroNoIN
==0 ){
4537 WHERETRACE(0x800, (" VirtualOne: all disabled and w/o IN\n"));
4538 rc
= whereLoopAddVirtualOne(
4539 pBuilder
, mPrereq
, mPrereq
, WO_IN
, p
, mNoOmit
, &bIn
, 0);
4543 if( p
->needToFreeIdxStr
) sqlite3_free(p
->idxStr
);
4544 freeIndexInfo(pParse
->db
, p
);
4545 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc
->pTab
->zName
, rc
));
4548 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4551 ** Add WhereLoop entries to handle OR terms. This works for either
4552 ** btrees or virtual tables.
4554 static int whereLoopAddOr(
4555 WhereLoopBuilder
*pBuilder
,
4559 WhereInfo
*pWInfo
= pBuilder
->pWInfo
;
4562 WhereTerm
*pTerm
, *pWCEnd
;
4566 WhereLoopBuilder sSubBuild
;
4567 WhereOrSet sSum
, sCur
;
4570 pWC
= pBuilder
->pWC
;
4571 pWCEnd
= pWC
->a
+ pWC
->nTerm
;
4572 pNew
= pBuilder
->pNew
;
4573 memset(&sSum
, 0, sizeof(sSum
));
4574 pItem
= pWInfo
->pTabList
->a
+ pNew
->iTab
;
4575 iCur
= pItem
->iCursor
;
4577 /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
4578 if( pItem
->fg
.jointype
& JT_RIGHT
) return SQLITE_OK
;
4580 for(pTerm
=pWC
->a
; pTerm
<pWCEnd
&& rc
==SQLITE_OK
; pTerm
++){
4581 if( (pTerm
->eOperator
& WO_OR
)!=0
4582 && (pTerm
->u
.pOrInfo
->indexable
& pNew
->maskSelf
)!=0
4584 WhereClause
* const pOrWC
= &pTerm
->u
.pOrInfo
->wc
;
4585 WhereTerm
* const pOrWCEnd
= &pOrWC
->a
[pOrWC
->nTerm
];
4590 sSubBuild
= *pBuilder
;
4591 sSubBuild
.pOrSet
= &sCur
;
4593 WHERETRACE(0x400, ("Begin processing OR-clause %p\n", pTerm
));
4594 for(pOrTerm
=pOrWC
->a
; pOrTerm
<pOrWCEnd
; pOrTerm
++){
4595 if( (pOrTerm
->eOperator
& WO_AND
)!=0 ){
4596 sSubBuild
.pWC
= &pOrTerm
->u
.pAndInfo
->wc
;
4597 }else if( pOrTerm
->leftCursor
==iCur
){
4598 tempWC
.pWInfo
= pWC
->pWInfo
;
4599 tempWC
.pOuter
= pWC
;
4604 sSubBuild
.pWC
= &tempWC
;
4609 #ifdef WHERETRACE_ENABLED
4610 WHERETRACE(0x400, ("OR-term %d of %p has %d subterms:\n",
4611 (int)(pOrTerm
-pOrWC
->a
), pTerm
, sSubBuild
.pWC
->nTerm
));
4612 if( sqlite3WhereTrace
& 0x20000 ){
4613 sqlite3WhereClausePrint(sSubBuild
.pWC
);
4616 #ifndef SQLITE_OMIT_VIRTUALTABLE
4617 if( IsVirtual(pItem
->pTab
) ){
4618 rc
= whereLoopAddVirtual(&sSubBuild
, mPrereq
, mUnusable
);
4622 rc
= whereLoopAddBtree(&sSubBuild
, mPrereq
);
4624 if( rc
==SQLITE_OK
){
4625 rc
= whereLoopAddOr(&sSubBuild
, mPrereq
, mUnusable
);
4627 testcase( rc
==SQLITE_NOMEM
&& sCur
.n
>0 );
4628 testcase( rc
==SQLITE_DONE
);
4633 whereOrMove(&sSum
, &sCur
);
4637 whereOrMove(&sPrev
, &sSum
);
4639 for(i
=0; i
<sPrev
.n
; i
++){
4640 for(j
=0; j
<sCur
.n
; j
++){
4641 whereOrInsert(&sSum
, sPrev
.a
[i
].prereq
| sCur
.a
[j
].prereq
,
4642 sqlite3LogEstAdd(sPrev
.a
[i
].rRun
, sCur
.a
[j
].rRun
),
4643 sqlite3LogEstAdd(sPrev
.a
[i
].nOut
, sCur
.a
[j
].nOut
));
4649 pNew
->aLTerm
[0] = pTerm
;
4650 pNew
->wsFlags
= WHERE_MULTI_OR
;
4653 memset(&pNew
->u
, 0, sizeof(pNew
->u
));
4654 for(i
=0; rc
==SQLITE_OK
&& i
<sSum
.n
; i
++){
4655 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
4656 ** of all sub-scans required by the OR-scan. However, due to rounding
4657 ** errors, it may be that the cost of the OR-scan is equal to its
4658 ** most expensive sub-scan. Add the smallest possible penalty
4659 ** (equivalent to multiplying the cost by 1.07) to ensure that
4660 ** this does not happen. Otherwise, for WHERE clauses such as the
4661 ** following where there is an index on "y":
4663 ** WHERE likelihood(x=?, 0.99) OR y=?
4665 ** the planner may elect to "OR" together a full-table scan and an
4666 ** index lookup. And other similarly odd results. */
4667 pNew
->rRun
= sSum
.a
[i
].rRun
+ 1;
4668 pNew
->nOut
= sSum
.a
[i
].nOut
;
4669 pNew
->prereq
= sSum
.a
[i
].prereq
;
4670 rc
= whereLoopInsert(pBuilder
, pNew
);
4672 WHERETRACE(0x400, ("End processing OR-clause %p\n", pTerm
));
4679 ** Add all WhereLoop objects for all tables
4681 static int whereLoopAddAll(WhereLoopBuilder
*pBuilder
){
4682 WhereInfo
*pWInfo
= pBuilder
->pWInfo
;
4683 Bitmask mPrereq
= 0;
4686 SrcList
*pTabList
= pWInfo
->pTabList
;
4688 SrcItem
*pEnd
= &pTabList
->a
[pWInfo
->nLevel
];
4689 sqlite3
*db
= pWInfo
->pParse
->db
;
4691 int bFirstPastRJ
= 0;
4692 int hasRightJoin
= 0;
4696 /* Loop over the tables in the join, from left to right */
4697 pNew
= pBuilder
->pNew
;
4699 /* Verify that pNew has already been initialized */
4700 assert( pNew
->nLTerm
==0 );
4701 assert( pNew
->wsFlags
==0 );
4702 assert( pNew
->nLSlot
>=ArraySize(pNew
->aLTermSpace
) );
4703 assert( pNew
->aLTerm
!=0 );
4705 pBuilder
->iPlanLimit
= SQLITE_QUERY_PLANNER_LIMIT
;
4706 for(iTab
=0, pItem
=pTabList
->a
; pItem
<pEnd
; iTab
++, pItem
++){
4707 Bitmask mUnusable
= 0;
4709 pBuilder
->iPlanLimit
+= SQLITE_QUERY_PLANNER_LIMIT_INCR
;
4710 pNew
->maskSelf
= sqlite3WhereGetMask(&pWInfo
->sMaskSet
, pItem
->iCursor
);
4712 || (pItem
->fg
.jointype
& (JT_OUTER
|JT_CROSS
|JT_LTORJ
))!=0
4714 /* Add prerequisites to prevent reordering of FROM clause terms
4715 ** across CROSS joins and outer joins. The bFirstPastRJ boolean
4716 ** prevents the right operand of a RIGHT JOIN from being swapped with
4717 ** other elements even further to the right.
4719 ** The JT_LTORJ case and the hasRightJoin flag work together to
4720 ** prevent FROM-clause terms from moving from the right side of
4721 ** a LEFT JOIN over to the left side of that join if the LEFT JOIN
4722 ** is itself on the left side of a RIGHT JOIN.
4724 if( pItem
->fg
.jointype
& JT_LTORJ
) hasRightJoin
= 1;
4726 bFirstPastRJ
= (pItem
->fg
.jointype
& JT_RIGHT
)!=0;
4727 }else if( !hasRightJoin
){
4730 #ifndef SQLITE_OMIT_VIRTUALTABLE
4731 if( IsVirtual(pItem
->pTab
) ){
4733 for(p
=&pItem
[1]; p
<pEnd
; p
++){
4734 if( mUnusable
|| (p
->fg
.jointype
& (JT_OUTER
|JT_CROSS
)) ){
4735 mUnusable
|= sqlite3WhereGetMask(&pWInfo
->sMaskSet
, p
->iCursor
);
4738 rc
= whereLoopAddVirtual(pBuilder
, mPrereq
, mUnusable
);
4740 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4742 rc
= whereLoopAddBtree(pBuilder
, mPrereq
);
4744 if( rc
==SQLITE_OK
&& pBuilder
->pWC
->hasOr
){
4745 rc
= whereLoopAddOr(pBuilder
, mPrereq
, mUnusable
);
4747 mPrior
|= pNew
->maskSelf
;
4748 if( rc
|| db
->mallocFailed
){
4749 if( rc
==SQLITE_DONE
){
4750 /* We hit the query planner search limit set by iPlanLimit */
4751 sqlite3_log(SQLITE_WARNING
, "abbreviated query algorithm search");
4759 whereLoopClear(db
, pNew
);
4764 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
4765 ** parameters) to see if it outputs rows in the requested ORDER BY
4766 ** (or GROUP BY) without requiring a separate sort operation. Return N:
4768 ** N>0: N terms of the ORDER BY clause are satisfied
4769 ** N==0: No terms of the ORDER BY clause are satisfied
4770 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
4772 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4773 ** strict. With GROUP BY and DISTINCT the only requirement is that
4774 ** equivalent rows appear immediately adjacent to one another. GROUP BY
4775 ** and DISTINCT do not require rows to appear in any particular order as long
4776 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
4777 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
4778 ** pOrderBy terms must be matched in strict left-to-right order.
4780 static i8
wherePathSatisfiesOrderBy(
4781 WhereInfo
*pWInfo
, /* The WHERE clause */
4782 ExprList
*pOrderBy
, /* ORDER BY or GROUP BY or DISTINCT clause to check */
4783 WherePath
*pPath
, /* The WherePath to check */
4784 u16 wctrlFlags
, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
4785 u16 nLoop
, /* Number of entries in pPath->aLoop[] */
4786 WhereLoop
*pLast
, /* Add this WhereLoop to the end of pPath->aLoop[] */
4787 Bitmask
*pRevMask
/* OUT: Mask of WhereLoops to run in reverse order */
4789 u8 revSet
; /* True if rev is known */
4790 u8 rev
; /* Composite sort order */
4791 u8 revIdx
; /* Index sort order */
4792 u8 isOrderDistinct
; /* All prior WhereLoops are order-distinct */
4793 u8 distinctColumns
; /* True if the loop has UNIQUE NOT NULL columns */
4794 u8 isMatch
; /* iColumn matches a term of the ORDER BY clause */
4795 u16 eqOpMask
; /* Allowed equality operators */
4796 u16 nKeyCol
; /* Number of key columns in pIndex */
4797 u16 nColumn
; /* Total number of ordered columns in the index */
4798 u16 nOrderBy
; /* Number terms in the ORDER BY clause */
4799 int iLoop
; /* Index of WhereLoop in pPath being processed */
4800 int i
, j
; /* Loop counters */
4801 int iCur
; /* Cursor number for current WhereLoop */
4802 int iColumn
; /* A column number within table iCur */
4803 WhereLoop
*pLoop
= 0; /* Current WhereLoop being processed. */
4804 WhereTerm
*pTerm
; /* A single term of the WHERE clause */
4805 Expr
*pOBExpr
; /* An expression from the ORDER BY clause */
4806 CollSeq
*pColl
; /* COLLATE function from an ORDER BY clause term */
4807 Index
*pIndex
; /* The index associated with pLoop */
4808 sqlite3
*db
= pWInfo
->pParse
->db
; /* Database connection */
4809 Bitmask obSat
= 0; /* Mask of ORDER BY terms satisfied so far */
4810 Bitmask obDone
; /* Mask of all ORDER BY terms */
4811 Bitmask orderDistinctMask
; /* Mask of all well-ordered loops */
4812 Bitmask ready
; /* Mask of inner loops */
4815 ** We say the WhereLoop is "one-row" if it generates no more than one
4816 ** row of output. A WhereLoop is one-row if all of the following are true:
4817 ** (a) All index columns match with WHERE_COLUMN_EQ.
4818 ** (b) The index is unique
4819 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4820 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
4822 ** We say the WhereLoop is "order-distinct" if the set of columns from
4823 ** that WhereLoop that are in the ORDER BY clause are different for every
4824 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4825 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4826 ** is not order-distinct. To be order-distinct is not quite the same as being
4827 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4828 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4829 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4831 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4832 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4833 ** automatically order-distinct.
4836 assert( pOrderBy
!=0 );
4837 if( nLoop
&& OptimizationDisabled(db
, SQLITE_OrderByIdxJoin
) ) return 0;
4839 nOrderBy
= pOrderBy
->nExpr
;
4840 testcase( nOrderBy
==BMS
-1 );
4841 if( nOrderBy
>BMS
-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4842 isOrderDistinct
= 1;
4843 obDone
= MASKBIT(nOrderBy
)-1;
4844 orderDistinctMask
= 0;
4846 eqOpMask
= WO_EQ
| WO_IS
| WO_ISNULL
;
4847 if( wctrlFlags
& (WHERE_ORDERBY_LIMIT
|WHERE_ORDERBY_MAX
|WHERE_ORDERBY_MIN
) ){
4850 for(iLoop
=0; isOrderDistinct
&& obSat
<obDone
&& iLoop
<=nLoop
; iLoop
++){
4851 if( iLoop
>0 ) ready
|= pLoop
->maskSelf
;
4853 pLoop
= pPath
->aLoop
[iLoop
];
4854 if( wctrlFlags
& WHERE_ORDERBY_LIMIT
) continue;
4858 if( pLoop
->wsFlags
& WHERE_VIRTUALTABLE
){
4859 if( pLoop
->u
.vtab
.isOrdered
4860 && ((wctrlFlags
&(WHERE_DISTINCTBY
|WHERE_SORTBYGROUP
))!=WHERE_DISTINCTBY
)
4865 }else if( wctrlFlags
& WHERE_DISTINCTBY
){
4866 pLoop
->u
.btree
.nDistinctCol
= 0;
4868 iCur
= pWInfo
->pTabList
->a
[pLoop
->iTab
].iCursor
;
4870 /* Mark off any ORDER BY term X that is a column in the table of
4871 ** the current loop for which there is term in the WHERE
4872 ** clause of the form X IS NULL or X=? that reference only outer
4875 for(i
=0; i
<nOrderBy
; i
++){
4876 if( MASKBIT(i
) & obSat
) continue;
4877 pOBExpr
= sqlite3ExprSkipCollateAndLikely(pOrderBy
->a
[i
].pExpr
);
4878 if( NEVER(pOBExpr
==0) ) continue;
4879 if( pOBExpr
->op
!=TK_COLUMN
&& pOBExpr
->op
!=TK_AGG_COLUMN
) continue;
4880 if( pOBExpr
->iTable
!=iCur
) continue;
4881 pTerm
= sqlite3WhereFindTerm(&pWInfo
->sWC
, iCur
, pOBExpr
->iColumn
,
4882 ~ready
, eqOpMask
, 0);
4883 if( pTerm
==0 ) continue;
4884 if( pTerm
->eOperator
==WO_IN
){
4885 /* IN terms are only valid for sorting in the ORDER BY LIMIT
4886 ** optimization, and then only if they are actually used
4887 ** by the query plan */
4888 assert( wctrlFlags
&
4889 (WHERE_ORDERBY_LIMIT
|WHERE_ORDERBY_MIN
|WHERE_ORDERBY_MAX
) );
4890 for(j
=0; j
<pLoop
->nLTerm
&& pTerm
!=pLoop
->aLTerm
[j
]; j
++){}
4891 if( j
>=pLoop
->nLTerm
) continue;
4893 if( (pTerm
->eOperator
&(WO_EQ
|WO_IS
))!=0 && pOBExpr
->iColumn
>=0 ){
4894 Parse
*pParse
= pWInfo
->pParse
;
4895 CollSeq
*pColl1
= sqlite3ExprNNCollSeq(pParse
, pOrderBy
->a
[i
].pExpr
);
4896 CollSeq
*pColl2
= sqlite3ExprCompareCollSeq(pParse
, pTerm
->pExpr
);
4898 if( pColl2
==0 || sqlite3StrICmp(pColl1
->zName
, pColl2
->zName
) ){
4901 testcase( pTerm
->pExpr
->op
==TK_IS
);
4903 obSat
|= MASKBIT(i
);
4906 if( (pLoop
->wsFlags
& WHERE_ONEROW
)==0 ){
4907 if( pLoop
->wsFlags
& WHERE_IPK
){
4911 }else if( (pIndex
= pLoop
->u
.btree
.pIndex
)==0 || pIndex
->bUnordered
){
4914 nKeyCol
= pIndex
->nKeyCol
;
4915 nColumn
= pIndex
->nColumn
;
4916 assert( nColumn
==nKeyCol
+1 || !HasRowid(pIndex
->pTable
) );
4917 assert( pIndex
->aiColumn
[nColumn
-1]==XN_ROWID
4918 || !HasRowid(pIndex
->pTable
));
4919 /* All relevant terms of the index must also be non-NULL in order
4920 ** for isOrderDistinct to be true. So the isOrderDistint value
4921 ** computed here might be a false positive. Corrections will be
4922 ** made at tag-20210426-1 below */
4923 isOrderDistinct
= IsUniqueIndex(pIndex
)
4924 && (pLoop
->wsFlags
& WHERE_SKIPSCAN
)==0;
4927 /* Loop through all columns of the index and deal with the ones
4928 ** that are not constrained by == or IN.
4931 distinctColumns
= 0;
4932 for(j
=0; j
<nColumn
; j
++){
4933 u8 bOnce
= 1; /* True to run the ORDER BY search loop */
4935 assert( j
>=pLoop
->u
.btree
.nEq
4936 || (pLoop
->aLTerm
[j
]==0)==(j
<pLoop
->nSkip
)
4938 if( j
<pLoop
->u
.btree
.nEq
&& j
>=pLoop
->nSkip
){
4939 u16 eOp
= pLoop
->aLTerm
[j
]->eOperator
;
4941 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
4942 ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL
4943 ** terms imply that the index is not UNIQUE NOT NULL in which case
4944 ** the loop need to be marked as not order-distinct because it can
4945 ** have repeated NULL rows.
4947 ** If the current term is a column of an ((?,?) IN (SELECT...))
4948 ** expression for which the SELECT returns more than one column,
4949 ** check that it is the only column used by this loop. Otherwise,
4950 ** if it is one of two or more, none of the columns can be
4951 ** considered to match an ORDER BY term.
4953 if( (eOp
& eqOpMask
)!=0 ){
4954 if( eOp
& (WO_ISNULL
|WO_IS
) ){
4955 testcase( eOp
& WO_ISNULL
);
4956 testcase( eOp
& WO_IS
);
4957 testcase( isOrderDistinct
);
4958 isOrderDistinct
= 0;
4961 }else if( ALWAYS(eOp
& WO_IN
) ){
4962 /* ALWAYS() justification: eOp is an equality operator due to the
4963 ** j<pLoop->u.btree.nEq constraint above. Any equality other
4964 ** than WO_IN is captured by the previous "if". So this one
4965 ** always has to be WO_IN. */
4966 Expr
*pX
= pLoop
->aLTerm
[j
]->pExpr
;
4967 for(i
=j
+1; i
<pLoop
->u
.btree
.nEq
; i
++){
4968 if( pLoop
->aLTerm
[i
]->pExpr
==pX
){
4969 assert( (pLoop
->aLTerm
[i
]->eOperator
& WO_IN
) );
4977 /* Get the column number in the table (iColumn) and sort order
4978 ** (revIdx) for the j-th column of the index.
4981 iColumn
= pIndex
->aiColumn
[j
];
4982 revIdx
= pIndex
->aSortOrder
[j
] & KEYINFO_ORDER_DESC
;
4983 if( iColumn
==pIndex
->pTable
->iPKey
) iColumn
= XN_ROWID
;
4989 /* An unconstrained column that might be NULL means that this
4990 ** WhereLoop is not well-ordered. tag-20210426-1
4992 if( isOrderDistinct
){
4994 && j
>=pLoop
->u
.btree
.nEq
4995 && pIndex
->pTable
->aCol
[iColumn
].notNull
==0
4997 isOrderDistinct
= 0;
4999 if( iColumn
==XN_EXPR
){
5000 isOrderDistinct
= 0;
5004 /* Find the ORDER BY term that corresponds to the j-th column
5005 ** of the index and mark that ORDER BY term off
5008 for(i
=0; bOnce
&& i
<nOrderBy
; i
++){
5009 if( MASKBIT(i
) & obSat
) continue;
5010 pOBExpr
= sqlite3ExprSkipCollateAndLikely(pOrderBy
->a
[i
].pExpr
);
5011 testcase( wctrlFlags
& WHERE_GROUPBY
);
5012 testcase( wctrlFlags
& WHERE_DISTINCTBY
);
5013 if( NEVER(pOBExpr
==0) ) continue;
5014 if( (wctrlFlags
& (WHERE_GROUPBY
|WHERE_DISTINCTBY
))==0 ) bOnce
= 0;
5015 if( iColumn
>=XN_ROWID
){
5016 if( pOBExpr
->op
!=TK_COLUMN
&& pOBExpr
->op
!=TK_AGG_COLUMN
) continue;
5017 if( pOBExpr
->iTable
!=iCur
) continue;
5018 if( pOBExpr
->iColumn
!=iColumn
) continue;
5020 Expr
*pIxExpr
= pIndex
->aColExpr
->a
[j
].pExpr
;
5021 if( sqlite3ExprCompareSkip(pOBExpr
, pIxExpr
, iCur
) ){
5025 if( iColumn
!=XN_ROWID
){
5026 pColl
= sqlite3ExprNNCollSeq(pWInfo
->pParse
, pOrderBy
->a
[i
].pExpr
);
5027 if( sqlite3StrICmp(pColl
->zName
, pIndex
->azColl
[j
])!=0 ) continue;
5029 if( wctrlFlags
& WHERE_DISTINCTBY
){
5030 pLoop
->u
.btree
.nDistinctCol
= j
+1;
5035 if( isMatch
&& (wctrlFlags
& WHERE_GROUPBY
)==0 ){
5036 /* Make sure the sort order is compatible in an ORDER BY clause.
5037 ** Sort order is irrelevant for a GROUP BY clause. */
5040 != (pOrderBy
->a
[i
].fg
.sortFlags
&KEYINFO_ORDER_DESC
)
5045 rev
= revIdx
^ (pOrderBy
->a
[i
].fg
.sortFlags
& KEYINFO_ORDER_DESC
);
5046 if( rev
) *pRevMask
|= MASKBIT(iLoop
);
5050 if( isMatch
&& (pOrderBy
->a
[i
].fg
.sortFlags
& KEYINFO_ORDER_BIGNULL
) ){
5051 if( j
==pLoop
->u
.btree
.nEq
){
5052 pLoop
->wsFlags
|= WHERE_BIGNULL_SORT
;
5058 if( iColumn
==XN_ROWID
){
5059 testcase( distinctColumns
==0 );
5060 distinctColumns
= 1;
5062 obSat
|= MASKBIT(i
);
5064 /* No match found */
5065 if( j
==0 || j
<nKeyCol
){
5066 testcase( isOrderDistinct
!=0 );
5067 isOrderDistinct
= 0;
5071 } /* end Loop over all index columns */
5072 if( distinctColumns
){
5073 testcase( isOrderDistinct
==0 );
5074 isOrderDistinct
= 1;
5076 } /* end-if not one-row */
5078 /* Mark off any other ORDER BY terms that reference pLoop */
5079 if( isOrderDistinct
){
5080 orderDistinctMask
|= pLoop
->maskSelf
;
5081 for(i
=0; i
<nOrderBy
; i
++){
5084 if( MASKBIT(i
) & obSat
) continue;
5085 p
= pOrderBy
->a
[i
].pExpr
;
5086 mTerm
= sqlite3WhereExprUsage(&pWInfo
->sMaskSet
,p
);
5087 if( mTerm
==0 && !sqlite3ExprIsConstant(0,p
) ) continue;
5088 if( (mTerm
&~orderDistinctMask
)==0 ){
5089 obSat
|= MASKBIT(i
);
5093 } /* End the loop over all WhereLoops from outer-most down to inner-most */
5094 if( obSat
==obDone
) return (i8
)nOrderBy
;
5095 if( !isOrderDistinct
){
5096 for(i
=nOrderBy
-1; i
>0; i
--){
5097 Bitmask m
= ALWAYS(i
<BMS
) ? MASKBIT(i
) - 1 : 0;
5098 if( (obSat
&m
)==m
) return i
;
5107 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5108 ** the planner assumes that the specified pOrderBy list is actually a GROUP
5109 ** BY clause - and so any order that groups rows as required satisfies the
5112 ** Normally, in this case it is not possible for the caller to determine
5113 ** whether or not the rows are really being delivered in sorted order, or
5114 ** just in some other order that provides the required grouping. However,
5115 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5116 ** this function may be called on the returned WhereInfo object. It returns
5117 ** true if the rows really will be sorted in the specified order, or false
5120 ** For example, assuming:
5122 ** CREATE INDEX i1 ON t1(x, Y);
5126 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5127 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5129 int sqlite3WhereIsSorted(WhereInfo
*pWInfo
){
5130 assert( pWInfo
->wctrlFlags
& (WHERE_GROUPBY
|WHERE_DISTINCTBY
) );
5131 assert( pWInfo
->wctrlFlags
& WHERE_SORTBYGROUP
);
5132 return pWInfo
->sorted
;
5135 #ifdef WHERETRACE_ENABLED
5136 /* For debugging use only: */
5137 static const char *wherePathName(WherePath
*pPath
, int nLoop
, WhereLoop
*pLast
){
5138 static char zName
[65];
5140 for(i
=0; i
<nLoop
; i
++){ zName
[i
] = pPath
->aLoop
[i
]->cId
; }
5141 if( pLast
) zName
[i
++] = pLast
->cId
;
5148 ** Return the cost of sorting nRow rows, assuming that the keys have
5149 ** nOrderby columns and that the first nSorted columns are already in
5152 static LogEst
whereSortingCost(
5153 WhereInfo
*pWInfo
, /* Query planning context */
5154 LogEst nRow
, /* Estimated number of rows to sort */
5155 int nOrderBy
, /* Number of ORDER BY clause terms */
5156 int nSorted
/* Number of initial ORDER BY terms naturally in order */
5158 /* Estimated cost of a full external sort, where N is
5159 ** the number of rows to sort is:
5161 ** cost = (K * N * log(N)).
5163 ** Or, if the order-by clause has X terms but only the last Y
5164 ** terms are out of order, then block-sorting will reduce the
5167 ** cost = (K * N * log(N)) * (Y/X)
5169 ** The constant K is at least 2.0 but will be larger if there are a
5170 ** large number of columns to be sorted, as the sorting time is
5171 ** proportional to the amount of content to be sorted. The algorithm
5172 ** does not currently distinguish between fat columns (BLOBs and TEXTs)
5173 ** and skinny columns (INTs). It just uses the number of columns as
5174 ** an approximation for the row width.
5176 ** And extra factor of 2.0 or 3.0 is added to the sorting cost if the sort
5177 ** is built using OP_IdxInsert and OP_Sort rather than with OP_SorterInsert.
5179 LogEst rSortCost
, nCol
;
5180 assert( pWInfo
->pSelect
!=0 );
5181 assert( pWInfo
->pSelect
->pEList
!=0 );
5182 /* TUNING: sorting cost proportional to the number of output columns: */
5183 nCol
= sqlite3LogEst((pWInfo
->pSelect
->pEList
->nExpr
+59)/30);
5184 rSortCost
= nRow
+ nCol
;
5186 /* Scale the result by (Y/X) */
5187 rSortCost
+= sqlite3LogEst((nOrderBy
-nSorted
)*100/nOrderBy
) - 66;
5190 /* Multiple by log(M) where M is the number of output rows.
5191 ** Use the LIMIT for M if it is smaller. Or if this sort is for
5192 ** a DISTINCT operator, M will be the number of distinct output
5193 ** rows, so fudge it downwards a bit.
5195 if( (pWInfo
->wctrlFlags
& WHERE_USE_LIMIT
)!=0 ){
5196 rSortCost
+= 10; /* TUNING: Extra 2.0x if using LIMIT */
5198 rSortCost
+= 6; /* TUNING: Extra 1.5x if also using partial sort */
5200 if( pWInfo
->iLimit
<nRow
){
5201 nRow
= pWInfo
->iLimit
;
5203 }else if( (pWInfo
->wctrlFlags
& WHERE_WANT_DISTINCT
) ){
5204 /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
5205 ** reduces the number of output rows by a factor of 2 */
5206 if( nRow
>10 ){ nRow
-= 10; assert( 10==sqlite3LogEst(2) ); }
5208 rSortCost
+= estLog(nRow
);
5213 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
5214 ** attempts to find the lowest cost path that visits each WhereLoop
5215 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5217 ** Assume that the total number of output rows that will need to be sorted
5218 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5219 ** costs if nRowEst==0.
5221 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5224 static int wherePathSolver(WhereInfo
*pWInfo
, LogEst nRowEst
){
5225 int mxChoice
; /* Maximum number of simultaneous paths tracked */
5226 int nLoop
; /* Number of terms in the join */
5227 Parse
*pParse
; /* Parsing context */
5228 int iLoop
; /* Loop counter over the terms of the join */
5229 int ii
, jj
; /* Loop counters */
5230 int mxI
= 0; /* Index of next entry to replace */
5231 int nOrderBy
; /* Number of ORDER BY clause terms */
5232 LogEst mxCost
= 0; /* Maximum cost of a set of paths */
5233 LogEst mxUnsorted
= 0; /* Maximum unsorted cost of a set of path */
5234 int nTo
, nFrom
; /* Number of valid entries in aTo[] and aFrom[] */
5235 WherePath
*aFrom
; /* All nFrom paths at the previous level */
5236 WherePath
*aTo
; /* The nTo best paths at the current level */
5237 WherePath
*pFrom
; /* An element of aFrom[] that we are working on */
5238 WherePath
*pTo
; /* An element of aTo[] that we are working on */
5239 WhereLoop
*pWLoop
; /* One of the WhereLoop objects */
5240 WhereLoop
**pX
; /* Used to divy up the pSpace memory */
5241 LogEst
*aSortCost
= 0; /* Sorting and partial sorting costs */
5242 char *pSpace
; /* Temporary memory used by this routine */
5243 int nSpace
; /* Bytes of space allocated at pSpace */
5245 pParse
= pWInfo
->pParse
;
5246 nLoop
= pWInfo
->nLevel
;
5247 /* TUNING: For simple queries, only the best path is tracked.
5248 ** For 2-way joins, the 5 best paths are followed.
5249 ** For joins of 3 or more tables, track the 10 best paths */
5250 mxChoice
= (nLoop
<=1) ? 1 : (nLoop
==2 ? 5 : 10);
5251 assert( nLoop
<=pWInfo
->pTabList
->nSrc
);
5252 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d, nQueryLoop=%d)\n",
5253 nRowEst
, pParse
->nQueryLoop
));
5255 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5256 ** case the purpose of this call is to estimate the number of rows returned
5257 ** by the overall query. Once this estimate has been obtained, the caller
5258 ** will invoke this function a second time, passing the estimate as the
5259 ** nRowEst parameter. */
5260 if( pWInfo
->pOrderBy
==0 || nRowEst
==0 ){
5263 nOrderBy
= pWInfo
->pOrderBy
->nExpr
;
5266 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
5267 nSpace
= (sizeof(WherePath
)+sizeof(WhereLoop
*)*nLoop
)*mxChoice
*2;
5268 nSpace
+= sizeof(LogEst
) * nOrderBy
;
5269 pSpace
= sqlite3StackAllocRawNN(pParse
->db
, nSpace
);
5270 if( pSpace
==0 ) return SQLITE_NOMEM_BKPT
;
5271 aTo
= (WherePath
*)pSpace
;
5272 aFrom
= aTo
+mxChoice
;
5273 memset(aFrom
, 0, sizeof(aFrom
[0]));
5274 pX
= (WhereLoop
**)(aFrom
+mxChoice
);
5275 for(ii
=mxChoice
*2, pFrom
=aTo
; ii
>0; ii
--, pFrom
++, pX
+= nLoop
){
5279 /* If there is an ORDER BY clause and it is not being ignored, set up
5280 ** space for the aSortCost[] array. Each element of the aSortCost array
5281 ** is either zero - meaning it has not yet been initialized - or the
5282 ** cost of sorting nRowEst rows of data where the first X terms of
5283 ** the ORDER BY clause are already in order, where X is the array
5285 aSortCost
= (LogEst
*)pX
;
5286 memset(aSortCost
, 0, sizeof(LogEst
) * nOrderBy
);
5288 assert( aSortCost
==0 || &pSpace
[nSpace
]==(char*)&aSortCost
[nOrderBy
] );
5289 assert( aSortCost
!=0 || &pSpace
[nSpace
]==(char*)pX
);
5291 /* Seed the search with a single WherePath containing zero WhereLoops.
5293 ** TUNING: Do not let the number of iterations go above 28. If the cost
5294 ** of computing an automatic index is not paid back within the first 28
5295 ** rows, then do not use the automatic index. */
5296 aFrom
[0].nRow
= MIN(pParse
->nQueryLoop
, 48); assert( 48==sqlite3LogEst(28) );
5298 assert( aFrom
[0].isOrdered
==0 );
5300 /* If nLoop is zero, then there are no FROM terms in the query. Since
5301 ** in this case the query may return a maximum of one row, the results
5302 ** are already in the requested order. Set isOrdered to nOrderBy to
5303 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
5304 ** -1, indicating that the result set may or may not be ordered,
5305 ** depending on the loops added to the current plan. */
5306 aFrom
[0].isOrdered
= nLoop
>0 ? -1 : nOrderBy
;
5309 /* Compute successively longer WherePaths using the previous generation
5310 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5311 ** best paths at each generation */
5312 for(iLoop
=0; iLoop
<nLoop
; iLoop
++){
5314 for(ii
=0, pFrom
=aFrom
; ii
<nFrom
; ii
++, pFrom
++){
5315 for(pWLoop
=pWInfo
->pLoops
; pWLoop
; pWLoop
=pWLoop
->pNextLoop
){
5316 LogEst nOut
; /* Rows visited by (pFrom+pWLoop) */
5317 LogEst rCost
; /* Cost of path (pFrom+pWLoop) */
5318 LogEst rUnsorted
; /* Unsorted cost of (pFrom+pWLoop) */
5319 i8 isOrdered
; /* isOrdered for (pFrom+pWLoop) */
5320 Bitmask maskNew
; /* Mask of src visited by (..) */
5321 Bitmask revMask
; /* Mask of rev-order loops for (..) */
5323 if( (pWLoop
->prereq
& ~pFrom
->maskLoop
)!=0 ) continue;
5324 if( (pWLoop
->maskSelf
& pFrom
->maskLoop
)!=0 ) continue;
5325 if( (pWLoop
->wsFlags
& WHERE_AUTO_INDEX
)!=0 && pFrom
->nRow
<3 ){
5326 /* Do not use an automatic index if the this loop is expected
5327 ** to run less than 1.25 times. It is tempting to also exclude
5328 ** automatic index usage on an outer loop, but sometimes an automatic
5329 ** index is useful in the outer loop of a correlated subquery. */
5330 assert( 10==sqlite3LogEst(2) );
5334 /* At this point, pWLoop is a candidate to be the next loop.
5335 ** Compute its cost */
5336 rUnsorted
= sqlite3LogEstAdd(pWLoop
->rSetup
,pWLoop
->rRun
+ pFrom
->nRow
);
5337 rUnsorted
= sqlite3LogEstAdd(rUnsorted
, pFrom
->rUnsorted
);
5338 nOut
= pFrom
->nRow
+ pWLoop
->nOut
;
5339 maskNew
= pFrom
->maskLoop
| pWLoop
->maskSelf
;
5340 isOrdered
= pFrom
->isOrdered
;
5343 isOrdered
= wherePathSatisfiesOrderBy(pWInfo
,
5344 pWInfo
->pOrderBy
, pFrom
, pWInfo
->wctrlFlags
,
5345 iLoop
, pWLoop
, &revMask
);
5347 revMask
= pFrom
->revLoop
;
5349 if( isOrdered
>=0 && isOrdered
<nOrderBy
){
5350 if( aSortCost
[isOrdered
]==0 ){
5351 aSortCost
[isOrdered
] = whereSortingCost(
5352 pWInfo
, nRowEst
, nOrderBy
, isOrdered
5355 /* TUNING: Add a small extra penalty (3) to sorting as an
5356 ** extra encouragement to the query planner to select a plan
5357 ** where the rows emerge in the correct order without any sorting
5359 rCost
= sqlite3LogEstAdd(rUnsorted
, aSortCost
[isOrdered
]) + 3;
5362 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5363 aSortCost
[isOrdered
], (nOrderBy
-isOrdered
), nOrderBy
,
5367 rUnsorted
-= 2; /* TUNING: Slight bias in favor of no-sort plans */
5370 /* Check to see if pWLoop should be added to the set of
5371 ** mxChoice best-so-far paths.
5373 ** First look for an existing path among best-so-far paths
5374 ** that covers the same set of loops and has the same isOrdered
5375 ** setting as the current path candidate.
5377 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
5378 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
5379 ** of legal values for isOrdered, -1..64.
5381 for(jj
=0, pTo
=aTo
; jj
<nTo
; jj
++, pTo
++){
5382 if( pTo
->maskLoop
==maskNew
5383 && ((pTo
->isOrdered
^isOrdered
)&0x80)==0
5385 testcase( jj
==nTo
-1 );
5390 /* None of the existing best-so-far paths match the candidate. */
5392 && (rCost
>mxCost
|| (rCost
==mxCost
&& rUnsorted
>=mxUnsorted
))
5394 /* The current candidate is no better than any of the mxChoice
5395 ** paths currently in the best-so-far buffer. So discard
5396 ** this candidate as not viable. */
5397 #ifdef WHERETRACE_ENABLED /* 0x4 */
5398 if( sqlite3WhereTrace
&0x4 ){
5399 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
5400 wherePathName(pFrom
, iLoop
, pWLoop
), rCost
, nOut
, rUnsorted
,
5401 isOrdered
>=0 ? isOrdered
+'0' : '?');
5406 /* If we reach this points it means that the new candidate path
5407 ** needs to be added to the set of best-so-far paths. */
5409 /* Increase the size of the aTo set by one */
5412 /* New path replaces the prior worst to keep count below mxChoice */
5416 #ifdef WHERETRACE_ENABLED /* 0x4 */
5417 if( sqlite3WhereTrace
&0x4 ){
5418 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
5419 wherePathName(pFrom
, iLoop
, pWLoop
), rCost
, nOut
, rUnsorted
,
5420 isOrdered
>=0 ? isOrdered
+'0' : '?');
5424 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
5425 ** same set of loops and has the same isOrdered setting as the
5426 ** candidate path. Check to see if the candidate should replace
5427 ** pTo or if the candidate should be skipped.
5429 ** The conditional is an expanded vector comparison equivalent to:
5430 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
5432 if( pTo
->rCost
<rCost
5433 || (pTo
->rCost
==rCost
5435 || (pTo
->nRow
==nOut
&& pTo
->rUnsorted
<=rUnsorted
)
5439 #ifdef WHERETRACE_ENABLED /* 0x4 */
5440 if( sqlite3WhereTrace
&0x4 ){
5442 "Skip %s cost=%-3d,%3d,%3d order=%c",
5443 wherePathName(pFrom
, iLoop
, pWLoop
), rCost
, nOut
, rUnsorted
,
5444 isOrdered
>=0 ? isOrdered
+'0' : '?');
5445 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
5446 wherePathName(pTo
, iLoop
+1, 0), pTo
->rCost
, pTo
->nRow
,
5447 pTo
->rUnsorted
, pTo
->isOrdered
>=0 ? pTo
->isOrdered
+'0' : '?');
5450 /* Discard the candidate path from further consideration */
5451 testcase( pTo
->rCost
==rCost
);
5454 testcase( pTo
->rCost
==rCost
+1 );
5455 /* Control reaches here if the candidate path is better than the
5456 ** pTo path. Replace pTo with the candidate. */
5457 #ifdef WHERETRACE_ENABLED /* 0x4 */
5458 if( sqlite3WhereTrace
&0x4 ){
5460 "Update %s cost=%-3d,%3d,%3d order=%c",
5461 wherePathName(pFrom
, iLoop
, pWLoop
), rCost
, nOut
, rUnsorted
,
5462 isOrdered
>=0 ? isOrdered
+'0' : '?');
5463 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
5464 wherePathName(pTo
, iLoop
+1, 0), pTo
->rCost
, pTo
->nRow
,
5465 pTo
->rUnsorted
, pTo
->isOrdered
>=0 ? pTo
->isOrdered
+'0' : '?');
5469 /* pWLoop is a winner. Add it to the set of best so far */
5470 pTo
->maskLoop
= pFrom
->maskLoop
| pWLoop
->maskSelf
;
5471 pTo
->revLoop
= revMask
;
5474 pTo
->rUnsorted
= rUnsorted
;
5475 pTo
->isOrdered
= isOrdered
;
5476 memcpy(pTo
->aLoop
, pFrom
->aLoop
, sizeof(WhereLoop
*)*iLoop
);
5477 pTo
->aLoop
[iLoop
] = pWLoop
;
5478 if( nTo
>=mxChoice
){
5480 mxCost
= aTo
[0].rCost
;
5481 mxUnsorted
= aTo
[0].nRow
;
5482 for(jj
=1, pTo
=&aTo
[1]; jj
<mxChoice
; jj
++, pTo
++){
5483 if( pTo
->rCost
>mxCost
5484 || (pTo
->rCost
==mxCost
&& pTo
->rUnsorted
>mxUnsorted
)
5486 mxCost
= pTo
->rCost
;
5487 mxUnsorted
= pTo
->rUnsorted
;
5495 #ifdef WHERETRACE_ENABLED /* >=2 */
5496 if( sqlite3WhereTrace
& 0x02 ){
5497 sqlite3DebugPrintf("---- after round %d ----\n", iLoop
);
5498 for(ii
=0, pTo
=aTo
; ii
<nTo
; ii
++, pTo
++){
5499 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
5500 wherePathName(pTo
, iLoop
+1, 0), pTo
->rCost
, pTo
->nRow
,
5501 pTo
->isOrdered
>=0 ? (pTo
->isOrdered
+'0') : '?');
5502 if( pTo
->isOrdered
>0 ){
5503 sqlite3DebugPrintf(" rev=0x%llx\n", pTo
->revLoop
);
5505 sqlite3DebugPrintf("\n");
5511 /* Swap the roles of aFrom and aTo for the next generation */
5519 sqlite3ErrorMsg(pParse
, "no query solution");
5520 sqlite3StackFreeNN(pParse
->db
, pSpace
);
5521 return SQLITE_ERROR
;
5524 /* Find the lowest cost path. pFrom will be left pointing to that path */
5526 for(ii
=1; ii
<nFrom
; ii
++){
5527 if( pFrom
->rCost
>aFrom
[ii
].rCost
) pFrom
= &aFrom
[ii
];
5529 assert( pWInfo
->nLevel
==nLoop
);
5530 /* Load the lowest cost path into pWInfo */
5531 for(iLoop
=0; iLoop
<nLoop
; iLoop
++){
5532 WhereLevel
*pLevel
= pWInfo
->a
+ iLoop
;
5533 pLevel
->pWLoop
= pWLoop
= pFrom
->aLoop
[iLoop
];
5534 pLevel
->iFrom
= pWLoop
->iTab
;
5535 pLevel
->iTabCur
= pWInfo
->pTabList
->a
[pLevel
->iFrom
].iCursor
;
5537 if( (pWInfo
->wctrlFlags
& WHERE_WANT_DISTINCT
)!=0
5538 && (pWInfo
->wctrlFlags
& WHERE_DISTINCTBY
)==0
5539 && pWInfo
->eDistinct
==WHERE_DISTINCT_NOOP
5543 int rc
= wherePathSatisfiesOrderBy(pWInfo
, pWInfo
->pResultSet
, pFrom
,
5544 WHERE_DISTINCTBY
, nLoop
-1, pFrom
->aLoop
[nLoop
-1], ¬Used
);
5545 if( rc
==pWInfo
->pResultSet
->nExpr
){
5546 pWInfo
->eDistinct
= WHERE_DISTINCT_ORDERED
;
5549 pWInfo
->bOrderedInnerLoop
= 0;
5550 if( pWInfo
->pOrderBy
){
5551 pWInfo
->nOBSat
= pFrom
->isOrdered
;
5552 if( pWInfo
->wctrlFlags
& WHERE_DISTINCTBY
){
5553 if( pFrom
->isOrdered
==pWInfo
->pOrderBy
->nExpr
){
5554 pWInfo
->eDistinct
= WHERE_DISTINCT_ORDERED
;
5556 /* vvv--- See check-in [12ad822d9b827777] on 2023-03-16 ---vvv */
5557 assert( pWInfo
->pSelect
->pOrderBy
==0
5558 || pWInfo
->nOBSat
<= pWInfo
->pSelect
->pOrderBy
->nExpr
);
5560 pWInfo
->revMask
= pFrom
->revLoop
;
5561 if( pWInfo
->nOBSat
<=0 ){
5564 u32 wsFlags
= pFrom
->aLoop
[nLoop
-1]->wsFlags
;
5565 if( (wsFlags
& WHERE_ONEROW
)==0
5566 && (wsFlags
&(WHERE_IPK
|WHERE_COLUMN_IN
))!=(WHERE_IPK
|WHERE_COLUMN_IN
)
5569 int rc
= wherePathSatisfiesOrderBy(pWInfo
, pWInfo
->pOrderBy
, pFrom
,
5570 WHERE_ORDERBY_LIMIT
, nLoop
-1, pFrom
->aLoop
[nLoop
-1], &m
);
5571 testcase( wsFlags
& WHERE_IPK
);
5572 testcase( wsFlags
& WHERE_COLUMN_IN
);
5573 if( rc
==pWInfo
->pOrderBy
->nExpr
){
5574 pWInfo
->bOrderedInnerLoop
= 1;
5575 pWInfo
->revMask
= m
;
5580 && pWInfo
->nOBSat
==1
5581 && (pWInfo
->wctrlFlags
& (WHERE_ORDERBY_MIN
|WHERE_ORDERBY_MAX
))!=0
5583 pWInfo
->bOrderedInnerLoop
= 1;
5586 if( (pWInfo
->wctrlFlags
& WHERE_SORTBYGROUP
)
5587 && pWInfo
->nOBSat
==pWInfo
->pOrderBy
->nExpr
&& nLoop
>0
5589 Bitmask revMask
= 0;
5590 int nOrder
= wherePathSatisfiesOrderBy(pWInfo
, pWInfo
->pOrderBy
,
5591 pFrom
, 0, nLoop
-1, pFrom
->aLoop
[nLoop
-1], &revMask
5593 assert( pWInfo
->sorted
==0 );
5594 if( nOrder
==pWInfo
->pOrderBy
->nExpr
){
5596 pWInfo
->revMask
= revMask
;
5601 pWInfo
->nRowOut
= pFrom
->nRow
;
5603 /* Free temporary memory and return success */
5604 sqlite3StackFreeNN(pParse
->db
, pSpace
);
5609 ** This routine implements a heuristic designed to improve query planning.
5610 ** This routine is called in between the first and second call to
5611 ** wherePathSolver(). Hence the name "Interstage" "Heuristic".
5613 ** The first call to wherePathSolver() (hereafter just "solver()") computes
5614 ** the best path without regard to the order of the outputs. The second call
5615 ** to the solver() builds upon the first call to try to find an alternative
5616 ** path that satisfies the ORDER BY clause.
5618 ** This routine looks at the results of the first solver() run, and for
5619 ** every FROM clause term in the resulting query plan that uses an equality
5620 ** constraint against an index, disable other WhereLoops for that same
5621 ** FROM clause term that would try to do a full-table scan. This prevents
5622 ** an index search from being converted into a full-table scan in order to
5623 ** satisfy an ORDER BY clause, since even though we might get slightly better
5624 ** performance using the full-scan without sorting if the output size
5625 ** estimates are very precise, we might also get severe performance
5626 ** degradation using the full-scan if the output size estimate is too large.
5627 ** It is better to err on the side of caution.
5629 ** Except, if the first solver() call generated a full-table scan in an outer
5630 ** loop then stop this analysis at the first full-scan, since the second
5631 ** solver() run might try to swap that full-scan for another in order to
5632 ** get the output into the correct order. In other words, we allow a
5633 ** rewrite like this:
5635 ** First Solver() Second Solver()
5636 ** |-- SCAN t1 |-- SCAN t2
5637 ** |-- SEARCH t2 `-- SEARCH t1
5638 ** `-- SORT USING B-TREE
5640 ** The purpose of this routine is to disallow rewrites such as:
5642 ** First Solver() Second Solver()
5643 ** |-- SEARCH t1 |-- SCAN t2 <--- bad!
5644 ** |-- SEARCH t2 `-- SEARCH t1
5645 ** `-- SORT USING B-TREE
5647 ** See test cases in test/whereN.test for the real-world query that
5648 ** originally provoked this heuristic.
5650 static SQLITE_NOINLINE
void whereInterstageHeuristic(WhereInfo
*pWInfo
){
5652 #ifdef WHERETRACE_ENABLED
5655 for(i
=0; i
<pWInfo
->nLevel
; i
++){
5656 WhereLoop
*p
= pWInfo
->a
[i
].pWLoop
;
5658 if( (p
->wsFlags
& WHERE_VIRTUALTABLE
)!=0 ) continue;
5659 if( (p
->wsFlags
& (WHERE_COLUMN_EQ
|WHERE_COLUMN_NULL
|WHERE_COLUMN_IN
))!=0 ){
5662 for(pLoop
=pWInfo
->pLoops
; pLoop
; pLoop
=pLoop
->pNextLoop
){
5663 if( pLoop
->iTab
!=iTab
) continue;
5664 if( (pLoop
->wsFlags
& (WHERE_CONSTRAINT
|WHERE_AUTO_INDEX
))!=0 ){
5665 /* Auto-index and index-constrained loops allowed to remain */
5668 #ifdef WHERETRACE_ENABLED
5669 if( sqlite3WhereTrace
& 0x80 ){
5671 sqlite3DebugPrintf("Loops disabled by interstage heuristic:\n");
5674 sqlite3WhereLoopPrint(pLoop
, &pWInfo
->sWC
);
5676 #endif /* WHERETRACE_ENABLED */
5677 pLoop
->prereq
= ALLBITS
; /* Prevent 2nd solver() from using this one */
5686 ** Most queries use only a single table (they are not joins) and have
5687 ** simple == constraints against indexed fields. This routine attempts
5688 ** to plan those simple cases using much less ceremony than the
5689 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5690 ** times for the common case.
5692 ** Return non-zero on success, if this query can be handled by this
5693 ** no-frills query planner. Return zero if this query needs the
5694 ** general-purpose query planner.
5696 static int whereShortCut(WhereLoopBuilder
*pBuilder
){
5708 pWInfo
= pBuilder
->pWInfo
;
5709 if( pWInfo
->wctrlFlags
& WHERE_OR_SUBCLAUSE
) return 0;
5710 assert( pWInfo
->pTabList
->nSrc
>=1 );
5711 pItem
= pWInfo
->pTabList
->a
;
5713 if( IsVirtual(pTab
) ) return 0;
5714 if( pItem
->fg
.isIndexedBy
|| pItem
->fg
.notIndexed
){
5715 testcase( pItem
->fg
.isIndexedBy
);
5716 testcase( pItem
->fg
.notIndexed
);
5719 iCur
= pItem
->iCursor
;
5721 pLoop
= pBuilder
->pNew
;
5724 pTerm
= whereScanInit(&scan
, pWC
, iCur
, -1, WO_EQ
|WO_IS
, 0);
5725 while( pTerm
&& pTerm
->prereqRight
) pTerm
= whereScanNext(&scan
);
5727 testcase( pTerm
->eOperator
& WO_IS
);
5728 pLoop
->wsFlags
= WHERE_COLUMN_EQ
|WHERE_IPK
|WHERE_ONEROW
;
5729 pLoop
->aLTerm
[0] = pTerm
;
5731 pLoop
->u
.btree
.nEq
= 1;
5732 /* TUNING: Cost of a rowid lookup is 10 */
5733 pLoop
->rRun
= 33; /* 33==sqlite3LogEst(10) */
5735 for(pIdx
=pTab
->pIndex
; pIdx
; pIdx
=pIdx
->pNext
){
5737 assert( pLoop
->aLTermSpace
==pLoop
->aLTerm
);
5738 if( !IsUniqueIndex(pIdx
)
5739 || pIdx
->pPartIdxWhere
!=0
5740 || pIdx
->nKeyCol
>ArraySize(pLoop
->aLTermSpace
)
5742 opMask
= pIdx
->uniqNotNull
? (WO_EQ
|WO_IS
) : WO_EQ
;
5743 for(j
=0; j
<pIdx
->nKeyCol
; j
++){
5744 pTerm
= whereScanInit(&scan
, pWC
, iCur
, j
, opMask
, pIdx
);
5745 while( pTerm
&& pTerm
->prereqRight
) pTerm
= whereScanNext(&scan
);
5746 if( pTerm
==0 ) break;
5747 testcase( pTerm
->eOperator
& WO_IS
);
5748 pLoop
->aLTerm
[j
] = pTerm
;
5750 if( j
!=pIdx
->nKeyCol
) continue;
5751 pLoop
->wsFlags
= WHERE_COLUMN_EQ
|WHERE_ONEROW
|WHERE_INDEXED
;
5752 if( pIdx
->isCovering
|| (pItem
->colUsed
& pIdx
->colNotIdxed
)==0 ){
5753 pLoop
->wsFlags
|= WHERE_IDX_ONLY
;
5756 pLoop
->u
.btree
.nEq
= j
;
5757 pLoop
->u
.btree
.pIndex
= pIdx
;
5758 /* TUNING: Cost of a unique index lookup is 15 */
5759 pLoop
->rRun
= 39; /* 39==sqlite3LogEst(15) */
5763 if( pLoop
->wsFlags
){
5764 pLoop
->nOut
= (LogEst
)1;
5765 pWInfo
->a
[0].pWLoop
= pLoop
;
5766 assert( pWInfo
->sMaskSet
.n
==1 && iCur
==pWInfo
->sMaskSet
.ix
[0] );
5767 pLoop
->maskSelf
= 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
5768 pWInfo
->a
[0].iTabCur
= iCur
;
5769 pWInfo
->nRowOut
= 1;
5770 if( pWInfo
->pOrderBy
) pWInfo
->nOBSat
= pWInfo
->pOrderBy
->nExpr
;
5771 if( pWInfo
->wctrlFlags
& WHERE_WANT_DISTINCT
){
5772 pWInfo
->eDistinct
= WHERE_DISTINCT_UNIQUE
;
5774 if( scan
.iEquiv
>1 ) pLoop
->wsFlags
|= WHERE_TRANSCONS
;
5778 #ifdef WHERETRACE_ENABLED
5779 if( sqlite3WhereTrace
& 0x02 ){
5780 sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
5789 ** Helper function for exprIsDeterministic().
5791 static int exprNodeIsDeterministic(Walker
*pWalker
, Expr
*pExpr
){
5792 if( pExpr
->op
==TK_FUNCTION
&& ExprHasProperty(pExpr
, EP_ConstFunc
)==0 ){
5796 return WRC_Continue
;
5800 ** Return true if the expression contains no non-deterministic SQL
5801 ** functions. Do not consider non-deterministic SQL functions that are
5802 ** part of sub-select statements.
5804 static int exprIsDeterministic(Expr
*p
){
5806 memset(&w
, 0, sizeof(w
));
5808 w
.xExprCallback
= exprNodeIsDeterministic
;
5809 w
.xSelectCallback
= sqlite3SelectWalkFail
;
5810 sqlite3WalkExpr(&w
, p
);
5815 #ifdef WHERETRACE_ENABLED
5817 ** Display all WhereLoops in pWInfo
5819 static void showAllWhereLoops(WhereInfo
*pWInfo
, WhereClause
*pWC
){
5820 if( sqlite3WhereTrace
){ /* Display all of the WhereLoop objects */
5823 static const char zLabel
[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5824 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5825 for(p
=pWInfo
->pLoops
, i
=0; p
; p
=p
->pNextLoop
, i
++){
5826 p
->cId
= zLabel
[i
%(sizeof(zLabel
)-1)];
5827 sqlite3WhereLoopPrint(p
, pWC
);
5831 # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
5833 # define WHERETRACE_ALL_LOOPS(W,C)
5836 /* Attempt to omit tables from a join that do not affect the result.
5837 ** For a table to not affect the result, the following must be true:
5839 ** 1) The query must not be an aggregate.
5840 ** 2) The table must be the RHS of a LEFT JOIN.
5841 ** 3) Either the query must be DISTINCT, or else the ON or USING clause
5842 ** must contain a constraint that limits the scan of the table to
5843 ** at most a single row.
5844 ** 4) The table must not be referenced by any part of the query apart
5845 ** from its own USING or ON clause.
5846 ** 5) The table must not have an inner-join ON or USING clause if there is
5847 ** a RIGHT JOIN anywhere in the query. Otherwise the ON/USING clause
5848 ** might move from the right side to the left side of the RIGHT JOIN.
5849 ** Note: Due to (2), this condition can only arise if the table is
5850 ** the right-most table of a subquery that was flattened into the
5851 ** main query and that subquery was the right-hand operand of an
5852 ** inner join that held an ON or USING clause.
5853 ** 6) The ORDER BY clause has 63 or fewer terms
5854 ** 7) The omit-noop-join optimization is enabled.
5856 ** Items (1), (6), and (7) are checked by the caller.
5858 ** For example, given:
5860 ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
5861 ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
5862 ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
5864 ** then table t2 can be omitted from the following:
5866 ** SELECT v1, v3 FROM t1
5867 ** LEFT JOIN t2 ON (t1.ipk=t2.ipk)
5868 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5872 ** SELECT DISTINCT v1, v3 FROM t1
5874 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5876 static SQLITE_NOINLINE Bitmask
whereOmitNoopJoin(
5884 /* Preconditions checked by the caller */
5885 assert( pWInfo
->nLevel
>=2 );
5886 assert( OptimizationEnabled(pWInfo
->pParse
->db
, SQLITE_OmitNoopJoin
) );
5888 /* These two preconditions checked by the caller combine to guarantee
5889 ** condition (1) of the header comment */
5890 assert( pWInfo
->pResultSet
!=0 );
5891 assert( 0==(pWInfo
->wctrlFlags
& WHERE_AGG_DISTINCT
) );
5893 tabUsed
= sqlite3WhereExprListUsage(&pWInfo
->sMaskSet
, pWInfo
->pResultSet
);
5894 if( pWInfo
->pOrderBy
){
5895 tabUsed
|= sqlite3WhereExprListUsage(&pWInfo
->sMaskSet
, pWInfo
->pOrderBy
);
5897 hasRightJoin
= (pWInfo
->pTabList
->a
[0].fg
.jointype
& JT_LTORJ
)!=0;
5898 for(i
=pWInfo
->nLevel
-1; i
>=1; i
--){
5899 WhereTerm
*pTerm
, *pEnd
;
5902 pLoop
= pWInfo
->a
[i
].pWLoop
;
5903 pItem
= &pWInfo
->pTabList
->a
[pLoop
->iTab
];
5904 if( (pItem
->fg
.jointype
& (JT_LEFT
|JT_RIGHT
))!=JT_LEFT
) continue;
5905 if( (pWInfo
->wctrlFlags
& WHERE_WANT_DISTINCT
)==0
5906 && (pLoop
->wsFlags
& WHERE_ONEROW
)==0
5910 if( (tabUsed
& pLoop
->maskSelf
)!=0 ) continue;
5911 pEnd
= pWInfo
->sWC
.a
+ pWInfo
->sWC
.nTerm
;
5912 for(pTerm
=pWInfo
->sWC
.a
; pTerm
<pEnd
; pTerm
++){
5913 if( (pTerm
->prereqAll
& pLoop
->maskSelf
)!=0 ){
5914 if( !ExprHasProperty(pTerm
->pExpr
, EP_OuterON
)
5915 || pTerm
->pExpr
->w
.iJoin
!=pItem
->iCursor
5921 && ExprHasProperty(pTerm
->pExpr
, EP_InnerON
)
5922 && pTerm
->pExpr
->w
.iJoin
==pItem
->iCursor
5924 break; /* restriction (5) */
5927 if( pTerm
<pEnd
) continue;
5928 WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop
->cId
));
5929 notReady
&= ~pLoop
->maskSelf
;
5930 for(pTerm
=pWInfo
->sWC
.a
; pTerm
<pEnd
; pTerm
++){
5931 if( (pTerm
->prereqAll
& pLoop
->maskSelf
)!=0 ){
5932 pTerm
->wtFlags
|= TERM_CODED
;
5935 if( i
!=pWInfo
->nLevel
-1 ){
5936 int nByte
= (pWInfo
->nLevel
-1-i
) * sizeof(WhereLevel
);
5937 memmove(&pWInfo
->a
[i
], &pWInfo
->a
[i
+1], nByte
);
5940 assert( pWInfo
->nLevel
>0 );
5946 ** Check to see if there are any SEARCH loops that might benefit from
5947 ** using a Bloom filter. Consider a Bloom filter if:
5949 ** (1) The SEARCH happens more than N times where N is the number
5950 ** of rows in the table that is being considered for the Bloom
5952 ** (2) Some searches are expected to find zero rows. (This is determined
5953 ** by the WHERE_SELFCULL flag on the term.)
5954 ** (3) Bloom-filter processing is not disabled. (Checked by the
5956 ** (4) The size of the table being searched is known by ANALYZE.
5958 ** This block of code merely checks to see if a Bloom filter would be
5959 ** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
5960 ** WhereLoop. The implementation of the Bloom filter comes further
5961 ** down where the code for each WhereLoop is generated.
5963 static SQLITE_NOINLINE
void whereCheckIfBloomFilterIsUseful(
5964 const WhereInfo
*pWInfo
5969 assert( pWInfo
->nLevel
>=2 );
5970 assert( OptimizationEnabled(pWInfo
->pParse
->db
, SQLITE_BloomFilter
) );
5971 for(i
=0; i
<pWInfo
->nLevel
; i
++){
5972 WhereLoop
*pLoop
= pWInfo
->a
[i
].pWLoop
;
5973 const unsigned int reqFlags
= (WHERE_SELFCULL
|WHERE_COLUMN_EQ
);
5974 SrcItem
*pItem
= &pWInfo
->pTabList
->a
[pLoop
->iTab
];
5975 Table
*pTab
= pItem
->pTab
;
5976 if( (pTab
->tabFlags
& TF_HasStat1
)==0 ) break;
5977 pTab
->tabFlags
|= TF_MaybeReanalyze
;
5979 && (pLoop
->wsFlags
& reqFlags
)==reqFlags
5980 /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
5981 && ALWAYS((pLoop
->wsFlags
& (WHERE_IPK
|WHERE_INDEXED
))!=0)
5983 if( nSearch
> pTab
->nRowLogEst
){
5984 testcase( pItem
->fg
.jointype
& JT_LEFT
);
5985 pLoop
->wsFlags
|= WHERE_BLOOMFILTER
;
5986 pLoop
->wsFlags
&= ~WHERE_IDX_ONLY
;
5987 WHERETRACE(0xffffffff, (
5988 "-> use Bloom-filter on loop %c because there are ~%.1e "
5989 "lookups into %s which has only ~%.1e rows\n",
5990 pLoop
->cId
, (double)sqlite3LogEstToInt(nSearch
), pTab
->zName
,
5991 (double)sqlite3LogEstToInt(pTab
->nRowLogEst
)));
5994 nSearch
+= pLoop
->nOut
;
5999 ** Expression Node callback for sqlite3ExprCanReturnSubtype().
6001 ** Only a function call is able to return a subtype. So if the node
6002 ** is not a function call, return WRC_Prune immediately.
6004 ** A function call is able to return a subtype if it has the
6005 ** SQLITE_RESULT_SUBTYPE property.
6007 ** Assume that every function is able to pass-through a subtype from
6008 ** one of its argument (using sqlite3_result_value()). Most functions
6009 ** are not this way, but we don't have a mechanism to distinguish those
6010 ** that are from those that are not, so assume they all work this way.
6011 ** That means that if one of its arguments is another function and that
6012 ** other function is able to return a subtype, then this function is
6013 ** able to return a subtype.
6015 static int exprNodeCanReturnSubtype(Walker
*pWalker
, Expr
*pExpr
){
6019 if( pExpr
->op
!=TK_FUNCTION
){
6022 assert( ExprUseXList(pExpr
) );
6023 db
= pWalker
->pParse
->db
;
6024 n
= pExpr
->x
.pList
? pExpr
->x
.pList
->nExpr
: 0;
6025 pDef
= sqlite3FindFunction(db
, pExpr
->u
.zToken
, n
, ENC(db
), 0);
6026 if( pDef
==0 || (pDef
->funcFlags
& SQLITE_RESULT_SUBTYPE
)!=0 ){
6030 return WRC_Continue
;
6034 ** Return TRUE if expression pExpr is able to return a subtype.
6036 ** A TRUE return does not guarantee that a subtype will be returned.
6037 ** It only indicates that a subtype return is possible. False positives
6038 ** are acceptable as they only disable an optimization. False negatives,
6039 ** on the other hand, can lead to incorrect answers.
6041 static int sqlite3ExprCanReturnSubtype(Parse
*pParse
, Expr
*pExpr
){
6043 memset(&w
, 0, sizeof(w
));
6045 w
.xExprCallback
= exprNodeCanReturnSubtype
;
6046 sqlite3WalkExpr(&w
, pExpr
);
6051 ** The index pIdx is used by a query and contains one or more expressions.
6052 ** In other words pIdx is an index on an expression. iIdxCur is the cursor
6053 ** number for the index and iDataCur is the cursor number for the corresponding
6056 ** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for
6057 ** each of the expressions in the index so that the expression code generator
6058 ** will know to replace occurrences of the indexed expression with
6059 ** references to the corresponding column of the index.
6061 static SQLITE_NOINLINE
void whereAddIndexedExpr(
6062 Parse
*pParse
, /* Add IndexedExpr entries to pParse->pIdxEpr */
6063 Index
*pIdx
, /* The index-on-expression that contains the expressions */
6064 int iIdxCur
, /* Cursor number for pIdx */
6065 SrcItem
*pTabItem
/* The FROM clause entry for the table */
6070 assert( pIdx
->bHasExpr
);
6071 pTab
= pIdx
->pTable
;
6072 for(i
=0; i
<pIdx
->nColumn
; i
++){
6074 int j
= pIdx
->aiColumn
[i
];
6076 pExpr
= pIdx
->aColExpr
->a
[i
].pExpr
;
6077 }else if( j
>=0 && (pTab
->aCol
[j
].colFlags
& COLFLAG_VIRTUAL
)!=0 ){
6078 pExpr
= sqlite3ColumnExpr(pTab
, &pTab
->aCol
[j
]);
6082 if( sqlite3ExprIsConstant(0,pExpr
) ) continue;
6083 if( pExpr
->op
==TK_FUNCTION
&& sqlite3ExprCanReturnSubtype(pParse
,pExpr
) ){
6084 /* Functions that might set a subtype should not be replaced by the
6085 ** value taken from an expression index since the index omits the
6086 ** subtype. https://sqlite.org/forum/forumpost/68d284c86b082c3e */
6089 p
= sqlite3DbMallocRaw(pParse
->db
, sizeof(IndexedExpr
));
6091 p
->pIENext
= pParse
->pIdxEpr
;
6092 #ifdef WHERETRACE_ENABLED
6093 if( sqlite3WhereTrace
& 0x200 ){
6094 sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur
, i
);
6095 if( sqlite3WhereTrace
& 0x5000 ) sqlite3ShowExpr(pExpr
);
6098 p
->pExpr
= sqlite3ExprDup(pParse
->db
, pExpr
, 0);
6099 p
->iDataCur
= pTabItem
->iCursor
;
6100 p
->iIdxCur
= iIdxCur
;
6102 p
->bMaybeNullRow
= (pTabItem
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
|JT_RIGHT
))!=0;
6103 if( sqlite3IndexAffinityStr(pParse
->db
, pIdx
) ){
6104 p
->aff
= pIdx
->zColAff
[i
];
6106 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
6107 p
->zIdxName
= pIdx
->zName
;
6109 pParse
->pIdxEpr
= p
;
6110 if( p
->pIENext
==0 ){
6111 void *pArg
= (void*)&pParse
->pIdxEpr
;
6112 sqlite3ParserAddCleanup(pParse
, whereIndexedExprCleanup
, pArg
);
6118 ** Set the reverse-scan order mask to one for all tables in the query
6119 ** with the exception of MATERIALIZED common table expressions that have
6120 ** their own internal ORDER BY clauses.
6122 ** This implements the PRAGMA reverse_unordered_selects=ON setting.
6123 ** (Also SQLITE_DBCONFIG_REVERSE_SCANORDER).
6125 static SQLITE_NOINLINE
void whereReverseScanOrder(WhereInfo
*pWInfo
){
6127 for(ii
=0; ii
<pWInfo
->pTabList
->nSrc
; ii
++){
6128 SrcItem
*pItem
= &pWInfo
->pTabList
->a
[ii
];
6129 if( !pItem
->fg
.isCte
6130 || pItem
->u2
.pCteUse
->eM10d
!=M10d_Yes
6131 || NEVER(pItem
->pSelect
==0)
6132 || pItem
->pSelect
->pOrderBy
==0
6134 pWInfo
->revMask
|= MASKBIT(ii
);
6140 ** Generate the beginning of the loop used for WHERE clause processing.
6141 ** The return value is a pointer to an opaque structure that contains
6142 ** information needed to terminate the loop. Later, the calling routine
6143 ** should invoke sqlite3WhereEnd() with the return value of this function
6144 ** in order to complete the WHERE clause processing.
6146 ** If an error occurs, this routine returns NULL.
6148 ** The basic idea is to do a nested loop, one loop for each table in
6149 ** the FROM clause of a select. (INSERT and UPDATE statements are the
6150 ** same as a SELECT with only a single table in the FROM clause.) For
6151 ** example, if the SQL is this:
6153 ** SELECT * FROM t1, t2, t3 WHERE ...;
6155 ** Then the code generated is conceptually like the following:
6157 ** foreach row1 in t1 do \ Code generated
6158 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
6159 ** foreach row3 in t3 do /
6161 ** end \ Code generated
6162 ** end |-- by sqlite3WhereEnd()
6165 ** Note that the loops might not be nested in the order in which they
6166 ** appear in the FROM clause if a different order is better able to make
6167 ** use of indices. Note also that when the IN operator appears in
6168 ** the WHERE clause, it might result in additional nested loops for
6169 ** scanning through all values on the right-hand side of the IN.
6171 ** There are Btree cursors associated with each table. t1 uses cursor
6172 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
6173 ** And so forth. This routine generates code to open those VDBE cursors
6174 ** and sqlite3WhereEnd() generates the code to close them.
6176 ** The code that sqlite3WhereBegin() generates leaves the cursors named
6177 ** in pTabList pointing at their appropriate entries. The [...] code
6178 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
6179 ** data from the various tables of the loop.
6181 ** If the WHERE clause is empty, the foreach loops must each scan their
6182 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
6183 ** the tables have indices and there are terms in the WHERE clause that
6184 ** refer to those indices, a complete table scan can be avoided and the
6185 ** code will run much faster. Most of the work of this routine is checking
6186 ** to see if there are indices that can be used to speed up the loop.
6188 ** Terms of the WHERE clause are also used to limit which rows actually
6189 ** make it to the "..." in the middle of the loop. After each "foreach",
6190 ** terms of the WHERE clause that use only terms in that loop and outer
6191 ** loops are evaluated and if false a jump is made around all subsequent
6192 ** inner loops (or around the "..." if the test occurs within the inner-
6197 ** An outer join of tables t1 and t2 is conceptually coded as follows:
6199 ** foreach row1 in t1 do
6201 ** foreach row2 in t2 do
6207 ** move the row2 cursor to a null row
6212 ** ORDER BY CLAUSE PROCESSING
6214 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
6215 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
6216 ** if there is one. If there is no ORDER BY clause or if this routine
6217 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
6219 ** The iIdxCur parameter is the cursor number of an index. If
6220 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
6221 ** to use for OR clause processing. The WHERE clause should use this
6222 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
6223 ** the first cursor in an array of cursors for all indices. iIdxCur should
6224 ** be used to compute the appropriate cursor depending on which index is
6227 WhereInfo
*sqlite3WhereBegin(
6228 Parse
*pParse
, /* The parser context */
6229 SrcList
*pTabList
, /* FROM clause: A list of all tables to be scanned */
6230 Expr
*pWhere
, /* The WHERE clause */
6231 ExprList
*pOrderBy
, /* An ORDER BY (or GROUP BY) clause, or NULL */
6232 ExprList
*pResultSet
, /* Query result set. Req'd for DISTINCT */
6233 Select
*pSelect
, /* The entire SELECT statement */
6234 u16 wctrlFlags
, /* The WHERE_* flags defined in sqliteInt.h */
6235 int iAuxArg
/* If WHERE_OR_SUBCLAUSE is set, index cursor number
6236 ** If WHERE_USE_LIMIT, then the limit amount */
6238 int nByteWInfo
; /* Num. bytes allocated for WhereInfo struct */
6239 int nTabList
; /* Number of elements in pTabList */
6240 WhereInfo
*pWInfo
; /* Will become the return value of this function */
6241 Vdbe
*v
= pParse
->pVdbe
; /* The virtual database engine */
6242 Bitmask notReady
; /* Cursors that are not yet positioned */
6243 WhereLoopBuilder sWLB
; /* The WhereLoop builder */
6244 WhereMaskSet
*pMaskSet
; /* The expression mask set */
6245 WhereLevel
*pLevel
; /* A single level in pWInfo->a[] */
6246 WhereLoop
*pLoop
; /* Pointer to a single WhereLoop object */
6247 int ii
; /* Loop counter */
6248 sqlite3
*db
; /* Database connection */
6249 int rc
; /* Return code */
6250 u8 bFordelete
= 0; /* OPFLAG_FORDELETE or zero, as appropriate */
6252 assert( (wctrlFlags
& WHERE_ONEPASS_MULTIROW
)==0 || (
6253 (wctrlFlags
& WHERE_ONEPASS_DESIRED
)!=0
6254 && (wctrlFlags
& WHERE_OR_SUBCLAUSE
)==0
6257 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
6258 assert( (wctrlFlags
& WHERE_OR_SUBCLAUSE
)==0
6259 || (wctrlFlags
& WHERE_USE_LIMIT
)==0 );
6261 /* Variable initialization */
6263 memset(&sWLB
, 0, sizeof(sWLB
));
6265 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
6266 testcase( pOrderBy
&& pOrderBy
->nExpr
==BMS
-1 );
6267 if( pOrderBy
&& pOrderBy
->nExpr
>=BMS
){
6269 wctrlFlags
&= ~WHERE_WANT_DISTINCT
;
6270 wctrlFlags
|= WHERE_KEEP_ALL_JOINS
; /* Disable omit-noop-join opt */
6273 /* The number of tables in the FROM clause is limited by the number of
6274 ** bits in a Bitmask
6276 testcase( pTabList
->nSrc
==BMS
);
6277 if( pTabList
->nSrc
>BMS
){
6278 sqlite3ErrorMsg(pParse
, "at most %d tables in a join", BMS
);
6282 /* This function normally generates a nested loop for all tables in
6283 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
6284 ** only generate code for the first table in pTabList and assume that
6285 ** any cursors associated with subsequent tables are uninitialized.
6287 nTabList
= (wctrlFlags
& WHERE_OR_SUBCLAUSE
) ? 1 : pTabList
->nSrc
;
6289 /* Allocate and initialize the WhereInfo structure that will become the
6290 ** return value. A single allocation is used to store the WhereInfo
6291 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6292 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6293 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6294 ** some architectures. Hence the ROUND8() below.
6296 nByteWInfo
= ROUND8P(sizeof(WhereInfo
));
6298 nByteWInfo
= ROUND8P(nByteWInfo
+ (nTabList
-1)*sizeof(WhereLevel
));
6300 pWInfo
= sqlite3DbMallocRawNN(db
, nByteWInfo
+ sizeof(WhereLoop
));
6301 if( db
->mallocFailed
){
6302 sqlite3DbFree(db
, pWInfo
);
6304 goto whereBeginError
;
6306 pWInfo
->pParse
= pParse
;
6307 pWInfo
->pTabList
= pTabList
;
6308 pWInfo
->pOrderBy
= pOrderBy
;
6309 #if WHERETRACE_ENABLED
6310 pWInfo
->pWhere
= pWhere
;
6312 pWInfo
->pResultSet
= pResultSet
;
6313 pWInfo
->aiCurOnePass
[0] = pWInfo
->aiCurOnePass
[1] = -1;
6314 pWInfo
->nLevel
= nTabList
;
6315 pWInfo
->iBreak
= pWInfo
->iContinue
= sqlite3VdbeMakeLabel(pParse
);
6316 pWInfo
->wctrlFlags
= wctrlFlags
;
6317 pWInfo
->iLimit
= iAuxArg
;
6318 pWInfo
->savedNQueryLoop
= pParse
->nQueryLoop
;
6319 pWInfo
->pSelect
= pSelect
;
6320 memset(&pWInfo
->nOBSat
, 0,
6321 offsetof(WhereInfo
,sWC
) - offsetof(WhereInfo
,nOBSat
));
6322 memset(&pWInfo
->a
[0], 0, sizeof(WhereLoop
)+nTabList
*sizeof(WhereLevel
));
6323 assert( pWInfo
->eOnePass
==ONEPASS_OFF
); /* ONEPASS defaults to OFF */
6324 pMaskSet
= &pWInfo
->sMaskSet
;
6326 pMaskSet
->ix
[0] = -99; /* Initialize ix[0] to a value that can never be
6327 ** a valid cursor number, to avoid an initial
6328 ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
6329 sWLB
.pWInfo
= pWInfo
;
6330 sWLB
.pWC
= &pWInfo
->sWC
;
6331 sWLB
.pNew
= (WhereLoop
*)(((char*)pWInfo
)+nByteWInfo
);
6332 assert( EIGHT_BYTE_ALIGNMENT(sWLB
.pNew
) );
6333 whereLoopInit(sWLB
.pNew
);
6335 sWLB
.pNew
->cId
= '*';
6338 /* Split the WHERE clause into separate subexpressions where each
6339 ** subexpression is separated by an AND operator.
6341 sqlite3WhereClauseInit(&pWInfo
->sWC
, pWInfo
);
6342 sqlite3WhereSplit(&pWInfo
->sWC
, pWhere
, TK_AND
);
6344 /* Special case: No FROM clause
6347 if( pOrderBy
) pWInfo
->nOBSat
= pOrderBy
->nExpr
;
6348 if( (wctrlFlags
& WHERE_WANT_DISTINCT
)!=0
6349 && OptimizationEnabled(db
, SQLITE_DistinctOpt
)
6351 pWInfo
->eDistinct
= WHERE_DISTINCT_UNIQUE
;
6353 if( ALWAYS(pWInfo
->pSelect
)
6354 && (pWInfo
->pSelect
->selFlags
& SF_MultiValue
)==0
6356 ExplainQueryPlan((pParse
, 0, "SCAN CONSTANT ROW"));
6359 /* Assign a bit from the bitmask to every term in the FROM clause.
6361 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
6363 ** The rule of the previous sentence ensures that if X is the bitmask for
6364 ** a table T, then X-1 is the bitmask for all other tables to the left of T.
6365 ** Knowing the bitmask for all tables to the left of a left join is
6366 ** important. Ticket #3015.
6368 ** Note that bitmasks are created for all pTabList->nSrc tables in
6369 ** pTabList, not just the first nTabList tables. nTabList is normally
6370 ** equal to pTabList->nSrc but might be shortened to 1 if the
6371 ** WHERE_OR_SUBCLAUSE flag is set.
6375 createMask(pMaskSet
, pTabList
->a
[ii
].iCursor
);
6376 sqlite3WhereTabFuncArgs(pParse
, &pTabList
->a
[ii
], &pWInfo
->sWC
);
6377 }while( (++ii
)<pTabList
->nSrc
);
6381 for(ii
=0; ii
<pTabList
->nSrc
; ii
++){
6382 Bitmask m
= sqlite3WhereGetMask(pMaskSet
, pTabList
->a
[ii
].iCursor
);
6390 /* Analyze all of the subexpressions. */
6391 sqlite3WhereExprAnalyze(pTabList
, &pWInfo
->sWC
);
6392 if( pSelect
&& pSelect
->pLimit
){
6393 sqlite3WhereAddLimit(&pWInfo
->sWC
, pSelect
);
6395 if( pParse
->nErr
) goto whereBeginError
;
6397 /* The False-WHERE-Term-Bypass optimization:
6399 ** If there are WHERE terms that are false, then no rows will be output,
6400 ** so skip over all of the code generated here.
6404 ** (1) The WHERE term must not refer to any tables in the join.
6405 ** (2) The term must not come from an ON clause on the
6406 ** right-hand side of a LEFT or FULL JOIN.
6407 ** (3) The term must not come from an ON clause, or there must be
6408 ** no RIGHT or FULL OUTER joins in pTabList.
6409 ** (4) If the expression contains non-deterministic functions
6410 ** that are not within a sub-select. This is not required
6411 ** for correctness but rather to preserves SQLite's legacy
6412 ** behaviour in the following two cases:
6414 ** WHERE random()>0; -- eval random() once per row
6415 ** WHERE (SELECT random())>0; -- eval random() just once overall
6417 ** Note that the Where term need not be a constant in order for this
6418 ** optimization to apply, though it does need to be constant relative to
6419 ** the current subquery (condition 1). The term might include variables
6420 ** from outer queries so that the value of the term changes from one
6421 ** invocation of the current subquery to the next.
6423 for(ii
=0; ii
<sWLB
.pWC
->nBase
; ii
++){
6424 WhereTerm
*pT
= &sWLB
.pWC
->a
[ii
]; /* A term of the WHERE clause */
6425 Expr
*pX
; /* The expression of pT */
6426 if( pT
->wtFlags
& TERM_VIRTUAL
) continue;
6429 assert( pT
->prereqAll
!=0 || !ExprHasProperty(pX
, EP_OuterON
) );
6430 if( pT
->prereqAll
==0 /* Conditions (1) and (2) */
6431 && (nTabList
==0 || exprIsDeterministic(pX
)) /* Condition (4) */
6432 && !(ExprHasProperty(pX
, EP_InnerON
) /* Condition (3) */
6433 && (pTabList
->a
[0].fg
.jointype
& JT_LTORJ
)!=0 )
6435 sqlite3ExprIfFalse(pParse
, pX
, pWInfo
->iBreak
, SQLITE_JUMPIFNULL
);
6436 pT
->wtFlags
|= TERM_CODED
;
6440 if( wctrlFlags
& WHERE_WANT_DISTINCT
){
6441 if( OptimizationDisabled(db
, SQLITE_DistinctOpt
) ){
6442 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6443 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6444 wctrlFlags
&= ~WHERE_WANT_DISTINCT
;
6445 pWInfo
->wctrlFlags
&= ~WHERE_WANT_DISTINCT
;
6446 }else if( isDistinctRedundant(pParse
, pTabList
, &pWInfo
->sWC
, pResultSet
) ){
6447 /* The DISTINCT marking is pointless. Ignore it. */
6448 pWInfo
->eDistinct
= WHERE_DISTINCT_UNIQUE
;
6449 }else if( pOrderBy
==0 ){
6450 /* Try to ORDER BY the result set to make distinct processing easier */
6451 pWInfo
->wctrlFlags
|= WHERE_DISTINCTBY
;
6452 pWInfo
->pOrderBy
= pResultSet
;
6456 /* Construct the WhereLoop objects */
6457 #if defined(WHERETRACE_ENABLED)
6458 if( sqlite3WhereTrace
& 0xffffffff ){
6459 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags
);
6460 if( wctrlFlags
& WHERE_USE_LIMIT
){
6461 sqlite3DebugPrintf(", limit: %d", iAuxArg
);
6463 sqlite3DebugPrintf(")\n");
6464 if( sqlite3WhereTrace
& 0x8000 ){
6466 memset(&sSelect
, 0, sizeof(sSelect
));
6467 sSelect
.selFlags
= SF_WhereBegin
;
6468 sSelect
.pSrc
= pTabList
;
6469 sSelect
.pWhere
= pWhere
;
6470 sSelect
.pOrderBy
= pOrderBy
;
6471 sSelect
.pEList
= pResultSet
;
6472 sqlite3TreeViewSelect(0, &sSelect
, 0);
6474 if( sqlite3WhereTrace
& 0x4000 ){ /* Display all WHERE clause terms */
6475 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
6476 sqlite3WhereClausePrint(sWLB
.pWC
);
6481 if( nTabList
!=1 || whereShortCut(&sWLB
)==0 ){
6482 rc
= whereLoopAddAll(&sWLB
);
6483 if( rc
) goto whereBeginError
;
6485 #ifdef SQLITE_ENABLE_STAT4
6486 /* If one or more WhereTerm.truthProb values were used in estimating
6487 ** loop parameters, but then those truthProb values were subsequently
6488 ** changed based on STAT4 information while computing subsequent loops,
6489 ** then we need to rerun the whole loop building process so that all
6490 ** loops will be built using the revised truthProb values. */
6491 if( sWLB
.bldFlags2
& SQLITE_BLDF2_2NDPASS
){
6492 WHERETRACE_ALL_LOOPS(pWInfo
, sWLB
.pWC
);
6493 WHERETRACE(0xffffffff,
6494 ("**** Redo all loop computations due to"
6495 " TERM_HIGHTRUTH changes ****\n"));
6496 while( pWInfo
->pLoops
){
6497 WhereLoop
*p
= pWInfo
->pLoops
;
6498 pWInfo
->pLoops
= p
->pNextLoop
;
6499 whereLoopDelete(db
, p
);
6501 rc
= whereLoopAddAll(&sWLB
);
6502 if( rc
) goto whereBeginError
;
6505 WHERETRACE_ALL_LOOPS(pWInfo
, sWLB
.pWC
);
6507 wherePathSolver(pWInfo
, 0);
6508 if( db
->mallocFailed
) goto whereBeginError
;
6509 if( pWInfo
->pOrderBy
){
6510 whereInterstageHeuristic(pWInfo
);
6511 wherePathSolver(pWInfo
, pWInfo
->nRowOut
+1);
6512 if( db
->mallocFailed
) goto whereBeginError
;
6515 /* TUNING: Assume that a DISTINCT clause on a subquery reduces
6516 ** the output size by a factor of 8 (LogEst -30).
6518 if( (pWInfo
->wctrlFlags
& WHERE_WANT_DISTINCT
)!=0 ){
6519 WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n",
6520 pWInfo
->nRowOut
, pWInfo
->nRowOut
-30));
6521 pWInfo
->nRowOut
-= 30;
6525 assert( pWInfo
->pTabList
!=0 );
6526 if( pWInfo
->pOrderBy
==0 && (db
->flags
& SQLITE_ReverseOrder
)!=0 ){
6527 whereReverseScanOrder(pWInfo
);
6530 goto whereBeginError
;
6532 assert( db
->mallocFailed
==0 );
6533 #ifdef WHERETRACE_ENABLED
6534 if( sqlite3WhereTrace
){
6535 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo
->nRowOut
);
6536 if( pWInfo
->nOBSat
>0 ){
6537 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo
->nOBSat
, pWInfo
->revMask
);
6539 switch( pWInfo
->eDistinct
){
6540 case WHERE_DISTINCT_UNIQUE
: {
6541 sqlite3DebugPrintf(" DISTINCT=unique");
6544 case WHERE_DISTINCT_ORDERED
: {
6545 sqlite3DebugPrintf(" DISTINCT=ordered");
6548 case WHERE_DISTINCT_UNORDERED
: {
6549 sqlite3DebugPrintf(" DISTINCT=unordered");
6553 sqlite3DebugPrintf("\n");
6554 for(ii
=0; ii
<pWInfo
->nLevel
; ii
++){
6555 sqlite3WhereLoopPrint(pWInfo
->a
[ii
].pWLoop
, sWLB
.pWC
);
6560 /* Attempt to omit tables from a join that do not affect the result.
6561 ** See the comment on whereOmitNoopJoin() for further information.
6563 ** This query optimization is factored out into a separate "no-inline"
6564 ** procedure to keep the sqlite3WhereBegin() procedure from becoming
6565 ** too large. If sqlite3WhereBegin() becomes too large, that prevents
6566 ** some C-compiler optimizers from in-lining the
6567 ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
6568 ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
6570 notReady
= ~(Bitmask
)0;
6571 if( pWInfo
->nLevel
>=2 /* Must be a join, or this opt8n is pointless */
6572 && pResultSet
!=0 /* Condition (1) */
6573 && 0==(wctrlFlags
& (WHERE_AGG_DISTINCT
|WHERE_KEEP_ALL_JOINS
)) /* (1),(6) */
6574 && OptimizationEnabled(db
, SQLITE_OmitNoopJoin
) /* (7) */
6576 notReady
= whereOmitNoopJoin(pWInfo
, notReady
);
6577 nTabList
= pWInfo
->nLevel
;
6578 assert( nTabList
>0 );
6581 /* Check to see if there are any SEARCH loops that might benefit from
6582 ** using a Bloom filter.
6584 if( pWInfo
->nLevel
>=2
6585 && OptimizationEnabled(db
, SQLITE_BloomFilter
)
6587 whereCheckIfBloomFilterIsUseful(pWInfo
);
6590 #if defined(WHERETRACE_ENABLED)
6591 if( sqlite3WhereTrace
& 0x4000 ){ /* Display all terms of the WHERE clause */
6592 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
6593 sqlite3WhereClausePrint(sWLB
.pWC
);
6595 WHERETRACE(0xffffffff,("*** Optimizer Finished ***\n"));
6597 pWInfo
->pParse
->nQueryLoop
+= pWInfo
->nRowOut
;
6599 /* If the caller is an UPDATE or DELETE statement that is requesting
6600 ** to use a one-pass algorithm, determine if this is appropriate.
6602 ** A one-pass approach can be used if the caller has requested one
6603 ** and either (a) the scan visits at most one row or (b) each
6604 ** of the following are true:
6606 ** * the caller has indicated that a one-pass approach can be used
6607 ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
6608 ** * the table is not a virtual table, and
6609 ** * either the scan does not use the OR optimization or the caller
6610 ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
6613 ** The last qualification is because an UPDATE statement uses
6614 ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
6615 ** use a one-pass approach, and this is not set accurately for scans
6616 ** that use the OR optimization.
6618 assert( (wctrlFlags
& WHERE_ONEPASS_DESIRED
)==0 || pWInfo
->nLevel
==1 );
6619 if( (wctrlFlags
& WHERE_ONEPASS_DESIRED
)!=0 ){
6620 int wsFlags
= pWInfo
->a
[0].pWLoop
->wsFlags
;
6621 int bOnerow
= (wsFlags
& WHERE_ONEROW
)!=0;
6622 assert( !(wsFlags
& WHERE_VIRTUALTABLE
) || IsVirtual(pTabList
->a
[0].pTab
) );
6624 0!=(wctrlFlags
& WHERE_ONEPASS_MULTIROW
)
6625 && !IsVirtual(pTabList
->a
[0].pTab
)
6626 && (0==(wsFlags
& WHERE_MULTI_OR
) || (wctrlFlags
& WHERE_DUPLICATES_OK
))
6627 && OptimizationEnabled(db
, SQLITE_OnePass
)
6629 pWInfo
->eOnePass
= bOnerow
? ONEPASS_SINGLE
: ONEPASS_MULTI
;
6630 if( HasRowid(pTabList
->a
[0].pTab
) && (wsFlags
& WHERE_IDX_ONLY
) ){
6631 if( wctrlFlags
& WHERE_ONEPASS_MULTIROW
){
6632 bFordelete
= OPFLAG_FORDELETE
;
6634 pWInfo
->a
[0].pWLoop
->wsFlags
= (wsFlags
& ~WHERE_IDX_ONLY
);
6639 /* Open all tables in the pTabList and any indices selected for
6640 ** searching those tables.
6642 for(ii
=0, pLevel
=pWInfo
->a
; ii
<nTabList
; ii
++, pLevel
++){
6643 Table
*pTab
; /* Table to open */
6644 int iDb
; /* Index of database containing table/index */
6647 pTabItem
= &pTabList
->a
[pLevel
->iFrom
];
6648 pTab
= pTabItem
->pTab
;
6649 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
6650 pLoop
= pLevel
->pWLoop
;
6651 if( (pTab
->tabFlags
& TF_Ephemeral
)!=0 || IsView(pTab
) ){
6654 #ifndef SQLITE_OMIT_VIRTUALTABLE
6655 if( (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)!=0 ){
6656 const char *pVTab
= (const char *)sqlite3GetVTable(db
, pTab
);
6657 int iCur
= pTabItem
->iCursor
;
6658 sqlite3VdbeAddOp4(v
, OP_VOpen
, iCur
, 0, 0, pVTab
, P4_VTAB
);
6659 }else if( IsVirtual(pTab
) ){
6663 if( ((pLoop
->wsFlags
& WHERE_IDX_ONLY
)==0
6664 && (wctrlFlags
& WHERE_OR_SUBCLAUSE
)==0)
6665 || (pTabItem
->fg
.jointype
& (JT_LTORJ
|JT_RIGHT
))!=0
6667 int op
= OP_OpenRead
;
6668 if( pWInfo
->eOnePass
!=ONEPASS_OFF
){
6670 pWInfo
->aiCurOnePass
[0] = pTabItem
->iCursor
;
6672 sqlite3OpenTable(pParse
, pTabItem
->iCursor
, iDb
, pTab
, op
);
6673 assert( pTabItem
->iCursor
==pLevel
->iTabCur
);
6674 testcase( pWInfo
->eOnePass
==ONEPASS_OFF
&& pTab
->nCol
==BMS
-1 );
6675 testcase( pWInfo
->eOnePass
==ONEPASS_OFF
&& pTab
->nCol
==BMS
);
6676 if( pWInfo
->eOnePass
==ONEPASS_OFF
6678 && (pTab
->tabFlags
& (TF_HasGenerated
|TF_WithoutRowid
))==0
6679 && (pLoop
->wsFlags
& (WHERE_AUTO_INDEX
|WHERE_BLOOMFILTER
))==0
6681 /* If we know that only a prefix of the record will be used,
6682 ** it is advantageous to reduce the "column count" field in
6683 ** the P4 operand of the OP_OpenRead/Write opcode. */
6684 Bitmask b
= pTabItem
->colUsed
;
6686 for(; b
; b
=b
>>1, n
++){}
6687 sqlite3VdbeChangeP4(v
, -1, SQLITE_INT_TO_PTR(n
), P4_INT32
);
6688 assert( n
<=pTab
->nCol
);
6690 #ifdef SQLITE_ENABLE_CURSOR_HINTS
6691 if( pLoop
->u
.btree
.pIndex
!=0 && (pTab
->tabFlags
& TF_WithoutRowid
)==0 ){
6692 sqlite3VdbeChangeP5(v
, OPFLAG_SEEKEQ
|bFordelete
);
6696 sqlite3VdbeChangeP5(v
, bFordelete
);
6698 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6699 sqlite3VdbeAddOp4Dup8(v
, OP_ColumnsUsed
, pTabItem
->iCursor
, 0, 0,
6700 (const u8
*)&pTabItem
->colUsed
, P4_INT64
);
6703 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
6705 if( pLoop
->wsFlags
& WHERE_INDEXED
){
6706 Index
*pIx
= pLoop
->u
.btree
.pIndex
;
6708 int op
= OP_OpenRead
;
6709 /* iAuxArg is always set to a positive value if ONEPASS is possible */
6710 assert( iAuxArg
!=0 || (pWInfo
->wctrlFlags
& WHERE_ONEPASS_DESIRED
)==0 );
6711 if( !HasRowid(pTab
) && IsPrimaryKeyIndex(pIx
)
6712 && (wctrlFlags
& WHERE_OR_SUBCLAUSE
)!=0
6714 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6715 ** WITHOUT ROWID table. No need for a separate index */
6716 iIndexCur
= pLevel
->iTabCur
;
6718 }else if( pWInfo
->eOnePass
!=ONEPASS_OFF
){
6719 Index
*pJ
= pTabItem
->pTab
->pIndex
;
6720 iIndexCur
= iAuxArg
;
6721 assert( wctrlFlags
& WHERE_ONEPASS_DESIRED
);
6722 while( ALWAYS(pJ
) && pJ
!=pIx
){
6727 pWInfo
->aiCurOnePass
[1] = iIndexCur
;
6728 }else if( iAuxArg
&& (wctrlFlags
& WHERE_OR_SUBCLAUSE
)!=0 ){
6729 iIndexCur
= iAuxArg
;
6732 iIndexCur
= pParse
->nTab
++;
6733 if( pIx
->bHasExpr
&& OptimizationEnabled(db
, SQLITE_IndexedExpr
) ){
6734 whereAddIndexedExpr(pParse
, pIx
, iIndexCur
, pTabItem
);
6736 if( pIx
->pPartIdxWhere
&& (pTabItem
->fg
.jointype
& JT_RIGHT
)==0 ){
6738 pParse
, pIx
, pIx
->pPartIdxWhere
, 0, iIndexCur
, pTabItem
6742 pLevel
->iIdxCur
= iIndexCur
;
6744 assert( pIx
->pSchema
==pTab
->pSchema
);
6745 assert( iIndexCur
>=0 );
6747 sqlite3VdbeAddOp3(v
, op
, iIndexCur
, pIx
->tnum
, iDb
);
6748 sqlite3VdbeSetP4KeyInfo(pParse
, pIx
);
6749 if( (pLoop
->wsFlags
& WHERE_CONSTRAINT
)!=0
6750 && (pLoop
->wsFlags
& (WHERE_COLUMN_RANGE
|WHERE_SKIPSCAN
))==0
6751 && (pLoop
->wsFlags
& WHERE_BIGNULL_SORT
)==0
6752 && (pLoop
->wsFlags
& WHERE_IN_SEEKSCAN
)==0
6753 && (pWInfo
->wctrlFlags
&WHERE_ORDERBY_MIN
)==0
6754 && pWInfo
->eDistinct
!=WHERE_DISTINCT_ORDERED
6756 sqlite3VdbeChangeP5(v
, OPFLAG_SEEKEQ
);
6758 VdbeComment((v
, "%s", pIx
->zName
));
6759 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6763 for(ii
=0; ii
<pIx
->nColumn
; ii
++){
6764 jj
= pIx
->aiColumn
[ii
];
6765 if( jj
<0 ) continue;
6766 if( jj
>63 ) jj
= 63;
6767 if( (pTabItem
->colUsed
& MASKBIT(jj
))==0 ) continue;
6768 colUsed
|= ((u64
)1)<<(ii
<63 ? ii
: 63);
6770 sqlite3VdbeAddOp4Dup8(v
, OP_ColumnsUsed
, iIndexCur
, 0, 0,
6771 (u8
*)&colUsed
, P4_INT64
);
6773 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
6776 if( iDb
>=0 ) sqlite3CodeVerifySchema(pParse
, iDb
);
6777 if( (pTabItem
->fg
.jointype
& JT_RIGHT
)!=0
6778 && (pLevel
->pRJ
= sqlite3WhereMalloc(pWInfo
, sizeof(WhereRightJoin
)))!=0
6780 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
6781 pRJ
->iMatch
= pParse
->nTab
++;
6782 pRJ
->regBloom
= ++pParse
->nMem
;
6783 sqlite3VdbeAddOp2(v
, OP_Blob
, 65536, pRJ
->regBloom
);
6784 pRJ
->regReturn
= ++pParse
->nMem
;
6785 sqlite3VdbeAddOp2(v
, OP_Null
, 0, pRJ
->regReturn
);
6786 assert( pTab
==pTabItem
->pTab
);
6787 if( HasRowid(pTab
) ){
6789 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pRJ
->iMatch
, 1);
6790 pInfo
= sqlite3KeyInfoAlloc(pParse
->db
, 1, 0);
6792 pInfo
->aColl
[0] = 0;
6793 pInfo
->aSortFlags
[0] = 0;
6794 sqlite3VdbeAppendP4(v
, pInfo
, P4_KEYINFO
);
6797 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
6798 sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pRJ
->iMatch
, pPk
->nKeyCol
);
6799 sqlite3VdbeSetP4KeyInfo(pParse
, pPk
);
6801 pLoop
->wsFlags
&= ~WHERE_IDX_ONLY
;
6802 /* The nature of RIGHT JOIN processing is such that it messes up
6803 ** the output order. So omit any ORDER BY/GROUP BY elimination
6804 ** optimizations. We need to do an actual sort for RIGHT JOIN. */
6806 pWInfo
->eDistinct
= WHERE_DISTINCT_UNORDERED
;
6809 pWInfo
->iTop
= sqlite3VdbeCurrentAddr(v
);
6810 if( db
->mallocFailed
) goto whereBeginError
;
6812 /* Generate the code to do the search. Each iteration of the for
6813 ** loop below generates code for a single nested loop of the VM
6816 for(ii
=0; ii
<nTabList
; ii
++){
6820 if( pParse
->nErr
) goto whereBeginError
;
6821 pLevel
= &pWInfo
->a
[ii
];
6822 wsFlags
= pLevel
->pWLoop
->wsFlags
;
6823 pSrc
= &pTabList
->a
[pLevel
->iFrom
];
6824 if( pSrc
->fg
.isMaterialized
){
6825 if( pSrc
->fg
.isCorrelated
){
6826 sqlite3VdbeAddOp2(v
, OP_Gosub
, pSrc
->regReturn
, pSrc
->addrFillSub
);
6828 int iOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
6829 sqlite3VdbeAddOp2(v
, OP_Gosub
, pSrc
->regReturn
, pSrc
->addrFillSub
);
6830 sqlite3VdbeJumpHere(v
, iOnce
);
6833 assert( pTabList
== pWInfo
->pTabList
);
6834 if( (wsFlags
& (WHERE_AUTO_INDEX
|WHERE_BLOOMFILTER
))!=0 ){
6835 if( (wsFlags
& WHERE_AUTO_INDEX
)!=0 ){
6836 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6837 constructAutomaticIndex(pParse
, &pWInfo
->sWC
, notReady
, pLevel
);
6840 sqlite3ConstructBloomFilter(pWInfo
, ii
, pLevel
, notReady
);
6842 if( db
->mallocFailed
) goto whereBeginError
;
6844 addrExplain
= sqlite3WhereExplainOneScan(
6845 pParse
, pTabList
, pLevel
, wctrlFlags
6847 pLevel
->addrBody
= sqlite3VdbeCurrentAddr(v
);
6848 notReady
= sqlite3WhereCodeOneLoopStart(pParse
,v
,pWInfo
,ii
,pLevel
,notReady
);
6849 pWInfo
->iContinue
= pLevel
->addrCont
;
6850 if( (wsFlags
&WHERE_MULTI_OR
)==0 && (wctrlFlags
&WHERE_OR_SUBCLAUSE
)==0 ){
6851 sqlite3WhereAddScanStatus(v
, pTabList
, pLevel
, addrExplain
);
6856 VdbeModuleComment((v
, "Begin WHERE-core"));
6857 pWInfo
->iEndWhere
= sqlite3VdbeCurrentAddr(v
);
6860 /* Jump here if malloc fails */
6863 pParse
->nQueryLoop
= pWInfo
->savedNQueryLoop
;
6864 whereInfoFree(db
, pWInfo
);
6866 #ifdef WHERETRACE_ENABLED
6867 /* Prevent harmless compiler warnings about debugging routines
6868 ** being declared but never used */
6869 sqlite3ShowWhereLoopList(0);
6870 #endif /* WHERETRACE_ENABLED */
6875 ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
6876 ** index rather than the main table. In SQLITE_DEBUG mode, we want
6877 ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
6880 #ifndef SQLITE_DEBUG
6881 # define OpcodeRewriteTrace(D,K,P) /* no-op */
6883 # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
6884 static void sqlite3WhereOpcodeRewriteTrace(
6889 if( (db
->flags
& SQLITE_VdbeAddopTrace
)==0 ) return;
6890 sqlite3VdbePrintOp(0, pc
, pOp
);
6895 ** Generate the end of the WHERE loop. See comments on
6896 ** sqlite3WhereBegin() for additional information.
6898 void sqlite3WhereEnd(WhereInfo
*pWInfo
){
6899 Parse
*pParse
= pWInfo
->pParse
;
6900 Vdbe
*v
= pParse
->pVdbe
;
6904 SrcList
*pTabList
= pWInfo
->pTabList
;
6905 sqlite3
*db
= pParse
->db
;
6906 int iEnd
= sqlite3VdbeCurrentAddr(v
);
6909 /* Generate loop termination code.
6911 VdbeModuleComment((v
, "End WHERE-core"));
6912 for(i
=pWInfo
->nLevel
-1; i
>=0; i
--){
6914 pLevel
= &pWInfo
->a
[i
];
6916 /* Terminate the subroutine that forms the interior of the loop of
6917 ** the RIGHT JOIN table */
6918 WhereRightJoin
*pRJ
= pLevel
->pRJ
;
6919 sqlite3VdbeResolveLabel(v
, pLevel
->addrCont
);
6920 pLevel
->addrCont
= 0;
6921 pRJ
->endSubrtn
= sqlite3VdbeCurrentAddr(v
);
6922 sqlite3VdbeAddOp3(v
, OP_Return
, pRJ
->regReturn
, pRJ
->addrSubrtn
, 1);
6926 pLoop
= pLevel
->pWLoop
;
6927 if( pLevel
->op
!=OP_Noop
){
6928 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6932 if( pWInfo
->eDistinct
==WHERE_DISTINCT_ORDERED
6933 && i
==pWInfo
->nLevel
-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
6934 && (pLoop
->wsFlags
& WHERE_INDEXED
)!=0
6935 && (pIdx
= pLoop
->u
.btree
.pIndex
)->hasStat1
6936 && (n
= pLoop
->u
.btree
.nDistinctCol
)>0
6937 && pIdx
->aiRowLogEst
[n
]>=36
6939 int r1
= pParse
->nMem
+1;
6942 sqlite3VdbeAddOp3(v
, OP_Column
, pLevel
->iIdxCur
, j
, r1
+j
);
6944 pParse
->nMem
+= n
+1;
6945 op
= pLevel
->op
==OP_Prev
? OP_SeekLT
: OP_SeekGT
;
6946 addrSeek
= sqlite3VdbeAddOp4Int(v
, op
, pLevel
->iIdxCur
, 0, r1
, n
);
6947 VdbeCoverageIf(v
, op
==OP_SeekLT
);
6948 VdbeCoverageIf(v
, op
==OP_SeekGT
);
6949 sqlite3VdbeAddOp2(v
, OP_Goto
, 1, pLevel
->p2
);
6951 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
6952 /* The common case: Advance to the next row */
6953 if( pLevel
->addrCont
) sqlite3VdbeResolveLabel(v
, pLevel
->addrCont
);
6954 sqlite3VdbeAddOp3(v
, pLevel
->op
, pLevel
->p1
, pLevel
->p2
, pLevel
->p3
);
6955 sqlite3VdbeChangeP5(v
, pLevel
->p5
);
6957 VdbeCoverageIf(v
, pLevel
->op
==OP_Next
);
6958 VdbeCoverageIf(v
, pLevel
->op
==OP_Prev
);
6959 VdbeCoverageIf(v
, pLevel
->op
==OP_VNext
);
6960 if( pLevel
->regBignull
){
6961 sqlite3VdbeResolveLabel(v
, pLevel
->addrBignull
);
6962 sqlite3VdbeAddOp2(v
, OP_DecrJumpZero
, pLevel
->regBignull
, pLevel
->p2
-1);
6965 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6966 if( addrSeek
) sqlite3VdbeJumpHere(v
, addrSeek
);
6968 }else if( pLevel
->addrCont
){
6969 sqlite3VdbeResolveLabel(v
, pLevel
->addrCont
);
6971 if( (pLoop
->wsFlags
& WHERE_IN_ABLE
)!=0 && pLevel
->u
.in
.nIn
>0 ){
6974 sqlite3VdbeResolveLabel(v
, pLevel
->addrNxt
);
6975 for(j
=pLevel
->u
.in
.nIn
, pIn
=&pLevel
->u
.in
.aInLoop
[j
-1]; j
>0; j
--, pIn
--){
6976 assert( sqlite3VdbeGetOp(v
, pIn
->addrInTop
+1)->opcode
==OP_IsNull
6977 || pParse
->db
->mallocFailed
);
6978 sqlite3VdbeJumpHere(v
, pIn
->addrInTop
+1);
6979 if( pIn
->eEndLoopOp
!=OP_Noop
){
6982 (pLoop
->wsFlags
& WHERE_VIRTUALTABLE
)==0
6983 && (pLoop
->wsFlags
& WHERE_IN_EARLYOUT
)!=0;
6984 if( pLevel
->iLeftJoin
){
6985 /* For LEFT JOIN queries, cursor pIn->iCur may not have been
6986 ** opened yet. This occurs for WHERE clauses such as
6987 ** "a = ? AND b IN (...)", where the index is on (a, b). If
6988 ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
6989 ** never have been coded, but the body of the loop run to
6990 ** return the null-row. So, if the cursor is not open yet,
6991 ** jump over the OP_Next or OP_Prev instruction about to
6993 sqlite3VdbeAddOp2(v
, OP_IfNotOpen
, pIn
->iCur
,
6994 sqlite3VdbeCurrentAddr(v
) + 2 + bEarlyOut
);
6998 sqlite3VdbeAddOp4Int(v
, OP_IfNoHope
, pLevel
->iIdxCur
,
6999 sqlite3VdbeCurrentAddr(v
)+2,
7000 pIn
->iBase
, pIn
->nPrefix
);
7002 /* Retarget the OP_IsNull against the left operand of IN so
7003 ** it jumps past the OP_IfNoHope. This is because the
7004 ** OP_IsNull also bypasses the OP_Affinity opcode that is
7005 ** required by OP_IfNoHope. */
7006 sqlite3VdbeJumpHere(v
, pIn
->addrInTop
+1);
7009 sqlite3VdbeAddOp2(v
, pIn
->eEndLoopOp
, pIn
->iCur
, pIn
->addrInTop
);
7011 VdbeCoverageIf(v
, pIn
->eEndLoopOp
==OP_Prev
);
7012 VdbeCoverageIf(v
, pIn
->eEndLoopOp
==OP_Next
);
7014 sqlite3VdbeJumpHere(v
, pIn
->addrInTop
-1);
7017 sqlite3VdbeResolveLabel(v
, pLevel
->addrBrk
);
7019 sqlite3VdbeAddOp3(v
, OP_Return
, pLevel
->pRJ
->regReturn
, 0, 1);
7022 if( pLevel
->addrSkip
){
7023 sqlite3VdbeGoto(v
, pLevel
->addrSkip
);
7024 VdbeComment((v
, "next skip-scan on %s", pLoop
->u
.btree
.pIndex
->zName
));
7025 sqlite3VdbeJumpHere(v
, pLevel
->addrSkip
);
7026 sqlite3VdbeJumpHere(v
, pLevel
->addrSkip
-2);
7028 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
7029 if( pLevel
->addrLikeRep
){
7030 sqlite3VdbeAddOp2(v
, OP_DecrJumpZero
, (int)(pLevel
->iLikeRepCntr
>>1),
7031 pLevel
->addrLikeRep
);
7035 if( pLevel
->iLeftJoin
){
7036 int ws
= pLoop
->wsFlags
;
7037 addr
= sqlite3VdbeAddOp1(v
, OP_IfPos
, pLevel
->iLeftJoin
); VdbeCoverage(v
);
7038 assert( (ws
& WHERE_IDX_ONLY
)==0 || (ws
& WHERE_INDEXED
)!=0 );
7039 if( (ws
& WHERE_IDX_ONLY
)==0 ){
7040 SrcItem
*pSrc
= &pTabList
->a
[pLevel
->iFrom
];
7041 assert( pLevel
->iTabCur
==pSrc
->iCursor
);
7042 if( pSrc
->fg
.viaCoroutine
){
7044 n
= pSrc
->regResult
;
7045 assert( pSrc
->pTab
!=0 );
7046 m
= pSrc
->pTab
->nCol
;
7047 sqlite3VdbeAddOp3(v
, OP_Null
, 0, n
, n
+m
-1);
7049 sqlite3VdbeAddOp1(v
, OP_NullRow
, pLevel
->iTabCur
);
7051 if( (ws
& WHERE_INDEXED
)
7052 || ((ws
& WHERE_MULTI_OR
) && pLevel
->u
.pCoveringIdx
)
7054 if( ws
& WHERE_MULTI_OR
){
7055 Index
*pIx
= pLevel
->u
.pCoveringIdx
;
7056 int iDb
= sqlite3SchemaToIndex(db
, pIx
->pSchema
);
7057 sqlite3VdbeAddOp3(v
, OP_ReopenIdx
, pLevel
->iIdxCur
, pIx
->tnum
, iDb
);
7058 sqlite3VdbeSetP4KeyInfo(pParse
, pIx
);
7060 sqlite3VdbeAddOp1(v
, OP_NullRow
, pLevel
->iIdxCur
);
7062 if( pLevel
->op
==OP_Return
){
7063 sqlite3VdbeAddOp2(v
, OP_Gosub
, pLevel
->p1
, pLevel
->addrFirst
);
7065 sqlite3VdbeGoto(v
, pLevel
->addrFirst
);
7067 sqlite3VdbeJumpHere(v
, addr
);
7069 VdbeModuleComment((v
, "End WHERE-loop%d: %s", i
,
7070 pWInfo
->pTabList
->a
[pLevel
->iFrom
].pTab
->zName
));
7073 assert( pWInfo
->nLevel
<=pTabList
->nSrc
);
7074 for(i
=0, pLevel
=pWInfo
->a
; i
<pWInfo
->nLevel
; i
++, pLevel
++){
7076 VdbeOp
*pOp
, *pLastOp
;
7078 SrcItem
*pTabItem
= &pTabList
->a
[pLevel
->iFrom
];
7079 Table
*pTab
= pTabItem
->pTab
;
7081 pLoop
= pLevel
->pWLoop
;
7083 /* Do RIGHT JOIN processing. Generate code that will output the
7084 ** unmatched rows of the right operand of the RIGHT JOIN with
7085 ** all of the columns of the left operand set to NULL.
7088 sqlite3WhereRightJoinLoop(pWInfo
, i
, pLevel
);
7092 /* For a co-routine, change all OP_Column references to the table of
7093 ** the co-routine into OP_Copy of result contained in a register.
7094 ** OP_Rowid becomes OP_Null.
7096 if( pTabItem
->fg
.viaCoroutine
){
7097 testcase( pParse
->db
->mallocFailed
);
7098 assert( pTabItem
->regResult
>=0 );
7099 translateColumnToCopy(pParse
, pLevel
->addrBody
, pLevel
->iTabCur
,
7100 pTabItem
->regResult
, 0);
7104 /* If this scan uses an index, make VDBE code substitutions to read data
7105 ** from the index instead of from the table where possible. In some cases
7106 ** this optimization prevents the table from ever being read, which can
7107 ** yield a significant performance boost.
7109 ** Calls to the code generator in between sqlite3WhereBegin and
7110 ** sqlite3WhereEnd will have created code that references the table
7111 ** directly. This loop scans all that code looking for opcodes
7112 ** that reference the table and converts them into opcodes that
7113 ** reference the index.
7115 if( pLoop
->wsFlags
& (WHERE_INDEXED
|WHERE_IDX_ONLY
) ){
7116 pIdx
= pLoop
->u
.btree
.pIndex
;
7117 }else if( pLoop
->wsFlags
& WHERE_MULTI_OR
){
7118 pIdx
= pLevel
->u
.pCoveringIdx
;
7121 && !db
->mallocFailed
7123 if( pWInfo
->eOnePass
==ONEPASS_OFF
|| !HasRowid(pIdx
->pTable
) ){
7126 last
= pWInfo
->iEndWhere
;
7128 if( pIdx
->bHasExpr
){
7129 IndexedExpr
*p
= pParse
->pIdxEpr
;
7131 if( p
->iIdxCur
==pLevel
->iIdxCur
){
7132 #ifdef WHERETRACE_ENABLED
7133 if( sqlite3WhereTrace
& 0x200 ){
7134 sqlite3DebugPrintf("Disable pParse->pIdxEpr term {%d,%d}\n",
7135 p
->iIdxCur
, p
->iIdxCol
);
7136 if( sqlite3WhereTrace
& 0x5000 ) sqlite3ShowExpr(p
->pExpr
);
7145 k
= pLevel
->addrBody
+ 1;
7147 if( db
->flags
& SQLITE_VdbeAddopTrace
){
7148 printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n",
7149 pLevel
->iTabCur
, pLevel
->iIdxCur
, k
, last
-1);
7151 /* Proof that the "+1" on the k value above is safe */
7152 pOp
= sqlite3VdbeGetOp(v
, k
- 1);
7153 assert( pOp
->opcode
!=OP_Column
|| pOp
->p1
!=pLevel
->iTabCur
);
7154 assert( pOp
->opcode
!=OP_Rowid
|| pOp
->p1
!=pLevel
->iTabCur
);
7155 assert( pOp
->opcode
!=OP_IfNullRow
|| pOp
->p1
!=pLevel
->iTabCur
);
7157 pOp
= sqlite3VdbeGetOp(v
, k
);
7158 pLastOp
= pOp
+ (last
- k
);
7159 assert( pOp
<=pLastOp
);
7161 if( pOp
->p1
!=pLevel
->iTabCur
){
7163 }else if( pOp
->opcode
==OP_Column
7164 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
7165 || pOp
->opcode
==OP_Offset
7169 assert( pIdx
->pTable
==pTab
);
7170 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
7171 if( pOp
->opcode
==OP_Offset
){
7172 /* Do not need to translate the column number */
7175 if( !HasRowid(pTab
) ){
7176 Index
*pPk
= sqlite3PrimaryKeyIndex(pTab
);
7177 x
= pPk
->aiColumn
[x
];
7180 testcase( x
!=sqlite3StorageColumnToTable(pTab
,x
) );
7181 x
= sqlite3StorageColumnToTable(pTab
,x
);
7183 x
= sqlite3TableColumnToIndex(pIdx
, x
);
7186 pOp
->p1
= pLevel
->iIdxCur
;
7187 OpcodeRewriteTrace(db
, k
, pOp
);
7189 /* Unable to translate the table reference into an index
7190 ** reference. Verify that this is harmless - that the
7191 ** table being referenced really is open.
7193 if( pLoop
->wsFlags
& WHERE_IDX_ONLY
){
7194 sqlite3ErrorMsg(pParse
, "internal query planner error");
7195 pParse
->rc
= SQLITE_INTERNAL
;
7198 }else if( pOp
->opcode
==OP_Rowid
){
7199 pOp
->p1
= pLevel
->iIdxCur
;
7200 pOp
->opcode
= OP_IdxRowid
;
7201 OpcodeRewriteTrace(db
, k
, pOp
);
7202 }else if( pOp
->opcode
==OP_IfNullRow
){
7203 pOp
->p1
= pLevel
->iIdxCur
;
7204 OpcodeRewriteTrace(db
, k
, pOp
);
7209 }while( (++pOp
)<pLastOp
);
7211 if( db
->flags
& SQLITE_VdbeAddopTrace
) printf("TRANSLATE complete\n");
7216 /* The "break" point is here, just past the end of the outer loop.
7219 sqlite3VdbeResolveLabel(v
, pWInfo
->iBreak
);
7223 pParse
->nQueryLoop
= pWInfo
->savedNQueryLoop
;
7224 whereInfoFree(db
, pWInfo
);
7225 pParse
->withinRJSubrtn
-= nRJ
;