Fix a problem causing the recovery extension to use excessive memory and CPU time...
[sqlite.git] / src / where.c
blob820e9224903ed1e2950bfec2e4db8867ee1c21a7
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This module contains C code that generates VDBE code used to process
13 ** the WHERE clause of SQL statements. This module is responsible for
14 ** generating the code that loops through a table looking for applicable
15 ** rows. Indices are selected and used to speed the search when doing
16 ** so is applicable. Because this module is responsible for selecting
17 ** indices, you might also think of this module as the "query optimizer".
19 #include "sqliteInt.h"
20 #include "whereInt.h"
23 ** Extra information appended to the end of sqlite3_index_info but not
24 ** visible to the xBestIndex function, at least not directly. The
25 ** sqlite3_vtab_collation() interface knows how to reach it, however.
27 ** This object is not an API and can be changed from one release to the
28 ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
29 ** agree on the structure, all will be well.
31 typedef struct HiddenIndexInfo HiddenIndexInfo;
32 struct HiddenIndexInfo {
33 WhereClause *pWC; /* The Where clause being analyzed */
34 Parse *pParse; /* The parsing context */
35 int eDistinct; /* Value to return from sqlite3_vtab_distinct() */
36 u32 mIn; /* Mask of terms that are <col> IN (...) */
37 u32 mHandleIn; /* Terms that vtab will handle as <col> IN (...) */
38 sqlite3_value *aRhs[1]; /* RHS values for constraints. MUST BE LAST
39 ** because extra space is allocated to hold up
40 ** to nTerm such values */
43 /* Forward declaration of methods */
44 static int whereLoopResize(sqlite3*, WhereLoop*, int);
47 ** Return the estimated number of output rows from a WHERE clause
49 LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
50 return pWInfo->nRowOut;
54 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
55 ** WHERE clause returns outputs for DISTINCT processing.
57 int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
58 return pWInfo->eDistinct;
62 ** Return the number of ORDER BY terms that are satisfied by the
63 ** WHERE clause. A return of 0 means that the output must be
64 ** completely sorted. A return equal to the number of ORDER BY
65 ** terms means that no sorting is needed at all. A return that
66 ** is positive but less than the number of ORDER BY terms means that
67 ** block sorting is required.
69 int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
70 return pWInfo->nOBSat<0 ? 0 : pWInfo->nOBSat;
74 ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
75 ** to emit rows in increasing order, and if the last row emitted by the
76 ** inner-most loop did not fit within the sorter, then we can skip all
77 ** subsequent rows for the current iteration of the inner loop (because they
78 ** will not fit in the sorter either) and continue with the second inner
79 ** loop - the loop immediately outside the inner-most.
81 ** When a row does not fit in the sorter (because the sorter already
82 ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
83 ** label returned by this function.
85 ** If the ORDER BY LIMIT optimization applies, the jump destination should
86 ** be the continuation for the second-inner-most loop. If the ORDER BY
87 ** LIMIT optimization does not apply, then the jump destination should
88 ** be the continuation for the inner-most loop.
90 ** It is always safe for this routine to return the continuation of the
91 ** inner-most loop, in the sense that a correct answer will result.
92 ** Returning the continuation the second inner loop is an optimization
93 ** that might make the code run a little faster, but should not change
94 ** the final answer.
96 int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
97 WhereLevel *pInner;
98 if( !pWInfo->bOrderedInnerLoop ){
99 /* The ORDER BY LIMIT optimization does not apply. Jump to the
100 ** continuation of the inner-most loop. */
101 return pWInfo->iContinue;
103 pInner = &pWInfo->a[pWInfo->nLevel-1];
104 assert( pInner->addrNxt!=0 );
105 return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt;
109 ** While generating code for the min/max optimization, after handling
110 ** the aggregate-step call to min() or max(), check to see if any
111 ** additional looping is required. If the output order is such that
112 ** we are certain that the correct answer has already been found, then
113 ** code an OP_Goto to by pass subsequent processing.
115 ** Any extra OP_Goto that is coded here is an optimization. The
116 ** correct answer should be obtained regardless. This OP_Goto just
117 ** makes the answer appear faster.
119 void sqlite3WhereMinMaxOptEarlyOut(Vdbe *v, WhereInfo *pWInfo){
120 WhereLevel *pInner;
121 int i;
122 if( !pWInfo->bOrderedInnerLoop ) return;
123 if( pWInfo->nOBSat==0 ) return;
124 for(i=pWInfo->nLevel-1; i>=0; i--){
125 pInner = &pWInfo->a[i];
126 if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){
127 sqlite3VdbeGoto(v, pInner->addrNxt);
128 return;
131 sqlite3VdbeGoto(v, pWInfo->iBreak);
135 ** Return the VDBE address or label to jump to in order to continue
136 ** immediately with the next row of a WHERE clause.
138 int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
139 assert( pWInfo->iContinue!=0 );
140 return pWInfo->iContinue;
144 ** Return the VDBE address or label to jump to in order to break
145 ** out of a WHERE loop.
147 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
148 return pWInfo->iBreak;
152 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
153 ** operate directly on the rowids returned by a WHERE clause. Return
154 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
155 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
156 ** optimization can be used on multiple
158 ** If the ONEPASS optimization is used (if this routine returns true)
159 ** then also write the indices of open cursors used by ONEPASS
160 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
161 ** table and iaCur[1] gets the cursor used by an auxiliary index.
162 ** Either value may be -1, indicating that cursor is not used.
163 ** Any cursors returned will have been opened for writing.
165 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
166 ** unable to use the ONEPASS optimization.
168 int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
169 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
170 #ifdef WHERETRACE_ENABLED
171 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
172 sqlite3DebugPrintf("%s cursors: %d %d\n",
173 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
174 aiCur[0], aiCur[1]);
176 #endif
177 return pWInfo->eOnePass;
181 ** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move
182 ** the data cursor to the row selected by the index cursor.
184 int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
185 return pWInfo->bDeferredSeek;
189 ** Move the content of pSrc into pDest
191 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
192 pDest->n = pSrc->n;
193 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
197 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
199 ** The new entry might overwrite an existing entry, or it might be
200 ** appended, or it might be discarded. Do whatever is the right thing
201 ** so that pSet keeps the N_OR_COST best entries seen so far.
203 static int whereOrInsert(
204 WhereOrSet *pSet, /* The WhereOrSet to be updated */
205 Bitmask prereq, /* Prerequisites of the new entry */
206 LogEst rRun, /* Run-cost of the new entry */
207 LogEst nOut /* Number of outputs for the new entry */
209 u16 i;
210 WhereOrCost *p;
211 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
212 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
213 goto whereOrInsert_done;
215 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
216 return 0;
219 if( pSet->n<N_OR_COST ){
220 p = &pSet->a[pSet->n++];
221 p->nOut = nOut;
222 }else{
223 p = pSet->a;
224 for(i=1; i<pSet->n; i++){
225 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
227 if( p->rRun<=rRun ) return 0;
229 whereOrInsert_done:
230 p->prereq = prereq;
231 p->rRun = rRun;
232 if( p->nOut>nOut ) p->nOut = nOut;
233 return 1;
237 ** Return the bitmask for the given cursor number. Return 0 if
238 ** iCursor is not in the set.
240 Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
241 int i;
242 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
243 assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 );
244 assert( iCursor>=-1 );
245 if( pMaskSet->ix[0]==iCursor ){
246 return 1;
248 for(i=1; i<pMaskSet->n; i++){
249 if( pMaskSet->ix[i]==iCursor ){
250 return MASKBIT(i);
253 return 0;
256 /* Allocate memory that is automatically freed when pWInfo is freed.
258 void *sqlite3WhereMalloc(WhereInfo *pWInfo, u64 nByte){
259 WhereMemBlock *pBlock;
260 pBlock = sqlite3DbMallocRawNN(pWInfo->pParse->db, nByte+sizeof(*pBlock));
261 if( pBlock ){
262 pBlock->pNext = pWInfo->pMemToFree;
263 pBlock->sz = nByte;
264 pWInfo->pMemToFree = pBlock;
265 pBlock++;
267 return (void*)pBlock;
269 void *sqlite3WhereRealloc(WhereInfo *pWInfo, void *pOld, u64 nByte){
270 void *pNew = sqlite3WhereMalloc(pWInfo, nByte);
271 if( pNew && pOld ){
272 WhereMemBlock *pOldBlk = (WhereMemBlock*)pOld;
273 pOldBlk--;
274 assert( pOldBlk->sz<nByte );
275 memcpy(pNew, pOld, pOldBlk->sz);
277 return pNew;
281 ** Create a new mask for cursor iCursor.
283 ** There is one cursor per table in the FROM clause. The number of
284 ** tables in the FROM clause is limited by a test early in the
285 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
286 ** array will never overflow.
288 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
289 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
290 pMaskSet->ix[pMaskSet->n++] = iCursor;
294 ** If the right-hand branch of the expression is a TK_COLUMN, then return
295 ** a pointer to the right-hand branch. Otherwise, return NULL.
297 static Expr *whereRightSubexprIsColumn(Expr *p){
298 p = sqlite3ExprSkipCollateAndLikely(p->pRight);
299 if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
300 return p;
302 return 0;
306 ** 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(
315 Parse *pParse,
316 WhereTerm *pTerm,
317 u8 idxaff
319 Expr *pX = pTerm->pExpr;
320 Expr inexpr;
322 assert( pTerm->eOperator & WO_IN );
324 if( sqlite3ExprIsVector(pX->pLeft) ){
325 int iField = pTerm->u.x.iField - 1;
326 inexpr.flags = 0;
327 inexpr.op = TK_EQ;
328 inexpr.pLeft = pX->pLeft->x.pList->a[iField].pExpr;
329 assert( ExprUseXSelect(pX) );
330 inexpr.pRight = pX->x.pSelect->pEList->a[iField].pExpr;
331 pX = &inexpr;
334 if( sqlite3IndexAffinityOk(pX, idxaff) ){
335 CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX);
336 return pRet ? pRet->zName : sqlite3StrBINARY;
338 return 0;
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 );
355 pWC = pScan->pWC;
356 while(1){
357 iColumn = pScan->aiColumn[pScan->iEquiv-1];
358 iCur = pScan->aiCur[pScan->iEquiv-1];
359 assert( pWC!=0 );
360 assert( iCur>=0 );
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
366 && (iColumn!=XN_EXPR
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
375 int j;
376 for(j=0; j<pScan->nEquiv; j++){
377 if( pScan->aiCur[j]==pX->iTable
378 && pScan->aiColumn[j]==pX->iColumn ){
379 break;
382 if( j==pScan->nEquiv ){
383 pScan->aiCur[j] = pX->iTable;
384 pScan->aiColumn[j] = pX->iColumn;
385 pScan->nEquiv++;
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;
393 pX = pTerm->pExpr;
395 if( (pTerm->eOperator & WO_IN) ){
396 zCollName = indexInAffinityOk(pParse, pTerm, pScan->idxaff);
397 if( !zCollName ) continue;
398 }else{
399 CollSeq *pColl;
400 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
401 continue;
403 assert(pX->pLeft);
404 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
405 zCollName = pColl ? pColl->zName : sqlite3StrBINARY;
408 if( sqlite3StrICmp(zCollName, pScan->zCollName) ){
409 continue;
412 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
413 && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
414 && pX->op==TK_COLUMN
415 && pX->iTable==pScan->aiCur[0]
416 && pX->iColumn==pScan->aiColumn[0]
418 testcase( pTerm->eOperator & WO_IS );
419 continue;
421 pScan->pWC = pWC;
422 pScan->k = k+1;
423 #ifdef WHERETRACE_ENABLED
424 if( sqlite3WhereTrace & 0x20000 ){
425 int ii;
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");
434 #endif
435 return pTerm;
439 pWC = pWC->pOuter;
440 k = 0;
441 }while( pWC!=0 );
442 if( pScan->iEquiv>=pScan->nEquiv ) break;
443 pWC = pScan->pOrigWC;
444 k = 0;
445 pScan->iEquiv++;
447 return 0;
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
478 ** index pIdx.
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;
489 pScan->pWC = pWC;
490 pScan->pIdxExpr = 0;
491 pScan->idxaff = 0;
492 pScan->zCollName = 0;
493 pScan->opMask = opMask;
494 pScan->k = 0;
495 pScan->aiCur[0] = iCur;
496 pScan->nEquiv = 1;
497 pScan->iEquiv = 1;
498 if( pIdx ){
499 int j = iColumn;
500 iColumn = pIdx->aiColumn[j];
501 if( iColumn==pIdx->pTable->iPKey ){
502 iColumn = XN_ROWID;
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 ){
513 return 0;
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;
553 WhereTerm *p;
554 WhereScan scan;
556 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
557 op &= WO_EQ|WO_IS;
558 while( p ){
559 if( (p->prereqRight & notReady)==0 ){
560 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
561 testcase( p->eOperator & WO_IS );
562 return p;
564 if( pResult==0 ) pResult = p;
566 p = whereScanNext(&scan);
568 return pResult;
572 ** This function searches pList for an entry that matches the iCol-th column
573 ** of index pIdx.
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 */
585 int i;
586 const char *zColl = pIdx->azColl[iCol];
588 for(i=0; i<pList->nExpr; i++){
589 Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
590 if( ALWAYS(p!=0)
591 && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
592 && p->iColumn==pIdx->aiColumn[iCol]
593 && p->iTable==iBase
595 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
596 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
597 return i;
602 return -1;
606 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
608 static int indexColumnNotNull(Index *pIdx, int iCol){
609 int j;
610 assert( pIdx!=0 );
611 assert( iCol>=0 && iCol<pIdx->nColumn );
612 j = pIdx->aiColumn[iCol];
613 if( j>=0 ){
614 return pIdx->pTable->aCol[j].notNull;
615 }else if( j==(-1) ){
616 return 1;
617 }else{
618 assert( j==(-2) );
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
626 ** is redundant.
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 */
637 Table *pTab;
638 Index *pIdx;
639 int i;
640 int iBase;
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. */
684 return 1;
688 return 0;
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 ){
725 #ifdef SQLITE_DEBUG
726 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
727 printf("TRANSLATE OP_Column to OP_Copy at %d\n", iStart);
729 #endif
730 pOp->opcode = OP_Copy;
731 pOp->p1 = pOp->p2 + iRegister;
732 pOp->p2 = pOp->p3;
733 pOp->p3 = 0;
734 pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */
735 }else if( pOp->opcode==OP_Rowid ){
736 #ifdef SQLITE_DEBUG
737 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
738 printf("TRANSLATE OP_Rowid to OP_Sequence at %d\n", iStart);
740 #endif
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;
746 pOp->p3 = 0;
748 #endif
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
757 ** are no-ops.
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 */
764 int i;
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++){
768 sqlite3DebugPrintf(
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 */
788 int i;
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);
803 #else
804 #define whereTraceIndexInfoInputs(A,B)
805 #define whereTraceIndexInfoOutputs(A,B)
806 #endif
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
833 return 0;
835 if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0
836 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
838 return 0;
840 return 1;
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
849 ** index existed.
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 */
856 char aff;
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 );
871 return 1;
873 #endif
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(
891 Parse *pParse,
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 = "";
899 char *zText = 0;
900 int ii = 0;
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);
911 zSep = ", ";
913 zText = sqlite3_str_finish(pStr);
914 if( zText==0 ){
915 sqlite3OomFault(pParse->db);
916 }else{
917 *pAddrExplain = sqlite3VdbeExplain(
918 pParse, 0, "%s)%s", zText, (bPartial ? " WHERE <expr>" : "")
920 sqlite3_free(zText);
924 #else
925 # define explainAutomaticIndex(a,b,c,d)
926 #endif
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 */
966 #endif
968 /* Generate code to skip over the creation and initialization of the
969 ** transient index on 2nd and subsequent iterations of the loop. */
970 v = pParse->pVdbe;
971 assert( v!=0 );
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 */
976 nKeyCol = 0;
977 pTabList = pWC->pWInfo->pTabList;
978 pSrc = &pTabList->a[pLevel->iFrom];
979 pTable = pSrc->pTab;
980 pWCEnd = &pWC->a[pWC->nTerm];
981 pLoop = pLevel->pWLoop;
982 idxCols = 0;
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) ){
995 int iCol;
996 Bitmask cMask;
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 );
1002 if( !sentWarning ){
1003 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
1004 "automatic index on %s(%s)", pTable->zName,
1005 pTable->aCol[iCol].zCnName);
1006 sentWarning = 1;
1008 if( (idxCols & cMask)==0 ){
1009 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
1010 goto end_auto_index_create;
1012 pLoop->aLTerm[nKeyCol++] = pTerm;
1013 idxCols |= cMask;
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
1020 | WHERE_AUTO_INDEX;
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;
1032 }else{
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;
1051 n = 0;
1052 idxCols = 0;
1053 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1054 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1055 int iCol;
1056 Bitmask cMask;
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;
1064 idxCols |= cMask;
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;
1069 n++;
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. */
1078 useBloomFilter = 1;
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;
1091 n++;
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;
1098 n++;
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);
1125 VdbeCoverage(v);
1126 VdbeComment((v, "next row of %s", pSrc->pTab->zName));
1127 }else{
1128 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
1130 if( pPartial ){
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;
1155 }else{
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
1173 ** for pLevel.
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
1178 ** been turned off.
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
1189 ** is set.
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;
1214 assert( pLoop!=0 );
1215 assert( v!=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;
1223 const Table *pTab;
1224 u64 sz;
1225 int iSrc;
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];
1242 assert( pItem!=0 );
1243 pTab = pItem->pTab;
1244 assert( pTab!=0 );
1245 sz = sqlite3LogEstToInt(pTab->nRowLogEst);
1246 if( sz<10000 ){
1247 sz = 10000;
1248 }else if( sz>10000000 ){
1249 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);
1268 }else{
1269 Index *pIdx = pLoop->u.btree.pIndex;
1270 int n = pLoop->u.btree.nEq;
1271 int r1 = sqlite3GetTempRange(pParse, n);
1272 int jj;
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);
1282 VdbeCoverage(v);
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))
1295 ==WHERE_BLOOMFILTER
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 */
1301 break;
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 */
1324 int i, j;
1325 int nTerm;
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;
1331 WhereTerm *pTerm;
1332 int nOrderBy;
1333 sqlite3_index_info *pIdxInfo;
1334 u16 mNoOmit = 0;
1335 const Table *pTab;
1336 int eDistinct = 0;
1337 ExprList *pOrderBy = pWInfo->pOrderBy;
1339 assert( pSrc!=0 );
1340 pTab = pSrc->pTab;
1341 assert( pTab!=0 );
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
1346 ** terms found.
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)
1366 continue;
1368 nTerm++;
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.
1376 nOrderBy = 0;
1377 if( pOrderBy ){
1378 int n = pOrderBy->nExpr;
1379 for(i=0; i<n; i++){
1380 Expr *pExpr = pOrderBy->a[i].pExpr;
1381 Expr *pE2;
1383 /* Skip over constant terms in the ORDER BY clause */
1384 if( sqlite3ExprIsConstant(0, pExpr) ){
1385 continue;
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 );
1394 continue;
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 */
1415 break;
1417 if( i==n ){
1418 nOrderBy = n;
1419 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) ){
1420 eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
1421 }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
1422 eDistinct = 1;
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 );
1433 if( pIdxInfo==0 ){
1434 sqlite3ErrorMsg(pParse, "out of memory");
1435 return 0;
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;
1444 pHidden->pWC = pWC;
1445 pHidden->pParse = pParse;
1446 pHidden->eDistinct = eDistinct;
1447 pHidden->mIn = 0;
1448 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1449 u16 op;
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;
1454 if( op==WO_IN ){
1455 if( (pTerm->wtFlags & TERM_SLICE)==0 ){
1456 pHidden->mIn |= SMASKBIT32(j);
1458 op = WO_EQ;
1460 if( op==WO_AUX ){
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;
1465 }else{
1466 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
1468 }else{
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)
1483 testcase( j!=i );
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;
1490 j++;
1492 assert( j==nTerm );
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;
1502 j++;
1504 pIdxInfo->nOrderBy = j;
1506 *pmNoOmit = mNoOmit;
1507 return pIdxInfo;
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;
1516 int i;
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;
1546 int rc;
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));
1559 }else{
1560 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1563 if( pTab->u.vtab.p->bAllSchemas ){
1564 sqlite3VtabUsesAllSchemas(pParse);
1566 sqlite3_free(pVtab->zErrMsg);
1567 pVtab->zErrMsg = 0;
1568 return rc;
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
1584 ** pRec.
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 );
1605 #endif
1606 assert( pRec!=0 );
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
1619 ** in aSample is:
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:
1631 ** 0: (a)
1632 ** 1: (a, 5)
1633 ** 2: (a, 10)
1634 ** 3: (a, 10)
1635 ** 4: (b)
1636 ** 5: (b, 5)
1637 ** 6: (c)
1638 ** 7: (c, 100)
1639 ** 8: (c, 105)
1640 ** 9: (c, 105)
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;
1657 }else{
1658 nField = pIdx->nColumn;
1660 nField = MIN(pRec->nField, nField);
1661 iCol = 0;
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;
1669 if( iSamp>0 ){
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;
1676 }else{
1677 n = iTest + 1;
1680 pRec->nField = n;
1681 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
1682 if( res<0 ){
1683 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
1684 iMin = iTest+1;
1685 }else if( res==0 && n<nField ){
1686 iLower = aSample[iSamp].anLt[n-1];
1687 iMin = iTest+1;
1688 res = -1;
1689 }else{
1690 iSample = iTest;
1691 iCol = n-1;
1693 }while( res && iMin<iSample );
1694 i = iSample / nField;
1696 #ifdef SQLITE_DEBUG
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 ){
1701 if( res==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
1709 }else{
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). */
1723 if( iCol>0 ){
1724 pRec->nField = iCol;
1725 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
1726 || pParse->db->mallocFailed || CORRUPT_DB );
1728 if( i>0 ){
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 */
1737 if( res==0 ){
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];
1742 }else{
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;
1749 }else{
1750 iUpper = aSample[i].anLt[iCol];
1753 if( iLower>=iUpper ){
1754 iGap = 0;
1755 }else{
1756 iGap = iUpper - iLower;
1758 if( roundUp ){
1759 iGap = (iGap*2)/3;
1760 }else{
1761 iGap = iGap/3;
1763 aStat[0] = iLower + iGap;
1764 aStat[1] = pIdx->aAvgEq[nField-1];
1767 /* Restore the pRec->nField value before returning. */
1768 pRec->nField = nField;
1769 return i;
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){
1785 LogEst nRet = nNew;
1786 if( pTerm ){
1787 if( pTerm->truthProb<=0 ){
1788 nRet += pTerm->truthProb;
1789 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
1790 nRet -= 20; assert( 20==sqlite3LogEst(4) );
1793 return nRet;
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];
1809 #endif
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
1825 ** by the caller.
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
1832 ** as follows:
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,
1838 ** U is set to N.
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
1843 ** is left as is.
1845 ** If an error occurs, an SQLite error code is returned. Otherwise,
1846 ** SQLITE_OK.
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;
1858 int nLower = -1;
1859 int nUpper = p->nSample+1;
1860 int rc = SQLITE_OK;
1861 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
1862 CollSeq *pColl;
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]);
1869 if( pLower ){
1870 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
1871 nLower = 0;
1873 if( pUpper && rc==SQLITE_OK ){
1874 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
1875 nUpper = p2 ? 0 : p->nSample;
1878 if( p1 || p2 ){
1879 int i;
1880 int nDiff;
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;
1903 *pbDone = 1;
1904 WHERETRACE(0x20, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
1905 nLower, nUpper, nAdjust*-1, pLoop->nOut));
1908 }else{
1909 assert( *pbDone==0 );
1912 sqlite3ValueFree(p1);
1913 sqlite3ValueFree(p2);
1914 sqlite3ValueFree(pVal);
1916 return rc;
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 < ? ...
1928 ** |_____| |_____|
1929 ** | |
1930 ** pLower pUpper
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 */
1967 int rc = SQLITE_OK;
1968 int nOut = pLoop->nOut;
1969 LogEst nNew;
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;
1980 tRowcnt a[2];
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 */
2008 if( pRec ){
2009 testcase( pRec->nField!=pBuilder->nRecValid );
2010 pRec->nField = pBuilder->nRecValid;
2012 /* Determine iLower and iUpper using ($P) only. */
2013 if( nEq==0 ){
2014 iLower = 0;
2015 iUpper = p->nRowEst0;
2016 }else{
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);
2020 iLower = a[0];
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). */
2034 if( pLower ){
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 ){
2039 tRowcnt iNew;
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;
2045 nOut--;
2046 pLower = 0;
2050 /* If possible, improve on the iUpper estimate using ($P:$U). */
2051 if( pUpper ){
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 ){
2056 tRowcnt iNew;
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;
2062 nOut--;
2063 pUpper = 0;
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) );
2077 }else{
2078 nNew = 10; assert( 10==sqlite3LogEst(2) );
2080 if( nNew<nOut ){
2081 nOut = nNew;
2083 WHERETRACE(0x20, ("STAT4 range scan: %u..%u est=%d\n",
2084 (u32)iLower, (u32)iUpper, nOut));
2086 }else{
2087 int bDone = 0;
2088 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2089 if( bDone ) return rc;
2092 #else
2093 UNUSED_PARAMETER(pParse);
2094 UNUSED_PARAMETER(pBuilder);
2095 assert( pLower || pUpper );
2096 #endif
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 ){
2108 nNew -= 20;
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));
2119 #endif
2120 pLoop->nOut = (LogEst)nOut;
2121 return rc;
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
2135 ** non-zero.
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 */
2153 int bOk;
2155 assert( nEq>=1 );
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 ){
2170 *pnRow = 1;
2171 return SQLITE_OK;
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]));
2183 *pnRow = a[1];
2185 return rc;
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
2199 ** non-zero.
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++){
2222 nEst = nRow0;
2223 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
2224 nRowEst += nEst;
2225 pBuilder->nRecValid = nRecValid;
2228 if( rc==SQLITE_OK ){
2229 if( nRowEst > (tRowcnt)nRow0 ) nRowEst = nRow0;
2230 *pnRow = nRowEst;
2231 WHERETRACE(0x20,("IN row estimate: est=%d\n", nRowEst));
2233 assert( pBuilder->nRecValid==nRecValid );
2234 return rc;
2236 #endif /* SQLITE_ENABLE_STAT4 */
2239 #ifdef WHERETRACE_ENABLED
2241 ** Print the content of a WhereTerm object
2243 void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
2244 if( pTerm==0 ){
2245 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
2246 }else{
2247 char zType[8];
2248 char zLeft[50];
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);
2261 }else{
2262 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
2264 sqlite3DebugPrintf(
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);
2283 #endif
2285 #ifdef WHERETRACE_ENABLED
2287 ** Show the complete content of a WhereClause
2289 void sqlite3WhereClausePrint(WhereClause *pWC){
2290 int i;
2291 for(i=0; i<pWC->nTerm; i++){
2292 sqlite3WhereTermPrint(&pWC->a[i], i);
2295 #endif
2297 #ifdef WHERETRACE_ENABLED
2299 ** Print a WhereLoop object for debugging purposes
2301 ** Format example:
2303 ** .--- Position in WHERE clause rSetup, rRun, nOut ---.
2304 ** | |
2305 ** | .--- selfMask nTerm ------. |
2306 ** | | | |
2307 ** | | .-- prereq Idx wsFlags----. | |
2308 ** | | | Name | | |
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){
2314 if( 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);
2324 }else{
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 ){
2329 const char *zName;
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--;
2334 zName += i;
2336 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
2337 }else{
2338 sqlite3DebugPrintf("%20s","");
2340 }else{
2341 char *z;
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);
2345 }else{
2346 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
2348 sqlite3DebugPrintf(" %-19s", z);
2349 sqlite3_free(z);
2351 if( p->wsFlags & WHERE_SKIPSCAN ){
2352 sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
2353 }else{
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 ){
2358 int i;
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){
2368 while( p ){
2369 sqlite3ShowWhereLoop(p);
2370 p = p->pNextLoop;
2373 #endif
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;
2381 p->nLTerm = 0;
2382 p->nLSlot = ArraySize(p->aLTermSpace);
2383 p->wsFlags = 0;
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);
2414 p->nLTerm = 0;
2415 p->wsFlags = 0;
2419 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
2421 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
2422 WhereTerm **paNew;
2423 if( p->nLSlot>=n ) return SQLITE_OK;
2424 n = (n+7)&~7;
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);
2429 p->aLTerm = paNew;
2430 p->nLSlot = n;
2431 return SQLITE_OK;
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;
2452 return SQLITE_OK;
2456 ** Delete a WhereLoop object
2458 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
2459 assert( db!=0 );
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 );
2469 assert( db!=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.
2493 ** Case 1:
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
2500 ** Case 2:
2502 ** (2a) X has the same or lower cost, or returns the same or fewer rows,
2503 ** than Y.
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 */
2513 int i, j;
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
2553 ** also used by Y.
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
2562 ** subset p. */
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(
2597 WhereLoop **ppPrev,
2598 const WhereLoop *pTemplate
2600 WhereLoop *p;
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. */
2606 continue;
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
2628 break;
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 */
2657 return ppPrev;
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;
2688 int rc;
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;
2694 return SQLITE_DONE;
2696 pBuilder->iPlanLimit--;
2698 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
2700 /* If pBuilder->pOrSet is defined, then only keep track of the costs
2701 ** and prereqs.
2703 if( pBuilder->pOrSet!=0 ){
2704 if( pTemplate->nLTerm ){
2705 #if WHERETRACE_ENABLED
2706 u16 n = pBuilder->pOrSet->n;
2707 int x =
2708 #endif
2709 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
2710 pTemplate->nOut);
2711 #if WHERETRACE_ENABLED /* 0x8 */
2712 if( sqlite3WhereTrace & 0x8 ){
2713 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
2714 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2716 #endif
2718 return SQLITE_OK;
2721 /* Look for an existing WhereLoop to replace with pTemplate
2723 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
2725 if( ppPrev==0 ){
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);
2733 #endif
2734 return SQLITE_OK;
2735 }else{
2736 p = *ppPrev;
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 ){
2745 if( p!=0 ){
2746 sqlite3DebugPrintf("replace: ");
2747 sqlite3WhereLoopPrint(p, pBuilder->pWC);
2748 sqlite3DebugPrintf(" with: ");
2749 }else{
2750 sqlite3DebugPrintf(" add: ");
2752 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2754 #endif
2755 if( p==0 ){
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;
2759 whereLoopInit(p);
2760 p->pNextLoop = 0;
2761 }else{
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;
2766 WhereLoop *pToDel;
2767 while( *ppTail ){
2768 ppTail = whereLoopFindLesser(ppTail, pTemplate);
2769 if( ppTail==0 ) break;
2770 pToDel = *ppTail;
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);
2778 #endif
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;
2789 return rc;
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
2795 ** index.
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);
2828 int i, j;
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++){
2833 assert( pTerm!=0 );
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;
2843 if( j<0 ){
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
2849 ** "self-culling".
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;
2866 }else{
2867 /* In the absence of explicit truth probabilities, use heuristics to
2868 ** guess a reasonable truth probability. */
2869 pLoop->nOut--;
2870 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
2871 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */
2873 Expr *pRight = pTerm->pExpr->pRight;
2874 int k = 0;
2875 testcase( pTerm->pExpr->op==TK_IS );
2876 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
2877 k = 10;
2878 }else{
2879 k = 20;
2881 if( iReduce<k ){
2882 pTerm->wtFlags |= TERM_HEURTRUTH;
2883 iReduce = k;
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) > (?, ?, ?)
2904 ** and the index:
2906 ** CREATE INDEX ... ON (a, b, c, d, e)
2908 ** then this function would be invoked with nEq=1. The value returned in
2909 ** this case is 3.
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);
2919 int i;
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 */
2928 Expr *pLhs, *pRhs;
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;
2935 }else{
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]
2948 break;
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;
2960 return i;
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
2969 #else
2970 # define ApplyCostMultiplier(C,T)
2971 #endif
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 );
3013 if( pParse->nErr ){
3014 return pParse->rc;
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;
3024 }else{
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,
3048 opMask, pProbe);
3049 pNew->rSetup = 0;
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 */
3054 LogEst rCostIdx;
3055 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
3056 int nIn = 0;
3057 #ifdef SQLITE_ENABLE_STAT4
3058 int nRecValid = pBuilder->nRecValid;
3059 #endif
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)
3074 continue;
3076 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
3077 pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
3078 }else{
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;
3094 assert( nInMul==0
3095 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
3096 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
3097 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
3100 if( eOp & WO_IN ){
3101 Expr *pExpr = pTerm->pExpr;
3102 if( ExprUseXSelect(pExpr) ){
3103 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
3104 int i;
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 ){
3120 LogEst M, logK, x;
3121 /* Let:
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];
3142 logK = estLog(nIn);
3143 /* TUNING v----- 10 to bias toward indexed IN */
3144 x = M + logK + 10 - (nIn + rLogSize);
3145 if( x>=0 ){
3146 WHERETRACE(0x40,
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) ){
3151 WHERETRACE(0x40,
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;
3156 }else{
3157 WHERETRACE(0x40,
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));
3161 continue;
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 );
3169 if( iCol==XN_ROWID
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;
3176 }else{
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;
3183 }else{
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;
3192 pBtm = pTerm;
3193 pTop = 0;
3194 if( pTerm->wtFlags & TERM_LIKEOPT ){
3195 /* Range constraints that come from the LIKE optimization are
3196 ** always used in pairs. */
3197 pTop = &pTerm[1];
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;
3206 }else{
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;
3212 pTop = pTerm;
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);
3228 }else{
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;
3237 pNew->nOut -= nIn;
3238 }else{
3239 #ifdef SQLITE_ENABLE_STAT4
3240 tRowcnt nOut = 0;
3241 if( nInMul==0
3242 && pProbe->nSample
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);
3253 }else{
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 */
3258 if( nOut ){
3259 pNew->nOut = sqlite3LogEst(nOut);
3260 if( nEq==1
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 ){
3268 sqlite3DebugPrintf(
3269 "STAT4 determines term has low selectivity:\n");
3270 sqlite3WhereTermPrint(pTerm, 999);
3272 #endif
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;
3282 pNew->nOut -= nIn;
3285 if( nOut==0 )
3286 #endif
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
3292 ** as (col=?). */
3293 pNew->nOut += 10;
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
3302 ** entry
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;
3313 }else{
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;
3338 }else{
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;
3355 #endif
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
3386 LogEst nIter;
3387 pNew->u.btree.nEq++;
3388 pNew->nSkip++;
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. */
3395 nIter += 5;
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));
3405 return 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
3414 ** ORDER BY clause.
3416 static int indexMightHelpWithOrderBy(
3417 WhereLoopBuilder *pBuilder,
3418 Index *pIndex,
3419 int iCursor
3421 ExprList *pOB;
3422 ExprList *aColExpr;
3423 int ii, jj;
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 ){
3441 return 1;
3446 return 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 */
3458 int i;
3459 WhereTerm *pTerm;
3460 Parse *pParse;
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++){
3470 Expr *pExpr;
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
3477 return 1;
3480 return 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(
3488 const Expr *pExpr,
3489 const Index *pIdx,
3490 int iTabCur
3492 int i;
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
3497 return 1;
3500 return 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;
3539 pIdx = pCk->pIdx;
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;
3549 pCk->bUnidx = 1;
3550 return WRC_Abort;
3551 }else if( pIdx->bHasExpr
3552 && exprIsCoveredByIndex(pExpr, pIdx, pWalk->u.pCovIdxCk->iTabCur) ){
3553 pCk->bExpr = 1;
3554 return WRC_Prune;
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 */
3588 int i, rc;
3589 struct CoveringIndexCheck ck;
3590 Walker w;
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. */
3594 return 0;
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 */
3604 return 0;
3607 ck.pIdx = pIdx;
3608 ck.iTabCur = iTabCur;
3609 ck.bExpr = 0;
3610 ck.bUnidx = 0;
3611 memset(&w, 0, sizeof(w));
3612 w.xExprCallback = whereIsCoveringIndexWalkCallback;
3613 w.xSelectCallback = sqlite3SelectWalkNoop;
3614 w.u.pCovIdxCk = &ck;
3615 sqlite3WalkSelect(&w, pWInfo->pSelect);
3616 if( ck.bUnidx ){
3617 rc = 0;
3618 }else if( ck.bExpr ){
3619 rc = WHERE_EXPRIDX;
3620 }else{
3621 rc = WHERE_IDX_ONLY;
3623 return rc;
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;
3632 while( *pp!=0 ){
3633 IndexedExpr *p = *pp;
3634 *pp = p->pIENext;
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
3645 ** SELECT:
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
3660 ** above.
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
3665 ** by a constant.
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;
3686 u8 aff;
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 ){
3694 if( pItem ){
3695 sqlite3 *db = pParse->db;
3696 IndexedExpr *p = (IndexedExpr*)sqlite3DbMallocRaw(db, sizeof(*p));
3697 if( 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;
3705 p->aff = aff;
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;
3779 pTab = pSrc->pTab;
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;
3789 }else{
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));
3796 sPk.nKeyCol = 1;
3797 sPk.nColumn = 1;
3798 sPk.aiColumn = &aiColumnPk;
3799 sPk.aiRowLogEst = aiRowEstPk;
3800 sPk.onError = OE_Replace;
3801 sPk.pTable = pTab;
3802 sPk.szIdxRow = 3; /* TUNING: Interior rows of IPK table are very small */
3803 sPk.idxType = SQLITE_IDXTYPE_IPK;
3804 aiRowEstPk[0] = pTab->nRowLogEst;
3805 aiRowEstPk[1] = 0;
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 */
3810 sPk.pNext = pFirst;
3812 pProbe = &sPk;
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 */
3830 WhereTerm *pTerm;
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;
3837 pNew->nSkip = 0;
3838 pNew->u.btree.pIndex = 0;
3839 pNew->nLTerm = 1;
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 ){
3851 pNew->rSetup += 28;
3852 }else{
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;
3889 pNew->nSkip = 0;
3890 pNew->nLTerm = 0;
3891 pNew->iSortIdx = 0;
3892 pNew->rSetup = 0;
3893 pNew->prereq = mPrereq;
3894 pNew->nOut = rSize;
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
3916 ** better.
3918 #ifdef SQLITE_ENABLE_STAT4
3919 pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
3920 #else
3921 pNew->rRun = rSize + 16;
3922 #endif
3923 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3924 whereLoopOutputAdjust(pWC, pNew, rSize);
3925 rc = whereLoopInsert(pBuilder, pNew);
3926 pNew->nOut = rSize;
3927 if( rc ) break;
3928 }else{
3929 Bitmask m;
3930 if( pProbe->isCovering ){
3931 m = 0;
3932 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3933 }else{
3934 m = pSrc->colUsed & pProbe->colNotIdxed;
3935 if( pProbe->pPartIdxWhere ){
3936 wherePartIdxExpr(
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);
3943 if( isCov==0 ){
3944 WHERETRACE(0x200,
3945 ("-> %s is not a covering index"
3946 " according to whereIsCoveringIndex()\n", pProbe->zName));
3947 assert( m!=0 );
3948 }else{
3949 m = 0;
3950 pNew->wsFlags |= isCov;
3951 if( isCov & WHERE_IDX_ONLY ){
3952 WHERETRACE(0x200,
3953 ("-> %s is a covering expression index"
3954 " according to whereIsCoveringIndex()\n", pProbe->zName));
3955 }else{
3956 assert( isCov==WHERE_EXPRIDX );
3957 WHERETRACE(0x200,
3958 ("-> %s might be a covering expression index"
3959 " according to whereIsCoveringIndex()\n", pProbe->zName));
3962 }else if( m==0 ){
3963 WHERETRACE(0x200,
3964 ("-> %s a covering index according to bitmasks\n",
3965 pProbe->zName, m==0 ? "is" : "is not"));
3966 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3970 /* Full scan via index */
3971 if( b
3972 || !HasRowid(pTab)
3973 || pProbe->pPartIdxWhere!=0
3974 || pSrc->fg.isIndexedBy
3975 || ( m==0
3976 && pProbe->bUnordered==0
3977 && (pProbe->szIdxRow<pTab->szTabRow)
3978 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3979 && sqlite3GlobalConfig.bUseCis
3980 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
3983 pNew->iSortIdx = b ? iSortIdx : 0;
3985 /* The cost of visiting the index rows is N*K, where K is
3986 ** between 1.1 and 3.0, depending on the relative sizes of the
3987 ** index and table rows. */
3988 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
3989 if( m!=0 ){
3990 /* If this is a non-covering index scan, add in the cost of
3991 ** doing table lookups. The cost will be 3x the number of
3992 ** lookups. Take into account WHERE clause terms that can be
3993 ** satisfied using just the index, and that do not require a
3994 ** table lookup. */
3995 LogEst nLookup = rSize + 16; /* Base cost: N*3 */
3996 int ii;
3997 int iCur = pSrc->iCursor;
3998 WhereClause *pWC2 = &pWInfo->sWC;
3999 for(ii=0; ii<pWC2->nTerm; ii++){
4000 WhereTerm *pTerm = &pWC2->a[ii];
4001 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
4002 break;
4004 /* pTerm can be evaluated using just the index. So reduce
4005 ** the expected number of table lookups accordingly */
4006 if( pTerm->truthProb<=0 ){
4007 nLookup += pTerm->truthProb;
4008 }else{
4009 nLookup--;
4010 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
4014 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
4016 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
4017 whereLoopOutputAdjust(pWC, pNew, rSize);
4018 if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){
4019 /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
4020 ** because the cursor used to access the index might not be
4021 ** positioned to the correct row during the right-join no-match
4022 ** loop. */
4023 }else{
4024 rc = whereLoopInsert(pBuilder, pNew);
4026 pNew->nOut = rSize;
4027 if( rc ) break;
4031 pBuilder->bldFlags1 = 0;
4032 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
4033 if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
4034 /* If a non-unique index is used, or if a prefix of the key for
4035 ** unique index is used (making the index functionally non-unique)
4036 ** then the sqlite_stat1 data becomes important for scoring the
4037 ** plan */
4038 pTab->tabFlags |= TF_MaybeReanalyze;
4040 #ifdef SQLITE_ENABLE_STAT4
4041 sqlite3Stat4ProbeFree(pBuilder->pRec);
4042 pBuilder->nRecValid = 0;
4043 pBuilder->pRec = 0;
4044 #endif
4046 return rc;
4049 #ifndef SQLITE_OMIT_VIRTUALTABLE
4052 ** Return true if pTerm is a virtual table LIMIT or OFFSET term.
4054 static int isLimitTerm(WhereTerm *pTerm){
4055 assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
4056 return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
4057 && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
4061 ** Return true if the first nCons constraints in the pUsage array are
4062 ** marked as in-use (have argvIndex>0). False otherwise.
4064 static int allConstraintsUsed(
4065 struct sqlite3_index_constraint_usage *aUsage,
4066 int nCons
4068 int ii;
4069 for(ii=0; ii<nCons; ii++){
4070 if( aUsage[ii].argvIndex<=0 ) return 0;
4072 return 1;
4076 ** Argument pIdxInfo is already populated with all constraints that may
4077 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
4078 ** function marks a subset of those constraints usable, invokes the
4079 ** xBestIndex method and adds the returned plan to pBuilder.
4081 ** A constraint is marked usable if:
4083 ** * Argument mUsable indicates that its prerequisites are available, and
4085 ** * It is not one of the operators specified in the mExclude mask passed
4086 ** as the fourth argument (which in practice is either WO_IN or 0).
4088 ** Argument mPrereq is a mask of tables that must be scanned before the
4089 ** virtual table in question. These are added to the plans prerequisites
4090 ** before it is added to pBuilder.
4092 ** Output parameter *pbIn is set to true if the plan added to pBuilder
4093 ** uses one or more WO_IN terms, or false otherwise.
4095 static int whereLoopAddVirtualOne(
4096 WhereLoopBuilder *pBuilder,
4097 Bitmask mPrereq, /* Mask of tables that must be used. */
4098 Bitmask mUsable, /* Mask of usable tables */
4099 u16 mExclude, /* Exclude terms using these operators */
4100 sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
4101 u16 mNoOmit, /* Do not omit these constraints */
4102 int *pbIn, /* OUT: True if plan uses an IN(...) op */
4103 int *pbRetryLimit /* OUT: Retry without LIMIT/OFFSET */
4105 WhereClause *pWC = pBuilder->pWC;
4106 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4107 struct sqlite3_index_constraint *pIdxCons;
4108 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
4109 int i;
4110 int mxTerm;
4111 int rc = SQLITE_OK;
4112 WhereLoop *pNew = pBuilder->pNew;
4113 Parse *pParse = pBuilder->pWInfo->pParse;
4114 SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
4115 int nConstraint = pIdxInfo->nConstraint;
4117 assert( (mUsable & mPrereq)==mPrereq );
4118 *pbIn = 0;
4119 pNew->prereq = mPrereq;
4121 /* Set the usable flag on the subset of constraints identified by
4122 ** arguments mUsable and mExclude. */
4123 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4124 for(i=0; i<nConstraint; i++, pIdxCons++){
4125 WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
4126 pIdxCons->usable = 0;
4127 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
4128 && (pTerm->eOperator & mExclude)==0
4129 && (pbRetryLimit || !isLimitTerm(pTerm))
4131 pIdxCons->usable = 1;
4135 /* Initialize the output fields of the sqlite3_index_info structure */
4136 memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
4137 assert( pIdxInfo->needToFreeIdxStr==0 );
4138 pIdxInfo->idxStr = 0;
4139 pIdxInfo->idxNum = 0;
4140 pIdxInfo->orderByConsumed = 0;
4141 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
4142 pIdxInfo->estimatedRows = 25;
4143 pIdxInfo->idxFlags = 0;
4144 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
4145 pHidden->mHandleIn = 0;
4147 /* Invoke the virtual table xBestIndex() method */
4148 rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
4149 if( rc ){
4150 if( rc==SQLITE_CONSTRAINT ){
4151 /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
4152 ** that the particular combination of parameters provided is unusable.
4153 ** Make no entries in the loop table.
4155 WHERETRACE(0xffffffff, (" ^^^^--- non-viable plan rejected!\n"));
4156 return SQLITE_OK;
4158 return rc;
4161 mxTerm = -1;
4162 assert( pNew->nLSlot>=nConstraint );
4163 memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
4164 memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
4165 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4166 for(i=0; i<nConstraint; i++, pIdxCons++){
4167 int iTerm;
4168 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4169 WhereTerm *pTerm;
4170 int j = pIdxCons->iTermOffset;
4171 if( iTerm>=nConstraint
4172 || j<0
4173 || j>=pWC->nTerm
4174 || pNew->aLTerm[iTerm]!=0
4175 || pIdxCons->usable==0
4177 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
4178 testcase( pIdxInfo->needToFreeIdxStr );
4179 return SQLITE_ERROR;
4181 testcase( iTerm==nConstraint-1 );
4182 testcase( j==0 );
4183 testcase( j==pWC->nTerm-1 );
4184 pTerm = &pWC->a[j];
4185 pNew->prereq |= pTerm->prereqRight;
4186 assert( iTerm<pNew->nLSlot );
4187 pNew->aLTerm[iTerm] = pTerm;
4188 if( iTerm>mxTerm ) mxTerm = iTerm;
4189 testcase( iTerm==15 );
4190 testcase( iTerm==16 );
4191 if( pUsage[i].omit ){
4192 if( i<16 && ((1<<i)&mNoOmit)==0 ){
4193 testcase( i!=iTerm );
4194 pNew->u.vtab.omitMask |= 1<<iTerm;
4195 }else{
4196 testcase( i!=iTerm );
4198 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
4199 pNew->u.vtab.bOmitOffset = 1;
4202 if( SMASKBIT32(i) & pHidden->mHandleIn ){
4203 pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
4204 }else if( (pTerm->eOperator & WO_IN)!=0 ){
4205 /* A virtual table that is constrained by an IN clause may not
4206 ** consume the ORDER BY clause because (1) the order of IN terms
4207 ** is not necessarily related to the order of output terms and
4208 ** (2) Multiple outputs from a single IN value will not merge
4209 ** together. */
4210 pIdxInfo->orderByConsumed = 0;
4211 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
4212 *pbIn = 1; assert( (mExclude & WO_IN)==0 );
4215 /* Unless pbRetryLimit is non-NULL, there should be no LIMIT/OFFSET
4216 ** terms. And if there are any, they should follow all other terms. */
4217 assert( pbRetryLimit || !isLimitTerm(pTerm) );
4218 assert( !isLimitTerm(pTerm) || i>=nConstraint-2 );
4219 assert( !isLimitTerm(pTerm) || i==nConstraint-1 || isLimitTerm(pTerm+1) );
4221 if( isLimitTerm(pTerm) && (*pbIn || !allConstraintsUsed(pUsage, i)) ){
4222 /* If there is an IN(...) term handled as an == (separate call to
4223 ** xFilter for each value on the RHS of the IN) and a LIMIT or
4224 ** OFFSET term handled as well, the plan is unusable. Similarly,
4225 ** if there is a LIMIT/OFFSET and there are other unused terms,
4226 ** the plan cannot be used. In these cases set variable *pbRetryLimit
4227 ** to true to tell the caller to retry with LIMIT and OFFSET
4228 ** disabled. */
4229 if( pIdxInfo->needToFreeIdxStr ){
4230 sqlite3_free(pIdxInfo->idxStr);
4231 pIdxInfo->idxStr = 0;
4232 pIdxInfo->needToFreeIdxStr = 0;
4234 *pbRetryLimit = 1;
4235 return SQLITE_OK;
4240 pNew->nLTerm = mxTerm+1;
4241 for(i=0; i<=mxTerm; i++){
4242 if( pNew->aLTerm[i]==0 ){
4243 /* The non-zero argvIdx values must be contiguous. Raise an
4244 ** error if they are not */
4245 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
4246 testcase( pIdxInfo->needToFreeIdxStr );
4247 return SQLITE_ERROR;
4250 assert( pNew->nLTerm<=pNew->nLSlot );
4251 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4252 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4253 pIdxInfo->needToFreeIdxStr = 0;
4254 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
4255 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
4256 pIdxInfo->nOrderBy : 0);
4257 pNew->rSetup = 0;
4258 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
4259 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
4261 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
4262 ** that the scan will visit at most one row. Clear it otherwise. */
4263 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
4264 pNew->wsFlags |= WHERE_ONEROW;
4265 }else{
4266 pNew->wsFlags &= ~WHERE_ONEROW;
4268 rc = whereLoopInsert(pBuilder, pNew);
4269 if( pNew->u.vtab.needFree ){
4270 sqlite3_free(pNew->u.vtab.idxStr);
4271 pNew->u.vtab.needFree = 0;
4273 WHERETRACE(0xffffffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
4274 *pbIn, (sqlite3_uint64)mPrereq,
4275 (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
4277 return rc;
4281 ** Return the collating sequence for a constraint passed into xBestIndex.
4283 ** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
4284 ** This routine depends on there being a HiddenIndexInfo structure immediately
4285 ** following the sqlite3_index_info structure.
4287 ** Return a pointer to the collation name:
4289 ** 1. If there is an explicit COLLATE operator on the constraint, return it.
4291 ** 2. Else, if the column has an alternative collation, return that.
4293 ** 3. Otherwise, return "BINARY".
4295 const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
4296 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4297 const char *zRet = 0;
4298 if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
4299 CollSeq *pC = 0;
4300 int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
4301 Expr *pX = pHidden->pWC->a[iTerm].pExpr;
4302 if( pX->pLeft ){
4303 pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
4305 zRet = (pC ? pC->zName : sqlite3StrBINARY);
4307 return zRet;
4311 ** Return true if constraint iCons is really an IN(...) constraint, or
4312 ** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
4313 ** or clear (if bHandle==0) the flag to handle it using an iterator.
4315 int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){
4316 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4317 u32 m = SMASKBIT32(iCons);
4318 if( m & pHidden->mIn ){
4319 if( bHandle==0 ){
4320 pHidden->mHandleIn &= ~m;
4321 }else if( bHandle>0 ){
4322 pHidden->mHandleIn |= m;
4324 return 1;
4326 return 0;
4330 ** This interface is callable from within the xBestIndex callback only.
4332 ** If possible, set (*ppVal) to point to an object containing the value
4333 ** on the right-hand-side of constraint iCons.
4335 int sqlite3_vtab_rhs_value(
4336 sqlite3_index_info *pIdxInfo, /* Copy of first argument to xBestIndex */
4337 int iCons, /* Constraint for which RHS is wanted */
4338 sqlite3_value **ppVal /* Write value extracted here */
4340 HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
4341 sqlite3_value *pVal = 0;
4342 int rc = SQLITE_OK;
4343 if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
4344 rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */
4345 }else{
4346 if( pH->aRhs[iCons]==0 ){
4347 WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
4348 rc = sqlite3ValueFromExpr(
4349 pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
4350 SQLITE_AFF_BLOB, &pH->aRhs[iCons]
4352 testcase( rc!=SQLITE_OK );
4354 pVal = pH->aRhs[iCons];
4356 *ppVal = pVal;
4358 if( rc==SQLITE_OK && pVal==0 ){ /* IMP: R-19933-32160 */
4359 rc = SQLITE_NOTFOUND; /* IMP: R-36424-56542 */
4362 return rc;
4366 ** Return true if ORDER BY clause may be handled as DISTINCT.
4368 int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
4369 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4370 assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
4371 return pHidden->eDistinct;
4375 ** Cause the prepared statement that is associated with a call to
4376 ** xBestIndex to potentially use all schemas. If the statement being
4377 ** prepared is read-only, then just start read transactions on all
4378 ** schemas. But if this is a write operation, start writes on all
4379 ** schemas.
4381 ** This is used by the (built-in) sqlite_dbpage virtual table.
4383 void sqlite3VtabUsesAllSchemas(Parse *pParse){
4384 int nDb = pParse->db->nDb;
4385 int i;
4386 for(i=0; i<nDb; i++){
4387 sqlite3CodeVerifySchema(pParse, i);
4389 if( DbMaskNonZero(pParse->writeMask) ){
4390 for(i=0; i<nDb; i++){
4391 sqlite3BeginWriteOperation(pParse, 0, i);
4397 ** Add all WhereLoop objects for a table of the join identified by
4398 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
4400 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
4401 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
4402 ** entries that occur before the virtual table in the FROM clause and are
4403 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
4404 ** mUnusable mask contains all FROM clause entries that occur after the
4405 ** virtual table and are separated from it by at least one LEFT or
4406 ** CROSS JOIN.
4408 ** For example, if the query were:
4410 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
4412 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
4414 ** All the tables in mPrereq must be scanned before the current virtual
4415 ** table. So any terms for which all prerequisites are satisfied by
4416 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
4417 ** Conversely, all tables in mUnusable must be scanned after the current
4418 ** virtual table, so any terms for which the prerequisites overlap with
4419 ** mUnusable should always be configured as "not-usable" for xBestIndex.
4421 static int whereLoopAddVirtual(
4422 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4423 Bitmask mPrereq, /* Tables that must be scanned before this one */
4424 Bitmask mUnusable /* Tables that must be scanned after this one */
4426 int rc = SQLITE_OK; /* Return code */
4427 WhereInfo *pWInfo; /* WHERE analysis context */
4428 Parse *pParse; /* The parsing context */
4429 WhereClause *pWC; /* The WHERE clause */
4430 SrcItem *pSrc; /* The FROM clause term to search */
4431 sqlite3_index_info *p; /* Object to pass to xBestIndex() */
4432 int nConstraint; /* Number of constraints in p */
4433 int bIn; /* True if plan uses IN(...) operator */
4434 WhereLoop *pNew;
4435 Bitmask mBest; /* Tables used by best possible plan */
4436 u16 mNoOmit;
4437 int bRetry = 0; /* True to retry with LIMIT/OFFSET disabled */
4439 assert( (mPrereq & mUnusable)==0 );
4440 pWInfo = pBuilder->pWInfo;
4441 pParse = pWInfo->pParse;
4442 pWC = pBuilder->pWC;
4443 pNew = pBuilder->pNew;
4444 pSrc = &pWInfo->pTabList->a[pNew->iTab];
4445 assert( IsVirtual(pSrc->pTab) );
4446 p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit);
4447 if( p==0 ) return SQLITE_NOMEM_BKPT;
4448 pNew->rSetup = 0;
4449 pNew->wsFlags = WHERE_VIRTUALTABLE;
4450 pNew->nLTerm = 0;
4451 pNew->u.vtab.needFree = 0;
4452 nConstraint = p->nConstraint;
4453 if( whereLoopResize(pParse->db, pNew, nConstraint) ){
4454 freeIndexInfo(pParse->db, p);
4455 return SQLITE_NOMEM_BKPT;
4458 /* First call xBestIndex() with all constraints usable. */
4459 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
4460 WHERETRACE(0x800, (" VirtualOne: all usable\n"));
4461 rc = whereLoopAddVirtualOne(
4462 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry
4464 if( bRetry ){
4465 assert( rc==SQLITE_OK );
4466 rc = whereLoopAddVirtualOne(
4467 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0
4471 /* If the call to xBestIndex() with all terms enabled produced a plan
4472 ** that does not require any source tables (IOW: a plan with mBest==0)
4473 ** and does not use an IN(...) operator, then there is no point in making
4474 ** any further calls to xBestIndex() since they will all return the same
4475 ** result (if the xBestIndex() implementation is sane). */
4476 if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
4477 int seenZero = 0; /* True if a plan with no prereqs seen */
4478 int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
4479 Bitmask mPrev = 0;
4480 Bitmask mBestNoIn = 0;
4482 /* If the plan produced by the earlier call uses an IN(...) term, call
4483 ** xBestIndex again, this time with IN(...) terms disabled. */
4484 if( bIn ){
4485 WHERETRACE(0x800, (" VirtualOne: all usable w/o IN\n"));
4486 rc = whereLoopAddVirtualOne(
4487 pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0);
4488 assert( bIn==0 );
4489 mBestNoIn = pNew->prereq & ~mPrereq;
4490 if( mBestNoIn==0 ){
4491 seenZero = 1;
4492 seenZeroNoIN = 1;
4496 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
4497 ** in the set of terms that apply to the current virtual table. */
4498 while( rc==SQLITE_OK ){
4499 int i;
4500 Bitmask mNext = ALLBITS;
4501 assert( mNext>0 );
4502 for(i=0; i<nConstraint; i++){
4503 Bitmask mThis = (
4504 pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
4506 if( mThis>mPrev && mThis<mNext ) mNext = mThis;
4508 mPrev = mNext;
4509 if( mNext==ALLBITS ) break;
4510 if( mNext==mBest || mNext==mBestNoIn ) continue;
4511 WHERETRACE(0x800, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
4512 (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
4513 rc = whereLoopAddVirtualOne(
4514 pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn, 0);
4515 if( pNew->prereq==mPrereq ){
4516 seenZero = 1;
4517 if( bIn==0 ) seenZeroNoIN = 1;
4521 /* If the calls to xBestIndex() in the above loop did not find a plan
4522 ** that requires no source tables at all (i.e. one guaranteed to be
4523 ** usable), make a call here with all source tables disabled */
4524 if( rc==SQLITE_OK && seenZero==0 ){
4525 WHERETRACE(0x800, (" VirtualOne: all disabled\n"));
4526 rc = whereLoopAddVirtualOne(
4527 pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0);
4528 if( bIn==0 ) seenZeroNoIN = 1;
4531 /* If the calls to xBestIndex() have so far failed to find a plan
4532 ** that requires no source tables at all and does not use an IN(...)
4533 ** operator, make a final call to obtain one here. */
4534 if( rc==SQLITE_OK && seenZeroNoIN==0 ){
4535 WHERETRACE(0x800, (" VirtualOne: all disabled and w/o IN\n"));
4536 rc = whereLoopAddVirtualOne(
4537 pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
4541 if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
4542 freeIndexInfo(pParse->db, p);
4543 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
4544 return rc;
4546 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4549 ** Add WhereLoop entries to handle OR terms. This works for either
4550 ** btrees or virtual tables.
4552 static int whereLoopAddOr(
4553 WhereLoopBuilder *pBuilder,
4554 Bitmask mPrereq,
4555 Bitmask mUnusable
4557 WhereInfo *pWInfo = pBuilder->pWInfo;
4558 WhereClause *pWC;
4559 WhereLoop *pNew;
4560 WhereTerm *pTerm, *pWCEnd;
4561 int rc = SQLITE_OK;
4562 int iCur;
4563 WhereClause tempWC;
4564 WhereLoopBuilder sSubBuild;
4565 WhereOrSet sSum, sCur;
4566 SrcItem *pItem;
4568 pWC = pBuilder->pWC;
4569 pWCEnd = pWC->a + pWC->nTerm;
4570 pNew = pBuilder->pNew;
4571 memset(&sSum, 0, sizeof(sSum));
4572 pItem = pWInfo->pTabList->a + pNew->iTab;
4573 iCur = pItem->iCursor;
4575 /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
4576 if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK;
4578 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4579 if( (pTerm->eOperator & WO_OR)!=0
4580 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4582 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4583 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4584 WhereTerm *pOrTerm;
4585 int once = 1;
4586 int i, j;
4588 sSubBuild = *pBuilder;
4589 sSubBuild.pOrSet = &sCur;
4591 WHERETRACE(0x400, ("Begin processing OR-clause %p\n", pTerm));
4592 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
4593 if( (pOrTerm->eOperator & WO_AND)!=0 ){
4594 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4595 }else if( pOrTerm->leftCursor==iCur ){
4596 tempWC.pWInfo = pWC->pWInfo;
4597 tempWC.pOuter = pWC;
4598 tempWC.op = TK_AND;
4599 tempWC.nTerm = 1;
4600 tempWC.nBase = 1;
4601 tempWC.a = pOrTerm;
4602 sSubBuild.pWC = &tempWC;
4603 }else{
4604 continue;
4606 sCur.n = 0;
4607 #ifdef WHERETRACE_ENABLED
4608 WHERETRACE(0x400, ("OR-term %d of %p has %d subterms:\n",
4609 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
4610 if( sqlite3WhereTrace & 0x20000 ){
4611 sqlite3WhereClausePrint(sSubBuild.pWC);
4613 #endif
4614 #ifndef SQLITE_OMIT_VIRTUALTABLE
4615 if( IsVirtual(pItem->pTab) ){
4616 rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
4617 }else
4618 #endif
4620 rc = whereLoopAddBtree(&sSubBuild, mPrereq);
4622 if( rc==SQLITE_OK ){
4623 rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
4625 testcase( rc==SQLITE_NOMEM && sCur.n>0 );
4626 testcase( rc==SQLITE_DONE );
4627 if( sCur.n==0 ){
4628 sSum.n = 0;
4629 break;
4630 }else if( once ){
4631 whereOrMove(&sSum, &sCur);
4632 once = 0;
4633 }else{
4634 WhereOrSet sPrev;
4635 whereOrMove(&sPrev, &sSum);
4636 sSum.n = 0;
4637 for(i=0; i<sPrev.n; i++){
4638 for(j=0; j<sCur.n; j++){
4639 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4640 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4641 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4646 pNew->nLTerm = 1;
4647 pNew->aLTerm[0] = pTerm;
4648 pNew->wsFlags = WHERE_MULTI_OR;
4649 pNew->rSetup = 0;
4650 pNew->iSortIdx = 0;
4651 memset(&pNew->u, 0, sizeof(pNew->u));
4652 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
4653 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
4654 ** of all sub-scans required by the OR-scan. However, due to rounding
4655 ** errors, it may be that the cost of the OR-scan is equal to its
4656 ** most expensive sub-scan. Add the smallest possible penalty
4657 ** (equivalent to multiplying the cost by 1.07) to ensure that
4658 ** this does not happen. Otherwise, for WHERE clauses such as the
4659 ** following where there is an index on "y":
4661 ** WHERE likelihood(x=?, 0.99) OR y=?
4663 ** the planner may elect to "OR" together a full-table scan and an
4664 ** index lookup. And other similarly odd results. */
4665 pNew->rRun = sSum.a[i].rRun + 1;
4666 pNew->nOut = sSum.a[i].nOut;
4667 pNew->prereq = sSum.a[i].prereq;
4668 rc = whereLoopInsert(pBuilder, pNew);
4670 WHERETRACE(0x400, ("End processing OR-clause %p\n", pTerm));
4673 return rc;
4677 ** Add all WhereLoop objects for all tables
4679 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
4680 WhereInfo *pWInfo = pBuilder->pWInfo;
4681 Bitmask mPrereq = 0;
4682 Bitmask mPrior = 0;
4683 int iTab;
4684 SrcList *pTabList = pWInfo->pTabList;
4685 SrcItem *pItem;
4686 SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
4687 sqlite3 *db = pWInfo->pParse->db;
4688 int rc = SQLITE_OK;
4689 int bFirstPastRJ = 0;
4690 int hasRightJoin = 0;
4691 WhereLoop *pNew;
4694 /* Loop over the tables in the join, from left to right */
4695 pNew = pBuilder->pNew;
4697 /* Verify that pNew has already been initialized */
4698 assert( pNew->nLTerm==0 );
4699 assert( pNew->wsFlags==0 );
4700 assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) );
4701 assert( pNew->aLTerm!=0 );
4703 pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
4704 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
4705 Bitmask mUnusable = 0;
4706 pNew->iTab = iTab;
4707 pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
4708 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
4709 if( bFirstPastRJ
4710 || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0
4712 /* Add prerequisites to prevent reordering of FROM clause terms
4713 ** across CROSS joins and outer joins. The bFirstPastRJ boolean
4714 ** prevents the right operand of a RIGHT JOIN from being swapped with
4715 ** other elements even further to the right.
4717 ** The JT_LTORJ case and the hasRightJoin flag work together to
4718 ** prevent FROM-clause terms from moving from the right side of
4719 ** a LEFT JOIN over to the left side of that join if the LEFT JOIN
4720 ** is itself on the left side of a RIGHT JOIN.
4722 if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1;
4723 mPrereq |= mPrior;
4724 bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0;
4725 }else if( !hasRightJoin ){
4726 mPrereq = 0;
4728 #ifndef SQLITE_OMIT_VIRTUALTABLE
4729 if( IsVirtual(pItem->pTab) ){
4730 SrcItem *p;
4731 for(p=&pItem[1]; p<pEnd; p++){
4732 if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
4733 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
4736 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
4737 }else
4738 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4740 rc = whereLoopAddBtree(pBuilder, mPrereq);
4742 if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
4743 rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
4745 mPrior |= pNew->maskSelf;
4746 if( rc || db->mallocFailed ){
4747 if( rc==SQLITE_DONE ){
4748 /* We hit the query planner search limit set by iPlanLimit */
4749 sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
4750 rc = SQLITE_OK;
4751 }else{
4752 break;
4757 whereLoopClear(db, pNew);
4758 return rc;
4762 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
4763 ** parameters) to see if it outputs rows in the requested ORDER BY
4764 ** (or GROUP BY) without requiring a separate sort operation. Return N:
4766 ** N>0: N terms of the ORDER BY clause are satisfied
4767 ** N==0: No terms of the ORDER BY clause are satisfied
4768 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
4770 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4771 ** strict. With GROUP BY and DISTINCT the only requirement is that
4772 ** equivalent rows appear immediately adjacent to one another. GROUP BY
4773 ** and DISTINCT do not require rows to appear in any particular order as long
4774 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
4775 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
4776 ** pOrderBy terms must be matched in strict left-to-right order.
4778 static i8 wherePathSatisfiesOrderBy(
4779 WhereInfo *pWInfo, /* The WHERE clause */
4780 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
4781 WherePath *pPath, /* The WherePath to check */
4782 u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
4783 u16 nLoop, /* Number of entries in pPath->aLoop[] */
4784 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
4785 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
4787 u8 revSet; /* True if rev is known */
4788 u8 rev; /* Composite sort order */
4789 u8 revIdx; /* Index sort order */
4790 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4791 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4792 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
4793 u16 eqOpMask; /* Allowed equality operators */
4794 u16 nKeyCol; /* Number of key columns in pIndex */
4795 u16 nColumn; /* Total number of ordered columns in the index */
4796 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4797 int iLoop; /* Index of WhereLoop in pPath being processed */
4798 int i, j; /* Loop counters */
4799 int iCur; /* Cursor number for current WhereLoop */
4800 int iColumn; /* A column number within table iCur */
4801 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
4802 WhereTerm *pTerm; /* A single term of the WHERE clause */
4803 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4804 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4805 Index *pIndex; /* The index associated with pLoop */
4806 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4807 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4808 Bitmask obDone; /* Mask of all ORDER BY terms */
4809 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
4810 Bitmask ready; /* Mask of inner loops */
4813 ** We say the WhereLoop is "one-row" if it generates no more than one
4814 ** row of output. A WhereLoop is one-row if all of the following are true:
4815 ** (a) All index columns match with WHERE_COLUMN_EQ.
4816 ** (b) The index is unique
4817 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4818 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
4820 ** We say the WhereLoop is "order-distinct" if the set of columns from
4821 ** that WhereLoop that are in the ORDER BY clause are different for every
4822 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4823 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4824 ** is not order-distinct. To be order-distinct is not quite the same as being
4825 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4826 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4827 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4829 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4830 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4831 ** automatically order-distinct.
4834 assert( pOrderBy!=0 );
4835 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
4837 nOrderBy = pOrderBy->nExpr;
4838 testcase( nOrderBy==BMS-1 );
4839 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4840 isOrderDistinct = 1;
4841 obDone = MASKBIT(nOrderBy)-1;
4842 orderDistinctMask = 0;
4843 ready = 0;
4844 eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
4845 if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
4846 eqOpMask |= WO_IN;
4848 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
4849 if( iLoop>0 ) ready |= pLoop->maskSelf;
4850 if( iLoop<nLoop ){
4851 pLoop = pPath->aLoop[iLoop];
4852 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
4853 }else{
4854 pLoop = pLast;
4856 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
4857 if( pLoop->u.vtab.isOrdered
4858 && ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY)
4860 obSat = obDone;
4862 break;
4863 }else if( wctrlFlags & WHERE_DISTINCTBY ){
4864 pLoop->u.btree.nDistinctCol = 0;
4866 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
4868 /* Mark off any ORDER BY term X that is a column in the table of
4869 ** the current loop for which there is term in the WHERE
4870 ** clause of the form X IS NULL or X=? that reference only outer
4871 ** loops.
4873 for(i=0; i<nOrderBy; i++){
4874 if( MASKBIT(i) & obSat ) continue;
4875 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4876 if( NEVER(pOBExpr==0) ) continue;
4877 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4878 if( pOBExpr->iTable!=iCur ) continue;
4879 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4880 ~ready, eqOpMask, 0);
4881 if( pTerm==0 ) continue;
4882 if( pTerm->eOperator==WO_IN ){
4883 /* IN terms are only valid for sorting in the ORDER BY LIMIT
4884 ** optimization, and then only if they are actually used
4885 ** by the query plan */
4886 assert( wctrlFlags &
4887 (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
4888 for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
4889 if( j>=pLoop->nLTerm ) continue;
4891 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
4892 Parse *pParse = pWInfo->pParse;
4893 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
4894 CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
4895 assert( pColl1 );
4896 if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
4897 continue;
4899 testcase( pTerm->pExpr->op==TK_IS );
4901 obSat |= MASKBIT(i);
4904 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4905 if( pLoop->wsFlags & WHERE_IPK ){
4906 pIndex = 0;
4907 nKeyCol = 0;
4908 nColumn = 1;
4909 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
4910 return 0;
4911 }else{
4912 nKeyCol = pIndex->nKeyCol;
4913 nColumn = pIndex->nColumn;
4914 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4915 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
4916 || !HasRowid(pIndex->pTable));
4917 /* All relevant terms of the index must also be non-NULL in order
4918 ** for isOrderDistinct to be true. So the isOrderDistint value
4919 ** computed here might be a false positive. Corrections will be
4920 ** made at tag-20210426-1 below */
4921 isOrderDistinct = IsUniqueIndex(pIndex)
4922 && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
4925 /* Loop through all columns of the index and deal with the ones
4926 ** that are not constrained by == or IN.
4928 rev = revSet = 0;
4929 distinctColumns = 0;
4930 for(j=0; j<nColumn; j++){
4931 u8 bOnce = 1; /* True to run the ORDER BY search loop */
4933 assert( j>=pLoop->u.btree.nEq
4934 || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
4936 if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
4937 u16 eOp = pLoop->aLTerm[j]->eOperator;
4939 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
4940 ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL
4941 ** terms imply that the index is not UNIQUE NOT NULL in which case
4942 ** the loop need to be marked as not order-distinct because it can
4943 ** have repeated NULL rows.
4945 ** If the current term is a column of an ((?,?) IN (SELECT...))
4946 ** expression for which the SELECT returns more than one column,
4947 ** check that it is the only column used by this loop. Otherwise,
4948 ** if it is one of two or more, none of the columns can be
4949 ** considered to match an ORDER BY term.
4951 if( (eOp & eqOpMask)!=0 ){
4952 if( eOp & (WO_ISNULL|WO_IS) ){
4953 testcase( eOp & WO_ISNULL );
4954 testcase( eOp & WO_IS );
4955 testcase( isOrderDistinct );
4956 isOrderDistinct = 0;
4958 continue;
4959 }else if( ALWAYS(eOp & WO_IN) ){
4960 /* ALWAYS() justification: eOp is an equality operator due to the
4961 ** j<pLoop->u.btree.nEq constraint above. Any equality other
4962 ** than WO_IN is captured by the previous "if". So this one
4963 ** always has to be WO_IN. */
4964 Expr *pX = pLoop->aLTerm[j]->pExpr;
4965 for(i=j+1; i<pLoop->u.btree.nEq; i++){
4966 if( pLoop->aLTerm[i]->pExpr==pX ){
4967 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
4968 bOnce = 0;
4969 break;
4975 /* Get the column number in the table (iColumn) and sort order
4976 ** (revIdx) for the j-th column of the index.
4978 if( pIndex ){
4979 iColumn = pIndex->aiColumn[j];
4980 revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
4981 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
4982 }else{
4983 iColumn = XN_ROWID;
4984 revIdx = 0;
4987 /* An unconstrained column that might be NULL means that this
4988 ** WhereLoop is not well-ordered. tag-20210426-1
4990 if( isOrderDistinct ){
4991 if( iColumn>=0
4992 && j>=pLoop->u.btree.nEq
4993 && pIndex->pTable->aCol[iColumn].notNull==0
4995 isOrderDistinct = 0;
4997 if( iColumn==XN_EXPR ){
4998 isOrderDistinct = 0;
5002 /* Find the ORDER BY term that corresponds to the j-th column
5003 ** of the index and mark that ORDER BY term off
5005 isMatch = 0;
5006 for(i=0; bOnce && i<nOrderBy; i++){
5007 if( MASKBIT(i) & obSat ) continue;
5008 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
5009 testcase( wctrlFlags & WHERE_GROUPBY );
5010 testcase( wctrlFlags & WHERE_DISTINCTBY );
5011 if( NEVER(pOBExpr==0) ) continue;
5012 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
5013 if( iColumn>=XN_ROWID ){
5014 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
5015 if( pOBExpr->iTable!=iCur ) continue;
5016 if( pOBExpr->iColumn!=iColumn ) continue;
5017 }else{
5018 Expr *pIxExpr = pIndex->aColExpr->a[j].pExpr;
5019 if( sqlite3ExprCompareSkip(pOBExpr, pIxExpr, iCur) ){
5020 continue;
5023 if( iColumn!=XN_ROWID ){
5024 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5025 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5027 if( wctrlFlags & WHERE_DISTINCTBY ){
5028 pLoop->u.btree.nDistinctCol = j+1;
5030 isMatch = 1;
5031 break;
5033 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
5034 /* Make sure the sort order is compatible in an ORDER BY clause.
5035 ** Sort order is irrelevant for a GROUP BY clause. */
5036 if( revSet ){
5037 if( (rev ^ revIdx)
5038 != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC)
5040 isMatch = 0;
5042 }else{
5043 rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC);
5044 if( rev ) *pRevMask |= MASKBIT(iLoop);
5045 revSet = 1;
5048 if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){
5049 if( j==pLoop->u.btree.nEq ){
5050 pLoop->wsFlags |= WHERE_BIGNULL_SORT;
5051 }else{
5052 isMatch = 0;
5055 if( isMatch ){
5056 if( iColumn==XN_ROWID ){
5057 testcase( distinctColumns==0 );
5058 distinctColumns = 1;
5060 obSat |= MASKBIT(i);
5061 }else{
5062 /* No match found */
5063 if( j==0 || j<nKeyCol ){
5064 testcase( isOrderDistinct!=0 );
5065 isOrderDistinct = 0;
5067 break;
5069 } /* end Loop over all index columns */
5070 if( distinctColumns ){
5071 testcase( isOrderDistinct==0 );
5072 isOrderDistinct = 1;
5074 } /* end-if not one-row */
5076 /* Mark off any other ORDER BY terms that reference pLoop */
5077 if( isOrderDistinct ){
5078 orderDistinctMask |= pLoop->maskSelf;
5079 for(i=0; i<nOrderBy; i++){
5080 Expr *p;
5081 Bitmask mTerm;
5082 if( MASKBIT(i) & obSat ) continue;
5083 p = pOrderBy->a[i].pExpr;
5084 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
5085 if( mTerm==0 && !sqlite3ExprIsConstant(0,p) ) continue;
5086 if( (mTerm&~orderDistinctMask)==0 ){
5087 obSat |= MASKBIT(i);
5091 } /* End the loop over all WhereLoops from outer-most down to inner-most */
5092 if( obSat==obDone ) return (i8)nOrderBy;
5093 if( !isOrderDistinct ){
5094 for(i=nOrderBy-1; i>0; i--){
5095 Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
5096 if( (obSat&m)==m ) return i;
5098 return 0;
5100 return -1;
5105 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
5106 ** the planner assumes that the specified pOrderBy list is actually a GROUP
5107 ** BY clause - and so any order that groups rows as required satisfies the
5108 ** request.
5110 ** Normally, in this case it is not possible for the caller to determine
5111 ** whether or not the rows are really being delivered in sorted order, or
5112 ** just in some other order that provides the required grouping. However,
5113 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
5114 ** this function may be called on the returned WhereInfo object. It returns
5115 ** true if the rows really will be sorted in the specified order, or false
5116 ** otherwise.
5118 ** For example, assuming:
5120 ** CREATE INDEX i1 ON t1(x, Y);
5122 ** then
5124 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
5125 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
5127 int sqlite3WhereIsSorted(WhereInfo *pWInfo){
5128 assert( pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) );
5129 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
5130 return pWInfo->sorted;
5133 #ifdef WHERETRACE_ENABLED
5134 /* For debugging use only: */
5135 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5136 static char zName[65];
5137 int i;
5138 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5139 if( pLast ) zName[i++] = pLast->cId;
5140 zName[i] = 0;
5141 return zName;
5143 #endif
5146 ** Return the cost of sorting nRow rows, assuming that the keys have
5147 ** nOrderby columns and that the first nSorted columns are already in
5148 ** order.
5150 static LogEst whereSortingCost(
5151 WhereInfo *pWInfo, /* Query planning context */
5152 LogEst nRow, /* Estimated number of rows to sort */
5153 int nOrderBy, /* Number of ORDER BY clause terms */
5154 int nSorted /* Number of initial ORDER BY terms naturally in order */
5156 /* Estimated cost of a full external sort, where N is
5157 ** the number of rows to sort is:
5159 ** cost = (K * N * log(N)).
5161 ** Or, if the order-by clause has X terms but only the last Y
5162 ** terms are out of order, then block-sorting will reduce the
5163 ** sorting cost to:
5165 ** cost = (K * N * log(N)) * (Y/X)
5167 ** The constant K is at least 2.0 but will be larger if there are a
5168 ** large number of columns to be sorted, as the sorting time is
5169 ** proportional to the amount of content to be sorted. The algorithm
5170 ** does not currently distinguish between fat columns (BLOBs and TEXTs)
5171 ** and skinny columns (INTs). It just uses the number of columns as
5172 ** an approximation for the row width.
5174 ** And extra factor of 2.0 or 3.0 is added to the sorting cost if the sort
5175 ** is built using OP_IdxInsert and OP_Sort rather than with OP_SorterInsert.
5177 LogEst rSortCost, nCol;
5178 assert( pWInfo->pSelect!=0 );
5179 assert( pWInfo->pSelect->pEList!=0 );
5180 /* TUNING: sorting cost proportional to the number of output columns: */
5181 nCol = sqlite3LogEst((pWInfo->pSelect->pEList->nExpr+59)/30);
5182 rSortCost = nRow + nCol;
5183 if( nSorted>0 ){
5184 /* Scale the result by (Y/X) */
5185 rSortCost += sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
5188 /* Multiple by log(M) where M is the number of output rows.
5189 ** Use the LIMIT for M if it is smaller. Or if this sort is for
5190 ** a DISTINCT operator, M will be the number of distinct output
5191 ** rows, so fudge it downwards a bit.
5193 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 ){
5194 rSortCost += 10; /* TUNING: Extra 2.0x if using LIMIT */
5195 if( nSorted!=0 ){
5196 rSortCost += 6; /* TUNING: Extra 1.5x if also using partial sort */
5198 if( pWInfo->iLimit<nRow ){
5199 nRow = pWInfo->iLimit;
5201 }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
5202 /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
5203 ** reduces the number of output rows by a factor of 2 */
5204 if( nRow>10 ){ nRow -= 10; assert( 10==sqlite3LogEst(2) ); }
5206 rSortCost += estLog(nRow);
5207 return rSortCost;
5211 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
5212 ** attempts to find the lowest cost path that visits each WhereLoop
5213 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5215 ** Assume that the total number of output rows that will need to be sorted
5216 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5217 ** costs if nRowEst==0.
5219 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5220 ** error occurs.
5222 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
5223 int mxChoice; /* Maximum number of simultaneous paths tracked */
5224 int nLoop; /* Number of terms in the join */
5225 Parse *pParse; /* Parsing context */
5226 int iLoop; /* Loop counter over the terms of the join */
5227 int ii, jj; /* Loop counters */
5228 int mxI = 0; /* Index of next entry to replace */
5229 int nOrderBy; /* Number of ORDER BY clause terms */
5230 LogEst mxCost = 0; /* Maximum cost of a set of paths */
5231 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
5232 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5233 WherePath *aFrom; /* All nFrom paths at the previous level */
5234 WherePath *aTo; /* The nTo best paths at the current level */
5235 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5236 WherePath *pTo; /* An element of aTo[] that we are working on */
5237 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5238 WhereLoop **pX; /* Used to divy up the pSpace memory */
5239 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
5240 char *pSpace; /* Temporary memory used by this routine */
5241 int nSpace; /* Bytes of space allocated at pSpace */
5243 pParse = pWInfo->pParse;
5244 nLoop = pWInfo->nLevel;
5245 /* TUNING: For simple queries, only the best path is tracked.
5246 ** For 2-way joins, the 5 best paths are followed.
5247 ** For joins of 3 or more tables, track the 10 best paths */
5248 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
5249 assert( nLoop<=pWInfo->pTabList->nSrc );
5250 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d, nQueryLoop=%d)\n",
5251 nRowEst, pParse->nQueryLoop));
5253 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5254 ** case the purpose of this call is to estimate the number of rows returned
5255 ** by the overall query. Once this estimate has been obtained, the caller
5256 ** will invoke this function a second time, passing the estimate as the
5257 ** nRowEst parameter. */
5258 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5259 nOrderBy = 0;
5260 }else{
5261 nOrderBy = pWInfo->pOrderBy->nExpr;
5264 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
5265 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5266 nSpace += sizeof(LogEst) * nOrderBy;
5267 pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace);
5268 if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
5269 aTo = (WherePath*)pSpace;
5270 aFrom = aTo+mxChoice;
5271 memset(aFrom, 0, sizeof(aFrom[0]));
5272 pX = (WhereLoop**)(aFrom+mxChoice);
5273 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
5274 pFrom->aLoop = pX;
5276 if( nOrderBy ){
5277 /* If there is an ORDER BY clause and it is not being ignored, set up
5278 ** space for the aSortCost[] array. Each element of the aSortCost array
5279 ** is either zero - meaning it has not yet been initialized - or the
5280 ** cost of sorting nRowEst rows of data where the first X terms of
5281 ** the ORDER BY clause are already in order, where X is the array
5282 ** index. */
5283 aSortCost = (LogEst*)pX;
5284 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
5286 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
5287 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
5289 /* Seed the search with a single WherePath containing zero WhereLoops.
5291 ** TUNING: Do not let the number of iterations go above 28. If the cost
5292 ** of computing an automatic index is not paid back within the first 28
5293 ** rows, then do not use the automatic index. */
5294 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
5295 nFrom = 1;
5296 assert( aFrom[0].isOrdered==0 );
5297 if( nOrderBy ){
5298 /* If nLoop is zero, then there are no FROM terms in the query. Since
5299 ** in this case the query may return a maximum of one row, the results
5300 ** are already in the requested order. Set isOrdered to nOrderBy to
5301 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
5302 ** -1, indicating that the result set may or may not be ordered,
5303 ** depending on the loops added to the current plan. */
5304 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
5307 /* Compute successively longer WherePaths using the previous generation
5308 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5309 ** best paths at each generation */
5310 for(iLoop=0; iLoop<nLoop; iLoop++){
5311 nTo = 0;
5312 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5313 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5314 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
5315 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
5316 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
5317 i8 isOrdered; /* isOrdered for (pFrom+pWLoop) */
5318 Bitmask maskNew; /* Mask of src visited by (..) */
5319 Bitmask revMask; /* Mask of rev-order loops for (..) */
5321 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5322 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
5323 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
5324 /* Do not use an automatic index if the this loop is expected
5325 ** to run less than 1.25 times. It is tempting to also exclude
5326 ** automatic index usage on an outer loop, but sometimes an automatic
5327 ** index is useful in the outer loop of a correlated subquery. */
5328 assert( 10==sqlite3LogEst(2) );
5329 continue;
5332 /* At this point, pWLoop is a candidate to be the next loop.
5333 ** Compute its cost */
5334 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5335 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
5336 nOut = pFrom->nRow + pWLoop->nOut;
5337 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
5338 isOrdered = pFrom->isOrdered;
5339 if( isOrdered<0 ){
5340 revMask = 0;
5341 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
5342 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
5343 iLoop, pWLoop, &revMask);
5344 }else{
5345 revMask = pFrom->revLoop;
5347 if( isOrdered>=0 && isOrdered<nOrderBy ){
5348 if( aSortCost[isOrdered]==0 ){
5349 aSortCost[isOrdered] = whereSortingCost(
5350 pWInfo, nRowEst, nOrderBy, isOrdered
5353 /* TUNING: Add a small extra penalty (3) to sorting as an
5354 ** extra encouragement to the query planner to select a plan
5355 ** where the rows emerge in the correct order without any sorting
5356 ** required. */
5357 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 3;
5359 WHERETRACE(0x002,
5360 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5361 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
5362 rUnsorted, rCost));
5363 }else{
5364 rCost = rUnsorted;
5365 rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
5368 /* Check to see if pWLoop should be added to the set of
5369 ** mxChoice best-so-far paths.
5371 ** First look for an existing path among best-so-far paths
5372 ** that covers the same set of loops and has the same isOrdered
5373 ** setting as the current path candidate.
5375 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
5376 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
5377 ** of legal values for isOrdered, -1..64.
5379 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5380 if( pTo->maskLoop==maskNew
5381 && ((pTo->isOrdered^isOrdered)&0x80)==0
5383 testcase( jj==nTo-1 );
5384 break;
5387 if( jj>=nTo ){
5388 /* None of the existing best-so-far paths match the candidate. */
5389 if( nTo>=mxChoice
5390 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
5392 /* The current candidate is no better than any of the mxChoice
5393 ** paths currently in the best-so-far buffer. So discard
5394 ** this candidate as not viable. */
5395 #ifdef WHERETRACE_ENABLED /* 0x4 */
5396 if( sqlite3WhereTrace&0x4 ){
5397 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
5398 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5399 isOrdered>=0 ? isOrdered+'0' : '?');
5401 #endif
5402 continue;
5404 /* If we reach this points it means that the new candidate path
5405 ** needs to be added to the set of best-so-far paths. */
5406 if( nTo<mxChoice ){
5407 /* Increase the size of the aTo set by one */
5408 jj = nTo++;
5409 }else{
5410 /* New path replaces the prior worst to keep count below mxChoice */
5411 jj = mxI;
5413 pTo = &aTo[jj];
5414 #ifdef WHERETRACE_ENABLED /* 0x4 */
5415 if( sqlite3WhereTrace&0x4 ){
5416 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
5417 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5418 isOrdered>=0 ? isOrdered+'0' : '?');
5420 #endif
5421 }else{
5422 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
5423 ** same set of loops and has the same isOrdered setting as the
5424 ** candidate path. Check to see if the candidate should replace
5425 ** pTo or if the candidate should be skipped.
5427 ** The conditional is an expanded vector comparison equivalent to:
5428 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
5430 if( pTo->rCost<rCost
5431 || (pTo->rCost==rCost
5432 && (pTo->nRow<nOut
5433 || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
5437 #ifdef WHERETRACE_ENABLED /* 0x4 */
5438 if( sqlite3WhereTrace&0x4 ){
5439 sqlite3DebugPrintf(
5440 "Skip %s cost=%-3d,%3d,%3d order=%c",
5441 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5442 isOrdered>=0 ? isOrdered+'0' : '?');
5443 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
5444 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5445 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5447 #endif
5448 /* Discard the candidate path from further consideration */
5449 testcase( pTo->rCost==rCost );
5450 continue;
5452 testcase( pTo->rCost==rCost+1 );
5453 /* Control reaches here if the candidate path is better than the
5454 ** pTo path. Replace pTo with the candidate. */
5455 #ifdef WHERETRACE_ENABLED /* 0x4 */
5456 if( sqlite3WhereTrace&0x4 ){
5457 sqlite3DebugPrintf(
5458 "Update %s cost=%-3d,%3d,%3d order=%c",
5459 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5460 isOrdered>=0 ? isOrdered+'0' : '?');
5461 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
5462 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5463 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5465 #endif
5467 /* pWLoop is a winner. Add it to the set of best so far */
5468 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
5469 pTo->revLoop = revMask;
5470 pTo->nRow = nOut;
5471 pTo->rCost = rCost;
5472 pTo->rUnsorted = rUnsorted;
5473 pTo->isOrdered = isOrdered;
5474 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5475 pTo->aLoop[iLoop] = pWLoop;
5476 if( nTo>=mxChoice ){
5477 mxI = 0;
5478 mxCost = aTo[0].rCost;
5479 mxUnsorted = aTo[0].nRow;
5480 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5481 if( pTo->rCost>mxCost
5482 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
5484 mxCost = pTo->rCost;
5485 mxUnsorted = pTo->rUnsorted;
5486 mxI = jj;
5493 #ifdef WHERETRACE_ENABLED /* >=2 */
5494 if( sqlite3WhereTrace & 0x02 ){
5495 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
5496 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
5497 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
5498 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5499 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
5500 if( pTo->isOrdered>0 ){
5501 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5502 }else{
5503 sqlite3DebugPrintf("\n");
5507 #endif
5509 /* Swap the roles of aFrom and aTo for the next generation */
5510 pFrom = aTo;
5511 aTo = aFrom;
5512 aFrom = pFrom;
5513 nFrom = nTo;
5516 if( nFrom==0 ){
5517 sqlite3ErrorMsg(pParse, "no query solution");
5518 sqlite3StackFreeNN(pParse->db, pSpace);
5519 return SQLITE_ERROR;
5522 /* Find the lowest cost path. pFrom will be left pointing to that path */
5523 pFrom = aFrom;
5524 for(ii=1; ii<nFrom; ii++){
5525 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5527 assert( pWInfo->nLevel==nLoop );
5528 /* Load the lowest cost path into pWInfo */
5529 for(iLoop=0; iLoop<nLoop; iLoop++){
5530 WhereLevel *pLevel = pWInfo->a + iLoop;
5531 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
5532 pLevel->iFrom = pWLoop->iTab;
5533 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
5535 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5536 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5537 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
5538 && nRowEst
5540 Bitmask notUsed;
5541 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
5542 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
5543 if( rc==pWInfo->pResultSet->nExpr ){
5544 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5547 pWInfo->bOrderedInnerLoop = 0;
5548 if( pWInfo->pOrderBy ){
5549 pWInfo->nOBSat = pFrom->isOrdered;
5550 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5551 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
5552 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5554 /* vvv--- See check-in [12ad822d9b827777] on 2023-03-16 ---vvv */
5555 assert( pWInfo->pSelect->pOrderBy==0
5556 || pWInfo->nOBSat <= pWInfo->pSelect->pOrderBy->nExpr );
5557 }else{
5558 pWInfo->revMask = pFrom->revLoop;
5559 if( pWInfo->nOBSat<=0 ){
5560 pWInfo->nOBSat = 0;
5561 if( nLoop>0 ){
5562 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
5563 if( (wsFlags & WHERE_ONEROW)==0
5564 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
5566 Bitmask m = 0;
5567 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
5568 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
5569 testcase( wsFlags & WHERE_IPK );
5570 testcase( wsFlags & WHERE_COLUMN_IN );
5571 if( rc==pWInfo->pOrderBy->nExpr ){
5572 pWInfo->bOrderedInnerLoop = 1;
5573 pWInfo->revMask = m;
5577 }else if( nLoop
5578 && pWInfo->nOBSat==1
5579 && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
5581 pWInfo->bOrderedInnerLoop = 1;
5584 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
5585 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
5587 Bitmask revMask = 0;
5588 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
5589 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
5591 assert( pWInfo->sorted==0 );
5592 if( nOrder==pWInfo->pOrderBy->nExpr ){
5593 pWInfo->sorted = 1;
5594 pWInfo->revMask = revMask;
5599 pWInfo->nRowOut = pFrom->nRow;
5601 /* Free temporary memory and return success */
5602 sqlite3StackFreeNN(pParse->db, pSpace);
5603 return SQLITE_OK;
5607 ** This routine implements a heuristic designed to improve query planning.
5608 ** This routine is called in between the first and second call to
5609 ** wherePathSolver(). Hence the name "Interstage" "Heuristic".
5611 ** The first call to wherePathSolver() (hereafter just "solver()") computes
5612 ** the best path without regard to the order of the outputs. The second call
5613 ** to the solver() builds upon the first call to try to find an alternative
5614 ** path that satisfies the ORDER BY clause.
5616 ** This routine looks at the results of the first solver() run, and for
5617 ** every FROM clause term in the resulting query plan that uses an equality
5618 ** constraint against an index, disable other WhereLoops for that same
5619 ** FROM clause term that would try to do a full-table scan. This prevents
5620 ** an index search from being converted into a full-table scan in order to
5621 ** satisfy an ORDER BY clause, since even though we might get slightly better
5622 ** performance using the full-scan without sorting if the output size
5623 ** estimates are very precise, we might also get severe performance
5624 ** degradation using the full-scan if the output size estimate is too large.
5625 ** It is better to err on the side of caution.
5627 ** Except, if the first solver() call generated a full-table scan in an outer
5628 ** loop then stop this analysis at the first full-scan, since the second
5629 ** solver() run might try to swap that full-scan for another in order to
5630 ** get the output into the correct order. In other words, we allow a
5631 ** rewrite like this:
5633 ** First Solver() Second Solver()
5634 ** |-- SCAN t1 |-- SCAN t2
5635 ** |-- SEARCH t2 `-- SEARCH t1
5636 ** `-- SORT USING B-TREE
5638 ** The purpose of this routine is to disallow rewrites such as:
5640 ** First Solver() Second Solver()
5641 ** |-- SEARCH t1 |-- SCAN t2 <--- bad!
5642 ** |-- SEARCH t2 `-- SEARCH t1
5643 ** `-- SORT USING B-TREE
5645 ** See test cases in test/whereN.test for the real-world query that
5646 ** originally provoked this heuristic.
5648 static SQLITE_NOINLINE void whereInterstageHeuristic(WhereInfo *pWInfo){
5649 int i;
5650 #ifdef WHERETRACE_ENABLED
5651 int once = 0;
5652 #endif
5653 for(i=0; i<pWInfo->nLevel; i++){
5654 WhereLoop *p = pWInfo->a[i].pWLoop;
5655 if( p==0 ) break;
5656 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 ) continue;
5657 if( (p->wsFlags & (WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0 ){
5658 u8 iTab = p->iTab;
5659 WhereLoop *pLoop;
5660 for(pLoop=pWInfo->pLoops; pLoop; pLoop=pLoop->pNextLoop){
5661 if( pLoop->iTab!=iTab ) continue;
5662 if( (pLoop->wsFlags & (WHERE_CONSTRAINT|WHERE_AUTO_INDEX))!=0 ){
5663 /* Auto-index and index-constrained loops allowed to remain */
5664 continue;
5666 #ifdef WHERETRACE_ENABLED
5667 if( sqlite3WhereTrace & 0x80 ){
5668 if( once==0 ){
5669 sqlite3DebugPrintf("Loops disabled by interstage heuristic:\n");
5670 once = 1;
5672 sqlite3WhereLoopPrint(pLoop, &pWInfo->sWC);
5674 #endif /* WHERETRACE_ENABLED */
5675 pLoop->prereq = ALLBITS; /* Prevent 2nd solver() from using this one */
5677 }else{
5678 break;
5684 ** Most queries use only a single table (they are not joins) and have
5685 ** simple == constraints against indexed fields. This routine attempts
5686 ** to plan those simple cases using much less ceremony than the
5687 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5688 ** times for the common case.
5690 ** Return non-zero on success, if this query can be handled by this
5691 ** no-frills query planner. Return zero if this query needs the
5692 ** general-purpose query planner.
5694 static int whereShortCut(WhereLoopBuilder *pBuilder){
5695 WhereInfo *pWInfo;
5696 SrcItem *pItem;
5697 WhereClause *pWC;
5698 WhereTerm *pTerm;
5699 WhereLoop *pLoop;
5700 int iCur;
5701 int j;
5702 Table *pTab;
5703 Index *pIdx;
5704 WhereScan scan;
5706 pWInfo = pBuilder->pWInfo;
5707 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
5708 assert( pWInfo->pTabList->nSrc>=1 );
5709 pItem = pWInfo->pTabList->a;
5710 pTab = pItem->pTab;
5711 if( IsVirtual(pTab) ) return 0;
5712 if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){
5713 testcase( pItem->fg.isIndexedBy );
5714 testcase( pItem->fg.notIndexed );
5715 return 0;
5717 iCur = pItem->iCursor;
5718 pWC = &pWInfo->sWC;
5719 pLoop = pBuilder->pNew;
5720 pLoop->wsFlags = 0;
5721 pLoop->nSkip = 0;
5722 pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
5723 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5724 if( pTerm ){
5725 testcase( pTerm->eOperator & WO_IS );
5726 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5727 pLoop->aLTerm[0] = pTerm;
5728 pLoop->nLTerm = 1;
5729 pLoop->u.btree.nEq = 1;
5730 /* TUNING: Cost of a rowid lookup is 10 */
5731 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
5732 }else{
5733 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5734 int opMask;
5735 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5736 if( !IsUniqueIndex(pIdx)
5737 || pIdx->pPartIdxWhere!=0
5738 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
5739 ) continue;
5740 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
5741 for(j=0; j<pIdx->nKeyCol; j++){
5742 pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx);
5743 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5744 if( pTerm==0 ) break;
5745 testcase( pTerm->eOperator & WO_IS );
5746 pLoop->aLTerm[j] = pTerm;
5748 if( j!=pIdx->nKeyCol ) continue;
5749 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
5750 if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
5751 pLoop->wsFlags |= WHERE_IDX_ONLY;
5753 pLoop->nLTerm = j;
5754 pLoop->u.btree.nEq = j;
5755 pLoop->u.btree.pIndex = pIdx;
5756 /* TUNING: Cost of a unique index lookup is 15 */
5757 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
5758 break;
5761 if( pLoop->wsFlags ){
5762 pLoop->nOut = (LogEst)1;
5763 pWInfo->a[0].pWLoop = pLoop;
5764 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
5765 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
5766 pWInfo->a[0].iTabCur = iCur;
5767 pWInfo->nRowOut = 1;
5768 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
5769 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5770 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5772 if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
5773 #ifdef SQLITE_DEBUG
5774 pLoop->cId = '0';
5775 #endif
5776 #ifdef WHERETRACE_ENABLED
5777 if( sqlite3WhereTrace & 0x02 ){
5778 sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
5780 #endif
5781 return 1;
5783 return 0;
5787 ** Helper function for exprIsDeterministic().
5789 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
5790 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
5791 pWalker->eCode = 0;
5792 return WRC_Abort;
5794 return WRC_Continue;
5798 ** Return true if the expression contains no non-deterministic SQL
5799 ** functions. Do not consider non-deterministic SQL functions that are
5800 ** part of sub-select statements.
5802 static int exprIsDeterministic(Expr *p){
5803 Walker w;
5804 memset(&w, 0, sizeof(w));
5805 w.eCode = 1;
5806 w.xExprCallback = exprNodeIsDeterministic;
5807 w.xSelectCallback = sqlite3SelectWalkFail;
5808 sqlite3WalkExpr(&w, p);
5809 return w.eCode;
5813 #ifdef WHERETRACE_ENABLED
5815 ** Display all WhereLoops in pWInfo
5817 static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
5818 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
5819 WhereLoop *p;
5820 int i;
5821 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5822 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5823 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5824 p->cId = zLabel[i%(sizeof(zLabel)-1)];
5825 sqlite3WhereLoopPrint(p, pWC);
5829 # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
5830 #else
5831 # define WHERETRACE_ALL_LOOPS(W,C)
5832 #endif
5834 /* Attempt to omit tables from a join that do not affect the result.
5835 ** For a table to not affect the result, the following must be true:
5837 ** 1) The query must not be an aggregate.
5838 ** 2) The table must be the RHS of a LEFT JOIN.
5839 ** 3) Either the query must be DISTINCT, or else the ON or USING clause
5840 ** must contain a constraint that limits the scan of the table to
5841 ** at most a single row.
5842 ** 4) The table must not be referenced by any part of the query apart
5843 ** from its own USING or ON clause.
5844 ** 5) The table must not have an inner-join ON or USING clause if there is
5845 ** a RIGHT JOIN anywhere in the query. Otherwise the ON/USING clause
5846 ** might move from the right side to the left side of the RIGHT JOIN.
5847 ** Note: Due to (2), this condition can only arise if the table is
5848 ** the right-most table of a subquery that was flattened into the
5849 ** main query and that subquery was the right-hand operand of an
5850 ** inner join that held an ON or USING clause.
5852 ** For example, given:
5854 ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
5855 ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
5856 ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
5858 ** then table t2 can be omitted from the following:
5860 ** SELECT v1, v3 FROM t1
5861 ** LEFT JOIN t2 ON (t1.ipk=t2.ipk)
5862 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5864 ** or from:
5866 ** SELECT DISTINCT v1, v3 FROM t1
5867 ** LEFT JOIN t2
5868 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5870 static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
5871 WhereInfo *pWInfo,
5872 Bitmask notReady
5874 int i;
5875 Bitmask tabUsed;
5876 int hasRightJoin;
5878 /* Preconditions checked by the caller */
5879 assert( pWInfo->nLevel>=2 );
5880 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
5882 /* These two preconditions checked by the caller combine to guarantee
5883 ** condition (1) of the header comment */
5884 assert( pWInfo->pResultSet!=0 );
5885 assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
5887 tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
5888 if( pWInfo->pOrderBy ){
5889 tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
5891 hasRightJoin = (pWInfo->pTabList->a[0].fg.jointype & JT_LTORJ)!=0;
5892 for(i=pWInfo->nLevel-1; i>=1; i--){
5893 WhereTerm *pTerm, *pEnd;
5894 SrcItem *pItem;
5895 WhereLoop *pLoop;
5896 pLoop = pWInfo->a[i].pWLoop;
5897 pItem = &pWInfo->pTabList->a[pLoop->iTab];
5898 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
5899 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
5900 && (pLoop->wsFlags & WHERE_ONEROW)==0
5902 continue;
5904 if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
5905 pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
5906 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5907 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5908 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
5909 || pTerm->pExpr->w.iJoin!=pItem->iCursor
5911 break;
5914 if( hasRightJoin
5915 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
5916 && pTerm->pExpr->w.iJoin==pItem->iCursor
5918 break; /* restriction (5) */
5921 if( pTerm<pEnd ) continue;
5922 WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop->cId));
5923 notReady &= ~pLoop->maskSelf;
5924 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5925 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5926 pTerm->wtFlags |= TERM_CODED;
5929 if( i!=pWInfo->nLevel-1 ){
5930 int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
5931 memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
5933 pWInfo->nLevel--;
5934 assert( pWInfo->nLevel>0 );
5936 return notReady;
5940 ** Check to see if there are any SEARCH loops that might benefit from
5941 ** using a Bloom filter. Consider a Bloom filter if:
5943 ** (1) The SEARCH happens more than N times where N is the number
5944 ** of rows in the table that is being considered for the Bloom
5945 ** filter.
5946 ** (2) Some searches are expected to find zero rows. (This is determined
5947 ** by the WHERE_SELFCULL flag on the term.)
5948 ** (3) Bloom-filter processing is not disabled. (Checked by the
5949 ** caller.)
5950 ** (4) The size of the table being searched is known by ANALYZE.
5952 ** This block of code merely checks to see if a Bloom filter would be
5953 ** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
5954 ** WhereLoop. The implementation of the Bloom filter comes further
5955 ** down where the code for each WhereLoop is generated.
5957 static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
5958 const WhereInfo *pWInfo
5960 int i;
5961 LogEst nSearch = 0;
5963 assert( pWInfo->nLevel>=2 );
5964 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
5965 for(i=0; i<pWInfo->nLevel; i++){
5966 WhereLoop *pLoop = pWInfo->a[i].pWLoop;
5967 const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ);
5968 SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
5969 Table *pTab = pItem->pTab;
5970 if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
5971 pTab->tabFlags |= TF_MaybeReanalyze;
5972 if( i>=1
5973 && (pLoop->wsFlags & reqFlags)==reqFlags
5974 /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
5975 && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
5977 if( nSearch > pTab->nRowLogEst ){
5978 testcase( pItem->fg.jointype & JT_LEFT );
5979 pLoop->wsFlags |= WHERE_BLOOMFILTER;
5980 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
5981 WHERETRACE(0xffffffff, (
5982 "-> use Bloom-filter on loop %c because there are ~%.1e "
5983 "lookups into %s which has only ~%.1e rows\n",
5984 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
5985 (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
5988 nSearch += pLoop->nOut;
5993 ** The index pIdx is used by a query and contains one or more expressions.
5994 ** In other words pIdx is an index on an expression. iIdxCur is the cursor
5995 ** number for the index and iDataCur is the cursor number for the corresponding
5996 ** table.
5998 ** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for
5999 ** each of the expressions in the index so that the expression code generator
6000 ** will know to replace occurrences of the indexed expression with
6001 ** references to the corresponding column of the index.
6003 static SQLITE_NOINLINE void whereAddIndexedExpr(
6004 Parse *pParse, /* Add IndexedExpr entries to pParse->pIdxEpr */
6005 Index *pIdx, /* The index-on-expression that contains the expressions */
6006 int iIdxCur, /* Cursor number for pIdx */
6007 SrcItem *pTabItem /* The FROM clause entry for the table */
6009 int i;
6010 IndexedExpr *p;
6011 Table *pTab;
6012 assert( pIdx->bHasExpr );
6013 pTab = pIdx->pTable;
6014 for(i=0; i<pIdx->nColumn; i++){
6015 Expr *pExpr;
6016 int j = pIdx->aiColumn[i];
6017 if( j==XN_EXPR ){
6018 pExpr = pIdx->aColExpr->a[i].pExpr;
6019 }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
6020 pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
6021 }else{
6022 continue;
6024 if( sqlite3ExprIsConstant(0,pExpr) ) continue;
6025 if( pExpr->op==TK_FUNCTION ){
6026 /* Functions that might set a subtype should not be replaced by the
6027 ** value taken from an expression index since the index omits the
6028 ** subtype. https://sqlite.org/forum/forumpost/68d284c86b082c3e */
6029 int n;
6030 FuncDef *pDef;
6031 sqlite3 *db = pParse->db;
6032 assert( ExprUseXList(pExpr) );
6033 n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
6034 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
6035 if( pDef==0 || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
6036 continue;
6039 p = sqlite3DbMallocRaw(pParse->db, sizeof(IndexedExpr));
6040 if( p==0 ) break;
6041 p->pIENext = pParse->pIdxEpr;
6042 #ifdef WHERETRACE_ENABLED
6043 if( sqlite3WhereTrace & 0x200 ){
6044 sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
6045 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr);
6047 #endif
6048 p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
6049 p->iDataCur = pTabItem->iCursor;
6050 p->iIdxCur = iIdxCur;
6051 p->iIdxCol = i;
6052 p->bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0;
6053 if( sqlite3IndexAffinityStr(pParse->db, pIdx) ){
6054 p->aff = pIdx->zColAff[i];
6056 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
6057 p->zIdxName = pIdx->zName;
6058 #endif
6059 pParse->pIdxEpr = p;
6060 if( p->pIENext==0 ){
6061 void *pArg = (void*)&pParse->pIdxEpr;
6062 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg);
6068 ** Set the reverse-scan order mask to one for all tables in the query
6069 ** with the exception of MATERIALIZED common table expressions that have
6070 ** their own internal ORDER BY clauses.
6072 ** This implements the PRAGMA reverse_unordered_selects=ON setting.
6073 ** (Also SQLITE_DBCONFIG_REVERSE_SCANORDER).
6075 static SQLITE_NOINLINE void whereReverseScanOrder(WhereInfo *pWInfo){
6076 int ii;
6077 for(ii=0; ii<pWInfo->pTabList->nSrc; ii++){
6078 SrcItem *pItem = &pWInfo->pTabList->a[ii];
6079 if( !pItem->fg.isCte
6080 || pItem->u2.pCteUse->eM10d!=M10d_Yes
6081 || NEVER(pItem->pSelect==0)
6082 || pItem->pSelect->pOrderBy==0
6084 pWInfo->revMask |= MASKBIT(ii);
6090 ** Generate the beginning of the loop used for WHERE clause processing.
6091 ** The return value is a pointer to an opaque structure that contains
6092 ** information needed to terminate the loop. Later, the calling routine
6093 ** should invoke sqlite3WhereEnd() with the return value of this function
6094 ** in order to complete the WHERE clause processing.
6096 ** If an error occurs, this routine returns NULL.
6098 ** The basic idea is to do a nested loop, one loop for each table in
6099 ** the FROM clause of a select. (INSERT and UPDATE statements are the
6100 ** same as a SELECT with only a single table in the FROM clause.) For
6101 ** example, if the SQL is this:
6103 ** SELECT * FROM t1, t2, t3 WHERE ...;
6105 ** Then the code generated is conceptually like the following:
6107 ** foreach row1 in t1 do \ Code generated
6108 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
6109 ** foreach row3 in t3 do /
6110 ** ...
6111 ** end \ Code generated
6112 ** end |-- by sqlite3WhereEnd()
6113 ** end /
6115 ** Note that the loops might not be nested in the order in which they
6116 ** appear in the FROM clause if a different order is better able to make
6117 ** use of indices. Note also that when the IN operator appears in
6118 ** the WHERE clause, it might result in additional nested loops for
6119 ** scanning through all values on the right-hand side of the IN.
6121 ** There are Btree cursors associated with each table. t1 uses cursor
6122 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
6123 ** And so forth. This routine generates code to open those VDBE cursors
6124 ** and sqlite3WhereEnd() generates the code to close them.
6126 ** The code that sqlite3WhereBegin() generates leaves the cursors named
6127 ** in pTabList pointing at their appropriate entries. The [...] code
6128 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
6129 ** data from the various tables of the loop.
6131 ** If the WHERE clause is empty, the foreach loops must each scan their
6132 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
6133 ** the tables have indices and there are terms in the WHERE clause that
6134 ** refer to those indices, a complete table scan can be avoided and the
6135 ** code will run much faster. Most of the work of this routine is checking
6136 ** to see if there are indices that can be used to speed up the loop.
6138 ** Terms of the WHERE clause are also used to limit which rows actually
6139 ** make it to the "..." in the middle of the loop. After each "foreach",
6140 ** terms of the WHERE clause that use only terms in that loop and outer
6141 ** loops are evaluated and if false a jump is made around all subsequent
6142 ** inner loops (or around the "..." if the test occurs within the inner-
6143 ** most loop)
6145 ** OUTER JOINS
6147 ** An outer join of tables t1 and t2 is conceptually coded as follows:
6149 ** foreach row1 in t1 do
6150 ** flag = 0
6151 ** foreach row2 in t2 do
6152 ** start:
6153 ** ...
6154 ** flag = 1
6155 ** end
6156 ** if flag==0 then
6157 ** move the row2 cursor to a null row
6158 ** goto start
6159 ** fi
6160 ** end
6162 ** ORDER BY CLAUSE PROCESSING
6164 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
6165 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
6166 ** if there is one. If there is no ORDER BY clause or if this routine
6167 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
6169 ** The iIdxCur parameter is the cursor number of an index. If
6170 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
6171 ** to use for OR clause processing. The WHERE clause should use this
6172 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
6173 ** the first cursor in an array of cursors for all indices. iIdxCur should
6174 ** be used to compute the appropriate cursor depending on which index is
6175 ** used.
6177 WhereInfo *sqlite3WhereBegin(
6178 Parse *pParse, /* The parser context */
6179 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
6180 Expr *pWhere, /* The WHERE clause */
6181 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
6182 ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
6183 Select *pSelect, /* The entire SELECT statement */
6184 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
6185 int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
6186 ** If WHERE_USE_LIMIT, then the limit amount */
6188 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
6189 int nTabList; /* Number of elements in pTabList */
6190 WhereInfo *pWInfo; /* Will become the return value of this function */
6191 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
6192 Bitmask notReady; /* Cursors that are not yet positioned */
6193 WhereLoopBuilder sWLB; /* The WhereLoop builder */
6194 WhereMaskSet *pMaskSet; /* The expression mask set */
6195 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
6196 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
6197 int ii; /* Loop counter */
6198 sqlite3 *db; /* Database connection */
6199 int rc; /* Return code */
6200 u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
6202 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
6203 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
6204 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
6207 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
6208 assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
6209 || (wctrlFlags & WHERE_USE_LIMIT)==0 );
6211 /* Variable initialization */
6212 db = pParse->db;
6213 memset(&sWLB, 0, sizeof(sWLB));
6215 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
6216 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
6217 if( pOrderBy && pOrderBy->nExpr>=BMS ){
6218 pOrderBy = 0;
6219 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6222 /* The number of tables in the FROM clause is limited by the number of
6223 ** bits in a Bitmask
6225 testcase( pTabList->nSrc==BMS );
6226 if( pTabList->nSrc>BMS ){
6227 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
6228 return 0;
6231 /* This function normally generates a nested loop for all tables in
6232 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
6233 ** only generate code for the first table in pTabList and assume that
6234 ** any cursors associated with subsequent tables are uninitialized.
6236 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
6238 /* Allocate and initialize the WhereInfo structure that will become the
6239 ** return value. A single allocation is used to store the WhereInfo
6240 ** struct, the contents of WhereInfo.a[], the WhereClause structure
6241 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
6242 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
6243 ** some architectures. Hence the ROUND8() below.
6245 nByteWInfo = ROUND8P(sizeof(WhereInfo));
6246 if( nTabList>1 ){
6247 nByteWInfo = ROUND8P(nByteWInfo + (nTabList-1)*sizeof(WhereLevel));
6249 pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
6250 if( db->mallocFailed ){
6251 sqlite3DbFree(db, pWInfo);
6252 pWInfo = 0;
6253 goto whereBeginError;
6255 pWInfo->pParse = pParse;
6256 pWInfo->pTabList = pTabList;
6257 pWInfo->pOrderBy = pOrderBy;
6258 #if WHERETRACE_ENABLED
6259 pWInfo->pWhere = pWhere;
6260 #endif
6261 pWInfo->pResultSet = pResultSet;
6262 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
6263 pWInfo->nLevel = nTabList;
6264 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
6265 pWInfo->wctrlFlags = wctrlFlags;
6266 pWInfo->iLimit = iAuxArg;
6267 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
6268 pWInfo->pSelect = pSelect;
6269 memset(&pWInfo->nOBSat, 0,
6270 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
6271 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
6272 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
6273 pMaskSet = &pWInfo->sMaskSet;
6274 pMaskSet->n = 0;
6275 pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
6276 ** a valid cursor number, to avoid an initial
6277 ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
6278 sWLB.pWInfo = pWInfo;
6279 sWLB.pWC = &pWInfo->sWC;
6280 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
6281 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
6282 whereLoopInit(sWLB.pNew);
6283 #ifdef SQLITE_DEBUG
6284 sWLB.pNew->cId = '*';
6285 #endif
6287 /* Split the WHERE clause into separate subexpressions where each
6288 ** subexpression is separated by an AND operator.
6290 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
6291 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
6293 /* Special case: No FROM clause
6295 if( nTabList==0 ){
6296 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
6297 if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0
6298 && OptimizationEnabled(db, SQLITE_DistinctOpt)
6300 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6302 if( ALWAYS(pWInfo->pSelect)
6303 && (pWInfo->pSelect->selFlags & SF_MultiValue)==0
6305 ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
6307 }else{
6308 /* Assign a bit from the bitmask to every term in the FROM clause.
6310 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
6312 ** The rule of the previous sentence ensures that if X is the bitmask for
6313 ** a table T, then X-1 is the bitmask for all other tables to the left of T.
6314 ** Knowing the bitmask for all tables to the left of a left join is
6315 ** important. Ticket #3015.
6317 ** Note that bitmasks are created for all pTabList->nSrc tables in
6318 ** pTabList, not just the first nTabList tables. nTabList is normally
6319 ** equal to pTabList->nSrc but might be shortened to 1 if the
6320 ** WHERE_OR_SUBCLAUSE flag is set.
6322 ii = 0;
6324 createMask(pMaskSet, pTabList->a[ii].iCursor);
6325 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
6326 }while( (++ii)<pTabList->nSrc );
6327 #ifdef SQLITE_DEBUG
6329 Bitmask mx = 0;
6330 for(ii=0; ii<pTabList->nSrc; ii++){
6331 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
6332 assert( m>=mx );
6333 mx = m;
6336 #endif
6339 /* Analyze all of the subexpressions. */
6340 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
6341 if( pSelect && pSelect->pLimit ){
6342 sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
6344 if( pParse->nErr ) goto whereBeginError;
6346 /* The False-WHERE-Term-Bypass optimization:
6348 ** If there are WHERE terms that are false, then no rows will be output,
6349 ** so skip over all of the code generated here.
6351 ** Conditions:
6353 ** (1) The WHERE term must not refer to any tables in the join.
6354 ** (2) The term must not come from an ON clause on the
6355 ** right-hand side of a LEFT or FULL JOIN.
6356 ** (3) The term must not come from an ON clause, or there must be
6357 ** no RIGHT or FULL OUTER joins in pTabList.
6358 ** (4) If the expression contains non-deterministic functions
6359 ** that are not within a sub-select. This is not required
6360 ** for correctness but rather to preserves SQLite's legacy
6361 ** behaviour in the following two cases:
6363 ** WHERE random()>0; -- eval random() once per row
6364 ** WHERE (SELECT random())>0; -- eval random() just once overall
6366 ** Note that the Where term need not be a constant in order for this
6367 ** optimization to apply, though it does need to be constant relative to
6368 ** the current subquery (condition 1). The term might include variables
6369 ** from outer queries so that the value of the term changes from one
6370 ** invocation of the current subquery to the next.
6372 for(ii=0; ii<sWLB.pWC->nBase; ii++){
6373 WhereTerm *pT = &sWLB.pWC->a[ii]; /* A term of the WHERE clause */
6374 Expr *pX; /* The expression of pT */
6375 if( pT->wtFlags & TERM_VIRTUAL ) continue;
6376 pX = pT->pExpr;
6377 assert( pX!=0 );
6378 assert( pT->prereqAll!=0 || !ExprHasProperty(pX, EP_OuterON) );
6379 if( pT->prereqAll==0 /* Conditions (1) and (2) */
6380 && (nTabList==0 || exprIsDeterministic(pX)) /* Condition (4) */
6381 && !(ExprHasProperty(pX, EP_InnerON) /* Condition (3) */
6382 && (pTabList->a[0].fg.jointype & JT_LTORJ)!=0 )
6384 sqlite3ExprIfFalse(pParse, pX, pWInfo->iBreak, SQLITE_JUMPIFNULL);
6385 pT->wtFlags |= TERM_CODED;
6389 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6390 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6391 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6392 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6393 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6394 pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
6395 }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6396 /* The DISTINCT marking is pointless. Ignore it. */
6397 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6398 }else if( pOrderBy==0 ){
6399 /* Try to ORDER BY the result set to make distinct processing easier */
6400 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
6401 pWInfo->pOrderBy = pResultSet;
6405 /* Construct the WhereLoop objects */
6406 #if defined(WHERETRACE_ENABLED)
6407 if( sqlite3WhereTrace & 0xffffffff ){
6408 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
6409 if( wctrlFlags & WHERE_USE_LIMIT ){
6410 sqlite3DebugPrintf(", limit: %d", iAuxArg);
6412 sqlite3DebugPrintf(")\n");
6413 if( sqlite3WhereTrace & 0x8000 ){
6414 Select sSelect;
6415 memset(&sSelect, 0, sizeof(sSelect));
6416 sSelect.selFlags = SF_WhereBegin;
6417 sSelect.pSrc = pTabList;
6418 sSelect.pWhere = pWhere;
6419 sSelect.pOrderBy = pOrderBy;
6420 sSelect.pEList = pResultSet;
6421 sqlite3TreeViewSelect(0, &sSelect, 0);
6423 if( sqlite3WhereTrace & 0x4000 ){ /* Display all WHERE clause terms */
6424 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
6425 sqlite3WhereClausePrint(sWLB.pWC);
6428 #endif
6430 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
6431 rc = whereLoopAddAll(&sWLB);
6432 if( rc ) goto whereBeginError;
6434 #ifdef SQLITE_ENABLE_STAT4
6435 /* If one or more WhereTerm.truthProb values were used in estimating
6436 ** loop parameters, but then those truthProb values were subsequently
6437 ** changed based on STAT4 information while computing subsequent loops,
6438 ** then we need to rerun the whole loop building process so that all
6439 ** loops will be built using the revised truthProb values. */
6440 if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
6441 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6442 WHERETRACE(0xffffffff,
6443 ("**** Redo all loop computations due to"
6444 " TERM_HIGHTRUTH changes ****\n"));
6445 while( pWInfo->pLoops ){
6446 WhereLoop *p = pWInfo->pLoops;
6447 pWInfo->pLoops = p->pNextLoop;
6448 whereLoopDelete(db, p);
6450 rc = whereLoopAddAll(&sWLB);
6451 if( rc ) goto whereBeginError;
6453 #endif
6454 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6456 wherePathSolver(pWInfo, 0);
6457 if( db->mallocFailed ) goto whereBeginError;
6458 if( pWInfo->pOrderBy ){
6459 whereInterstageHeuristic(pWInfo);
6460 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
6461 if( db->mallocFailed ) goto whereBeginError;
6464 /* TUNING: Assume that a DISTINCT clause on a subquery reduces
6465 ** the output size by a factor of 8 (LogEst -30).
6467 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
6468 WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n",
6469 pWInfo->nRowOut, pWInfo->nRowOut-30));
6470 pWInfo->nRowOut -= 30;
6474 assert( pWInfo->pTabList!=0 );
6475 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
6476 whereReverseScanOrder(pWInfo);
6478 if( pParse->nErr ){
6479 goto whereBeginError;
6481 assert( db->mallocFailed==0 );
6482 #ifdef WHERETRACE_ENABLED
6483 if( sqlite3WhereTrace ){
6484 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
6485 if( pWInfo->nOBSat>0 ){
6486 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
6488 switch( pWInfo->eDistinct ){
6489 case WHERE_DISTINCT_UNIQUE: {
6490 sqlite3DebugPrintf(" DISTINCT=unique");
6491 break;
6493 case WHERE_DISTINCT_ORDERED: {
6494 sqlite3DebugPrintf(" DISTINCT=ordered");
6495 break;
6497 case WHERE_DISTINCT_UNORDERED: {
6498 sqlite3DebugPrintf(" DISTINCT=unordered");
6499 break;
6502 sqlite3DebugPrintf("\n");
6503 for(ii=0; ii<pWInfo->nLevel; ii++){
6504 sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
6507 #endif
6509 /* Attempt to omit tables from a join that do not affect the result.
6510 ** See the comment on whereOmitNoopJoin() for further information.
6512 ** This query optimization is factored out into a separate "no-inline"
6513 ** procedure to keep the sqlite3WhereBegin() procedure from becoming
6514 ** too large. If sqlite3WhereBegin() becomes too large, that prevents
6515 ** some C-compiler optimizers from in-lining the
6516 ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
6517 ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
6519 notReady = ~(Bitmask)0;
6520 if( pWInfo->nLevel>=2
6521 && pResultSet!=0 /* these two combine to guarantee */
6522 && 0==(wctrlFlags & WHERE_AGG_DISTINCT) /* condition (1) above */
6523 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6525 notReady = whereOmitNoopJoin(pWInfo, notReady);
6526 nTabList = pWInfo->nLevel;
6527 assert( nTabList>0 );
6530 /* Check to see if there are any SEARCH loops that might benefit from
6531 ** using a Bloom filter.
6533 if( pWInfo->nLevel>=2
6534 && OptimizationEnabled(db, SQLITE_BloomFilter)
6536 whereCheckIfBloomFilterIsUseful(pWInfo);
6539 #if defined(WHERETRACE_ENABLED)
6540 if( sqlite3WhereTrace & 0x4000 ){ /* Display all terms of the WHERE clause */
6541 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
6542 sqlite3WhereClausePrint(sWLB.pWC);
6544 WHERETRACE(0xffffffff,("*** Optimizer Finished ***\n"));
6545 #endif
6546 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
6548 /* If the caller is an UPDATE or DELETE statement that is requesting
6549 ** to use a one-pass algorithm, determine if this is appropriate.
6551 ** A one-pass approach can be used if the caller has requested one
6552 ** and either (a) the scan visits at most one row or (b) each
6553 ** of the following are true:
6555 ** * the caller has indicated that a one-pass approach can be used
6556 ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
6557 ** * the table is not a virtual table, and
6558 ** * either the scan does not use the OR optimization or the caller
6559 ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
6560 ** for DELETE).
6562 ** The last qualification is because an UPDATE statement uses
6563 ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
6564 ** use a one-pass approach, and this is not set accurately for scans
6565 ** that use the OR optimization.
6567 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
6568 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
6569 int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
6570 int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
6571 assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
6572 if( bOnerow || (
6573 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
6574 && !IsVirtual(pTabList->a[0].pTab)
6575 && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
6576 && OptimizationEnabled(db, SQLITE_OnePass)
6578 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
6579 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
6580 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
6581 bFordelete = OPFLAG_FORDELETE;
6583 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
6588 /* Open all tables in the pTabList and any indices selected for
6589 ** searching those tables.
6591 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
6592 Table *pTab; /* Table to open */
6593 int iDb; /* Index of database containing table/index */
6594 SrcItem *pTabItem;
6596 pTabItem = &pTabList->a[pLevel->iFrom];
6597 pTab = pTabItem->pTab;
6598 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6599 pLoop = pLevel->pWLoop;
6600 if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
6601 /* Do nothing */
6602 }else
6603 #ifndef SQLITE_OMIT_VIRTUALTABLE
6604 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
6605 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
6606 int iCur = pTabItem->iCursor;
6607 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
6608 }else if( IsVirtual(pTab) ){
6609 /* noop */
6610 }else
6611 #endif
6612 if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0
6613 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0)
6614 || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0
6616 int op = OP_OpenRead;
6617 if( pWInfo->eOnePass!=ONEPASS_OFF ){
6618 op = OP_OpenWrite;
6619 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6621 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
6622 assert( pTabItem->iCursor==pLevel->iTabCur );
6623 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
6624 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
6625 if( pWInfo->eOnePass==ONEPASS_OFF
6626 && pTab->nCol<BMS
6627 && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
6628 && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
6630 /* If we know that only a prefix of the record will be used,
6631 ** it is advantageous to reduce the "column count" field in
6632 ** the P4 operand of the OP_OpenRead/Write opcode. */
6633 Bitmask b = pTabItem->colUsed;
6634 int n = 0;
6635 for(; b; b=b>>1, n++){}
6636 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
6637 assert( n<=pTab->nCol );
6639 #ifdef SQLITE_ENABLE_CURSOR_HINTS
6640 if( pLoop->u.btree.pIndex!=0 && (pTab->tabFlags & TF_WithoutRowid)==0 ){
6641 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
6642 }else
6643 #endif
6645 sqlite3VdbeChangeP5(v, bFordelete);
6647 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6648 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
6649 (const u8*)&pTabItem->colUsed, P4_INT64);
6650 #endif
6651 }else{
6652 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
6654 if( pLoop->wsFlags & WHERE_INDEXED ){
6655 Index *pIx = pLoop->u.btree.pIndex;
6656 int iIndexCur;
6657 int op = OP_OpenRead;
6658 /* iAuxArg is always set to a positive value if ONEPASS is possible */
6659 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
6660 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
6661 && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
6663 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6664 ** WITHOUT ROWID table. No need for a separate index */
6665 iIndexCur = pLevel->iTabCur;
6666 op = 0;
6667 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
6668 Index *pJ = pTabItem->pTab->pIndex;
6669 iIndexCur = iAuxArg;
6670 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6671 while( ALWAYS(pJ) && pJ!=pIx ){
6672 iIndexCur++;
6673 pJ = pJ->pNext;
6675 op = OP_OpenWrite;
6676 pWInfo->aiCurOnePass[1] = iIndexCur;
6677 }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
6678 iIndexCur = iAuxArg;
6679 op = OP_ReopenIdx;
6680 }else{
6681 iIndexCur = pParse->nTab++;
6682 if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
6683 whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem);
6685 if( pIx->pPartIdxWhere && (pTabItem->fg.jointype & JT_RIGHT)==0 ){
6686 wherePartIdxExpr(
6687 pParse, pIx, pIx->pPartIdxWhere, 0, iIndexCur, pTabItem
6691 pLevel->iIdxCur = iIndexCur;
6692 assert( pIx!=0 );
6693 assert( pIx->pSchema==pTab->pSchema );
6694 assert( iIndexCur>=0 );
6695 if( op ){
6696 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6697 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6698 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
6699 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
6700 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
6701 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
6702 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
6703 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
6705 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
6707 VdbeComment((v, "%s", pIx->zName));
6708 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6710 u64 colUsed = 0;
6711 int ii, jj;
6712 for(ii=0; ii<pIx->nColumn; ii++){
6713 jj = pIx->aiColumn[ii];
6714 if( jj<0 ) continue;
6715 if( jj>63 ) jj = 63;
6716 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
6717 colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
6719 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
6720 (u8*)&colUsed, P4_INT64);
6722 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
6725 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
6726 if( (pTabItem->fg.jointype & JT_RIGHT)!=0
6727 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
6729 WhereRightJoin *pRJ = pLevel->pRJ;
6730 pRJ->iMatch = pParse->nTab++;
6731 pRJ->regBloom = ++pParse->nMem;
6732 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
6733 pRJ->regReturn = ++pParse->nMem;
6734 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
6735 assert( pTab==pTabItem->pTab );
6736 if( HasRowid(pTab) ){
6737 KeyInfo *pInfo;
6738 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
6739 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
6740 if( pInfo ){
6741 pInfo->aColl[0] = 0;
6742 pInfo->aSortFlags[0] = 0;
6743 sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
6745 }else{
6746 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6747 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
6748 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
6750 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
6751 /* The nature of RIGHT JOIN processing is such that it messes up
6752 ** the output order. So omit any ORDER BY/GROUP BY elimination
6753 ** optimizations. We need to do an actual sort for RIGHT JOIN. */
6754 pWInfo->nOBSat = 0;
6755 pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED;
6758 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
6759 if( db->mallocFailed ) goto whereBeginError;
6761 /* Generate the code to do the search. Each iteration of the for
6762 ** loop below generates code for a single nested loop of the VM
6763 ** program.
6765 for(ii=0; ii<nTabList; ii++){
6766 int addrExplain;
6767 int wsFlags;
6768 SrcItem *pSrc;
6769 if( pParse->nErr ) goto whereBeginError;
6770 pLevel = &pWInfo->a[ii];
6771 wsFlags = pLevel->pWLoop->wsFlags;
6772 pSrc = &pTabList->a[pLevel->iFrom];
6773 if( pSrc->fg.isMaterialized ){
6774 if( pSrc->fg.isCorrelated ){
6775 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6776 }else{
6777 int iOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
6778 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6779 sqlite3VdbeJumpHere(v, iOnce);
6782 assert( pTabList == pWInfo->pTabList );
6783 if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
6784 if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
6785 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6786 constructAutomaticIndex(pParse, &pWInfo->sWC, notReady, pLevel);
6787 #endif
6788 }else{
6789 sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
6791 if( db->mallocFailed ) goto whereBeginError;
6793 addrExplain = sqlite3WhereExplainOneScan(
6794 pParse, pTabList, pLevel, wctrlFlags
6796 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
6797 notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
6798 pWInfo->iContinue = pLevel->addrCont;
6799 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
6800 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
6804 /* Done. */
6805 VdbeModuleComment((v, "Begin WHERE-core"));
6806 pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
6807 return pWInfo;
6809 /* Jump here if malloc fails */
6810 whereBeginError:
6811 if( pWInfo ){
6812 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6813 whereInfoFree(db, pWInfo);
6815 #ifdef WHERETRACE_ENABLED
6816 /* Prevent harmless compiler warnings about debugging routines
6817 ** being declared but never used */
6818 sqlite3ShowWhereLoopList(0);
6819 #endif /* WHERETRACE_ENABLED */
6820 return 0;
6824 ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
6825 ** index rather than the main table. In SQLITE_DEBUG mode, we want
6826 ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
6827 ** does that.
6829 #ifndef SQLITE_DEBUG
6830 # define OpcodeRewriteTrace(D,K,P) /* no-op */
6831 #else
6832 # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
6833 static void sqlite3WhereOpcodeRewriteTrace(
6834 sqlite3 *db,
6835 int pc,
6836 VdbeOp *pOp
6838 if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
6839 sqlite3VdbePrintOp(0, pc, pOp);
6841 #endif
6843 #ifdef SQLITE_DEBUG
6845 ** Return true if cursor iCur is opened by instruction k of the
6846 ** bytecode. Used inside of assert() only.
6848 static int cursorIsOpen(Vdbe *v, int iCur, int k){
6849 while( k>=0 ){
6850 VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
6851 if( pOp->p1!=iCur ) continue;
6852 if( pOp->opcode==OP_Close ) return 0;
6853 if( pOp->opcode==OP_OpenRead ) return 1;
6854 if( pOp->opcode==OP_OpenWrite ) return 1;
6855 if( pOp->opcode==OP_OpenDup ) return 1;
6856 if( pOp->opcode==OP_OpenAutoindex ) return 1;
6857 if( pOp->opcode==OP_OpenEphemeral ) return 1;
6859 return 0;
6861 #endif /* SQLITE_DEBUG */
6864 ** Generate the end of the WHERE loop. See comments on
6865 ** sqlite3WhereBegin() for additional information.
6867 void sqlite3WhereEnd(WhereInfo *pWInfo){
6868 Parse *pParse = pWInfo->pParse;
6869 Vdbe *v = pParse->pVdbe;
6870 int i;
6871 WhereLevel *pLevel;
6872 WhereLoop *pLoop;
6873 SrcList *pTabList = pWInfo->pTabList;
6874 sqlite3 *db = pParse->db;
6875 int iEnd = sqlite3VdbeCurrentAddr(v);
6876 int nRJ = 0;
6878 /* Generate loop termination code.
6880 VdbeModuleComment((v, "End WHERE-core"));
6881 for(i=pWInfo->nLevel-1; i>=0; i--){
6882 int addr;
6883 pLevel = &pWInfo->a[i];
6884 if( pLevel->pRJ ){
6885 /* Terminate the subroutine that forms the interior of the loop of
6886 ** the RIGHT JOIN table */
6887 WhereRightJoin *pRJ = pLevel->pRJ;
6888 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6889 pLevel->addrCont = 0;
6890 pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);
6891 sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);
6892 VdbeCoverage(v);
6893 nRJ++;
6895 pLoop = pLevel->pWLoop;
6896 if( pLevel->op!=OP_Noop ){
6897 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6898 int addrSeek = 0;
6899 Index *pIdx;
6900 int n;
6901 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
6902 && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
6903 && (pLoop->wsFlags & WHERE_INDEXED)!=0
6904 && (pIdx = pLoop->u.btree.pIndex)->hasStat1
6905 && (n = pLoop->u.btree.nDistinctCol)>0
6906 && pIdx->aiRowLogEst[n]>=36
6908 int r1 = pParse->nMem+1;
6909 int j, op;
6910 for(j=0; j<n; j++){
6911 sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
6913 pParse->nMem += n+1;
6914 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
6915 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
6916 VdbeCoverageIf(v, op==OP_SeekLT);
6917 VdbeCoverageIf(v, op==OP_SeekGT);
6918 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
6920 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
6921 /* The common case: Advance to the next row */
6922 if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6923 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
6924 sqlite3VdbeChangeP5(v, pLevel->p5);
6925 VdbeCoverage(v);
6926 VdbeCoverageIf(v, pLevel->op==OP_Next);
6927 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6928 VdbeCoverageIf(v, pLevel->op==OP_VNext);
6929 if( pLevel->regBignull ){
6930 sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
6931 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
6932 VdbeCoverage(v);
6934 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6935 if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
6936 #endif
6937 }else if( pLevel->addrCont ){
6938 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6940 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
6941 struct InLoop *pIn;
6942 int j;
6943 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
6944 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
6945 assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
6946 || pParse->db->mallocFailed );
6947 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6948 if( pIn->eEndLoopOp!=OP_Noop ){
6949 if( pIn->nPrefix ){
6950 int bEarlyOut =
6951 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
6952 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
6953 if( pLevel->iLeftJoin ){
6954 /* For LEFT JOIN queries, cursor pIn->iCur may not have been
6955 ** opened yet. This occurs for WHERE clauses such as
6956 ** "a = ? AND b IN (...)", where the index is on (a, b). If
6957 ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
6958 ** never have been coded, but the body of the loop run to
6959 ** return the null-row. So, if the cursor is not open yet,
6960 ** jump over the OP_Next or OP_Prev instruction about to
6961 ** be coded. */
6962 sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
6963 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
6964 VdbeCoverage(v);
6966 if( bEarlyOut ){
6967 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
6968 sqlite3VdbeCurrentAddr(v)+2,
6969 pIn->iBase, pIn->nPrefix);
6970 VdbeCoverage(v);
6971 /* Retarget the OP_IsNull against the left operand of IN so
6972 ** it jumps past the OP_IfNoHope. This is because the
6973 ** OP_IsNull also bypasses the OP_Affinity opcode that is
6974 ** required by OP_IfNoHope. */
6975 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6978 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
6979 VdbeCoverage(v);
6980 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
6981 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
6983 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
6986 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
6987 if( pLevel->pRJ ){
6988 sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1);
6989 VdbeCoverage(v);
6991 if( pLevel->addrSkip ){
6992 sqlite3VdbeGoto(v, pLevel->addrSkip);
6993 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
6994 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6995 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
6997 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
6998 if( pLevel->addrLikeRep ){
6999 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
7000 pLevel->addrLikeRep);
7001 VdbeCoverage(v);
7003 #endif
7004 if( pLevel->iLeftJoin ){
7005 int ws = pLoop->wsFlags;
7006 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
7007 assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
7008 if( (ws & WHERE_IDX_ONLY)==0 ){
7009 SrcItem *pSrc = &pTabList->a[pLevel->iFrom];
7010 assert( pLevel->iTabCur==pSrc->iCursor );
7011 if( pSrc->fg.viaCoroutine ){
7012 int m, n;
7013 n = pSrc->regResult;
7014 assert( pSrc->pTab!=0 );
7015 m = pSrc->pTab->nCol;
7016 sqlite3VdbeAddOp3(v, OP_Null, 0, n, n+m-1);
7018 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
7020 if( (ws & WHERE_INDEXED)
7021 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
7023 if( ws & WHERE_MULTI_OR ){
7024 Index *pIx = pLevel->u.pCoveringIdx;
7025 int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
7026 sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
7027 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
7029 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
7031 if( pLevel->op==OP_Return ){
7032 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
7033 }else{
7034 sqlite3VdbeGoto(v, pLevel->addrFirst);
7036 sqlite3VdbeJumpHere(v, addr);
7038 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
7039 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
7042 assert( pWInfo->nLevel<=pTabList->nSrc );
7043 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
7044 int k, last;
7045 VdbeOp *pOp, *pLastOp;
7046 Index *pIdx = 0;
7047 SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
7048 Table *pTab = pTabItem->pTab;
7049 assert( pTab!=0 );
7050 pLoop = pLevel->pWLoop;
7052 /* Do RIGHT JOIN processing. Generate code that will output the
7053 ** unmatched rows of the right operand of the RIGHT JOIN with
7054 ** all of the columns of the left operand set to NULL.
7056 if( pLevel->pRJ ){
7057 sqlite3WhereRightJoinLoop(pWInfo, i, pLevel);
7058 continue;
7061 /* For a co-routine, change all OP_Column references to the table of
7062 ** the co-routine into OP_Copy of result contained in a register.
7063 ** OP_Rowid becomes OP_Null.
7065 if( pTabItem->fg.viaCoroutine ){
7066 testcase( pParse->db->mallocFailed );
7067 assert( pTabItem->regResult>=0 );
7068 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
7069 pTabItem->regResult, 0);
7070 continue;
7073 /* If this scan uses an index, make VDBE code substitutions to read data
7074 ** from the index instead of from the table where possible. In some cases
7075 ** this optimization prevents the table from ever being read, which can
7076 ** yield a significant performance boost.
7078 ** Calls to the code generator in between sqlite3WhereBegin and
7079 ** sqlite3WhereEnd will have created code that references the table
7080 ** directly. This loop scans all that code looking for opcodes
7081 ** that reference the table and converts them into opcodes that
7082 ** reference the index.
7084 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
7085 pIdx = pLoop->u.btree.pIndex;
7086 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
7087 pIdx = pLevel->u.pCoveringIdx;
7089 if( pIdx
7090 && !db->mallocFailed
7092 if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
7093 last = iEnd;
7094 }else{
7095 last = pWInfo->iEndWhere;
7097 if( pIdx->bHasExpr ){
7098 IndexedExpr *p = pParse->pIdxEpr;
7099 while( p ){
7100 if( p->iIdxCur==pLevel->iIdxCur ){
7101 #ifdef WHERETRACE_ENABLED
7102 if( sqlite3WhereTrace & 0x200 ){
7103 sqlite3DebugPrintf("Disable pParse->pIdxEpr term {%d,%d}\n",
7104 p->iIdxCur, p->iIdxCol);
7105 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(p->pExpr);
7107 #endif
7108 p->iDataCur = -1;
7109 p->iIdxCur = -1;
7111 p = p->pIENext;
7114 k = pLevel->addrBody + 1;
7115 #ifdef SQLITE_DEBUG
7116 if( db->flags & SQLITE_VdbeAddopTrace ){
7117 printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n",
7118 pLevel->iTabCur, pLevel->iIdxCur, k, last-1);
7120 /* Proof that the "+1" on the k value above is safe */
7121 pOp = sqlite3VdbeGetOp(v, k - 1);
7122 assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
7123 assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur );
7124 assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
7125 #endif
7126 pOp = sqlite3VdbeGetOp(v, k);
7127 pLastOp = pOp + (last - k);
7128 assert( pOp<=pLastOp );
7130 if( pOp->p1!=pLevel->iTabCur ){
7131 /* no-op */
7132 }else if( pOp->opcode==OP_Column
7133 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
7134 || pOp->opcode==OP_Offset
7135 #endif
7137 int x = pOp->p2;
7138 assert( pIdx->pTable==pTab );
7139 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
7140 if( pOp->opcode==OP_Offset ){
7141 /* Do not need to translate the column number */
7142 }else
7143 #endif
7144 if( !HasRowid(pTab) ){
7145 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
7146 x = pPk->aiColumn[x];
7147 assert( x>=0 );
7148 }else{
7149 testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
7150 x = sqlite3StorageColumnToTable(pTab,x);
7152 x = sqlite3TableColumnToIndex(pIdx, x);
7153 if( x>=0 ){
7154 pOp->p2 = x;
7155 pOp->p1 = pLevel->iIdxCur;
7156 OpcodeRewriteTrace(db, k, pOp);
7157 }else{
7158 /* Unable to translate the table reference into an index
7159 ** reference. Verify that this is harmless - that the
7160 ** table being referenced really is open.
7162 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
7163 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
7164 || cursorIsOpen(v,pOp->p1,k)
7165 || pOp->opcode==OP_Offset
7167 #else
7168 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
7169 || cursorIsOpen(v,pOp->p1,k)
7171 #endif
7173 }else if( pOp->opcode==OP_Rowid ){
7174 pOp->p1 = pLevel->iIdxCur;
7175 pOp->opcode = OP_IdxRowid;
7176 OpcodeRewriteTrace(db, k, pOp);
7177 }else if( pOp->opcode==OP_IfNullRow ){
7178 pOp->p1 = pLevel->iIdxCur;
7179 OpcodeRewriteTrace(db, k, pOp);
7181 #ifdef SQLITE_DEBUG
7182 k++;
7183 #endif
7184 }while( (++pOp)<pLastOp );
7185 #ifdef SQLITE_DEBUG
7186 if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
7187 #endif
7191 /* The "break" point is here, just past the end of the outer loop.
7192 ** Set it.
7194 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
7196 /* Final cleanup
7198 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
7199 whereInfoFree(db, pWInfo);
7200 pParse->withinRJSubrtn -= nRJ;
7201 return;