Merge sqlite-release(3.43.1) into prerelease-integration
[sqlcipher.git] / src / where.c
blob213df4223024002c4d38c1db13b0561cbd8c46ef
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This module contains C code that generates VDBE code used to process
13 ** the WHERE clause of SQL statements. This module is responsible for
14 ** generating the code that loops through a table looking for applicable
15 ** rows. Indices are selected and used to speed the search when doing
16 ** so is applicable. Because this module is responsible for selecting
17 ** indices, you might also think of this module as the "query optimizer".
19 #include "sqliteInt.h"
20 #include "whereInt.h"
23 ** Extra information appended to the end of sqlite3_index_info but not
24 ** visible to the xBestIndex function, at least not directly. The
25 ** sqlite3_vtab_collation() interface knows how to reach it, however.
27 ** This object is not an API and can be changed from one release to the
28 ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
29 ** agree on the structure, all will be well.
31 typedef struct HiddenIndexInfo HiddenIndexInfo;
32 struct HiddenIndexInfo {
33 WhereClause *pWC; /* The Where clause being analyzed */
34 Parse *pParse; /* The parsing context */
35 int eDistinct; /* Value to return from sqlite3_vtab_distinct() */
36 u32 mIn; /* Mask of terms that are <col> IN (...) */
37 u32 mHandleIn; /* Terms that vtab will handle as <col> IN (...) */
38 sqlite3_value *aRhs[1]; /* RHS values for constraints. MUST BE LAST
39 ** because extra space is allocated to hold up
40 ** to nTerm such values */
43 /* Forward declaration of methods */
44 static int whereLoopResize(sqlite3*, WhereLoop*, int);
47 ** Return the estimated number of output rows from a WHERE clause
49 LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
50 return pWInfo->nRowOut;
54 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
55 ** WHERE clause returns outputs for DISTINCT processing.
57 int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
58 return pWInfo->eDistinct;
62 ** Return the number of ORDER BY terms that are satisfied by the
63 ** WHERE clause. A return of 0 means that the output must be
64 ** completely sorted. A return equal to the number of ORDER BY
65 ** terms means that no sorting is needed at all. A return that
66 ** is positive but less than the number of ORDER BY terms means that
67 ** block sorting is required.
69 int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
70 return pWInfo->nOBSat<0 ? 0 : pWInfo->nOBSat;
74 ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
75 ** to emit rows in increasing order, and if the last row emitted by the
76 ** inner-most loop did not fit within the sorter, then we can skip all
77 ** subsequent rows for the current iteration of the inner loop (because they
78 ** will not fit in the sorter either) and continue with the second inner
79 ** loop - the loop immediately outside the inner-most.
81 ** When a row does not fit in the sorter (because the sorter already
82 ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
83 ** label returned by this function.
85 ** If the ORDER BY LIMIT optimization applies, the jump destination should
86 ** be the continuation for the second-inner-most loop. If the ORDER BY
87 ** LIMIT optimization does not apply, then the jump destination should
88 ** be the continuation for the inner-most loop.
90 ** It is always safe for this routine to return the continuation of the
91 ** inner-most loop, in the sense that a correct answer will result.
92 ** Returning the continuation the second inner loop is an optimization
93 ** that might make the code run a little faster, but should not change
94 ** the final answer.
96 int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
97 WhereLevel *pInner;
98 if( !pWInfo->bOrderedInnerLoop ){
99 /* The ORDER BY LIMIT optimization does not apply. Jump to the
100 ** continuation of the inner-most loop. */
101 return pWInfo->iContinue;
103 pInner = &pWInfo->a[pWInfo->nLevel-1];
104 assert( pInner->addrNxt!=0 );
105 return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt;
109 ** While generating code for the min/max optimization, after handling
110 ** the aggregate-step call to min() or max(), check to see if any
111 ** additional looping is required. If the output order is such that
112 ** we are certain that the correct answer has already been found, then
113 ** code an OP_Goto to by pass subsequent processing.
115 ** Any extra OP_Goto that is coded here is an optimization. The
116 ** correct answer should be obtained regardless. This OP_Goto just
117 ** makes the answer appear faster.
119 void sqlite3WhereMinMaxOptEarlyOut(Vdbe *v, WhereInfo *pWInfo){
120 WhereLevel *pInner;
121 int i;
122 if( !pWInfo->bOrderedInnerLoop ) return;
123 if( pWInfo->nOBSat==0 ) return;
124 for(i=pWInfo->nLevel-1; i>=0; i--){
125 pInner = &pWInfo->a[i];
126 if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){
127 sqlite3VdbeGoto(v, pInner->addrNxt);
128 return;
131 sqlite3VdbeGoto(v, pWInfo->iBreak);
135 ** Return the VDBE address or label to jump to in order to continue
136 ** immediately with the next row of a WHERE clause.
138 int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
139 assert( pWInfo->iContinue!=0 );
140 return pWInfo->iContinue;
144 ** Return the VDBE address or label to jump to in order to break
145 ** out of a WHERE loop.
147 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
148 return pWInfo->iBreak;
152 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
153 ** operate directly on the rowids returned by a WHERE clause. Return
154 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
155 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
156 ** optimization can be used on multiple
158 ** If the ONEPASS optimization is used (if this routine returns true)
159 ** then also write the indices of open cursors used by ONEPASS
160 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
161 ** table and iaCur[1] gets the cursor used by an auxiliary index.
162 ** Either value may be -1, indicating that cursor is not used.
163 ** Any cursors returned will have been opened for writing.
165 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
166 ** unable to use the ONEPASS optimization.
168 int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
169 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
170 #ifdef WHERETRACE_ENABLED
171 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
172 sqlite3DebugPrintf("%s cursors: %d %d\n",
173 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
174 aiCur[0], aiCur[1]);
176 #endif
177 return pWInfo->eOnePass;
181 ** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move
182 ** the data cursor to the row selected by the index cursor.
184 int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
185 return pWInfo->bDeferredSeek;
189 ** Move the content of pSrc into pDest
191 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
192 pDest->n = pSrc->n;
193 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
197 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
199 ** The new entry might overwrite an existing entry, or it might be
200 ** appended, or it might be discarded. Do whatever is the right thing
201 ** so that pSet keeps the N_OR_COST best entries seen so far.
203 static int whereOrInsert(
204 WhereOrSet *pSet, /* The WhereOrSet to be updated */
205 Bitmask prereq, /* Prerequisites of the new entry */
206 LogEst rRun, /* Run-cost of the new entry */
207 LogEst nOut /* Number of outputs for the new entry */
209 u16 i;
210 WhereOrCost *p;
211 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
212 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
213 goto whereOrInsert_done;
215 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
216 return 0;
219 if( pSet->n<N_OR_COST ){
220 p = &pSet->a[pSet->n++];
221 p->nOut = nOut;
222 }else{
223 p = pSet->a;
224 for(i=1; i<pSet->n; i++){
225 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
227 if( p->rRun<=rRun ) return 0;
229 whereOrInsert_done:
230 p->prereq = prereq;
231 p->rRun = rRun;
232 if( p->nOut>nOut ) p->nOut = nOut;
233 return 1;
237 ** Return the bitmask for the given cursor number. Return 0 if
238 ** iCursor is not in the set.
240 Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
241 int i;
242 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
243 assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 );
244 assert( iCursor>=-1 );
245 if( pMaskSet->ix[0]==iCursor ){
246 return 1;
248 for(i=1; i<pMaskSet->n; i++){
249 if( pMaskSet->ix[i]==iCursor ){
250 return MASKBIT(i);
253 return 0;
256 /* Allocate memory that is automatically freed when pWInfo is freed.
258 void *sqlite3WhereMalloc(WhereInfo *pWInfo, u64 nByte){
259 WhereMemBlock *pBlock;
260 pBlock = sqlite3DbMallocRawNN(pWInfo->pParse->db, nByte+sizeof(*pBlock));
261 if( pBlock ){
262 pBlock->pNext = pWInfo->pMemToFree;
263 pBlock->sz = nByte;
264 pWInfo->pMemToFree = pBlock;
265 pBlock++;
267 return (void*)pBlock;
269 void *sqlite3WhereRealloc(WhereInfo *pWInfo, void *pOld, u64 nByte){
270 void *pNew = sqlite3WhereMalloc(pWInfo, nByte);
271 if( pNew && pOld ){
272 WhereMemBlock *pOldBlk = (WhereMemBlock*)pOld;
273 pOldBlk--;
274 assert( pOldBlk->sz<nByte );
275 memcpy(pNew, pOld, pOldBlk->sz);
277 return pNew;
281 ** Create a new mask for cursor iCursor.
283 ** There is one cursor per table in the FROM clause. The number of
284 ** tables in the FROM clause is limited by a test early in the
285 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
286 ** array will never overflow.
288 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
289 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
290 pMaskSet->ix[pMaskSet->n++] = iCursor;
294 ** If the right-hand branch of the expression is a TK_COLUMN, then return
295 ** a pointer to the right-hand branch. Otherwise, return NULL.
297 static Expr *whereRightSubexprIsColumn(Expr *p){
298 p = sqlite3ExprSkipCollateAndLikely(p->pRight);
299 if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
300 return p;
302 return 0;
306 ** Advance to the next WhereTerm that matches according to the criteria
307 ** established when the pScan object was initialized by whereScanInit().
308 ** Return NULL if there are no more matching WhereTerms.
310 static WhereTerm *whereScanNext(WhereScan *pScan){
311 int iCur; /* The cursor on the LHS of the term */
312 i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
313 Expr *pX; /* An expression being tested */
314 WhereClause *pWC; /* Shorthand for pScan->pWC */
315 WhereTerm *pTerm; /* The term being tested */
316 int k = pScan->k; /* Where to start scanning */
318 assert( pScan->iEquiv<=pScan->nEquiv );
319 pWC = pScan->pWC;
320 while(1){
321 iColumn = pScan->aiColumn[pScan->iEquiv-1];
322 iCur = pScan->aiCur[pScan->iEquiv-1];
323 assert( pWC!=0 );
324 assert( iCur>=0 );
326 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
327 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 || pTerm->leftCursor<0 );
328 if( pTerm->leftCursor==iCur
329 && pTerm->u.x.leftColumn==iColumn
330 && (iColumn!=XN_EXPR
331 || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
332 pScan->pIdxExpr,iCur)==0)
333 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))
335 if( (pTerm->eOperator & WO_EQUIV)!=0
336 && pScan->nEquiv<ArraySize(pScan->aiCur)
337 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
339 int j;
340 for(j=0; j<pScan->nEquiv; j++){
341 if( pScan->aiCur[j]==pX->iTable
342 && pScan->aiColumn[j]==pX->iColumn ){
343 break;
346 if( j==pScan->nEquiv ){
347 pScan->aiCur[j] = pX->iTable;
348 pScan->aiColumn[j] = pX->iColumn;
349 pScan->nEquiv++;
352 if( (pTerm->eOperator & pScan->opMask)!=0 ){
353 /* Verify the affinity and collating sequence match */
354 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
355 CollSeq *pColl;
356 Parse *pParse = pWC->pWInfo->pParse;
357 pX = pTerm->pExpr;
358 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
359 continue;
361 assert(pX->pLeft);
362 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
363 if( pColl==0 ) pColl = pParse->db->pDfltColl;
364 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
365 continue;
368 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
369 && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
370 && pX->op==TK_COLUMN
371 && pX->iTable==pScan->aiCur[0]
372 && pX->iColumn==pScan->aiColumn[0]
374 testcase( pTerm->eOperator & WO_IS );
375 continue;
377 pScan->pWC = pWC;
378 pScan->k = k+1;
379 #ifdef WHERETRACE_ENABLED
380 if( sqlite3WhereTrace & 0x20000 ){
381 int ii;
382 sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d",
383 pTerm, pScan->nEquiv);
384 for(ii=0; ii<pScan->nEquiv; ii++){
385 sqlite3DebugPrintf(" {%d:%d}",
386 pScan->aiCur[ii], pScan->aiColumn[ii]);
388 sqlite3DebugPrintf("\n");
390 #endif
391 return pTerm;
395 pWC = pWC->pOuter;
396 k = 0;
397 }while( pWC!=0 );
398 if( pScan->iEquiv>=pScan->nEquiv ) break;
399 pWC = pScan->pOrigWC;
400 k = 0;
401 pScan->iEquiv++;
403 return 0;
407 ** This is whereScanInit() for the case of an index on an expression.
408 ** It is factored out into a separate tail-recursion subroutine so that
409 ** the normal whereScanInit() routine, which is a high-runner, does not
410 ** need to push registers onto the stack as part of its prologue.
412 static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
413 pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
414 return whereScanNext(pScan);
418 ** Initialize a WHERE clause scanner object. Return a pointer to the
419 ** first match. Return NULL if there are no matches.
421 ** The scanner will be searching the WHERE clause pWC. It will look
422 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
423 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
424 ** must be one of the indexes of table iCur.
426 ** The <op> must be one of the operators described by opMask.
428 ** If the search is for X and the WHERE clause contains terms of the
429 ** form X=Y then this routine might also return terms of the form
430 ** "Y <op> <expr>". The number of levels of transitivity is limited,
431 ** but is enough to handle most commonly occurring SQL statements.
433 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
434 ** index pIdx.
436 static WhereTerm *whereScanInit(
437 WhereScan *pScan, /* The WhereScan object being initialized */
438 WhereClause *pWC, /* The WHERE clause to be scanned */
439 int iCur, /* Cursor to scan for */
440 int iColumn, /* Column to scan for */
441 u32 opMask, /* Operator(s) to scan for */
442 Index *pIdx /* Must be compatible with this index */
444 pScan->pOrigWC = pWC;
445 pScan->pWC = pWC;
446 pScan->pIdxExpr = 0;
447 pScan->idxaff = 0;
448 pScan->zCollName = 0;
449 pScan->opMask = opMask;
450 pScan->k = 0;
451 pScan->aiCur[0] = iCur;
452 pScan->nEquiv = 1;
453 pScan->iEquiv = 1;
454 if( pIdx ){
455 int j = iColumn;
456 iColumn = pIdx->aiColumn[j];
457 if( iColumn==pIdx->pTable->iPKey ){
458 iColumn = XN_ROWID;
459 }else if( iColumn>=0 ){
460 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
461 pScan->zCollName = pIdx->azColl[j];
462 }else if( iColumn==XN_EXPR ){
463 pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
464 pScan->zCollName = pIdx->azColl[j];
465 pScan->aiColumn[0] = XN_EXPR;
466 return whereScanInitIndexExpr(pScan);
468 }else if( iColumn==XN_EXPR ){
469 return 0;
471 pScan->aiColumn[0] = iColumn;
472 return whereScanNext(pScan);
476 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
477 ** where X is a reference to the iColumn of table iCur or of index pIdx
478 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
479 ** the op parameter. Return a pointer to the term. Return 0 if not found.
481 ** If pIdx!=0 then it must be one of the indexes of table iCur.
482 ** Search for terms matching the iColumn-th column of pIdx
483 ** rather than the iColumn-th column of table iCur.
485 ** The term returned might by Y=<expr> if there is another constraint in
486 ** the WHERE clause that specifies that X=Y. Any such constraints will be
487 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
488 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
489 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
490 ** other equivalent values. Hence a search for X will return <expr> if X=A1
491 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
493 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
494 ** then try for the one with no dependencies on <expr> - in other words where
495 ** <expr> is a constant expression of some kind. Only return entries of
496 ** the form "X <op> Y" where Y is a column in another table if no terms of
497 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
498 ** exist, try to return a term that does not use WO_EQUIV.
500 WhereTerm *sqlite3WhereFindTerm(
501 WhereClause *pWC, /* The WHERE clause to be searched */
502 int iCur, /* Cursor number of LHS */
503 int iColumn, /* Column number of LHS */
504 Bitmask notReady, /* RHS must not overlap with this mask */
505 u32 op, /* Mask of WO_xx values describing operator */
506 Index *pIdx /* Must be compatible with this index, if not NULL */
508 WhereTerm *pResult = 0;
509 WhereTerm *p;
510 WhereScan scan;
512 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
513 op &= WO_EQ|WO_IS;
514 while( p ){
515 if( (p->prereqRight & notReady)==0 ){
516 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
517 testcase( p->eOperator & WO_IS );
518 return p;
520 if( pResult==0 ) pResult = p;
522 p = whereScanNext(&scan);
524 return pResult;
528 ** This function searches pList for an entry that matches the iCol-th column
529 ** of index pIdx.
531 ** If such an expression is found, its index in pList->a[] is returned. If
532 ** no expression is found, -1 is returned.
534 static int findIndexCol(
535 Parse *pParse, /* Parse context */
536 ExprList *pList, /* Expression list to search */
537 int iBase, /* Cursor for table associated with pIdx */
538 Index *pIdx, /* Index to match column of */
539 int iCol /* Column of index to match */
541 int i;
542 const char *zColl = pIdx->azColl[iCol];
544 for(i=0; i<pList->nExpr; i++){
545 Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
546 if( ALWAYS(p!=0)
547 && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
548 && p->iColumn==pIdx->aiColumn[iCol]
549 && p->iTable==iBase
551 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
552 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
553 return i;
558 return -1;
562 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
564 static int indexColumnNotNull(Index *pIdx, int iCol){
565 int j;
566 assert( pIdx!=0 );
567 assert( iCol>=0 && iCol<pIdx->nColumn );
568 j = pIdx->aiColumn[iCol];
569 if( j>=0 ){
570 return pIdx->pTable->aCol[j].notNull;
571 }else if( j==(-1) ){
572 return 1;
573 }else{
574 assert( j==(-2) );
575 return 0; /* Assume an indexed expression can always yield a NULL */
581 ** Return true if the DISTINCT expression-list passed as the third argument
582 ** is redundant.
584 ** A DISTINCT list is redundant if any subset of the columns in the
585 ** DISTINCT list are collectively unique and individually non-null.
587 static int isDistinctRedundant(
588 Parse *pParse, /* Parsing context */
589 SrcList *pTabList, /* The FROM clause */
590 WhereClause *pWC, /* The WHERE clause */
591 ExprList *pDistinct /* The result set that needs to be DISTINCT */
593 Table *pTab;
594 Index *pIdx;
595 int i;
596 int iBase;
598 /* If there is more than one table or sub-select in the FROM clause of
599 ** this query, then it will not be possible to show that the DISTINCT
600 ** clause is redundant. */
601 if( pTabList->nSrc!=1 ) return 0;
602 iBase = pTabList->a[0].iCursor;
603 pTab = pTabList->a[0].pTab;
605 /* If any of the expressions is an IPK column on table iBase, then return
606 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
607 ** current SELECT is a correlated sub-query.
609 for(i=0; i<pDistinct->nExpr; i++){
610 Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
611 if( NEVER(p==0) ) continue;
612 if( p->op!=TK_COLUMN && p->op!=TK_AGG_COLUMN ) continue;
613 if( p->iTable==iBase && p->iColumn<0 ) return 1;
616 /* Loop through all indices on the table, checking each to see if it makes
617 ** the DISTINCT qualifier redundant. It does so if:
619 ** 1. The index is itself UNIQUE, and
621 ** 2. All of the columns in the index are either part of the pDistinct
622 ** list, or else the WHERE clause contains a term of the form "col=X",
623 ** where X is a constant value. The collation sequences of the
624 ** comparison and select-list expressions must match those of the index.
626 ** 3. All of those index columns for which the WHERE clause does not
627 ** contain a "col=X" term are subject to a NOT NULL constraint.
629 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
630 if( !IsUniqueIndex(pIdx) ) continue;
631 if( pIdx->pPartIdxWhere ) continue;
632 for(i=0; i<pIdx->nKeyCol; i++){
633 if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
634 if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
635 if( indexColumnNotNull(pIdx, i)==0 ) break;
638 if( i==pIdx->nKeyCol ){
639 /* This index implies that the DISTINCT qualifier is redundant. */
640 return 1;
644 return 0;
649 ** Estimate the logarithm of the input value to base 2.
651 static LogEst estLog(LogEst N){
652 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
656 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
658 ** This routine runs over generated VDBE code and translates OP_Column
659 ** opcodes into OP_Copy when the table is being accessed via co-routine
660 ** instead of via table lookup.
662 ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
663 ** cursor iTabCur are transformed into OP_Sequence opcode for the
664 ** iAutoidxCur cursor, in order to generate unique rowids for the
665 ** automatic index being generated.
667 static void translateColumnToCopy(
668 Parse *pParse, /* Parsing context */
669 int iStart, /* Translate from this opcode to the end */
670 int iTabCur, /* OP_Column/OP_Rowid references to this table */
671 int iRegister, /* The first column is in this register */
672 int iAutoidxCur /* If non-zero, cursor of autoindex being generated */
674 Vdbe *v = pParse->pVdbe;
675 VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
676 int iEnd = sqlite3VdbeCurrentAddr(v);
677 if( pParse->db->mallocFailed ) return;
678 for(; iStart<iEnd; iStart++, pOp++){
679 if( pOp->p1!=iTabCur ) continue;
680 if( pOp->opcode==OP_Column ){
681 pOp->opcode = OP_Copy;
682 pOp->p1 = pOp->p2 + iRegister;
683 pOp->p2 = pOp->p3;
684 pOp->p3 = 0;
685 pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */
686 }else if( pOp->opcode==OP_Rowid ){
687 pOp->opcode = OP_Sequence;
688 pOp->p1 = iAutoidxCur;
689 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
690 if( iAutoidxCur==0 ){
691 pOp->opcode = OP_Null;
692 pOp->p3 = 0;
694 #endif
700 ** Two routines for printing the content of an sqlite3_index_info
701 ** structure. Used for testing and debugging only. If neither
702 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
703 ** are no-ops.
705 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
706 static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
707 int i;
708 if( (sqlite3WhereTrace & 0x10)==0 ) return;
709 for(i=0; i<p->nConstraint; i++){
710 sqlite3DebugPrintf(
711 " constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",
713 p->aConstraint[i].iColumn,
714 p->aConstraint[i].iTermOffset,
715 p->aConstraint[i].op,
716 p->aConstraint[i].usable,
717 sqlite3_vtab_collation(p,i));
719 for(i=0; i<p->nOrderBy; i++){
720 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
722 p->aOrderBy[i].iColumn,
723 p->aOrderBy[i].desc);
726 static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
727 int i;
728 if( (sqlite3WhereTrace & 0x10)==0 ) return;
729 for(i=0; i<p->nConstraint; i++){
730 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
732 p->aConstraintUsage[i].argvIndex,
733 p->aConstraintUsage[i].omit);
735 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
736 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
737 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
738 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
739 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
741 #else
742 #define whereTraceIndexInfoInputs(A)
743 #define whereTraceIndexInfoOutputs(A)
744 #endif
747 ** We know that pSrc is an operand of an outer join. Return true if
748 ** pTerm is a constraint that is compatible with that join.
750 ** pTerm must be EP_OuterON if pSrc is the right operand of an
751 ** outer join. pTerm can be either EP_OuterON or EP_InnerON if pSrc
752 ** is the left operand of a RIGHT join.
754 ** See https://sqlite.org/forum/forumpost/206d99a16dd9212f
755 ** for an example of a WHERE clause constraints that may not be used on
756 ** the right table of a RIGHT JOIN because the constraint implies a
757 ** not-NULL condition on the left table of the RIGHT JOIN.
759 static int constraintCompatibleWithOuterJoin(
760 const WhereTerm *pTerm, /* WHERE clause term to check */
761 const SrcItem *pSrc /* Table we are trying to access */
763 assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */
764 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT );
765 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ );
766 testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) )
767 testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) );
768 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON)
769 || pTerm->pExpr->w.iJoin != pSrc->iCursor
771 return 0;
773 if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0
774 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
776 return 0;
778 return 1;
783 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
785 ** Return TRUE if the WHERE clause term pTerm is of a form where it
786 ** could be used with an index to access pSrc, assuming an appropriate
787 ** index existed.
789 static int termCanDriveIndex(
790 const WhereTerm *pTerm, /* WHERE clause term to check */
791 const SrcItem *pSrc, /* Table we are trying to access */
792 const Bitmask notReady /* Tables in outer loops of the join */
794 char aff;
795 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
796 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
797 assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
798 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
799 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
801 return 0; /* See https://sqlite.org/forum/forumpost/51e6959f61 */
803 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
804 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
805 if( pTerm->u.x.leftColumn<0 ) return 0;
806 aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
807 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
808 testcase( pTerm->pExpr->op==TK_IS );
809 return 1;
811 #endif
814 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
816 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
818 ** Argument pIdx represents an automatic index that the current statement
819 ** will create and populate. Add an OP_Explain with text of the form:
821 ** CREATE AUTOMATIC INDEX ON <table>(<cols>) [WHERE <expr>]
823 ** This is only required if sqlite3_stmt_scanstatus() is enabled, to
824 ** associate an SQLITE_SCANSTAT_NCYCLE and SQLITE_SCANSTAT_NLOOP
825 ** values with. In order to avoid breaking legacy code and test cases,
826 ** the OP_Explain is not added if this is an EXPLAIN QUERY PLAN command.
828 static void explainAutomaticIndex(
829 Parse *pParse,
830 Index *pIdx, /* Automatic index to explain */
831 int bPartial, /* True if pIdx is a partial index */
832 int *pAddrExplain /* OUT: Address of OP_Explain */
834 if( IS_STMT_SCANSTATUS(pParse->db) && pParse->explain!=2 ){
835 Table *pTab = pIdx->pTable;
836 const char *zSep = "";
837 char *zText = 0;
838 int ii = 0;
839 sqlite3_str *pStr = sqlite3_str_new(pParse->db);
840 sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName);
841 assert( pIdx->nColumn>1 );
842 assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID );
843 for(ii=0; ii<(pIdx->nColumn-1); ii++){
844 const char *zName = 0;
845 int iCol = pIdx->aiColumn[ii];
847 zName = pTab->aCol[iCol].zCnName;
848 sqlite3_str_appendf(pStr, "%s%s", zSep, zName);
849 zSep = ", ";
851 zText = sqlite3_str_finish(pStr);
852 if( zText==0 ){
853 sqlite3OomFault(pParse->db);
854 }else{
855 *pAddrExplain = sqlite3VdbeExplain(
856 pParse, 0, "%s)%s", zText, (bPartial ? " WHERE <expr>" : "")
858 sqlite3_free(zText);
862 #else
863 # define explainAutomaticIndex(a,b,c,d)
864 #endif
867 ** Generate code to construct the Index object for an automatic index
868 ** and to set up the WhereLevel object pLevel so that the code generator
869 ** makes use of the automatic index.
871 static SQLITE_NOINLINE void constructAutomaticIndex(
872 Parse *pParse, /* The parsing context */
873 WhereClause *pWC, /* The WHERE clause */
874 const Bitmask notReady, /* Mask of cursors that are not available */
875 WhereLevel *pLevel /* Write new index here */
877 int nKeyCol; /* Number of columns in the constructed index */
878 WhereTerm *pTerm; /* A single term of the WHERE clause */
879 WhereTerm *pWCEnd; /* End of pWC->a[] */
880 Index *pIdx; /* Object describing the transient index */
881 Vdbe *v; /* Prepared statement under construction */
882 int addrInit; /* Address of the initialization bypass jump */
883 Table *pTable; /* The table being indexed */
884 int addrTop; /* Top of the index fill loop */
885 int regRecord; /* Register holding an index record */
886 int n; /* Column counter */
887 int i; /* Loop counter */
888 int mxBitCol; /* Maximum column in pSrc->colUsed */
889 CollSeq *pColl; /* Collating sequence to on a column */
890 WhereLoop *pLoop; /* The Loop object */
891 char *zNotUsed; /* Extra space on the end of pIdx */
892 Bitmask idxCols; /* Bitmap of columns used for indexing */
893 Bitmask extraCols; /* Bitmap of additional columns */
894 u8 sentWarning = 0; /* True if a warning has been issued */
895 u8 useBloomFilter = 0; /* True to also add a Bloom filter */
896 Expr *pPartial = 0; /* Partial Index Expression */
897 int iContinue = 0; /* Jump here to skip excluded rows */
898 SrcList *pTabList; /* The complete FROM clause */
899 SrcItem *pSrc; /* The FROM clause term to get the next index */
900 int addrCounter = 0; /* Address where integer counter is initialized */
901 int regBase; /* Array of registers where record is assembled */
902 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
903 int addrExp = 0; /* Address of OP_Explain */
904 #endif
906 /* Generate code to skip over the creation and initialization of the
907 ** transient index on 2nd and subsequent iterations of the loop. */
908 v = pParse->pVdbe;
909 assert( v!=0 );
910 addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
912 /* Count the number of columns that will be added to the index
913 ** and used to match WHERE clause constraints */
914 nKeyCol = 0;
915 pTabList = pWC->pWInfo->pTabList;
916 pSrc = &pTabList->a[pLevel->iFrom];
917 pTable = pSrc->pTab;
918 pWCEnd = &pWC->a[pWC->nTerm];
919 pLoop = pLevel->pWLoop;
920 idxCols = 0;
921 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
922 Expr *pExpr = pTerm->pExpr;
923 /* Make the automatic index a partial index if there are terms in the
924 ** WHERE clause (or the ON clause of a LEFT join) that constrain which
925 ** rows of the target table (pSrc) that can be used. */
926 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
927 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, pLevel->iFrom)
929 pPartial = sqlite3ExprAnd(pParse, pPartial,
930 sqlite3ExprDup(pParse->db, pExpr, 0));
932 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
933 int iCol;
934 Bitmask cMask;
935 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
936 iCol = pTerm->u.x.leftColumn;
937 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
938 testcase( iCol==BMS );
939 testcase( iCol==BMS-1 );
940 if( !sentWarning ){
941 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
942 "automatic index on %s(%s)", pTable->zName,
943 pTable->aCol[iCol].zCnName);
944 sentWarning = 1;
946 if( (idxCols & cMask)==0 ){
947 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
948 goto end_auto_index_create;
950 pLoop->aLTerm[nKeyCol++] = pTerm;
951 idxCols |= cMask;
955 assert( nKeyCol>0 || pParse->db->mallocFailed );
956 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
957 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
958 | WHERE_AUTO_INDEX;
960 /* Count the number of additional columns needed to create a
961 ** covering index. A "covering index" is an index that contains all
962 ** columns that are needed by the query. With a covering index, the
963 ** original table never needs to be accessed. Automatic indices must
964 ** be a covering index because the index will not be updated if the
965 ** original table changes and the index and table cannot both be used
966 ** if they go out of sync.
968 if( IsView(pTable) ){
969 extraCols = ALLBITS;
970 }else{
971 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
973 mxBitCol = MIN(BMS-1,pTable->nCol);
974 testcase( pTable->nCol==BMS-1 );
975 testcase( pTable->nCol==BMS-2 );
976 for(i=0; i<mxBitCol; i++){
977 if( extraCols & MASKBIT(i) ) nKeyCol++;
979 if( pSrc->colUsed & MASKBIT(BMS-1) ){
980 nKeyCol += pTable->nCol - BMS + 1;
983 /* Construct the Index object to describe this index */
984 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
985 if( pIdx==0 ) goto end_auto_index_create;
986 pLoop->u.btree.pIndex = pIdx;
987 pIdx->zName = "auto-index";
988 pIdx->pTable = pTable;
989 n = 0;
990 idxCols = 0;
991 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
992 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
993 int iCol;
994 Bitmask cMask;
995 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
996 iCol = pTerm->u.x.leftColumn;
997 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
998 testcase( iCol==BMS-1 );
999 testcase( iCol==BMS );
1000 if( (idxCols & cMask)==0 ){
1001 Expr *pX = pTerm->pExpr;
1002 idxCols |= cMask;
1003 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
1004 pColl = sqlite3ExprCompareCollSeq(pParse, pX);
1005 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
1006 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
1007 n++;
1008 if( ALWAYS(pX->pLeft!=0)
1009 && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT
1011 /* TUNING: only use a Bloom filter on an automatic index
1012 ** if one or more key columns has the ability to hold numeric
1013 ** values, since strings all have the same hash in the Bloom
1014 ** filter implementation and hence a Bloom filter on a text column
1015 ** is not usually helpful. */
1016 useBloomFilter = 1;
1021 assert( (u32)n==pLoop->u.btree.nEq );
1023 /* Add additional columns needed to make the automatic index into
1024 ** a covering index */
1025 for(i=0; i<mxBitCol; i++){
1026 if( extraCols & MASKBIT(i) ){
1027 pIdx->aiColumn[n] = i;
1028 pIdx->azColl[n] = sqlite3StrBINARY;
1029 n++;
1032 if( pSrc->colUsed & MASKBIT(BMS-1) ){
1033 for(i=BMS-1; i<pTable->nCol; i++){
1034 pIdx->aiColumn[n] = i;
1035 pIdx->azColl[n] = sqlite3StrBINARY;
1036 n++;
1039 assert( n==nKeyCol );
1040 pIdx->aiColumn[n] = XN_ROWID;
1041 pIdx->azColl[n] = sqlite3StrBINARY;
1043 /* Create the automatic index */
1044 explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp);
1045 assert( pLevel->iIdxCur>=0 );
1046 pLevel->iIdxCur = pParse->nTab++;
1047 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
1048 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1049 VdbeComment((v, "for %s", pTable->zName));
1050 if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) && useBloomFilter ){
1051 sqlite3WhereExplainBloomFilter(pParse, pWC->pWInfo, pLevel);
1052 pLevel->regFilter = ++pParse->nMem;
1053 sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
1056 /* Fill the automatic index with content */
1057 assert( pSrc == &pWC->pWInfo->pTabList->a[pLevel->iFrom] );
1058 if( pSrc->fg.viaCoroutine ){
1059 int regYield = pSrc->regReturn;
1060 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
1061 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSrc->addrFillSub);
1062 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
1063 VdbeCoverage(v);
1064 VdbeComment((v, "next row of %s", pSrc->pTab->zName));
1065 }else{
1066 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
1068 if( pPartial ){
1069 iContinue = sqlite3VdbeMakeLabel(pParse);
1070 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
1071 pLoop->wsFlags |= WHERE_PARTIALIDX;
1073 regRecord = sqlite3GetTempReg(pParse);
1074 regBase = sqlite3GenerateIndexKey(
1075 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
1077 if( pLevel->regFilter ){
1078 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
1079 regBase, pLoop->u.btree.nEq);
1081 sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v));
1082 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1083 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1084 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
1085 if( pSrc->fg.viaCoroutine ){
1086 sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
1087 testcase( pParse->db->mallocFailed );
1088 assert( pLevel->iIdxCur>0 );
1089 translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
1090 pSrc->regResult, pLevel->iIdxCur);
1091 sqlite3VdbeGoto(v, addrTop);
1092 pSrc->fg.viaCoroutine = 0;
1093 }else{
1094 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
1095 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
1097 sqlite3VdbeJumpHere(v, addrTop);
1098 sqlite3ReleaseTempReg(pParse, regRecord);
1100 /* Jump here when skipping the initialization */
1101 sqlite3VdbeJumpHere(v, addrInit);
1102 sqlite3VdbeScanStatusRange(v, addrExp, addrExp, -1);
1104 end_auto_index_create:
1105 sqlite3ExprDelete(pParse->db, pPartial);
1107 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1110 ** Generate bytecode that will initialize a Bloom filter that is appropriate
1111 ** for pLevel.
1113 ** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER
1114 ** flag set, initialize a Bloomfilter for them as well. Except don't do
1115 ** this recursive initialization if the SQLITE_BloomPulldown optimization has
1116 ** been turned off.
1118 ** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared
1119 ** from the loop, but the regFilter value is set to a register that implements
1120 ** the Bloom filter. When regFilter is positive, the
1121 ** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter
1122 ** and skip the subsequence B-Tree seek if the Bloom filter indicates that
1123 ** no matching rows exist.
1125 ** This routine may only be called if it has previously been determined that
1126 ** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit
1127 ** is set.
1129 static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
1130 WhereInfo *pWInfo, /* The WHERE clause */
1131 int iLevel, /* Index in pWInfo->a[] that is pLevel */
1132 WhereLevel *pLevel, /* Make a Bloom filter for this FROM term */
1133 Bitmask notReady /* Loops that are not ready */
1135 int addrOnce; /* Address of opening OP_Once */
1136 int addrTop; /* Address of OP_Rewind */
1137 int addrCont; /* Jump here to skip a row */
1138 const WhereTerm *pTerm; /* For looping over WHERE clause terms */
1139 const WhereTerm *pWCEnd; /* Last WHERE clause term */
1140 Parse *pParse = pWInfo->pParse; /* Parsing context */
1141 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
1142 WhereLoop *pLoop = pLevel->pWLoop; /* The loop being coded */
1143 int iCur; /* Cursor for table getting the filter */
1144 IndexedExpr *saved_pIdxEpr; /* saved copy of Parse.pIdxEpr */
1146 saved_pIdxEpr = pParse->pIdxEpr;
1147 pParse->pIdxEpr = 0;
1149 assert( pLoop!=0 );
1150 assert( v!=0 );
1151 assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
1153 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
1155 const SrcList *pTabList;
1156 const SrcItem *pItem;
1157 const Table *pTab;
1158 u64 sz;
1159 int iSrc;
1160 sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
1161 addrCont = sqlite3VdbeMakeLabel(pParse);
1162 iCur = pLevel->iTabCur;
1163 pLevel->regFilter = ++pParse->nMem;
1165 /* The Bloom filter is a Blob held in a register. Initialize it
1166 ** to zero-filled blob of at least 80K bits, but maybe more if the
1167 ** estimated size of the table is larger. We could actually
1168 ** measure the size of the table at run-time using OP_Count with
1169 ** P3==1 and use that value to initialize the blob. But that makes
1170 ** testing complicated. By basing the blob size on the value in the
1171 ** sqlite_stat1 table, testing is much easier.
1173 pTabList = pWInfo->pTabList;
1174 iSrc = pLevel->iFrom;
1175 pItem = &pTabList->a[iSrc];
1176 assert( pItem!=0 );
1177 pTab = pItem->pTab;
1178 assert( pTab!=0 );
1179 sz = sqlite3LogEstToInt(pTab->nRowLogEst);
1180 if( sz<10000 ){
1181 sz = 10000;
1182 }else if( sz>10000000 ){
1183 sz = 10000000;
1185 sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
1187 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
1188 pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
1189 for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
1190 Expr *pExpr = pTerm->pExpr;
1191 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
1192 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, iSrc)
1194 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1197 if( pLoop->wsFlags & WHERE_IPK ){
1198 int r1 = sqlite3GetTempReg(pParse);
1199 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
1200 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
1201 sqlite3ReleaseTempReg(pParse, r1);
1202 }else{
1203 Index *pIdx = pLoop->u.btree.pIndex;
1204 int n = pLoop->u.btree.nEq;
1205 int r1 = sqlite3GetTempRange(pParse, n);
1206 int jj;
1207 for(jj=0; jj<n; jj++){
1208 assert( pIdx->pTable==pItem->pTab );
1209 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj);
1211 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
1212 sqlite3ReleaseTempRange(pParse, r1, n);
1214 sqlite3VdbeResolveLabel(v, addrCont);
1215 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
1216 VdbeCoverage(v);
1217 sqlite3VdbeJumpHere(v, addrTop);
1218 pLoop->wsFlags &= ~WHERE_BLOOMFILTER;
1219 if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break;
1220 while( ++iLevel < pWInfo->nLevel ){
1221 const SrcItem *pTabItem;
1222 pLevel = &pWInfo->a[iLevel];
1223 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
1224 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ) ) continue;
1225 pLoop = pLevel->pWLoop;
1226 if( NEVER(pLoop==0) ) continue;
1227 if( pLoop->prereq & notReady ) continue;
1228 if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN))
1229 ==WHERE_BLOOMFILTER
1231 /* This is a candidate for bloom-filter pull-down (early evaluation).
1232 ** The test that WHERE_COLUMN_IN is omitted is important, as we are
1233 ** not able to do early evaluation of bloom filters that make use of
1234 ** the IN operator */
1235 break;
1238 }while( iLevel < pWInfo->nLevel );
1239 sqlite3VdbeJumpHere(v, addrOnce);
1240 pParse->pIdxEpr = saved_pIdxEpr;
1244 #ifndef SQLITE_OMIT_VIRTUALTABLE
1246 ** Allocate and populate an sqlite3_index_info structure. It is the
1247 ** responsibility of the caller to eventually release the structure
1248 ** by passing the pointer returned by this function to freeIndexInfo().
1250 static sqlite3_index_info *allocateIndexInfo(
1251 WhereInfo *pWInfo, /* The WHERE clause */
1252 WhereClause *pWC, /* The WHERE clause being analyzed */
1253 Bitmask mUnusable, /* Ignore terms with these prereqs */
1254 SrcItem *pSrc, /* The FROM clause term that is the vtab */
1255 u16 *pmNoOmit /* Mask of terms not to omit */
1257 int i, j;
1258 int nTerm;
1259 Parse *pParse = pWInfo->pParse;
1260 struct sqlite3_index_constraint *pIdxCons;
1261 struct sqlite3_index_orderby *pIdxOrderBy;
1262 struct sqlite3_index_constraint_usage *pUsage;
1263 struct HiddenIndexInfo *pHidden;
1264 WhereTerm *pTerm;
1265 int nOrderBy;
1266 sqlite3_index_info *pIdxInfo;
1267 u16 mNoOmit = 0;
1268 const Table *pTab;
1269 int eDistinct = 0;
1270 ExprList *pOrderBy = pWInfo->pOrderBy;
1272 assert( pSrc!=0 );
1273 pTab = pSrc->pTab;
1274 assert( pTab!=0 );
1275 assert( IsVirtual(pTab) );
1277 /* Find all WHERE clause constraints referring to this virtual table.
1278 ** Mark each term with the TERM_OK flag. Set nTerm to the number of
1279 ** terms found.
1281 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1282 pTerm->wtFlags &= ~TERM_OK;
1283 if( pTerm->leftCursor != pSrc->iCursor ) continue;
1284 if( pTerm->prereqRight & mUnusable ) continue;
1285 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
1286 testcase( pTerm->eOperator & WO_IN );
1287 testcase( pTerm->eOperator & WO_ISNULL );
1288 testcase( pTerm->eOperator & WO_IS );
1289 testcase( pTerm->eOperator & WO_ALL );
1290 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
1291 if( pTerm->wtFlags & TERM_VNULL ) continue;
1293 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
1294 assert( pTerm->u.x.leftColumn>=XN_ROWID );
1295 assert( pTerm->u.x.leftColumn<pTab->nCol );
1296 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
1297 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
1299 continue;
1301 nTerm++;
1302 pTerm->wtFlags |= TERM_OK;
1305 /* If the ORDER BY clause contains only columns in the current
1306 ** virtual table then allocate space for the aOrderBy part of
1307 ** the sqlite3_index_info structure.
1309 nOrderBy = 0;
1310 if( pOrderBy ){
1311 int n = pOrderBy->nExpr;
1312 for(i=0; i<n; i++){
1313 Expr *pExpr = pOrderBy->a[i].pExpr;
1314 Expr *pE2;
1316 /* Skip over constant terms in the ORDER BY clause */
1317 if( sqlite3ExprIsConstant(pExpr) ){
1318 continue;
1321 /* Virtual tables are unable to deal with NULLS FIRST */
1322 if( pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) break;
1324 /* First case - a direct column references without a COLLATE operator */
1325 if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){
1326 assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumn<pTab->nCol );
1327 continue;
1330 /* 2nd case - a column reference with a COLLATE operator. Only match
1331 ** of the COLLATE operator matches the collation of the column. */
1332 if( pExpr->op==TK_COLLATE
1333 && (pE2 = pExpr->pLeft)->op==TK_COLUMN
1334 && pE2->iTable==pSrc->iCursor
1336 const char *zColl; /* The collating sequence name */
1337 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1338 assert( pExpr->u.zToken!=0 );
1339 assert( pE2->iColumn>=XN_ROWID && pE2->iColumn<pTab->nCol );
1340 pExpr->iColumn = pE2->iColumn;
1341 if( pE2->iColumn<0 ) continue; /* Collseq does not matter for rowid */
1342 zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]);
1343 if( zColl==0 ) zColl = sqlite3StrBINARY;
1344 if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue;
1347 /* No matches cause a break out of the loop */
1348 break;
1350 if( i==n ){
1351 nOrderBy = n;
1352 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) ){
1353 eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
1354 }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
1355 eDistinct = 1;
1360 /* Allocate the sqlite3_index_info structure
1362 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1363 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1364 + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden)
1365 + sizeof(sqlite3_value*)*nTerm );
1366 if( pIdxInfo==0 ){
1367 sqlite3ErrorMsg(pParse, "out of memory");
1368 return 0;
1370 pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
1371 pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm];
1372 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1373 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1374 pIdxInfo->aConstraint = pIdxCons;
1375 pIdxInfo->aOrderBy = pIdxOrderBy;
1376 pIdxInfo->aConstraintUsage = pUsage;
1377 pHidden->pWC = pWC;
1378 pHidden->pParse = pParse;
1379 pHidden->eDistinct = eDistinct;
1380 pHidden->mIn = 0;
1381 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1382 u16 op;
1383 if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
1384 pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
1385 pIdxCons[j].iTermOffset = i;
1386 op = pTerm->eOperator & WO_ALL;
1387 if( op==WO_IN ){
1388 if( (pTerm->wtFlags & TERM_SLICE)==0 ){
1389 pHidden->mIn |= SMASKBIT32(j);
1391 op = WO_EQ;
1393 if( op==WO_AUX ){
1394 pIdxCons[j].op = pTerm->eMatchOp;
1395 }else if( op & (WO_ISNULL|WO_IS) ){
1396 if( op==WO_ISNULL ){
1397 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
1398 }else{
1399 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
1401 }else{
1402 pIdxCons[j].op = (u8)op;
1403 /* The direct assignment in the previous line is possible only because
1404 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1405 ** following asserts verify this fact. */
1406 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1407 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1408 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1409 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1410 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1411 assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
1413 if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
1414 && sqlite3ExprIsVector(pTerm->pExpr->pRight)
1416 testcase( j!=i );
1417 if( j<16 ) mNoOmit |= (1 << j);
1418 if( op==WO_LT ) pIdxCons[j].op = WO_LE;
1419 if( op==WO_GT ) pIdxCons[j].op = WO_GE;
1423 j++;
1425 assert( j==nTerm );
1426 pIdxInfo->nConstraint = j;
1427 for(i=j=0; i<nOrderBy; i++){
1428 Expr *pExpr = pOrderBy->a[i].pExpr;
1429 if( sqlite3ExprIsConstant(pExpr) ) continue;
1430 assert( pExpr->op==TK_COLUMN
1431 || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
1432 && pExpr->iColumn==pExpr->pLeft->iColumn) );
1433 pIdxOrderBy[j].iColumn = pExpr->iColumn;
1434 pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
1435 j++;
1437 pIdxInfo->nOrderBy = j;
1439 *pmNoOmit = mNoOmit;
1440 return pIdxInfo;
1444 ** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
1445 ** and possibly modified by xBestIndex methods.
1447 static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
1448 HiddenIndexInfo *pHidden;
1449 int i;
1450 assert( pIdxInfo!=0 );
1451 pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
1452 assert( pHidden->pParse!=0 );
1453 assert( pHidden->pParse->db==db );
1454 for(i=0; i<pIdxInfo->nConstraint; i++){
1455 sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
1456 pHidden->aRhs[i] = 0;
1458 sqlite3DbFree(db, pIdxInfo);
1462 ** The table object reference passed as the second argument to this function
1463 ** must represent a virtual table. This function invokes the xBestIndex()
1464 ** method of the virtual table with the sqlite3_index_info object that
1465 ** comes in as the 3rd argument to this function.
1467 ** If an error occurs, pParse is populated with an error message and an
1468 ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
1469 ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
1470 ** the current configuration of "unusable" flags in sqlite3_index_info can
1471 ** not result in a valid plan.
1473 ** Whether or not an error is returned, it is the responsibility of the
1474 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
1475 ** that this is required.
1477 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
1478 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
1479 int rc;
1481 whereTraceIndexInfoInputs(p);
1482 pParse->db->nSchemaLock++;
1483 rc = pVtab->pModule->xBestIndex(pVtab, p);
1484 pParse->db->nSchemaLock--;
1485 whereTraceIndexInfoOutputs(p);
1487 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
1488 if( rc==SQLITE_NOMEM ){
1489 sqlite3OomFault(pParse->db);
1490 }else if( !pVtab->zErrMsg ){
1491 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
1492 }else{
1493 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
1496 if( pTab->u.vtab.p->bAllSchemas ){
1497 sqlite3VtabUsesAllSchemas(pParse);
1499 sqlite3_free(pVtab->zErrMsg);
1500 pVtab->zErrMsg = 0;
1501 return rc;
1503 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
1505 #ifdef SQLITE_ENABLE_STAT4
1507 ** Estimate the location of a particular key among all keys in an
1508 ** index. Store the results in aStat as follows:
1510 ** aStat[0] Est. number of rows less than pRec
1511 ** aStat[1] Est. number of rows equal to pRec
1513 ** Return the index of the sample that is the smallest sample that
1514 ** is greater than or equal to pRec. Note that this index is not an index
1515 ** into the aSample[] array - it is an index into a virtual set of samples
1516 ** based on the contents of aSample[] and the number of fields in record
1517 ** pRec.
1519 static int whereKeyStats(
1520 Parse *pParse, /* Database connection */
1521 Index *pIdx, /* Index to consider domain of */
1522 UnpackedRecord *pRec, /* Vector of values to consider */
1523 int roundUp, /* Round up if true. Round down if false */
1524 tRowcnt *aStat /* OUT: stats written here */
1526 IndexSample *aSample = pIdx->aSample;
1527 int iCol; /* Index of required stats in anEq[] etc. */
1528 int i; /* Index of first sample >= pRec */
1529 int iSample; /* Smallest sample larger than or equal to pRec */
1530 int iMin = 0; /* Smallest sample not yet tested */
1531 int iTest; /* Next sample to test */
1532 int res; /* Result of comparison operation */
1533 int nField; /* Number of fields in pRec */
1534 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
1536 #ifndef SQLITE_DEBUG
1537 UNUSED_PARAMETER( pParse );
1538 #endif
1539 assert( pRec!=0 );
1540 assert( pIdx->nSample>0 );
1541 assert( pRec->nField>0 );
1544 /* Do a binary search to find the first sample greater than or equal
1545 ** to pRec. If pRec contains a single field, the set of samples to search
1546 ** is simply the aSample[] array. If the samples in aSample[] contain more
1547 ** than one fields, all fields following the first are ignored.
1549 ** If pRec contains N fields, where N is more than one, then as well as the
1550 ** samples in aSample[] (truncated to N fields), the search also has to
1551 ** consider prefixes of those samples. For example, if the set of samples
1552 ** in aSample is:
1554 ** aSample[0] = (a, 5)
1555 ** aSample[1] = (a, 10)
1556 ** aSample[2] = (b, 5)
1557 ** aSample[3] = (c, 100)
1558 ** aSample[4] = (c, 105)
1560 ** Then the search space should ideally be the samples above and the
1561 ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
1562 ** the code actually searches this set:
1564 ** 0: (a)
1565 ** 1: (a, 5)
1566 ** 2: (a, 10)
1567 ** 3: (a, 10)
1568 ** 4: (b)
1569 ** 5: (b, 5)
1570 ** 6: (c)
1571 ** 7: (c, 100)
1572 ** 8: (c, 105)
1573 ** 9: (c, 105)
1575 ** For each sample in the aSample[] array, N samples are present in the
1576 ** effective sample array. In the above, samples 0 and 1 are based on
1577 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
1579 ** Often, sample i of each block of N effective samples has (i+1) fields.
1580 ** Except, each sample may be extended to ensure that it is greater than or
1581 ** equal to the previous sample in the array. For example, in the above,
1582 ** sample 2 is the first sample of a block of N samples, so at first it
1583 ** appears that it should be 1 field in size. However, that would make it
1584 ** smaller than sample 1, so the binary search would not work. As a result,
1585 ** it is extended to two fields. The duplicates that this creates do not
1586 ** cause any problems.
1588 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
1589 nField = pIdx->nKeyCol;
1590 }else{
1591 nField = pIdx->nColumn;
1593 nField = MIN(pRec->nField, nField);
1594 iCol = 0;
1595 iSample = pIdx->nSample * nField;
1597 int iSamp; /* Index in aSample[] of test sample */
1598 int n; /* Number of fields in test sample */
1600 iTest = (iMin+iSample)/2;
1601 iSamp = iTest / nField;
1602 if( iSamp>0 ){
1603 /* The proposed effective sample is a prefix of sample aSample[iSamp].
1604 ** Specifically, the shortest prefix of at least (1 + iTest%nField)
1605 ** fields that is greater than the previous effective sample. */
1606 for(n=(iTest % nField) + 1; n<nField; n++){
1607 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
1609 }else{
1610 n = iTest + 1;
1613 pRec->nField = n;
1614 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
1615 if( res<0 ){
1616 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
1617 iMin = iTest+1;
1618 }else if( res==0 && n<nField ){
1619 iLower = aSample[iSamp].anLt[n-1];
1620 iMin = iTest+1;
1621 res = -1;
1622 }else{
1623 iSample = iTest;
1624 iCol = n-1;
1626 }while( res && iMin<iSample );
1627 i = iSample / nField;
1629 #ifdef SQLITE_DEBUG
1630 /* The following assert statements check that the binary search code
1631 ** above found the right answer. This block serves no purpose other
1632 ** than to invoke the asserts. */
1633 if( pParse->db->mallocFailed==0 ){
1634 if( res==0 ){
1635 /* If (res==0) is true, then pRec must be equal to sample i. */
1636 assert( i<pIdx->nSample );
1637 assert( iCol==nField-1 );
1638 pRec->nField = nField;
1639 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
1640 || pParse->db->mallocFailed
1642 }else{
1643 /* Unless i==pIdx->nSample, indicating that pRec is larger than
1644 ** all samples in the aSample[] array, pRec must be smaller than the
1645 ** (iCol+1) field prefix of sample i. */
1646 assert( i<=pIdx->nSample && i>=0 );
1647 pRec->nField = iCol+1;
1648 assert( i==pIdx->nSample
1649 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
1650 || pParse->db->mallocFailed );
1652 /* if i==0 and iCol==0, then record pRec is smaller than all samples
1653 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
1654 ** be greater than or equal to the (iCol) field prefix of sample i.
1655 ** If (i>0), then pRec must also be greater than sample (i-1). */
1656 if( iCol>0 ){
1657 pRec->nField = iCol;
1658 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
1659 || pParse->db->mallocFailed || CORRUPT_DB );
1661 if( i>0 ){
1662 pRec->nField = nField;
1663 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
1664 || pParse->db->mallocFailed || CORRUPT_DB );
1668 #endif /* ifdef SQLITE_DEBUG */
1670 if( res==0 ){
1671 /* Record pRec is equal to sample i */
1672 assert( iCol==nField-1 );
1673 aStat[0] = aSample[i].anLt[iCol];
1674 aStat[1] = aSample[i].anEq[iCol];
1675 }else{
1676 /* At this point, the (iCol+1) field prefix of aSample[i] is the first
1677 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
1678 ** is larger than all samples in the array. */
1679 tRowcnt iUpper, iGap;
1680 if( i>=pIdx->nSample ){
1681 iUpper = pIdx->nRowEst0;
1682 }else{
1683 iUpper = aSample[i].anLt[iCol];
1686 if( iLower>=iUpper ){
1687 iGap = 0;
1688 }else{
1689 iGap = iUpper - iLower;
1691 if( roundUp ){
1692 iGap = (iGap*2)/3;
1693 }else{
1694 iGap = iGap/3;
1696 aStat[0] = iLower + iGap;
1697 aStat[1] = pIdx->aAvgEq[nField-1];
1700 /* Restore the pRec->nField value before returning. */
1701 pRec->nField = nField;
1702 return i;
1704 #endif /* SQLITE_ENABLE_STAT4 */
1707 ** If it is not NULL, pTerm is a term that provides an upper or lower
1708 ** bound on a range scan. Without considering pTerm, it is estimated
1709 ** that the scan will visit nNew rows. This function returns the number
1710 ** estimated to be visited after taking pTerm into account.
1712 ** If the user explicitly specified a likelihood() value for this term,
1713 ** then the return value is the likelihood multiplied by the number of
1714 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
1715 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
1717 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
1718 LogEst nRet = nNew;
1719 if( pTerm ){
1720 if( pTerm->truthProb<=0 ){
1721 nRet += pTerm->truthProb;
1722 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
1723 nRet -= 20; assert( 20==sqlite3LogEst(4) );
1726 return nRet;
1730 #ifdef SQLITE_ENABLE_STAT4
1732 ** Return the affinity for a single column of an index.
1734 char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
1735 assert( iCol>=0 && iCol<pIdx->nColumn );
1736 if( !pIdx->zColAff ){
1737 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
1739 assert( pIdx->zColAff[iCol]!=0 );
1740 return pIdx->zColAff[iCol];
1742 #endif
1745 #ifdef SQLITE_ENABLE_STAT4
1747 ** This function is called to estimate the number of rows visited by a
1748 ** range-scan on a skip-scan index. For example:
1750 ** CREATE INDEX i1 ON t1(a, b, c);
1751 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
1753 ** Value pLoop->nOut is currently set to the estimated number of rows
1754 ** visited for scanning (a=? AND b=?). This function reduces that estimate
1755 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
1756 ** on the stat4 data for the index. this scan will be performed multiple
1757 ** times (once for each (a,b) combination that matches a=?) is dealt with
1758 ** by the caller.
1760 ** It does this by scanning through all stat4 samples, comparing values
1761 ** extracted from pLower and pUpper with the corresponding column in each
1762 ** sample. If L and U are the number of samples found to be less than or
1763 ** equal to the values extracted from pLower and pUpper respectively, and
1764 ** N is the total number of samples, the pLoop->nOut value is adjusted
1765 ** as follows:
1767 ** nOut = nOut * ( min(U - L, 1) / N )
1769 ** If pLower is NULL, or a value cannot be extracted from the term, L is
1770 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
1771 ** U is set to N.
1773 ** Normally, this function sets *pbDone to 1 before returning. However,
1774 ** if no value can be extracted from either pLower or pUpper (and so the
1775 ** estimate of the number of rows delivered remains unchanged), *pbDone
1776 ** is left as is.
1778 ** If an error occurs, an SQLite error code is returned. Otherwise,
1779 ** SQLITE_OK.
1781 static int whereRangeSkipScanEst(
1782 Parse *pParse, /* Parsing & code generating context */
1783 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
1784 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
1785 WhereLoop *pLoop, /* Update the .nOut value of this loop */
1786 int *pbDone /* Set to true if at least one expr. value extracted */
1788 Index *p = pLoop->u.btree.pIndex;
1789 int nEq = pLoop->u.btree.nEq;
1790 sqlite3 *db = pParse->db;
1791 int nLower = -1;
1792 int nUpper = p->nSample+1;
1793 int rc = SQLITE_OK;
1794 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
1795 CollSeq *pColl;
1797 sqlite3_value *p1 = 0; /* Value extracted from pLower */
1798 sqlite3_value *p2 = 0; /* Value extracted from pUpper */
1799 sqlite3_value *pVal = 0; /* Value extracted from record */
1801 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
1802 if( pLower ){
1803 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
1804 nLower = 0;
1806 if( pUpper && rc==SQLITE_OK ){
1807 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
1808 nUpper = p2 ? 0 : p->nSample;
1811 if( p1 || p2 ){
1812 int i;
1813 int nDiff;
1814 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
1815 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
1816 if( rc==SQLITE_OK && p1 ){
1817 int res = sqlite3MemCompare(p1, pVal, pColl);
1818 if( res>=0 ) nLower++;
1820 if( rc==SQLITE_OK && p2 ){
1821 int res = sqlite3MemCompare(p2, pVal, pColl);
1822 if( res>=0 ) nUpper++;
1825 nDiff = (nUpper - nLower);
1826 if( nDiff<=0 ) nDiff = 1;
1828 /* If there is both an upper and lower bound specified, and the
1829 ** comparisons indicate that they are close together, use the fallback
1830 ** method (assume that the scan visits 1/64 of the rows) for estimating
1831 ** the number of rows visited. Otherwise, estimate the number of rows
1832 ** using the method described in the header comment for this function. */
1833 if( nDiff!=1 || pUpper==0 || pLower==0 ){
1834 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
1835 pLoop->nOut -= nAdjust;
1836 *pbDone = 1;
1837 WHERETRACE(0x20, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
1838 nLower, nUpper, nAdjust*-1, pLoop->nOut));
1841 }else{
1842 assert( *pbDone==0 );
1845 sqlite3ValueFree(p1);
1846 sqlite3ValueFree(p2);
1847 sqlite3ValueFree(pVal);
1849 return rc;
1851 #endif /* SQLITE_ENABLE_STAT4 */
1854 ** This function is used to estimate the number of rows that will be visited
1855 ** by scanning an index for a range of values. The range may have an upper
1856 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
1857 ** and lower bounds are represented by pLower and pUpper respectively. For
1858 ** example, assuming that index p is on t1(a):
1860 ** ... FROM t1 WHERE a > ? AND a < ? ...
1861 ** |_____| |_____|
1862 ** | |
1863 ** pLower pUpper
1865 ** If either of the upper or lower bound is not present, then NULL is passed in
1866 ** place of the corresponding WhereTerm.
1868 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
1869 ** column subject to the range constraint. Or, equivalently, the number of
1870 ** equality constraints optimized by the proposed index scan. For example,
1871 ** assuming index p is on t1(a, b), and the SQL query is:
1873 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
1875 ** then nEq is set to 1 (as the range restricted column, b, is the second
1876 ** left-most column of the index). Or, if the query is:
1878 ** ... FROM t1 WHERE a > ? AND a < ? ...
1880 ** then nEq is set to 0.
1882 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
1883 ** number of rows that the index scan is expected to visit without
1884 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
1885 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
1886 ** to account for the range constraints pLower and pUpper.
1888 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
1889 ** used, a single range inequality reduces the search space by a factor of 4.
1890 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
1891 ** rows visited by a factor of 64.
1893 static int whereRangeScanEst(
1894 Parse *pParse, /* Parsing & code generating context */
1895 WhereLoopBuilder *pBuilder,
1896 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
1897 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
1898 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
1900 int rc = SQLITE_OK;
1901 int nOut = pLoop->nOut;
1902 LogEst nNew;
1904 #ifdef SQLITE_ENABLE_STAT4
1905 Index *p = pLoop->u.btree.pIndex;
1906 int nEq = pLoop->u.btree.nEq;
1908 if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
1909 && OptimizationEnabled(pParse->db, SQLITE_Stat4)
1911 if( nEq==pBuilder->nRecValid ){
1912 UnpackedRecord *pRec = pBuilder->pRec;
1913 tRowcnt a[2];
1914 int nBtm = pLoop->u.btree.nBtm;
1915 int nTop = pLoop->u.btree.nTop;
1917 /* Variable iLower will be set to the estimate of the number of rows in
1918 ** the index that are less than the lower bound of the range query. The
1919 ** lower bound being the concatenation of $P and $L, where $P is the
1920 ** key-prefix formed by the nEq values matched against the nEq left-most
1921 ** columns of the index, and $L is the value in pLower.
1923 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
1924 ** is not a simple variable or literal value), the lower bound of the
1925 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
1926 ** if $L is available, whereKeyStats() is called for both ($P) and
1927 ** ($P:$L) and the larger of the two returned values is used.
1929 ** Similarly, iUpper is to be set to the estimate of the number of rows
1930 ** less than the upper bound of the range query. Where the upper bound
1931 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
1932 ** of iUpper are requested of whereKeyStats() and the smaller used.
1934 ** The number of rows between the two bounds is then just iUpper-iLower.
1936 tRowcnt iLower; /* Rows less than the lower bound */
1937 tRowcnt iUpper; /* Rows less than the upper bound */
1938 int iLwrIdx = -2; /* aSample[] for the lower bound */
1939 int iUprIdx = -1; /* aSample[] for the upper bound */
1941 if( pRec ){
1942 testcase( pRec->nField!=pBuilder->nRecValid );
1943 pRec->nField = pBuilder->nRecValid;
1945 /* Determine iLower and iUpper using ($P) only. */
1946 if( nEq==0 ){
1947 iLower = 0;
1948 iUpper = p->nRowEst0;
1949 }else{
1950 /* Note: this call could be optimized away - since the same values must
1951 ** have been requested when testing key $P in whereEqualScanEst(). */
1952 whereKeyStats(pParse, p, pRec, 0, a);
1953 iLower = a[0];
1954 iUpper = a[0] + a[1];
1957 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
1958 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
1959 assert( p->aSortOrder!=0 );
1960 if( p->aSortOrder[nEq] ){
1961 /* The roles of pLower and pUpper are swapped for a DESC index */
1962 SWAP(WhereTerm*, pLower, pUpper);
1963 SWAP(int, nBtm, nTop);
1966 /* If possible, improve on the iLower estimate using ($P:$L). */
1967 if( pLower ){
1968 int n; /* Values extracted from pExpr */
1969 Expr *pExpr = pLower->pExpr->pRight;
1970 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
1971 if( rc==SQLITE_OK && n ){
1972 tRowcnt iNew;
1973 u16 mask = WO_GT|WO_LE;
1974 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
1975 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
1976 iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
1977 if( iNew>iLower ) iLower = iNew;
1978 nOut--;
1979 pLower = 0;
1983 /* If possible, improve on the iUpper estimate using ($P:$U). */
1984 if( pUpper ){
1985 int n; /* Values extracted from pExpr */
1986 Expr *pExpr = pUpper->pExpr->pRight;
1987 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
1988 if( rc==SQLITE_OK && n ){
1989 tRowcnt iNew;
1990 u16 mask = WO_GT|WO_LE;
1991 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
1992 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
1993 iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
1994 if( iNew<iUpper ) iUpper = iNew;
1995 nOut--;
1996 pUpper = 0;
2000 pBuilder->pRec = pRec;
2001 if( rc==SQLITE_OK ){
2002 if( iUpper>iLower ){
2003 nNew = sqlite3LogEst(iUpper - iLower);
2004 /* TUNING: If both iUpper and iLower are derived from the same
2005 ** sample, then assume they are 4x more selective. This brings
2006 ** the estimated selectivity more in line with what it would be
2007 ** if estimated without the use of STAT4 tables. */
2008 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
2009 }else{
2010 nNew = 10; assert( 10==sqlite3LogEst(2) );
2012 if( nNew<nOut ){
2013 nOut = nNew;
2015 WHERETRACE(0x20, ("STAT4 range scan: %u..%u est=%d\n",
2016 (u32)iLower, (u32)iUpper, nOut));
2018 }else{
2019 int bDone = 0;
2020 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
2021 if( bDone ) return rc;
2024 #else
2025 UNUSED_PARAMETER(pParse);
2026 UNUSED_PARAMETER(pBuilder);
2027 assert( pLower || pUpper );
2028 #endif
2029 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 || pParse->nErr>0 );
2030 nNew = whereRangeAdjust(pLower, nOut);
2031 nNew = whereRangeAdjust(pUpper, nNew);
2033 /* TUNING: If there is both an upper and lower limit and neither limit
2034 ** has an application-defined likelihood(), assume the range is
2035 ** reduced by an additional 75%. This means that, by default, an open-ended
2036 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
2037 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
2038 ** match 1/64 of the index. */
2039 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
2040 nNew -= 20;
2043 nOut -= (pLower!=0) + (pUpper!=0);
2044 if( nNew<10 ) nNew = 10;
2045 if( nNew<nOut ) nOut = nNew;
2046 #if defined(WHERETRACE_ENABLED)
2047 if( pLoop->nOut>nOut ){
2048 WHERETRACE(0x20,("Range scan lowers nOut from %d to %d\n",
2049 pLoop->nOut, nOut));
2051 #endif
2052 pLoop->nOut = (LogEst)nOut;
2053 return rc;
2056 #ifdef SQLITE_ENABLE_STAT4
2058 ** Estimate the number of rows that will be returned based on
2059 ** an equality constraint x=VALUE and where that VALUE occurs in
2060 ** the histogram data. This only works when x is the left-most
2061 ** column of an index and sqlite_stat4 histogram data is available
2062 ** for that index. When pExpr==NULL that means the constraint is
2063 ** "x IS NULL" instead of "x=VALUE".
2065 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2066 ** If unable to make an estimate, leave *pnRow unchanged and return
2067 ** non-zero.
2069 ** This routine can fail if it is unable to load a collating sequence
2070 ** required for string comparison, or if unable to allocate memory
2071 ** for a UTF conversion required for comparison. The error is stored
2072 ** in the pParse structure.
2074 static int whereEqualScanEst(
2075 Parse *pParse, /* Parsing & code generating context */
2076 WhereLoopBuilder *pBuilder,
2077 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
2078 tRowcnt *pnRow /* Write the revised row estimate here */
2080 Index *p = pBuilder->pNew->u.btree.pIndex;
2081 int nEq = pBuilder->pNew->u.btree.nEq;
2082 UnpackedRecord *pRec = pBuilder->pRec;
2083 int rc; /* Subfunction return code */
2084 tRowcnt a[2]; /* Statistics */
2085 int bOk;
2087 assert( nEq>=1 );
2088 assert( nEq<=p->nColumn );
2089 assert( p->aSample!=0 );
2090 assert( p->nSample>0 );
2091 assert( pBuilder->nRecValid<nEq );
2093 /* If values are not available for all fields of the index to the left
2094 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2095 if( pBuilder->nRecValid<(nEq-1) ){
2096 return SQLITE_NOTFOUND;
2099 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2100 ** below would return the same value. */
2101 if( nEq>=p->nColumn ){
2102 *pnRow = 1;
2103 return SQLITE_OK;
2106 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
2107 pBuilder->pRec = pRec;
2108 if( rc!=SQLITE_OK ) return rc;
2109 if( bOk==0 ) return SQLITE_NOTFOUND;
2110 pBuilder->nRecValid = nEq;
2112 whereKeyStats(pParse, p, pRec, 0, a);
2113 WHERETRACE(0x20,("equality scan regions %s(%d): %d\n",
2114 p->zName, nEq-1, (int)a[1]));
2115 *pnRow = a[1];
2117 return rc;
2119 #endif /* SQLITE_ENABLE_STAT4 */
2121 #ifdef SQLITE_ENABLE_STAT4
2123 ** Estimate the number of rows that will be returned based on
2124 ** an IN constraint where the right-hand side of the IN operator
2125 ** is a list of values. Example:
2127 ** WHERE x IN (1,2,3,4)
2129 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2130 ** If unable to make an estimate, leave *pnRow unchanged and return
2131 ** non-zero.
2133 ** This routine can fail if it is unable to load a collating sequence
2134 ** required for string comparison, or if unable to allocate memory
2135 ** for a UTF conversion required for comparison. The error is stored
2136 ** in the pParse structure.
2138 static int whereInScanEst(
2139 Parse *pParse, /* Parsing & code generating context */
2140 WhereLoopBuilder *pBuilder,
2141 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
2142 tRowcnt *pnRow /* Write the revised row estimate here */
2144 Index *p = pBuilder->pNew->u.btree.pIndex;
2145 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
2146 int nRecValid = pBuilder->nRecValid;
2147 int rc = SQLITE_OK; /* Subfunction return code */
2148 tRowcnt nEst; /* Number of rows for a single term */
2149 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2150 int i; /* Loop counter */
2152 assert( p->aSample!=0 );
2153 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2154 nEst = nRow0;
2155 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
2156 nRowEst += nEst;
2157 pBuilder->nRecValid = nRecValid;
2160 if( rc==SQLITE_OK ){
2161 if( nRowEst > (tRowcnt)nRow0 ) nRowEst = nRow0;
2162 *pnRow = nRowEst;
2163 WHERETRACE(0x20,("IN row estimate: est=%d\n", nRowEst));
2165 assert( pBuilder->nRecValid==nRecValid );
2166 return rc;
2168 #endif /* SQLITE_ENABLE_STAT4 */
2171 #ifdef WHERETRACE_ENABLED
2173 ** Print the content of a WhereTerm object
2175 void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
2176 if( pTerm==0 ){
2177 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
2178 }else{
2179 char zType[8];
2180 char zLeft[50];
2181 memcpy(zType, "....", 5);
2182 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
2183 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
2184 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) zType[2] = 'L';
2185 if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C';
2186 if( pTerm->eOperator & WO_SINGLE ){
2187 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
2188 sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
2189 pTerm->leftCursor, pTerm->u.x.leftColumn);
2190 }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
2191 sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx",
2192 pTerm->u.pOrInfo->indexable);
2193 }else{
2194 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
2196 sqlite3DebugPrintf(
2197 "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
2198 iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
2199 /* The 0x10000 .wheretrace flag causes extra information to be
2200 ** shown about each Term */
2201 if( sqlite3WhereTrace & 0x10000 ){
2202 sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
2203 pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
2205 if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){
2206 sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
2208 if( pTerm->iParent>=0 ){
2209 sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
2211 sqlite3DebugPrintf("\n");
2212 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
2215 #endif
2217 #ifdef WHERETRACE_ENABLED
2219 ** Show the complete content of a WhereClause
2221 void sqlite3WhereClausePrint(WhereClause *pWC){
2222 int i;
2223 for(i=0; i<pWC->nTerm; i++){
2224 sqlite3WhereTermPrint(&pWC->a[i], i);
2227 #endif
2229 #ifdef WHERETRACE_ENABLED
2231 ** Print a WhereLoop object for debugging purposes
2233 void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
2234 WhereInfo *pWInfo = pWC->pWInfo;
2235 int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
2236 SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
2237 Table *pTab = pItem->pTab;
2238 Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
2239 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
2240 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
2241 sqlite3DebugPrintf(" %12s",
2242 pItem->zAlias ? pItem->zAlias : pTab->zName);
2243 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2244 const char *zName;
2245 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
2246 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
2247 int i = sqlite3Strlen30(zName) - 1;
2248 while( zName[i]!='_' ) i--;
2249 zName += i;
2251 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
2252 }else{
2253 sqlite3DebugPrintf("%20s","");
2255 }else{
2256 char *z;
2257 if( p->u.vtab.idxStr ){
2258 z = sqlite3_mprintf("(%d,\"%s\",%#x)",
2259 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
2260 }else{
2261 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
2263 sqlite3DebugPrintf(" %-19s", z);
2264 sqlite3_free(z);
2266 if( p->wsFlags & WHERE_SKIPSCAN ){
2267 sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
2268 }else{
2269 sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm);
2271 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
2272 if( p->nLTerm && (sqlite3WhereTrace & 0x4000)!=0 ){
2273 int i;
2274 for(i=0; i<p->nLTerm; i++){
2275 sqlite3WhereTermPrint(p->aLTerm[i], i);
2279 #endif
2282 ** Convert bulk memory into a valid WhereLoop that can be passed
2283 ** to whereLoopClear harmlessly.
2285 static void whereLoopInit(WhereLoop *p){
2286 p->aLTerm = p->aLTermSpace;
2287 p->nLTerm = 0;
2288 p->nLSlot = ArraySize(p->aLTermSpace);
2289 p->wsFlags = 0;
2293 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
2295 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
2296 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
2297 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
2298 sqlite3_free(p->u.vtab.idxStr);
2299 p->u.vtab.needFree = 0;
2300 p->u.vtab.idxStr = 0;
2301 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
2302 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
2303 sqlite3DbFreeNN(db, p->u.btree.pIndex);
2304 p->u.btree.pIndex = 0;
2310 ** Deallocate internal memory used by a WhereLoop object. Leave the
2311 ** object in an initialized state, as if it had been newly allocated.
2313 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
2314 if( p->aLTerm!=p->aLTermSpace ){
2315 sqlite3DbFreeNN(db, p->aLTerm);
2316 p->aLTerm = p->aLTermSpace;
2317 p->nLSlot = ArraySize(p->aLTermSpace);
2319 whereLoopClearUnion(db, p);
2320 p->nLTerm = 0;
2321 p->wsFlags = 0;
2325 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
2327 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
2328 WhereTerm **paNew;
2329 if( p->nLSlot>=n ) return SQLITE_OK;
2330 n = (n+7)&~7;
2331 paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
2332 if( paNew==0 ) return SQLITE_NOMEM_BKPT;
2333 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
2334 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
2335 p->aLTerm = paNew;
2336 p->nLSlot = n;
2337 return SQLITE_OK;
2341 ** Transfer content from the second pLoop into the first.
2343 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
2344 whereLoopClearUnion(db, pTo);
2345 if( pFrom->nLTerm > pTo->nLSlot
2346 && whereLoopResize(db, pTo, pFrom->nLTerm)
2348 memset(pTo, 0, WHERE_LOOP_XFER_SZ);
2349 return SQLITE_NOMEM_BKPT;
2351 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
2352 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
2353 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
2354 pFrom->u.vtab.needFree = 0;
2355 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
2356 pFrom->u.btree.pIndex = 0;
2358 return SQLITE_OK;
2362 ** Delete a WhereLoop object
2364 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
2365 assert( db!=0 );
2366 whereLoopClear(db, p);
2367 sqlite3DbNNFreeNN(db, p);
2371 ** Free a WhereInfo structure
2373 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
2374 assert( pWInfo!=0 );
2375 assert( db!=0 );
2376 sqlite3WhereClauseClear(&pWInfo->sWC);
2377 while( pWInfo->pLoops ){
2378 WhereLoop *p = pWInfo->pLoops;
2379 pWInfo->pLoops = p->pNextLoop;
2380 whereLoopDelete(db, p);
2382 while( pWInfo->pMemToFree ){
2383 WhereMemBlock *pNext = pWInfo->pMemToFree->pNext;
2384 sqlite3DbNNFreeNN(db, pWInfo->pMemToFree);
2385 pWInfo->pMemToFree = pNext;
2387 sqlite3DbNNFreeNN(db, pWInfo);
2391 ** Return TRUE if all of the following are true:
2393 ** (1) X has the same or lower cost, or returns the same or fewer rows,
2394 ** than Y.
2395 ** (2) X uses fewer WHERE clause terms than Y
2396 ** (3) Every WHERE clause term used by X is also used by Y
2397 ** (4) X skips at least as many columns as Y
2398 ** (5) If X is a covering index, than Y is too
2400 ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
2401 ** If X is a proper subset of Y then Y is a better choice and ought
2402 ** to have a lower cost. This routine returns TRUE when that cost
2403 ** relationship is inverted and needs to be adjusted. Constraint (4)
2404 ** was added because if X uses skip-scan less than Y it still might
2405 ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
2406 ** was added because a covering index probably deserves to have a lower cost
2407 ** than a non-covering index even if it is a proper subset.
2409 static int whereLoopCheaperProperSubset(
2410 const WhereLoop *pX, /* First WhereLoop to compare */
2411 const WhereLoop *pY /* Compare against this WhereLoop */
2413 int i, j;
2414 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
2415 return 0; /* X is not a subset of Y */
2417 if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0;
2418 if( pY->nSkip > pX->nSkip ) return 0;
2419 for(i=pX->nLTerm-1; i>=0; i--){
2420 if( pX->aLTerm[i]==0 ) continue;
2421 for(j=pY->nLTerm-1; j>=0; j--){
2422 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
2424 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
2426 if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
2427 && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
2428 return 0; /* Constraint (5) */
2430 return 1; /* All conditions meet */
2434 ** Try to adjust the cost and number of output rows of WhereLoop pTemplate
2435 ** upwards or downwards so that:
2437 ** (1) pTemplate costs less than any other WhereLoops that are a proper
2438 ** subset of pTemplate
2440 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
2441 ** is a proper subset.
2443 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
2444 ** WHERE clause terms than Y and that every WHERE clause term used by X is
2445 ** also used by Y.
2447 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
2448 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
2449 for(; p; p=p->pNextLoop){
2450 if( p->iTab!=pTemplate->iTab ) continue;
2451 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
2452 if( whereLoopCheaperProperSubset(p, pTemplate) ){
2453 /* Adjust pTemplate cost downward so that it is cheaper than its
2454 ** subset p. */
2455 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2456 pTemplate->rRun, pTemplate->nOut,
2457 MIN(p->rRun, pTemplate->rRun),
2458 MIN(p->nOut - 1, pTemplate->nOut)));
2459 pTemplate->rRun = MIN(p->rRun, pTemplate->rRun);
2460 pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut);
2461 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
2462 /* Adjust pTemplate cost upward so that it is costlier than p since
2463 ** pTemplate is a proper subset of p */
2464 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2465 pTemplate->rRun, pTemplate->nOut,
2466 MAX(p->rRun, pTemplate->rRun),
2467 MAX(p->nOut + 1, pTemplate->nOut)));
2468 pTemplate->rRun = MAX(p->rRun, pTemplate->rRun);
2469 pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut);
2475 ** Search the list of WhereLoops in *ppPrev looking for one that can be
2476 ** replaced by pTemplate.
2478 ** Return NULL if pTemplate does not belong on the WhereLoop list.
2479 ** In other words if pTemplate ought to be dropped from further consideration.
2481 ** If pX is a WhereLoop that pTemplate can replace, then return the
2482 ** link that points to pX.
2484 ** If pTemplate cannot replace any existing element of the list but needs
2485 ** to be added to the list as a new entry, then return a pointer to the
2486 ** tail of the list.
2488 static WhereLoop **whereLoopFindLesser(
2489 WhereLoop **ppPrev,
2490 const WhereLoop *pTemplate
2492 WhereLoop *p;
2493 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
2494 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
2495 /* If either the iTab or iSortIdx values for two WhereLoop are different
2496 ** then those WhereLoops need to be considered separately. Neither is
2497 ** a candidate to replace the other. */
2498 continue;
2500 /* In the current implementation, the rSetup value is either zero
2501 ** or the cost of building an automatic index (NlogN) and the NlogN
2502 ** is the same for compatible WhereLoops. */
2503 assert( p->rSetup==0 || pTemplate->rSetup==0
2504 || p->rSetup==pTemplate->rSetup );
2506 /* whereLoopAddBtree() always generates and inserts the automatic index
2507 ** case first. Hence compatible candidate WhereLoops never have a larger
2508 ** rSetup. Call this SETUP-INVARIANT */
2509 assert( p->rSetup>=pTemplate->rSetup );
2511 /* Any loop using an application-defined index (or PRIMARY KEY or
2512 ** UNIQUE constraint) with one or more == constraints is better
2513 ** than an automatic index. Unless it is a skip-scan. */
2514 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
2515 && (pTemplate->nSkip)==0
2516 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
2517 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
2518 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
2520 break;
2523 /* If existing WhereLoop p is better than pTemplate, pTemplate can be
2524 ** discarded. WhereLoop p is better if:
2525 ** (1) p has no more dependencies than pTemplate, and
2526 ** (2) p has an equal or lower cost than pTemplate
2528 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
2529 && p->rSetup<=pTemplate->rSetup /* (2a) */
2530 && p->rRun<=pTemplate->rRun /* (2b) */
2531 && p->nOut<=pTemplate->nOut /* (2c) */
2533 return 0; /* Discard pTemplate */
2536 /* If pTemplate is always better than p, then cause p to be overwritten
2537 ** with pTemplate. pTemplate is better than p if:
2538 ** (1) pTemplate has no more dependencies than p, and
2539 ** (2) pTemplate has an equal or lower cost than p.
2541 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
2542 && p->rRun>=pTemplate->rRun /* (2a) */
2543 && p->nOut>=pTemplate->nOut /* (2b) */
2545 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
2546 break; /* Cause p to be overwritten by pTemplate */
2549 return ppPrev;
2553 ** Insert or replace a WhereLoop entry using the template supplied.
2555 ** An existing WhereLoop entry might be overwritten if the new template
2556 ** is better and has fewer dependencies. Or the template will be ignored
2557 ** and no insert will occur if an existing WhereLoop is faster and has
2558 ** fewer dependencies than the template. Otherwise a new WhereLoop is
2559 ** added based on the template.
2561 ** If pBuilder->pOrSet is not NULL then we care about only the
2562 ** prerequisites and rRun and nOut costs of the N best loops. That
2563 ** information is gathered in the pBuilder->pOrSet object. This special
2564 ** processing mode is used only for OR clause processing.
2566 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
2567 ** still might overwrite similar loops with the new template if the
2568 ** new template is better. Loops may be overwritten if the following
2569 ** conditions are met:
2571 ** (1) They have the same iTab.
2572 ** (2) They have the same iSortIdx.
2573 ** (3) The template has same or fewer dependencies than the current loop
2574 ** (4) The template has the same or lower cost than the current loop
2576 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
2577 WhereLoop **ppPrev, *p;
2578 WhereInfo *pWInfo = pBuilder->pWInfo;
2579 sqlite3 *db = pWInfo->pParse->db;
2580 int rc;
2582 /* Stop the search once we hit the query planner search limit */
2583 if( pBuilder->iPlanLimit==0 ){
2584 WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
2585 if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
2586 return SQLITE_DONE;
2588 pBuilder->iPlanLimit--;
2590 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
2592 /* If pBuilder->pOrSet is defined, then only keep track of the costs
2593 ** and prereqs.
2595 if( pBuilder->pOrSet!=0 ){
2596 if( pTemplate->nLTerm ){
2597 #if WHERETRACE_ENABLED
2598 u16 n = pBuilder->pOrSet->n;
2599 int x =
2600 #endif
2601 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
2602 pTemplate->nOut);
2603 #if WHERETRACE_ENABLED /* 0x8 */
2604 if( sqlite3WhereTrace & 0x8 ){
2605 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
2606 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2608 #endif
2610 return SQLITE_OK;
2613 /* Look for an existing WhereLoop to replace with pTemplate
2615 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
2617 if( ppPrev==0 ){
2618 /* There already exists a WhereLoop on the list that is better
2619 ** than pTemplate, so just ignore pTemplate */
2620 #if WHERETRACE_ENABLED /* 0x8 */
2621 if( sqlite3WhereTrace & 0x8 ){
2622 sqlite3DebugPrintf(" skip: ");
2623 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2625 #endif
2626 return SQLITE_OK;
2627 }else{
2628 p = *ppPrev;
2631 /* If we reach this point it means that either p[] should be overwritten
2632 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
2633 ** WhereLoop and insert it.
2635 #if WHERETRACE_ENABLED /* 0x8 */
2636 if( sqlite3WhereTrace & 0x8 ){
2637 if( p!=0 ){
2638 sqlite3DebugPrintf("replace: ");
2639 sqlite3WhereLoopPrint(p, pBuilder->pWC);
2640 sqlite3DebugPrintf(" with: ");
2641 }else{
2642 sqlite3DebugPrintf(" add: ");
2644 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2646 #endif
2647 if( p==0 ){
2648 /* Allocate a new WhereLoop to add to the end of the list */
2649 *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
2650 if( p==0 ) return SQLITE_NOMEM_BKPT;
2651 whereLoopInit(p);
2652 p->pNextLoop = 0;
2653 }else{
2654 /* We will be overwriting WhereLoop p[]. But before we do, first
2655 ** go through the rest of the list and delete any other entries besides
2656 ** p[] that are also supplanted by pTemplate */
2657 WhereLoop **ppTail = &p->pNextLoop;
2658 WhereLoop *pToDel;
2659 while( *ppTail ){
2660 ppTail = whereLoopFindLesser(ppTail, pTemplate);
2661 if( ppTail==0 ) break;
2662 pToDel = *ppTail;
2663 if( pToDel==0 ) break;
2664 *ppTail = pToDel->pNextLoop;
2665 #if WHERETRACE_ENABLED /* 0x8 */
2666 if( sqlite3WhereTrace & 0x8 ){
2667 sqlite3DebugPrintf(" delete: ");
2668 sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
2670 #endif
2671 whereLoopDelete(db, pToDel);
2674 rc = whereLoopXfer(db, p, pTemplate);
2675 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2676 Index *pIndex = p->u.btree.pIndex;
2677 if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
2678 p->u.btree.pIndex = 0;
2681 return rc;
2685 ** Adjust the WhereLoop.nOut value downward to account for terms of the
2686 ** WHERE clause that reference the loop but which are not used by an
2687 ** index.
2689 ** For every WHERE clause term that is not used by the index
2690 ** and which has a truth probability assigned by one of the likelihood(),
2691 ** likely(), or unlikely() SQL functions, reduce the estimated number
2692 ** of output rows by the probability specified.
2694 ** TUNING: For every WHERE clause term that is not used by the index
2695 ** and which does not have an assigned truth probability, heuristics
2696 ** described below are used to try to estimate the truth probability.
2697 ** TODO --> Perhaps this is something that could be improved by better
2698 ** table statistics.
2700 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
2701 ** value corresponds to -1 in LogEst notation, so this means decrement
2702 ** the WhereLoop.nOut field for every such WHERE clause term.
2704 ** Heuristic 2: If there exists one or more WHERE clause terms of the
2705 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
2706 ** final output row estimate is no greater than 1/4 of the total number
2707 ** of rows in the table. In other words, assume that x==EXPR will filter
2708 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
2709 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
2710 ** on the "x" column and so in that case only cap the output row estimate
2711 ** at 1/2 instead of 1/4.
2713 static void whereLoopOutputAdjust(
2714 WhereClause *pWC, /* The WHERE clause */
2715 WhereLoop *pLoop, /* The loop to adjust downward */
2716 LogEst nRow /* Number of rows in the entire table */
2718 WhereTerm *pTerm, *pX;
2719 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
2720 int i, j;
2721 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
2723 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
2724 for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){
2725 assert( pTerm!=0 );
2726 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
2727 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
2728 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue;
2729 for(j=pLoop->nLTerm-1; j>=0; j--){
2730 pX = pLoop->aLTerm[j];
2731 if( pX==0 ) continue;
2732 if( pX==pTerm ) break;
2733 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
2735 if( j<0 ){
2736 sqlite3ProgressCheck(pWC->pWInfo->pParse);
2737 if( pLoop->maskSelf==pTerm->prereqAll ){
2738 /* If there are extra terms in the WHERE clause not used by an index
2739 ** that depend only on the table being scanned, and that will tend to
2740 ** cause many rows to be omitted, then mark that table as
2741 ** "self-culling".
2743 ** 2022-03-24: Self-culling only applies if either the extra terms
2744 ** are straight comparison operators that are non-true with NULL
2745 ** operand, or if the loop is not an OUTER JOIN.
2747 if( (pTerm->eOperator & 0x3f)!=0
2748 || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype
2749 & (JT_LEFT|JT_LTORJ))==0
2751 pLoop->wsFlags |= WHERE_SELFCULL;
2754 if( pTerm->truthProb<=0 ){
2755 /* If a truth probability is specified using the likelihood() hints,
2756 ** then use the probability provided by the application. */
2757 pLoop->nOut += pTerm->truthProb;
2758 }else{
2759 /* In the absence of explicit truth probabilities, use heuristics to
2760 ** guess a reasonable truth probability. */
2761 pLoop->nOut--;
2762 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
2763 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */
2765 Expr *pRight = pTerm->pExpr->pRight;
2766 int k = 0;
2767 testcase( pTerm->pExpr->op==TK_IS );
2768 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
2769 k = 10;
2770 }else{
2771 k = 20;
2773 if( iReduce<k ){
2774 pTerm->wtFlags |= TERM_HEURTRUTH;
2775 iReduce = k;
2781 if( pLoop->nOut > nRow-iReduce ){
2782 pLoop->nOut = nRow - iReduce;
2787 ** Term pTerm is a vector range comparison operation. The first comparison
2788 ** in the vector can be optimized using column nEq of the index. This
2789 ** function returns the total number of vector elements that can be used
2790 ** as part of the range comparison.
2792 ** For example, if the query is:
2794 ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
2796 ** and the index:
2798 ** CREATE INDEX ... ON (a, b, c, d, e)
2800 ** then this function would be invoked with nEq=1. The value returned in
2801 ** this case is 3.
2803 static int whereRangeVectorLen(
2804 Parse *pParse, /* Parsing context */
2805 int iCur, /* Cursor open on pIdx */
2806 Index *pIdx, /* The index to be used for a inequality constraint */
2807 int nEq, /* Number of prior equality constraints on same index */
2808 WhereTerm *pTerm /* The vector inequality constraint */
2810 int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
2811 int i;
2813 nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
2814 for(i=1; i<nCmp; i++){
2815 /* Test if comparison i of pTerm is compatible with column (i+nEq)
2816 ** of the index. If not, exit the loop. */
2817 char aff; /* Comparison affinity */
2818 char idxaff = 0; /* Indexed columns affinity */
2819 CollSeq *pColl; /* Comparison collation sequence */
2820 Expr *pLhs, *pRhs;
2822 assert( ExprUseXList(pTerm->pExpr->pLeft) );
2823 pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
2824 pRhs = pTerm->pExpr->pRight;
2825 if( ExprUseXSelect(pRhs) ){
2826 pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
2827 }else{
2828 pRhs = pRhs->x.pList->a[i].pExpr;
2831 /* Check that the LHS of the comparison is a column reference to
2832 ** the right column of the right source table. And that the sort
2833 ** order of the index column is the same as the sort order of the
2834 ** leftmost index column. */
2835 if( pLhs->op!=TK_COLUMN
2836 || pLhs->iTable!=iCur
2837 || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
2838 || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
2840 break;
2843 testcase( pLhs->iColumn==XN_ROWID );
2844 aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
2845 idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
2846 if( aff!=idxaff ) break;
2848 pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2849 if( pColl==0 ) break;
2850 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
2852 return i;
2856 ** Adjust the cost C by the costMult factor T. This only occurs if
2857 ** compiled with -DSQLITE_ENABLE_COSTMULT
2859 #ifdef SQLITE_ENABLE_COSTMULT
2860 # define ApplyCostMultiplier(C,T) C += T
2861 #else
2862 # define ApplyCostMultiplier(C,T)
2863 #endif
2866 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
2867 ** index pIndex. Try to match one more.
2869 ** When this function is called, pBuilder->pNew->nOut contains the
2870 ** number of rows expected to be visited by filtering using the nEq
2871 ** terms only. If it is modified, this value is restored before this
2872 ** function returns.
2874 ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
2875 ** a fake index used for the INTEGER PRIMARY KEY.
2877 static int whereLoopAddBtreeIndex(
2878 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
2879 SrcItem *pSrc, /* FROM clause term being analyzed */
2880 Index *pProbe, /* An index on pSrc */
2881 LogEst nInMul /* log(Number of iterations due to IN) */
2883 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyze context */
2884 Parse *pParse = pWInfo->pParse; /* Parsing context */
2885 sqlite3 *db = pParse->db; /* Database connection malloc context */
2886 WhereLoop *pNew; /* Template WhereLoop under construction */
2887 WhereTerm *pTerm; /* A WhereTerm under consideration */
2888 int opMask; /* Valid operators for constraints */
2889 WhereScan scan; /* Iterator for WHERE terms */
2890 Bitmask saved_prereq; /* Original value of pNew->prereq */
2891 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
2892 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
2893 u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
2894 u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
2895 u16 saved_nSkip; /* Original value of pNew->nSkip */
2896 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
2897 LogEst saved_nOut; /* Original value of pNew->nOut */
2898 int rc = SQLITE_OK; /* Return code */
2899 LogEst rSize; /* Number of rows in the table */
2900 LogEst rLogSize; /* Logarithm of table size */
2901 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
2903 pNew = pBuilder->pNew;
2904 assert( db->mallocFailed==0 || pParse->nErr>0 );
2905 if( pParse->nErr ){
2906 return pParse->rc;
2908 WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n",
2909 pProbe->pTable->zName,pProbe->zName,
2910 pNew->u.btree.nEq, pNew->nSkip, pNew->rRun));
2912 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
2913 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
2914 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
2915 opMask = WO_LT|WO_LE;
2916 }else{
2917 assert( pNew->u.btree.nBtm==0 );
2918 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
2920 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
2922 assert( pNew->u.btree.nEq<pProbe->nColumn );
2923 assert( pNew->u.btree.nEq<pProbe->nKeyCol
2924 || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
2926 saved_nEq = pNew->u.btree.nEq;
2927 saved_nBtm = pNew->u.btree.nBtm;
2928 saved_nTop = pNew->u.btree.nTop;
2929 saved_nSkip = pNew->nSkip;
2930 saved_nLTerm = pNew->nLTerm;
2931 saved_wsFlags = pNew->wsFlags;
2932 saved_prereq = pNew->prereq;
2933 saved_nOut = pNew->nOut;
2934 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
2935 opMask, pProbe);
2936 pNew->rSetup = 0;
2937 rSize = pProbe->aiRowLogEst[0];
2938 rLogSize = estLog(rSize);
2939 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
2940 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
2941 LogEst rCostIdx;
2942 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
2943 int nIn = 0;
2944 #ifdef SQLITE_ENABLE_STAT4
2945 int nRecValid = pBuilder->nRecValid;
2946 #endif
2947 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
2948 && indexColumnNotNull(pProbe, saved_nEq)
2950 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
2952 if( pTerm->prereqRight & pNew->maskSelf ) continue;
2954 /* Do not allow the upper bound of a LIKE optimization range constraint
2955 ** to mix with a lower range bound from some other source */
2956 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
2958 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
2959 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
2961 continue;
2963 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
2964 pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
2965 }else{
2966 pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
2968 pNew->wsFlags = saved_wsFlags;
2969 pNew->u.btree.nEq = saved_nEq;
2970 pNew->u.btree.nBtm = saved_nBtm;
2971 pNew->u.btree.nTop = saved_nTop;
2972 pNew->nLTerm = saved_nLTerm;
2973 if( pNew->nLTerm>=pNew->nLSlot
2974 && whereLoopResize(db, pNew, pNew->nLTerm+1)
2976 break; /* OOM while trying to enlarge the pNew->aLTerm array */
2978 pNew->aLTerm[pNew->nLTerm++] = pTerm;
2979 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
2981 assert( nInMul==0
2982 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
2983 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
2984 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
2987 if( eOp & WO_IN ){
2988 Expr *pExpr = pTerm->pExpr;
2989 if( ExprUseXSelect(pExpr) ){
2990 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
2991 int i;
2992 nIn = 46; assert( 46==sqlite3LogEst(25) );
2994 /* The expression may actually be of the form (x, y) IN (SELECT...).
2995 ** In this case there is a separate term for each of (x) and (y).
2996 ** However, the nIn multiplier should only be applied once, not once
2997 ** for each such term. The following loop checks that pTerm is the
2998 ** first such term in use, and sets nIn back to 0 if it is not. */
2999 for(i=0; i<pNew->nLTerm-1; i++){
3000 if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
3002 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3003 /* "x IN (value, value, ...)" */
3004 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
3006 if( pProbe->hasStat1 && rLogSize>=10 ){
3007 LogEst M, logK, x;
3008 /* Let:
3009 ** N = the total number of rows in the table
3010 ** K = the number of entries on the RHS of the IN operator
3011 ** M = the number of rows in the table that match terms to the
3012 ** to the left in the same index. If the IN operator is on
3013 ** the left-most index column, M==N.
3015 ** Given the definitions above, it is better to omit the IN operator
3016 ** from the index lookup and instead do a scan of the M elements,
3017 ** testing each scanned row against the IN operator separately, if:
3019 ** M*log(K) < K*log(N)
3021 ** Our estimates for M, K, and N might be inaccurate, so we build in
3022 ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
3023 ** with the index, as using an index has better worst-case behavior.
3024 ** If we do not have real sqlite_stat1 data, always prefer to use
3025 ** the index. Do not bother with this optimization on very small
3026 ** tables (less than 2 rows) as it is pointless in that case.
3028 M = pProbe->aiRowLogEst[saved_nEq];
3029 logK = estLog(nIn);
3030 /* TUNING v----- 10 to bias toward indexed IN */
3031 x = M + logK + 10 - (nIn + rLogSize);
3032 if( x>=0 ){
3033 WHERETRACE(0x40,
3034 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) "
3035 "prefers indexed lookup\n",
3036 saved_nEq, M, logK, nIn, rLogSize, x));
3037 }else if( nInMul<2 && OptimizationEnabled(db, SQLITE_SeekScan) ){
3038 WHERETRACE(0x40,
3039 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3040 " nInMul=%d) prefers skip-scan\n",
3041 saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
3042 pNew->wsFlags |= WHERE_IN_SEEKSCAN;
3043 }else{
3044 WHERETRACE(0x40,
3045 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
3046 " nInMul=%d) prefers normal scan\n",
3047 saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
3048 continue;
3051 pNew->wsFlags |= WHERE_COLUMN_IN;
3052 }else if( eOp & (WO_EQ|WO_IS) ){
3053 int iCol = pProbe->aiColumn[saved_nEq];
3054 pNew->wsFlags |= WHERE_COLUMN_EQ;
3055 assert( saved_nEq==pNew->u.btree.nEq );
3056 if( iCol==XN_ROWID
3057 || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
3059 if( iCol==XN_ROWID || pProbe->uniqNotNull
3060 || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
3062 pNew->wsFlags |= WHERE_ONEROW;
3063 }else{
3064 pNew->wsFlags |= WHERE_UNQ_WANTED;
3067 if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
3068 }else if( eOp & WO_ISNULL ){
3069 pNew->wsFlags |= WHERE_COLUMN_NULL;
3070 }else{
3071 int nVecLen = whereRangeVectorLen(
3072 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
3074 if( eOp & (WO_GT|WO_GE) ){
3075 testcase( eOp & WO_GT );
3076 testcase( eOp & WO_GE );
3077 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
3078 pNew->u.btree.nBtm = nVecLen;
3079 pBtm = pTerm;
3080 pTop = 0;
3081 if( pTerm->wtFlags & TERM_LIKEOPT ){
3082 /* Range constraints that come from the LIKE optimization are
3083 ** always used in pairs. */
3084 pTop = &pTerm[1];
3085 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
3086 assert( pTop->wtFlags & TERM_LIKEOPT );
3087 assert( pTop->eOperator==WO_LT );
3088 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
3089 pNew->aLTerm[pNew->nLTerm++] = pTop;
3090 pNew->wsFlags |= WHERE_TOP_LIMIT;
3091 pNew->u.btree.nTop = 1;
3093 }else{
3094 assert( eOp & (WO_LT|WO_LE) );
3095 testcase( eOp & WO_LT );
3096 testcase( eOp & WO_LE );
3097 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
3098 pNew->u.btree.nTop = nVecLen;
3099 pTop = pTerm;
3100 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
3101 pNew->aLTerm[pNew->nLTerm-2] : 0;
3105 /* At this point pNew->nOut is set to the number of rows expected to
3106 ** be visited by the index scan before considering term pTerm, or the
3107 ** values of nIn and nInMul. In other words, assuming that all
3108 ** "x IN(...)" terms are replaced with "x = ?". This block updates
3109 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
3110 assert( pNew->nOut==saved_nOut );
3111 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3112 /* Adjust nOut using stat4 data. Or, if there is no stat4
3113 ** data, using some other estimate. */
3114 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
3115 }else{
3116 int nEq = ++pNew->u.btree.nEq;
3117 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
3119 assert( pNew->nOut==saved_nOut );
3120 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
3121 assert( (eOp & WO_IN) || nIn==0 );
3122 testcase( eOp & WO_IN );
3123 pNew->nOut += pTerm->truthProb;
3124 pNew->nOut -= nIn;
3125 }else{
3126 #ifdef SQLITE_ENABLE_STAT4
3127 tRowcnt nOut = 0;
3128 if( nInMul==0
3129 && pProbe->nSample
3130 && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol)
3131 && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr))
3132 && OptimizationEnabled(db, SQLITE_Stat4)
3134 Expr *pExpr = pTerm->pExpr;
3135 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
3136 testcase( eOp & WO_EQ );
3137 testcase( eOp & WO_IS );
3138 testcase( eOp & WO_ISNULL );
3139 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
3140 }else{
3141 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
3143 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
3144 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
3145 if( nOut ){
3146 pNew->nOut = sqlite3LogEst(nOut);
3147 if( nEq==1
3148 /* TUNING: Mark terms as "low selectivity" if they seem likely
3149 ** to be true for half or more of the rows in the table.
3150 ** See tag-202002240-1 */
3151 && pNew->nOut+10 > pProbe->aiRowLogEst[0]
3153 #if WHERETRACE_ENABLED /* 0x01 */
3154 if( sqlite3WhereTrace & 0x20 ){
3155 sqlite3DebugPrintf(
3156 "STAT4 determines term has low selectivity:\n");
3157 sqlite3WhereTermPrint(pTerm, 999);
3159 #endif
3160 pTerm->wtFlags |= TERM_HIGHTRUTH;
3161 if( pTerm->wtFlags & TERM_HEURTRUTH ){
3162 /* If the term has previously been used with an assumption of
3163 ** higher selectivity, then set the flag to rerun the
3164 ** loop computations. */
3165 pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
3168 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
3169 pNew->nOut -= nIn;
3172 if( nOut==0 )
3173 #endif
3175 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
3176 if( eOp & WO_ISNULL ){
3177 /* TUNING: If there is no likelihood() value, assume that a
3178 ** "col IS NULL" expression matches twice as many rows
3179 ** as (col=?). */
3180 pNew->nOut += 10;
3186 /* Set rCostIdx to the cost of visiting selected rows in index. Add
3187 ** it to pNew->rRun, which is currently set to the cost of the index
3188 ** seek only. Then, if this is a non-covering index, add the cost of
3189 ** visiting the rows in the main table. */
3190 assert( pSrc->pTab->szTabRow>0 );
3191 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
3192 /* The pProbe->szIdxRow is low for an IPK table since the interior
3193 ** pages are small. Thus szIdxRow gives a good estimate of seek cost.
3194 ** But the leaf pages are full-size, so pProbe->szIdxRow would badly
3195 ** under-estimate the scanning cost. */
3196 rCostIdx = pNew->nOut + 16;
3197 }else{
3198 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
3200 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
3201 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK|WHERE_EXPRIDX))==0 ){
3202 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
3204 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
3206 nOutUnadjusted = pNew->nOut;
3207 pNew->rRun += nInMul + nIn;
3208 pNew->nOut += nInMul + nIn;
3209 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
3210 rc = whereLoopInsert(pBuilder, pNew);
3212 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3213 pNew->nOut = saved_nOut;
3214 }else{
3215 pNew->nOut = nOutUnadjusted;
3218 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
3219 && pNew->u.btree.nEq<pProbe->nColumn
3220 && (pNew->u.btree.nEq<pProbe->nKeyCol ||
3221 pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)
3223 if( pNew->u.btree.nEq>3 ){
3224 sqlite3ProgressCheck(pParse);
3226 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
3228 pNew->nOut = saved_nOut;
3229 #ifdef SQLITE_ENABLE_STAT4
3230 pBuilder->nRecValid = nRecValid;
3231 #endif
3233 pNew->prereq = saved_prereq;
3234 pNew->u.btree.nEq = saved_nEq;
3235 pNew->u.btree.nBtm = saved_nBtm;
3236 pNew->u.btree.nTop = saved_nTop;
3237 pNew->nSkip = saved_nSkip;
3238 pNew->wsFlags = saved_wsFlags;
3239 pNew->nOut = saved_nOut;
3240 pNew->nLTerm = saved_nLTerm;
3242 /* Consider using a skip-scan if there are no WHERE clause constraints
3243 ** available for the left-most terms of the index, and if the average
3244 ** number of repeats in the left-most terms is at least 18.
3246 ** The magic number 18 is selected on the basis that scanning 17 rows
3247 ** is almost always quicker than an index seek (even though if the index
3248 ** contains fewer than 2^17 rows we assume otherwise in other parts of
3249 ** the code). And, even if it is not, it should not be too much slower.
3250 ** On the other hand, the extra seeks could end up being significantly
3251 ** more expensive. */
3252 assert( 42==sqlite3LogEst(18) );
3253 if( saved_nEq==saved_nSkip
3254 && saved_nEq+1<pProbe->nKeyCol
3255 && saved_nEq==pNew->nLTerm
3256 && pProbe->noSkipScan==0
3257 && pProbe->hasStat1!=0
3258 && OptimizationEnabled(db, SQLITE_SkipScan)
3259 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
3260 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
3262 LogEst nIter;
3263 pNew->u.btree.nEq++;
3264 pNew->nSkip++;
3265 pNew->aLTerm[pNew->nLTerm++] = 0;
3266 pNew->wsFlags |= WHERE_SKIPSCAN;
3267 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
3268 pNew->nOut -= nIter;
3269 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
3270 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
3271 nIter += 5;
3272 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
3273 pNew->nOut = saved_nOut;
3274 pNew->u.btree.nEq = saved_nEq;
3275 pNew->nSkip = saved_nSkip;
3276 pNew->wsFlags = saved_wsFlags;
3279 WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
3280 pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
3281 return rc;
3285 ** Return True if it is possible that pIndex might be useful in
3286 ** implementing the ORDER BY clause in pBuilder.
3288 ** Return False if pBuilder does not contain an ORDER BY clause or
3289 ** if there is no way for pIndex to be useful in implementing that
3290 ** ORDER BY clause.
3292 static int indexMightHelpWithOrderBy(
3293 WhereLoopBuilder *pBuilder,
3294 Index *pIndex,
3295 int iCursor
3297 ExprList *pOB;
3298 ExprList *aColExpr;
3299 int ii, jj;
3301 if( pIndex->bUnordered ) return 0;
3302 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
3303 for(ii=0; ii<pOB->nExpr; ii++){
3304 Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
3305 if( NEVER(pExpr==0) ) continue;
3306 if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
3307 if( pExpr->iColumn<0 ) return 1;
3308 for(jj=0; jj<pIndex->nKeyCol; jj++){
3309 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
3311 }else if( (aColExpr = pIndex->aColExpr)!=0 ){
3312 for(jj=0; jj<pIndex->nKeyCol; jj++){
3313 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
3314 if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
3315 return 1;
3320 return 0;
3323 /* Check to see if a partial index with pPartIndexWhere can be used
3324 ** in the current query. Return true if it can be and false if not.
3326 static int whereUsablePartialIndex(
3327 int iTab, /* The table for which we want an index */
3328 u8 jointype, /* The JT_* flags on the join */
3329 WhereClause *pWC, /* The WHERE clause of the query */
3330 Expr *pWhere /* The WHERE clause from the partial index */
3332 int i;
3333 WhereTerm *pTerm;
3334 Parse *pParse;
3336 if( jointype & JT_LTORJ ) return 0;
3337 pParse = pWC->pWInfo->pParse;
3338 while( pWhere->op==TK_AND ){
3339 if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0;
3340 pWhere = pWhere->pRight;
3342 if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
3343 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
3344 Expr *pExpr;
3345 pExpr = pTerm->pExpr;
3346 if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab)
3347 && ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON))
3348 && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
3349 && (pTerm->wtFlags & TERM_VNULL)==0
3351 return 1;
3354 return 0;
3358 ** pIdx is an index containing expressions. Check it see if any of the
3359 ** expressions in the index match the pExpr expression.
3361 static int exprIsCoveredByIndex(
3362 const Expr *pExpr,
3363 const Index *pIdx,
3364 int iTabCur
3366 int i;
3367 for(i=0; i<pIdx->nColumn; i++){
3368 if( pIdx->aiColumn[i]==XN_EXPR
3369 && sqlite3ExprCompare(0, pExpr, pIdx->aColExpr->a[i].pExpr, iTabCur)==0
3371 return 1;
3374 return 0;
3378 ** Structure passed to the whereIsCoveringIndex Walker callback.
3380 typedef struct CoveringIndexCheck CoveringIndexCheck;
3381 struct CoveringIndexCheck {
3382 Index *pIdx; /* The index */
3383 int iTabCur; /* Cursor number for the corresponding table */
3384 u8 bExpr; /* Uses an indexed expression */
3385 u8 bUnidx; /* Uses an unindexed column not within an indexed expr */
3389 ** Information passed in is pWalk->u.pCovIdxCk. Call it pCk.
3391 ** If the Expr node references the table with cursor pCk->iTabCur, then
3392 ** make sure that column is covered by the index pCk->pIdx. We know that
3393 ** all columns less than 63 (really BMS-1) are covered, so we don't need
3394 ** to check them. But we do need to check any column at 63 or greater.
3396 ** If the index does not cover the column, then set pWalk->eCode to
3397 ** non-zero and return WRC_Abort to stop the search.
3399 ** If this node does not disprove that the index can be a covering index,
3400 ** then just return WRC_Continue, to continue the search.
3402 ** If pCk->pIdx contains indexed expressions and one of those expressions
3403 ** matches pExpr, then prune the search.
3405 static int whereIsCoveringIndexWalkCallback(Walker *pWalk, Expr *pExpr){
3406 int i; /* Loop counter */
3407 const Index *pIdx; /* The index of interest */
3408 const i16 *aiColumn; /* Columns contained in the index */
3409 u16 nColumn; /* Number of columns in the index */
3410 CoveringIndexCheck *pCk; /* Info about this search */
3412 pCk = pWalk->u.pCovIdxCk;
3413 pIdx = pCk->pIdx;
3414 if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){
3415 /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/
3416 if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue;
3417 pIdx = pWalk->u.pCovIdxCk->pIdx;
3418 aiColumn = pIdx->aiColumn;
3419 nColumn = pIdx->nColumn;
3420 for(i=0; i<nColumn; i++){
3421 if( aiColumn[i]==pExpr->iColumn ) return WRC_Continue;
3423 pCk->bUnidx = 1;
3424 return WRC_Abort;
3425 }else if( pIdx->bHasExpr
3426 && exprIsCoveredByIndex(pExpr, pIdx, pWalk->u.pCovIdxCk->iTabCur) ){
3427 pCk->bExpr = 1;
3428 return WRC_Prune;
3430 return WRC_Continue;
3435 ** pIdx is an index that covers all of the low-number columns used by
3436 ** pWInfo->pSelect (columns from 0 through 62) or an index that has
3437 ** expressions terms. Hence, we cannot determine whether or not it is
3438 ** a covering index by using the colUsed bitmasks. We have to do a search
3439 ** to see if the index is covering. This routine does that search.
3441 ** The return value is one of these:
3443 ** 0 The index is definitely not a covering index
3445 ** WHERE_IDX_ONLY The index is definitely a covering index
3447 ** WHERE_EXPRIDX The index is likely a covering index, but it is
3448 ** difficult to determine precisely because of the
3449 ** expressions that are indexed. Score it as a
3450 ** covering index, but still keep the main table open
3451 ** just in case we need it.
3453 ** This routine is an optimization. It is always safe to return zero.
3454 ** But returning one of the other two values when zero should have been
3455 ** returned can lead to incorrect bytecode and assertion faults.
3457 static SQLITE_NOINLINE u32 whereIsCoveringIndex(
3458 WhereInfo *pWInfo, /* The WHERE clause context */
3459 Index *pIdx, /* Index that is being tested */
3460 int iTabCur /* Cursor for the table being indexed */
3462 int i, rc;
3463 struct CoveringIndexCheck ck;
3464 Walker w;
3465 if( pWInfo->pSelect==0 ){
3466 /* We don't have access to the full query, so we cannot check to see
3467 ** if pIdx is covering. Assume it is not. */
3468 return 0;
3470 if( pIdx->bHasExpr==0 ){
3471 for(i=0; i<pIdx->nColumn; i++){
3472 if( pIdx->aiColumn[i]>=BMS-1 ) break;
3474 if( i>=pIdx->nColumn ){
3475 /* pIdx does not index any columns greater than 62, but we know from
3476 ** colMask that columns greater than 62 are used, so this is not a
3477 ** covering index */
3478 return 0;
3481 ck.pIdx = pIdx;
3482 ck.iTabCur = iTabCur;
3483 ck.bExpr = 0;
3484 ck.bUnidx = 0;
3485 memset(&w, 0, sizeof(w));
3486 w.xExprCallback = whereIsCoveringIndexWalkCallback;
3487 w.xSelectCallback = sqlite3SelectWalkNoop;
3488 w.u.pCovIdxCk = &ck;
3489 sqlite3WalkSelect(&w, pWInfo->pSelect);
3490 if( ck.bUnidx ){
3491 rc = 0;
3492 }else if( ck.bExpr ){
3493 rc = WHERE_EXPRIDX;
3494 }else{
3495 rc = WHERE_IDX_ONLY;
3497 return rc;
3501 ** Add all WhereLoop objects for a single table of the join where the table
3502 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
3503 ** a b-tree table, not a virtual table.
3505 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
3506 ** are calculated as follows:
3508 ** For a full scan, assuming the table (or index) contains nRow rows:
3510 ** cost = nRow * 3.0 // full-table scan
3511 ** cost = nRow * K // scan of covering index
3512 ** cost = nRow * (K+3.0) // scan of non-covering index
3514 ** where K is a value between 1.1 and 3.0 set based on the relative
3515 ** estimated average size of the index and table records.
3517 ** For an index scan, where nVisit is the number of index rows visited
3518 ** by the scan, and nSeek is the number of seek operations required on
3519 ** the index b-tree:
3521 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
3522 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
3524 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
3525 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
3526 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
3528 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
3529 ** of uncertainty. For this reason, scoring is designed to pick plans that
3530 ** "do the least harm" if the estimates are inaccurate. For example, a
3531 ** log(nRow) factor is omitted from a non-covering index scan in order to
3532 ** bias the scoring in favor of using an index, since the worst-case
3533 ** performance of using an index is far better than the worst-case performance
3534 ** of a full table scan.
3536 static int whereLoopAddBtree(
3537 WhereLoopBuilder *pBuilder, /* WHERE clause information */
3538 Bitmask mPrereq /* Extra prerequisites for using this table */
3540 WhereInfo *pWInfo; /* WHERE analysis context */
3541 Index *pProbe; /* An index we are evaluating */
3542 Index sPk; /* A fake index object for the primary key */
3543 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
3544 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
3545 SrcList *pTabList; /* The FROM clause */
3546 SrcItem *pSrc; /* The FROM clause btree term to add */
3547 WhereLoop *pNew; /* Template WhereLoop object */
3548 int rc = SQLITE_OK; /* Return code */
3549 int iSortIdx = 1; /* Index number */
3550 int b; /* A boolean value */
3551 LogEst rSize; /* number of rows in the table */
3552 WhereClause *pWC; /* The parsed WHERE clause */
3553 Table *pTab; /* Table being queried */
3555 pNew = pBuilder->pNew;
3556 pWInfo = pBuilder->pWInfo;
3557 pTabList = pWInfo->pTabList;
3558 pSrc = pTabList->a + pNew->iTab;
3559 pTab = pSrc->pTab;
3560 pWC = pBuilder->pWC;
3561 assert( !IsVirtual(pSrc->pTab) );
3563 if( pSrc->fg.isIndexedBy ){
3564 assert( pSrc->fg.isCte==0 );
3565 /* An INDEXED BY clause specifies a particular index to use */
3566 pProbe = pSrc->u2.pIBIndex;
3567 }else if( !HasRowid(pTab) ){
3568 pProbe = pTab->pIndex;
3569 }else{
3570 /* There is no INDEXED BY clause. Create a fake Index object in local
3571 ** variable sPk to represent the rowid primary key index. Make this
3572 ** fake index the first in a chain of Index objects with all of the real
3573 ** indices to follow */
3574 Index *pFirst; /* First of real indices on the table */
3575 memset(&sPk, 0, sizeof(Index));
3576 sPk.nKeyCol = 1;
3577 sPk.nColumn = 1;
3578 sPk.aiColumn = &aiColumnPk;
3579 sPk.aiRowLogEst = aiRowEstPk;
3580 sPk.onError = OE_Replace;
3581 sPk.pTable = pTab;
3582 sPk.szIdxRow = 3; /* TUNING: Interior rows of IPK table are very small */
3583 sPk.idxType = SQLITE_IDXTYPE_IPK;
3584 aiRowEstPk[0] = pTab->nRowLogEst;
3585 aiRowEstPk[1] = 0;
3586 pFirst = pSrc->pTab->pIndex;
3587 if( pSrc->fg.notIndexed==0 ){
3588 /* The real indices of the table are only considered if the
3589 ** NOT INDEXED qualifier is omitted from the FROM clause */
3590 sPk.pNext = pFirst;
3592 pProbe = &sPk;
3594 rSize = pTab->nRowLogEst;
3596 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
3597 /* Automatic indexes */
3598 if( !pBuilder->pOrSet /* Not part of an OR optimization */
3599 && (pWInfo->wctrlFlags & (WHERE_RIGHT_JOIN|WHERE_OR_SUBCLAUSE))==0
3600 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
3601 && !pSrc->fg.isIndexedBy /* Has no INDEXED BY clause */
3602 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
3603 && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
3604 && !pSrc->fg.isCorrelated /* Not a correlated subquery */
3605 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
3606 && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */
3608 /* Generate auto-index WhereLoops */
3609 LogEst rLogSize; /* Logarithm of the number of rows in the table */
3610 WhereTerm *pTerm;
3611 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
3612 rLogSize = estLog(rSize);
3613 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
3614 if( pTerm->prereqRight & pNew->maskSelf ) continue;
3615 if( termCanDriveIndex(pTerm, pSrc, 0) ){
3616 pNew->u.btree.nEq = 1;
3617 pNew->nSkip = 0;
3618 pNew->u.btree.pIndex = 0;
3619 pNew->nLTerm = 1;
3620 pNew->aLTerm[0] = pTerm;
3621 /* TUNING: One-time cost for computing the automatic index is
3622 ** estimated to be X*N*log2(N) where N is the number of rows in
3623 ** the table being indexed and where X is 7 (LogEst=28) for normal
3624 ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
3625 ** of X is smaller for views and subqueries so that the query planner
3626 ** will be more aggressive about generating automatic indexes for
3627 ** those objects, since there is no opportunity to add schema
3628 ** indexes on subqueries and views. */
3629 pNew->rSetup = rLogSize + rSize;
3630 if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){
3631 pNew->rSetup += 28;
3632 }else{
3633 pNew->rSetup -= 25; /* Greatly reduced setup cost for auto indexes
3634 ** on ephemeral materializations of views */
3636 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
3637 if( pNew->rSetup<0 ) pNew->rSetup = 0;
3638 /* TUNING: Each index lookup yields 20 rows in the table. This
3639 ** is more than the usual guess of 10 rows, since we have no way
3640 ** of knowing how selective the index will ultimately be. It would
3641 ** not be unreasonable to make this value much larger. */
3642 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
3643 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
3644 pNew->wsFlags = WHERE_AUTO_INDEX;
3645 pNew->prereq = mPrereq | pTerm->prereqRight;
3646 rc = whereLoopInsert(pBuilder, pNew);
3650 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
3652 /* Loop over all indices. If there was an INDEXED BY clause, then only
3653 ** consider index pProbe. */
3654 for(; rc==SQLITE_OK && pProbe;
3655 pProbe=(pSrc->fg.isIndexedBy ? 0 : pProbe->pNext), iSortIdx++
3657 if( pProbe->pPartIdxWhere!=0
3658 && !whereUsablePartialIndex(pSrc->iCursor, pSrc->fg.jointype, pWC,
3659 pProbe->pPartIdxWhere)
3661 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
3662 continue; /* Partial index inappropriate for this query */
3664 if( pProbe->bNoQuery ) continue;
3665 rSize = pProbe->aiRowLogEst[0];
3666 pNew->u.btree.nEq = 0;
3667 pNew->u.btree.nBtm = 0;
3668 pNew->u.btree.nTop = 0;
3669 pNew->nSkip = 0;
3670 pNew->nLTerm = 0;
3671 pNew->iSortIdx = 0;
3672 pNew->rSetup = 0;
3673 pNew->prereq = mPrereq;
3674 pNew->nOut = rSize;
3675 pNew->u.btree.pIndex = pProbe;
3676 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
3678 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
3679 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
3680 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
3681 /* Integer primary key index */
3682 pNew->wsFlags = WHERE_IPK;
3684 /* Full table scan */
3685 pNew->iSortIdx = b ? iSortIdx : 0;
3686 /* TUNING: Cost of full table scan is 3.0*N. The 3.0 factor is an
3687 ** extra cost designed to discourage the use of full table scans,
3688 ** since index lookups have better worst-case performance if our
3689 ** stat guesses are wrong. Reduce the 3.0 penalty slightly
3690 ** (to 2.75) if we have valid STAT4 information for the table.
3691 ** At 2.75, a full table scan is preferred over using an index on
3692 ** a column with just two distinct values where each value has about
3693 ** an equal number of appearances. Without STAT4 data, we still want
3694 ** to use an index in that case, since the constraint might be for
3695 ** the scarcer of the two values, and in that case an index lookup is
3696 ** better.
3698 #ifdef SQLITE_ENABLE_STAT4
3699 pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
3700 #else
3701 pNew->rRun = rSize + 16;
3702 #endif
3703 if( IsView(pTab) || (pTab->tabFlags & TF_Ephemeral)!=0 ){
3704 pNew->wsFlags |= WHERE_VIEWSCAN;
3706 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3707 whereLoopOutputAdjust(pWC, pNew, rSize);
3708 rc = whereLoopInsert(pBuilder, pNew);
3709 pNew->nOut = rSize;
3710 if( rc ) break;
3711 }else{
3712 Bitmask m;
3713 if( pProbe->isCovering ){
3714 m = 0;
3715 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3716 }else{
3717 m = pSrc->colUsed & pProbe->colNotIdxed;
3718 pNew->wsFlags = WHERE_INDEXED;
3719 if( m==TOPBIT || (pProbe->bHasExpr && !pProbe->bHasVCol && m!=0) ){
3720 u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
3721 if( isCov==0 ){
3722 WHERETRACE(0x200,
3723 ("-> %s is not a covering index"
3724 " according to whereIsCoveringIndex()\n", pProbe->zName));
3725 assert( m!=0 );
3726 }else{
3727 m = 0;
3728 pNew->wsFlags |= isCov;
3729 if( isCov & WHERE_IDX_ONLY ){
3730 WHERETRACE(0x200,
3731 ("-> %s is a covering expression index"
3732 " according to whereIsCoveringIndex()\n", pProbe->zName));
3733 }else{
3734 assert( isCov==WHERE_EXPRIDX );
3735 WHERETRACE(0x200,
3736 ("-> %s might be a covering expression index"
3737 " according to whereIsCoveringIndex()\n", pProbe->zName));
3740 }else if( m==0 ){
3741 WHERETRACE(0x200,
3742 ("-> %s a covering index according to bitmasks\n",
3743 pProbe->zName, m==0 ? "is" : "is not"));
3744 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3748 /* Full scan via index */
3749 if( b
3750 || !HasRowid(pTab)
3751 || pProbe->pPartIdxWhere!=0
3752 || pSrc->fg.isIndexedBy
3753 || ( m==0
3754 && pProbe->bUnordered==0
3755 && (pProbe->szIdxRow<pTab->szTabRow)
3756 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3757 && sqlite3GlobalConfig.bUseCis
3758 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
3761 pNew->iSortIdx = b ? iSortIdx : 0;
3763 /* The cost of visiting the index rows is N*K, where K is
3764 ** between 1.1 and 3.0, depending on the relative sizes of the
3765 ** index and table rows. */
3766 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
3767 if( m!=0 ){
3768 /* If this is a non-covering index scan, add in the cost of
3769 ** doing table lookups. The cost will be 3x the number of
3770 ** lookups. Take into account WHERE clause terms that can be
3771 ** satisfied using just the index, and that do not require a
3772 ** table lookup. */
3773 LogEst nLookup = rSize + 16; /* Base cost: N*3 */
3774 int ii;
3775 int iCur = pSrc->iCursor;
3776 WhereClause *pWC2 = &pWInfo->sWC;
3777 for(ii=0; ii<pWC2->nTerm; ii++){
3778 WhereTerm *pTerm = &pWC2->a[ii];
3779 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
3780 break;
3782 /* pTerm can be evaluated using just the index. So reduce
3783 ** the expected number of table lookups accordingly */
3784 if( pTerm->truthProb<=0 ){
3785 nLookup += pTerm->truthProb;
3786 }else{
3787 nLookup--;
3788 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
3792 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
3794 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3795 whereLoopOutputAdjust(pWC, pNew, rSize);
3796 if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){
3797 /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
3798 ** because the cursor used to access the index might not be
3799 ** positioned to the correct row during the right-join no-match
3800 ** loop. */
3801 }else{
3802 rc = whereLoopInsert(pBuilder, pNew);
3804 pNew->nOut = rSize;
3805 if( rc ) break;
3809 pBuilder->bldFlags1 = 0;
3810 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
3811 if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
3812 /* If a non-unique index is used, or if a prefix of the key for
3813 ** unique index is used (making the index functionally non-unique)
3814 ** then the sqlite_stat1 data becomes important for scoring the
3815 ** plan */
3816 pTab->tabFlags |= TF_StatsUsed;
3818 #ifdef SQLITE_ENABLE_STAT4
3819 sqlite3Stat4ProbeFree(pBuilder->pRec);
3820 pBuilder->nRecValid = 0;
3821 pBuilder->pRec = 0;
3822 #endif
3824 return rc;
3827 #ifndef SQLITE_OMIT_VIRTUALTABLE
3830 ** Return true if pTerm is a virtual table LIMIT or OFFSET term.
3832 static int isLimitTerm(WhereTerm *pTerm){
3833 assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
3834 return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
3835 && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
3839 ** Argument pIdxInfo is already populated with all constraints that may
3840 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
3841 ** function marks a subset of those constraints usable, invokes the
3842 ** xBestIndex method and adds the returned plan to pBuilder.
3844 ** A constraint is marked usable if:
3846 ** * Argument mUsable indicates that its prerequisites are available, and
3848 ** * It is not one of the operators specified in the mExclude mask passed
3849 ** as the fourth argument (which in practice is either WO_IN or 0).
3851 ** Argument mPrereq is a mask of tables that must be scanned before the
3852 ** virtual table in question. These are added to the plans prerequisites
3853 ** before it is added to pBuilder.
3855 ** Output parameter *pbIn is set to true if the plan added to pBuilder
3856 ** uses one or more WO_IN terms, or false otherwise.
3858 static int whereLoopAddVirtualOne(
3859 WhereLoopBuilder *pBuilder,
3860 Bitmask mPrereq, /* Mask of tables that must be used. */
3861 Bitmask mUsable, /* Mask of usable tables */
3862 u16 mExclude, /* Exclude terms using these operators */
3863 sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
3864 u16 mNoOmit, /* Do not omit these constraints */
3865 int *pbIn, /* OUT: True if plan uses an IN(...) op */
3866 int *pbRetryLimit /* OUT: Retry without LIMIT/OFFSET */
3868 WhereClause *pWC = pBuilder->pWC;
3869 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
3870 struct sqlite3_index_constraint *pIdxCons;
3871 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
3872 int i;
3873 int mxTerm;
3874 int rc = SQLITE_OK;
3875 WhereLoop *pNew = pBuilder->pNew;
3876 Parse *pParse = pBuilder->pWInfo->pParse;
3877 SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
3878 int nConstraint = pIdxInfo->nConstraint;
3880 assert( (mUsable & mPrereq)==mPrereq );
3881 *pbIn = 0;
3882 pNew->prereq = mPrereq;
3884 /* Set the usable flag on the subset of constraints identified by
3885 ** arguments mUsable and mExclude. */
3886 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
3887 for(i=0; i<nConstraint; i++, pIdxCons++){
3888 WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
3889 pIdxCons->usable = 0;
3890 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
3891 && (pTerm->eOperator & mExclude)==0
3892 && (pbRetryLimit || !isLimitTerm(pTerm))
3894 pIdxCons->usable = 1;
3898 /* Initialize the output fields of the sqlite3_index_info structure */
3899 memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
3900 assert( pIdxInfo->needToFreeIdxStr==0 );
3901 pIdxInfo->idxStr = 0;
3902 pIdxInfo->idxNum = 0;
3903 pIdxInfo->orderByConsumed = 0;
3904 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
3905 pIdxInfo->estimatedRows = 25;
3906 pIdxInfo->idxFlags = 0;
3907 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
3908 pHidden->mHandleIn = 0;
3910 /* Invoke the virtual table xBestIndex() method */
3911 rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
3912 if( rc ){
3913 if( rc==SQLITE_CONSTRAINT ){
3914 /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
3915 ** that the particular combination of parameters provided is unusable.
3916 ** Make no entries in the loop table.
3918 WHERETRACE(0xffffffff, (" ^^^^--- non-viable plan rejected!\n"));
3919 return SQLITE_OK;
3921 return rc;
3924 mxTerm = -1;
3925 assert( pNew->nLSlot>=nConstraint );
3926 memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
3927 memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
3928 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
3929 for(i=0; i<nConstraint; i++, pIdxCons++){
3930 int iTerm;
3931 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
3932 WhereTerm *pTerm;
3933 int j = pIdxCons->iTermOffset;
3934 if( iTerm>=nConstraint
3935 || j<0
3936 || j>=pWC->nTerm
3937 || pNew->aLTerm[iTerm]!=0
3938 || pIdxCons->usable==0
3940 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
3941 testcase( pIdxInfo->needToFreeIdxStr );
3942 return SQLITE_ERROR;
3944 testcase( iTerm==nConstraint-1 );
3945 testcase( j==0 );
3946 testcase( j==pWC->nTerm-1 );
3947 pTerm = &pWC->a[j];
3948 pNew->prereq |= pTerm->prereqRight;
3949 assert( iTerm<pNew->nLSlot );
3950 pNew->aLTerm[iTerm] = pTerm;
3951 if( iTerm>mxTerm ) mxTerm = iTerm;
3952 testcase( iTerm==15 );
3953 testcase( iTerm==16 );
3954 if( pUsage[i].omit ){
3955 if( i<16 && ((1<<i)&mNoOmit)==0 ){
3956 testcase( i!=iTerm );
3957 pNew->u.vtab.omitMask |= 1<<iTerm;
3958 }else{
3959 testcase( i!=iTerm );
3961 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
3962 pNew->u.vtab.bOmitOffset = 1;
3965 if( SMASKBIT32(i) & pHidden->mHandleIn ){
3966 pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
3967 }else if( (pTerm->eOperator & WO_IN)!=0 ){
3968 /* A virtual table that is constrained by an IN clause may not
3969 ** consume the ORDER BY clause because (1) the order of IN terms
3970 ** is not necessarily related to the order of output terms and
3971 ** (2) Multiple outputs from a single IN value will not merge
3972 ** together. */
3973 pIdxInfo->orderByConsumed = 0;
3974 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
3975 *pbIn = 1; assert( (mExclude & WO_IN)==0 );
3978 assert( pbRetryLimit || !isLimitTerm(pTerm) );
3979 if( isLimitTerm(pTerm) && *pbIn ){
3980 /* If there is an IN(...) term handled as an == (separate call to
3981 ** xFilter for each value on the RHS of the IN) and a LIMIT or
3982 ** OFFSET term handled as well, the plan is unusable. Set output
3983 ** variable *pbRetryLimit to true to tell the caller to retry with
3984 ** LIMIT and OFFSET disabled. */
3985 if( pIdxInfo->needToFreeIdxStr ){
3986 sqlite3_free(pIdxInfo->idxStr);
3987 pIdxInfo->idxStr = 0;
3988 pIdxInfo->needToFreeIdxStr = 0;
3990 *pbRetryLimit = 1;
3991 return SQLITE_OK;
3996 pNew->nLTerm = mxTerm+1;
3997 for(i=0; i<=mxTerm; i++){
3998 if( pNew->aLTerm[i]==0 ){
3999 /* The non-zero argvIdx values must be contiguous. Raise an
4000 ** error if they are not */
4001 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
4002 testcase( pIdxInfo->needToFreeIdxStr );
4003 return SQLITE_ERROR;
4006 assert( pNew->nLTerm<=pNew->nLSlot );
4007 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4008 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4009 pIdxInfo->needToFreeIdxStr = 0;
4010 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
4011 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
4012 pIdxInfo->nOrderBy : 0);
4013 pNew->rSetup = 0;
4014 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
4015 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
4017 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
4018 ** that the scan will visit at most one row. Clear it otherwise. */
4019 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
4020 pNew->wsFlags |= WHERE_ONEROW;
4021 }else{
4022 pNew->wsFlags &= ~WHERE_ONEROW;
4024 rc = whereLoopInsert(pBuilder, pNew);
4025 if( pNew->u.vtab.needFree ){
4026 sqlite3_free(pNew->u.vtab.idxStr);
4027 pNew->u.vtab.needFree = 0;
4029 WHERETRACE(0xffffffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
4030 *pbIn, (sqlite3_uint64)mPrereq,
4031 (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
4033 return rc;
4037 ** Return the collating sequence for a constraint passed into xBestIndex.
4039 ** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
4040 ** This routine depends on there being a HiddenIndexInfo structure immediately
4041 ** following the sqlite3_index_info structure.
4043 ** Return a pointer to the collation name:
4045 ** 1. If there is an explicit COLLATE operator on the constraint, return it.
4047 ** 2. Else, if the column has an alternative collation, return that.
4049 ** 3. Otherwise, return "BINARY".
4051 const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
4052 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4053 const char *zRet = 0;
4054 if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
4055 CollSeq *pC = 0;
4056 int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
4057 Expr *pX = pHidden->pWC->a[iTerm].pExpr;
4058 if( pX->pLeft ){
4059 pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
4061 zRet = (pC ? pC->zName : sqlite3StrBINARY);
4063 return zRet;
4067 ** Return true if constraint iCons is really an IN(...) constraint, or
4068 ** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
4069 ** or clear (if bHandle==0) the flag to handle it using an iterator.
4071 int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){
4072 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4073 u32 m = SMASKBIT32(iCons);
4074 if( m & pHidden->mIn ){
4075 if( bHandle==0 ){
4076 pHidden->mHandleIn &= ~m;
4077 }else if( bHandle>0 ){
4078 pHidden->mHandleIn |= m;
4080 return 1;
4082 return 0;
4086 ** This interface is callable from within the xBestIndex callback only.
4088 ** If possible, set (*ppVal) to point to an object containing the value
4089 ** on the right-hand-side of constraint iCons.
4091 int sqlite3_vtab_rhs_value(
4092 sqlite3_index_info *pIdxInfo, /* Copy of first argument to xBestIndex */
4093 int iCons, /* Constraint for which RHS is wanted */
4094 sqlite3_value **ppVal /* Write value extracted here */
4096 HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
4097 sqlite3_value *pVal = 0;
4098 int rc = SQLITE_OK;
4099 if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
4100 rc = SQLITE_MISUSE; /* EV: R-30545-25046 */
4101 }else{
4102 if( pH->aRhs[iCons]==0 ){
4103 WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
4104 rc = sqlite3ValueFromExpr(
4105 pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
4106 SQLITE_AFF_BLOB, &pH->aRhs[iCons]
4108 testcase( rc!=SQLITE_OK );
4110 pVal = pH->aRhs[iCons];
4112 *ppVal = pVal;
4114 if( rc==SQLITE_OK && pVal==0 ){ /* IMP: R-19933-32160 */
4115 rc = SQLITE_NOTFOUND; /* IMP: R-36424-56542 */
4118 return rc;
4122 ** Return true if ORDER BY clause may be handled as DISTINCT.
4124 int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
4125 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
4126 assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
4127 return pHidden->eDistinct;
4131 ** Cause the prepared statement that is associated with a call to
4132 ** xBestIndex to potentially use all schemas. If the statement being
4133 ** prepared is read-only, then just start read transactions on all
4134 ** schemas. But if this is a write operation, start writes on all
4135 ** schemas.
4137 ** This is used by the (built-in) sqlite_dbpage virtual table.
4139 void sqlite3VtabUsesAllSchemas(Parse *pParse){
4140 int nDb = pParse->db->nDb;
4141 int i;
4142 for(i=0; i<nDb; i++){
4143 sqlite3CodeVerifySchema(pParse, i);
4145 if( DbMaskNonZero(pParse->writeMask) ){
4146 for(i=0; i<nDb; i++){
4147 sqlite3BeginWriteOperation(pParse, 0, i);
4153 ** Add all WhereLoop objects for a table of the join identified by
4154 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
4156 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
4157 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
4158 ** entries that occur before the virtual table in the FROM clause and are
4159 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
4160 ** mUnusable mask contains all FROM clause entries that occur after the
4161 ** virtual table and are separated from it by at least one LEFT or
4162 ** CROSS JOIN.
4164 ** For example, if the query were:
4166 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
4168 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
4170 ** All the tables in mPrereq must be scanned before the current virtual
4171 ** table. So any terms for which all prerequisites are satisfied by
4172 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
4173 ** Conversely, all tables in mUnusable must be scanned after the current
4174 ** virtual table, so any terms for which the prerequisites overlap with
4175 ** mUnusable should always be configured as "not-usable" for xBestIndex.
4177 static int whereLoopAddVirtual(
4178 WhereLoopBuilder *pBuilder, /* WHERE clause information */
4179 Bitmask mPrereq, /* Tables that must be scanned before this one */
4180 Bitmask mUnusable /* Tables that must be scanned after this one */
4182 int rc = SQLITE_OK; /* Return code */
4183 WhereInfo *pWInfo; /* WHERE analysis context */
4184 Parse *pParse; /* The parsing context */
4185 WhereClause *pWC; /* The WHERE clause */
4186 SrcItem *pSrc; /* The FROM clause term to search */
4187 sqlite3_index_info *p; /* Object to pass to xBestIndex() */
4188 int nConstraint; /* Number of constraints in p */
4189 int bIn; /* True if plan uses IN(...) operator */
4190 WhereLoop *pNew;
4191 Bitmask mBest; /* Tables used by best possible plan */
4192 u16 mNoOmit;
4193 int bRetry = 0; /* True to retry with LIMIT/OFFSET disabled */
4195 assert( (mPrereq & mUnusable)==0 );
4196 pWInfo = pBuilder->pWInfo;
4197 pParse = pWInfo->pParse;
4198 pWC = pBuilder->pWC;
4199 pNew = pBuilder->pNew;
4200 pSrc = &pWInfo->pTabList->a[pNew->iTab];
4201 assert( IsVirtual(pSrc->pTab) );
4202 p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit);
4203 if( p==0 ) return SQLITE_NOMEM_BKPT;
4204 pNew->rSetup = 0;
4205 pNew->wsFlags = WHERE_VIRTUALTABLE;
4206 pNew->nLTerm = 0;
4207 pNew->u.vtab.needFree = 0;
4208 nConstraint = p->nConstraint;
4209 if( whereLoopResize(pParse->db, pNew, nConstraint) ){
4210 freeIndexInfo(pParse->db, p);
4211 return SQLITE_NOMEM_BKPT;
4214 /* First call xBestIndex() with all constraints usable. */
4215 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
4216 WHERETRACE(0x800, (" VirtualOne: all usable\n"));
4217 rc = whereLoopAddVirtualOne(
4218 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry
4220 if( bRetry ){
4221 assert( rc==SQLITE_OK );
4222 rc = whereLoopAddVirtualOne(
4223 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0
4227 /* If the call to xBestIndex() with all terms enabled produced a plan
4228 ** that does not require any source tables (IOW: a plan with mBest==0)
4229 ** and does not use an IN(...) operator, then there is no point in making
4230 ** any further calls to xBestIndex() since they will all return the same
4231 ** result (if the xBestIndex() implementation is sane). */
4232 if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
4233 int seenZero = 0; /* True if a plan with no prereqs seen */
4234 int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
4235 Bitmask mPrev = 0;
4236 Bitmask mBestNoIn = 0;
4238 /* If the plan produced by the earlier call uses an IN(...) term, call
4239 ** xBestIndex again, this time with IN(...) terms disabled. */
4240 if( bIn ){
4241 WHERETRACE(0x800, (" VirtualOne: all usable w/o IN\n"));
4242 rc = whereLoopAddVirtualOne(
4243 pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0);
4244 assert( bIn==0 );
4245 mBestNoIn = pNew->prereq & ~mPrereq;
4246 if( mBestNoIn==0 ){
4247 seenZero = 1;
4248 seenZeroNoIN = 1;
4252 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
4253 ** in the set of terms that apply to the current virtual table. */
4254 while( rc==SQLITE_OK ){
4255 int i;
4256 Bitmask mNext = ALLBITS;
4257 assert( mNext>0 );
4258 for(i=0; i<nConstraint; i++){
4259 Bitmask mThis = (
4260 pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
4262 if( mThis>mPrev && mThis<mNext ) mNext = mThis;
4264 mPrev = mNext;
4265 if( mNext==ALLBITS ) break;
4266 if( mNext==mBest || mNext==mBestNoIn ) continue;
4267 WHERETRACE(0x800, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
4268 (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
4269 rc = whereLoopAddVirtualOne(
4270 pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn, 0);
4271 if( pNew->prereq==mPrereq ){
4272 seenZero = 1;
4273 if( bIn==0 ) seenZeroNoIN = 1;
4277 /* If the calls to xBestIndex() in the above loop did not find a plan
4278 ** that requires no source tables at all (i.e. one guaranteed to be
4279 ** usable), make a call here with all source tables disabled */
4280 if( rc==SQLITE_OK && seenZero==0 ){
4281 WHERETRACE(0x800, (" VirtualOne: all disabled\n"));
4282 rc = whereLoopAddVirtualOne(
4283 pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0);
4284 if( bIn==0 ) seenZeroNoIN = 1;
4287 /* If the calls to xBestIndex() have so far failed to find a plan
4288 ** that requires no source tables at all and does not use an IN(...)
4289 ** operator, make a final call to obtain one here. */
4290 if( rc==SQLITE_OK && seenZeroNoIN==0 ){
4291 WHERETRACE(0x800, (" VirtualOne: all disabled and w/o IN\n"));
4292 rc = whereLoopAddVirtualOne(
4293 pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
4297 if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
4298 freeIndexInfo(pParse->db, p);
4299 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
4300 return rc;
4302 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4305 ** Add WhereLoop entries to handle OR terms. This works for either
4306 ** btrees or virtual tables.
4308 static int whereLoopAddOr(
4309 WhereLoopBuilder *pBuilder,
4310 Bitmask mPrereq,
4311 Bitmask mUnusable
4313 WhereInfo *pWInfo = pBuilder->pWInfo;
4314 WhereClause *pWC;
4315 WhereLoop *pNew;
4316 WhereTerm *pTerm, *pWCEnd;
4317 int rc = SQLITE_OK;
4318 int iCur;
4319 WhereClause tempWC;
4320 WhereLoopBuilder sSubBuild;
4321 WhereOrSet sSum, sCur;
4322 SrcItem *pItem;
4324 pWC = pBuilder->pWC;
4325 pWCEnd = pWC->a + pWC->nTerm;
4326 pNew = pBuilder->pNew;
4327 memset(&sSum, 0, sizeof(sSum));
4328 pItem = pWInfo->pTabList->a + pNew->iTab;
4329 iCur = pItem->iCursor;
4331 /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
4332 if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK;
4334 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4335 if( (pTerm->eOperator & WO_OR)!=0
4336 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4338 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4339 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4340 WhereTerm *pOrTerm;
4341 int once = 1;
4342 int i, j;
4344 sSubBuild = *pBuilder;
4345 sSubBuild.pOrSet = &sCur;
4347 WHERETRACE(0x400, ("Begin processing OR-clause %p\n", pTerm));
4348 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
4349 if( (pOrTerm->eOperator & WO_AND)!=0 ){
4350 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4351 }else if( pOrTerm->leftCursor==iCur ){
4352 tempWC.pWInfo = pWC->pWInfo;
4353 tempWC.pOuter = pWC;
4354 tempWC.op = TK_AND;
4355 tempWC.nTerm = 1;
4356 tempWC.nBase = 1;
4357 tempWC.a = pOrTerm;
4358 sSubBuild.pWC = &tempWC;
4359 }else{
4360 continue;
4362 sCur.n = 0;
4363 #ifdef WHERETRACE_ENABLED
4364 WHERETRACE(0x400, ("OR-term %d of %p has %d subterms:\n",
4365 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
4366 if( sqlite3WhereTrace & 0x20000 ){
4367 sqlite3WhereClausePrint(sSubBuild.pWC);
4369 #endif
4370 #ifndef SQLITE_OMIT_VIRTUALTABLE
4371 if( IsVirtual(pItem->pTab) ){
4372 rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
4373 }else
4374 #endif
4376 rc = whereLoopAddBtree(&sSubBuild, mPrereq);
4378 if( rc==SQLITE_OK ){
4379 rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
4381 testcase( rc==SQLITE_NOMEM && sCur.n>0 );
4382 testcase( rc==SQLITE_DONE );
4383 if( sCur.n==0 ){
4384 sSum.n = 0;
4385 break;
4386 }else if( once ){
4387 whereOrMove(&sSum, &sCur);
4388 once = 0;
4389 }else{
4390 WhereOrSet sPrev;
4391 whereOrMove(&sPrev, &sSum);
4392 sSum.n = 0;
4393 for(i=0; i<sPrev.n; i++){
4394 for(j=0; j<sCur.n; j++){
4395 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4396 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4397 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4402 pNew->nLTerm = 1;
4403 pNew->aLTerm[0] = pTerm;
4404 pNew->wsFlags = WHERE_MULTI_OR;
4405 pNew->rSetup = 0;
4406 pNew->iSortIdx = 0;
4407 memset(&pNew->u, 0, sizeof(pNew->u));
4408 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
4409 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
4410 ** of all sub-scans required by the OR-scan. However, due to rounding
4411 ** errors, it may be that the cost of the OR-scan is equal to its
4412 ** most expensive sub-scan. Add the smallest possible penalty
4413 ** (equivalent to multiplying the cost by 1.07) to ensure that
4414 ** this does not happen. Otherwise, for WHERE clauses such as the
4415 ** following where there is an index on "y":
4417 ** WHERE likelihood(x=?, 0.99) OR y=?
4419 ** the planner may elect to "OR" together a full-table scan and an
4420 ** index lookup. And other similarly odd results. */
4421 pNew->rRun = sSum.a[i].rRun + 1;
4422 pNew->nOut = sSum.a[i].nOut;
4423 pNew->prereq = sSum.a[i].prereq;
4424 rc = whereLoopInsert(pBuilder, pNew);
4426 WHERETRACE(0x400, ("End processing OR-clause %p\n", pTerm));
4429 return rc;
4433 ** Add all WhereLoop objects for all tables
4435 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
4436 WhereInfo *pWInfo = pBuilder->pWInfo;
4437 Bitmask mPrereq = 0;
4438 Bitmask mPrior = 0;
4439 int iTab;
4440 SrcList *pTabList = pWInfo->pTabList;
4441 SrcItem *pItem;
4442 SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
4443 sqlite3 *db = pWInfo->pParse->db;
4444 int rc = SQLITE_OK;
4445 int bFirstPastRJ = 0;
4446 int hasRightJoin = 0;
4447 WhereLoop *pNew;
4450 /* Loop over the tables in the join, from left to right */
4451 pNew = pBuilder->pNew;
4453 /* Verify that pNew has already been initialized */
4454 assert( pNew->nLTerm==0 );
4455 assert( pNew->wsFlags==0 );
4456 assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) );
4457 assert( pNew->aLTerm!=0 );
4459 pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
4460 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
4461 Bitmask mUnusable = 0;
4462 pNew->iTab = iTab;
4463 pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
4464 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
4465 if( bFirstPastRJ
4466 || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0
4468 /* Add prerequisites to prevent reordering of FROM clause terms
4469 ** across CROSS joins and outer joins. The bFirstPastRJ boolean
4470 ** prevents the right operand of a RIGHT JOIN from being swapped with
4471 ** other elements even further to the right.
4473 ** The JT_LTORJ case and the hasRightJoin flag work together to
4474 ** prevent FROM-clause terms from moving from the right side of
4475 ** a LEFT JOIN over to the left side of that join if the LEFT JOIN
4476 ** is itself on the left side of a RIGHT JOIN.
4478 if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1;
4479 mPrereq |= mPrior;
4480 bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0;
4481 }else if( !hasRightJoin ){
4482 mPrereq = 0;
4484 #ifndef SQLITE_OMIT_VIRTUALTABLE
4485 if( IsVirtual(pItem->pTab) ){
4486 SrcItem *p;
4487 for(p=&pItem[1]; p<pEnd; p++){
4488 if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
4489 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
4492 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
4493 }else
4494 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4496 rc = whereLoopAddBtree(pBuilder, mPrereq);
4498 if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
4499 rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
4501 mPrior |= pNew->maskSelf;
4502 if( rc || db->mallocFailed ){
4503 if( rc==SQLITE_DONE ){
4504 /* We hit the query planner search limit set by iPlanLimit */
4505 sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
4506 rc = SQLITE_OK;
4507 }else{
4508 break;
4513 whereLoopClear(db, pNew);
4514 return rc;
4518 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
4519 ** parameters) to see if it outputs rows in the requested ORDER BY
4520 ** (or GROUP BY) without requiring a separate sort operation. Return N:
4522 ** N>0: N terms of the ORDER BY clause are satisfied
4523 ** N==0: No terms of the ORDER BY clause are satisfied
4524 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
4526 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4527 ** strict. With GROUP BY and DISTINCT the only requirement is that
4528 ** equivalent rows appear immediately adjacent to one another. GROUP BY
4529 ** and DISTINCT do not require rows to appear in any particular order as long
4530 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
4531 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
4532 ** pOrderBy terms must be matched in strict left-to-right order.
4534 static i8 wherePathSatisfiesOrderBy(
4535 WhereInfo *pWInfo, /* The WHERE clause */
4536 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
4537 WherePath *pPath, /* The WherePath to check */
4538 u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
4539 u16 nLoop, /* Number of entries in pPath->aLoop[] */
4540 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
4541 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
4543 u8 revSet; /* True if rev is known */
4544 u8 rev; /* Composite sort order */
4545 u8 revIdx; /* Index sort order */
4546 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
4547 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
4548 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
4549 u16 eqOpMask; /* Allowed equality operators */
4550 u16 nKeyCol; /* Number of key columns in pIndex */
4551 u16 nColumn; /* Total number of ordered columns in the index */
4552 u16 nOrderBy; /* Number terms in the ORDER BY clause */
4553 int iLoop; /* Index of WhereLoop in pPath being processed */
4554 int i, j; /* Loop counters */
4555 int iCur; /* Cursor number for current WhereLoop */
4556 int iColumn; /* A column number within table iCur */
4557 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
4558 WhereTerm *pTerm; /* A single term of the WHERE clause */
4559 Expr *pOBExpr; /* An expression from the ORDER BY clause */
4560 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
4561 Index *pIndex; /* The index associated with pLoop */
4562 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
4563 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
4564 Bitmask obDone; /* Mask of all ORDER BY terms */
4565 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
4566 Bitmask ready; /* Mask of inner loops */
4569 ** We say the WhereLoop is "one-row" if it generates no more than one
4570 ** row of output. A WhereLoop is one-row if all of the following are true:
4571 ** (a) All index columns match with WHERE_COLUMN_EQ.
4572 ** (b) The index is unique
4573 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
4574 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
4576 ** We say the WhereLoop is "order-distinct" if the set of columns from
4577 ** that WhereLoop that are in the ORDER BY clause are different for every
4578 ** row of the WhereLoop. Every one-row WhereLoop is automatically
4579 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
4580 ** is not order-distinct. To be order-distinct is not quite the same as being
4581 ** UNIQUE since a UNIQUE column or index can have multiple rows that
4582 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4583 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4585 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4586 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4587 ** automatically order-distinct.
4590 assert( pOrderBy!=0 );
4591 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
4593 nOrderBy = pOrderBy->nExpr;
4594 testcase( nOrderBy==BMS-1 );
4595 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
4596 isOrderDistinct = 1;
4597 obDone = MASKBIT(nOrderBy)-1;
4598 orderDistinctMask = 0;
4599 ready = 0;
4600 eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
4601 if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
4602 eqOpMask |= WO_IN;
4604 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
4605 if( iLoop>0 ) ready |= pLoop->maskSelf;
4606 if( iLoop<nLoop ){
4607 pLoop = pPath->aLoop[iLoop];
4608 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
4609 }else{
4610 pLoop = pLast;
4612 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
4613 if( pLoop->u.vtab.isOrdered
4614 && ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY)
4616 obSat = obDone;
4618 break;
4619 }else if( wctrlFlags & WHERE_DISTINCTBY ){
4620 pLoop->u.btree.nDistinctCol = 0;
4622 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
4624 /* Mark off any ORDER BY term X that is a column in the table of
4625 ** the current loop for which there is term in the WHERE
4626 ** clause of the form X IS NULL or X=? that reference only outer
4627 ** loops.
4629 for(i=0; i<nOrderBy; i++){
4630 if( MASKBIT(i) & obSat ) continue;
4631 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4632 if( NEVER(pOBExpr==0) ) continue;
4633 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4634 if( pOBExpr->iTable!=iCur ) continue;
4635 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4636 ~ready, eqOpMask, 0);
4637 if( pTerm==0 ) continue;
4638 if( pTerm->eOperator==WO_IN ){
4639 /* IN terms are only valid for sorting in the ORDER BY LIMIT
4640 ** optimization, and then only if they are actually used
4641 ** by the query plan */
4642 assert( wctrlFlags &
4643 (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
4644 for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
4645 if( j>=pLoop->nLTerm ) continue;
4647 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
4648 Parse *pParse = pWInfo->pParse;
4649 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
4650 CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
4651 assert( pColl1 );
4652 if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
4653 continue;
4655 testcase( pTerm->pExpr->op==TK_IS );
4657 obSat |= MASKBIT(i);
4660 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4661 if( pLoop->wsFlags & WHERE_IPK ){
4662 pIndex = 0;
4663 nKeyCol = 0;
4664 nColumn = 1;
4665 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
4666 return 0;
4667 }else{
4668 nKeyCol = pIndex->nKeyCol;
4669 nColumn = pIndex->nColumn;
4670 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
4671 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
4672 || !HasRowid(pIndex->pTable));
4673 /* All relevant terms of the index must also be non-NULL in order
4674 ** for isOrderDistinct to be true. So the isOrderDistint value
4675 ** computed here might be a false positive. Corrections will be
4676 ** made at tag-20210426-1 below */
4677 isOrderDistinct = IsUniqueIndex(pIndex)
4678 && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
4681 /* Loop through all columns of the index and deal with the ones
4682 ** that are not constrained by == or IN.
4684 rev = revSet = 0;
4685 distinctColumns = 0;
4686 for(j=0; j<nColumn; j++){
4687 u8 bOnce = 1; /* True to run the ORDER BY search loop */
4689 assert( j>=pLoop->u.btree.nEq
4690 || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
4692 if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
4693 u16 eOp = pLoop->aLTerm[j]->eOperator;
4695 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
4696 ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL
4697 ** terms imply that the index is not UNIQUE NOT NULL in which case
4698 ** the loop need to be marked as not order-distinct because it can
4699 ** have repeated NULL rows.
4701 ** If the current term is a column of an ((?,?) IN (SELECT...))
4702 ** expression for which the SELECT returns more than one column,
4703 ** check that it is the only column used by this loop. Otherwise,
4704 ** if it is one of two or more, none of the columns can be
4705 ** considered to match an ORDER BY term.
4707 if( (eOp & eqOpMask)!=0 ){
4708 if( eOp & (WO_ISNULL|WO_IS) ){
4709 testcase( eOp & WO_ISNULL );
4710 testcase( eOp & WO_IS );
4711 testcase( isOrderDistinct );
4712 isOrderDistinct = 0;
4714 continue;
4715 }else if( ALWAYS(eOp & WO_IN) ){
4716 /* ALWAYS() justification: eOp is an equality operator due to the
4717 ** j<pLoop->u.btree.nEq constraint above. Any equality other
4718 ** than WO_IN is captured by the previous "if". So this one
4719 ** always has to be WO_IN. */
4720 Expr *pX = pLoop->aLTerm[j]->pExpr;
4721 for(i=j+1; i<pLoop->u.btree.nEq; i++){
4722 if( pLoop->aLTerm[i]->pExpr==pX ){
4723 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
4724 bOnce = 0;
4725 break;
4731 /* Get the column number in the table (iColumn) and sort order
4732 ** (revIdx) for the j-th column of the index.
4734 if( pIndex ){
4735 iColumn = pIndex->aiColumn[j];
4736 revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
4737 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
4738 }else{
4739 iColumn = XN_ROWID;
4740 revIdx = 0;
4743 /* An unconstrained column that might be NULL means that this
4744 ** WhereLoop is not well-ordered. tag-20210426-1
4746 if( isOrderDistinct ){
4747 if( iColumn>=0
4748 && j>=pLoop->u.btree.nEq
4749 && pIndex->pTable->aCol[iColumn].notNull==0
4751 isOrderDistinct = 0;
4753 if( iColumn==XN_EXPR ){
4754 isOrderDistinct = 0;
4758 /* Find the ORDER BY term that corresponds to the j-th column
4759 ** of the index and mark that ORDER BY term off
4761 isMatch = 0;
4762 for(i=0; bOnce && i<nOrderBy; i++){
4763 if( MASKBIT(i) & obSat ) continue;
4764 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4765 testcase( wctrlFlags & WHERE_GROUPBY );
4766 testcase( wctrlFlags & WHERE_DISTINCTBY );
4767 if( NEVER(pOBExpr==0) ) continue;
4768 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
4769 if( iColumn>=XN_ROWID ){
4770 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4771 if( pOBExpr->iTable!=iCur ) continue;
4772 if( pOBExpr->iColumn!=iColumn ) continue;
4773 }else{
4774 Expr *pIxExpr = pIndex->aColExpr->a[j].pExpr;
4775 if( sqlite3ExprCompareSkip(pOBExpr, pIxExpr, iCur) ){
4776 continue;
4779 if( iColumn!=XN_ROWID ){
4780 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
4781 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
4783 if( wctrlFlags & WHERE_DISTINCTBY ){
4784 pLoop->u.btree.nDistinctCol = j+1;
4786 isMatch = 1;
4787 break;
4789 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
4790 /* Make sure the sort order is compatible in an ORDER BY clause.
4791 ** Sort order is irrelevant for a GROUP BY clause. */
4792 if( revSet ){
4793 if( (rev ^ revIdx)
4794 != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC)
4796 isMatch = 0;
4798 }else{
4799 rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC);
4800 if( rev ) *pRevMask |= MASKBIT(iLoop);
4801 revSet = 1;
4804 if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){
4805 if( j==pLoop->u.btree.nEq ){
4806 pLoop->wsFlags |= WHERE_BIGNULL_SORT;
4807 }else{
4808 isMatch = 0;
4811 if( isMatch ){
4812 if( iColumn==XN_ROWID ){
4813 testcase( distinctColumns==0 );
4814 distinctColumns = 1;
4816 obSat |= MASKBIT(i);
4817 }else{
4818 /* No match found */
4819 if( j==0 || j<nKeyCol ){
4820 testcase( isOrderDistinct!=0 );
4821 isOrderDistinct = 0;
4823 break;
4825 } /* end Loop over all index columns */
4826 if( distinctColumns ){
4827 testcase( isOrderDistinct==0 );
4828 isOrderDistinct = 1;
4830 } /* end-if not one-row */
4832 /* Mark off any other ORDER BY terms that reference pLoop */
4833 if( isOrderDistinct ){
4834 orderDistinctMask |= pLoop->maskSelf;
4835 for(i=0; i<nOrderBy; i++){
4836 Expr *p;
4837 Bitmask mTerm;
4838 if( MASKBIT(i) & obSat ) continue;
4839 p = pOrderBy->a[i].pExpr;
4840 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
4841 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
4842 if( (mTerm&~orderDistinctMask)==0 ){
4843 obSat |= MASKBIT(i);
4847 } /* End the loop over all WhereLoops from outer-most down to inner-most */
4848 if( obSat==obDone ) return (i8)nOrderBy;
4849 if( !isOrderDistinct ){
4850 for(i=nOrderBy-1; i>0; i--){
4851 Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
4852 if( (obSat&m)==m ) return i;
4854 return 0;
4856 return -1;
4861 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
4862 ** the planner assumes that the specified pOrderBy list is actually a GROUP
4863 ** BY clause - and so any order that groups rows as required satisfies the
4864 ** request.
4866 ** Normally, in this case it is not possible for the caller to determine
4867 ** whether or not the rows are really being delivered in sorted order, or
4868 ** just in some other order that provides the required grouping. However,
4869 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
4870 ** this function may be called on the returned WhereInfo object. It returns
4871 ** true if the rows really will be sorted in the specified order, or false
4872 ** otherwise.
4874 ** For example, assuming:
4876 ** CREATE INDEX i1 ON t1(x, Y);
4878 ** then
4880 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
4881 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
4883 int sqlite3WhereIsSorted(WhereInfo *pWInfo){
4884 assert( pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) );
4885 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
4886 return pWInfo->sorted;
4889 #ifdef WHERETRACE_ENABLED
4890 /* For debugging use only: */
4891 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4892 static char zName[65];
4893 int i;
4894 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
4895 if( pLast ) zName[i++] = pLast->cId;
4896 zName[i] = 0;
4897 return zName;
4899 #endif
4902 ** Return the cost of sorting nRow rows, assuming that the keys have
4903 ** nOrderby columns and that the first nSorted columns are already in
4904 ** order.
4906 static LogEst whereSortingCost(
4907 WhereInfo *pWInfo, /* Query planning context */
4908 LogEst nRow, /* Estimated number of rows to sort */
4909 int nOrderBy, /* Number of ORDER BY clause terms */
4910 int nSorted /* Number of initial ORDER BY terms naturally in order */
4912 /* Estimated cost of a full external sort, where N is
4913 ** the number of rows to sort is:
4915 ** cost = (K * N * log(N)).
4917 ** Or, if the order-by clause has X terms but only the last Y
4918 ** terms are out of order, then block-sorting will reduce the
4919 ** sorting cost to:
4921 ** cost = (K * N * log(N)) * (Y/X)
4923 ** The constant K is at least 2.0 but will be larger if there are a
4924 ** large number of columns to be sorted, as the sorting time is
4925 ** proportional to the amount of content to be sorted. The algorithm
4926 ** does not currently distinguish between fat columns (BLOBs and TEXTs)
4927 ** and skinny columns (INTs). It just uses the number of columns as
4928 ** an approximation for the row width.
4930 ** And extra factor of 2.0 or 3.0 is added to the sorting cost if the sort
4931 ** is built using OP_IdxInsert and OP_Sort rather than with OP_SorterInsert.
4933 LogEst rSortCost, nCol;
4934 assert( pWInfo->pSelect!=0 );
4935 assert( pWInfo->pSelect->pEList!=0 );
4936 /* TUNING: sorting cost proportional to the number of output columns: */
4937 nCol = sqlite3LogEst((pWInfo->pSelect->pEList->nExpr+59)/30);
4938 rSortCost = nRow + nCol;
4939 if( nSorted>0 ){
4940 /* Scale the result by (Y/X) */
4941 rSortCost += sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
4944 /* Multiple by log(M) where M is the number of output rows.
4945 ** Use the LIMIT for M if it is smaller. Or if this sort is for
4946 ** a DISTINCT operator, M will be the number of distinct output
4947 ** rows, so fudge it downwards a bit.
4949 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 ){
4950 rSortCost += 10; /* TUNING: Extra 2.0x if using LIMIT */
4951 if( nSorted!=0 ){
4952 rSortCost += 6; /* TUNING: Extra 1.5x if also using partial sort */
4954 if( pWInfo->iLimit<nRow ){
4955 nRow = pWInfo->iLimit;
4957 }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
4958 /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
4959 ** reduces the number of output rows by a factor of 2 */
4960 if( nRow>10 ){ nRow -= 10; assert( 10==sqlite3LogEst(2) ); }
4962 rSortCost += estLog(nRow);
4963 return rSortCost;
4967 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
4968 ** attempts to find the lowest cost path that visits each WhereLoop
4969 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
4971 ** Assume that the total number of output rows that will need to be sorted
4972 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
4973 ** costs if nRowEst==0.
4975 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
4976 ** error occurs.
4978 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
4979 int mxChoice; /* Maximum number of simultaneous paths tracked */
4980 int nLoop; /* Number of terms in the join */
4981 Parse *pParse; /* Parsing context */
4982 int iLoop; /* Loop counter over the terms of the join */
4983 int ii, jj; /* Loop counters */
4984 int mxI = 0; /* Index of next entry to replace */
4985 int nOrderBy; /* Number of ORDER BY clause terms */
4986 LogEst mxCost = 0; /* Maximum cost of a set of paths */
4987 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
4988 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
4989 WherePath *aFrom; /* All nFrom paths at the previous level */
4990 WherePath *aTo; /* The nTo best paths at the current level */
4991 WherePath *pFrom; /* An element of aFrom[] that we are working on */
4992 WherePath *pTo; /* An element of aTo[] that we are working on */
4993 WhereLoop *pWLoop; /* One of the WhereLoop objects */
4994 WhereLoop **pX; /* Used to divy up the pSpace memory */
4995 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
4996 char *pSpace; /* Temporary memory used by this routine */
4997 int nSpace; /* Bytes of space allocated at pSpace */
4999 pParse = pWInfo->pParse;
5000 nLoop = pWInfo->nLevel;
5001 /* TUNING: For simple queries, only the best path is tracked.
5002 ** For 2-way joins, the 5 best paths are followed.
5003 ** For joins of 3 or more tables, track the 10 best paths */
5004 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
5005 assert( nLoop<=pWInfo->pTabList->nSrc );
5006 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d, nQueryLoop=%d)\n",
5007 nRowEst, pParse->nQueryLoop));
5009 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
5010 ** case the purpose of this call is to estimate the number of rows returned
5011 ** by the overall query. Once this estimate has been obtained, the caller
5012 ** will invoke this function a second time, passing the estimate as the
5013 ** nRowEst parameter. */
5014 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
5015 nOrderBy = 0;
5016 }else{
5017 nOrderBy = pWInfo->pOrderBy->nExpr;
5020 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
5021 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5022 nSpace += sizeof(LogEst) * nOrderBy;
5023 pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace);
5024 if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
5025 aTo = (WherePath*)pSpace;
5026 aFrom = aTo+mxChoice;
5027 memset(aFrom, 0, sizeof(aFrom[0]));
5028 pX = (WhereLoop**)(aFrom+mxChoice);
5029 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
5030 pFrom->aLoop = pX;
5032 if( nOrderBy ){
5033 /* If there is an ORDER BY clause and it is not being ignored, set up
5034 ** space for the aSortCost[] array. Each element of the aSortCost array
5035 ** is either zero - meaning it has not yet been initialized - or the
5036 ** cost of sorting nRowEst rows of data where the first X terms of
5037 ** the ORDER BY clause are already in order, where X is the array
5038 ** index. */
5039 aSortCost = (LogEst*)pX;
5040 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
5042 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
5043 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
5045 /* Seed the search with a single WherePath containing zero WhereLoops.
5047 ** TUNING: Do not let the number of iterations go above 28. If the cost
5048 ** of computing an automatic index is not paid back within the first 28
5049 ** rows, then do not use the automatic index. */
5050 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
5051 nFrom = 1;
5052 assert( aFrom[0].isOrdered==0 );
5053 if( nOrderBy ){
5054 /* If nLoop is zero, then there are no FROM terms in the query. Since
5055 ** in this case the query may return a maximum of one row, the results
5056 ** are already in the requested order. Set isOrdered to nOrderBy to
5057 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
5058 ** -1, indicating that the result set may or may not be ordered,
5059 ** depending on the loops added to the current plan. */
5060 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
5063 /* Compute successively longer WherePaths using the previous generation
5064 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5065 ** best paths at each generation */
5066 for(iLoop=0; iLoop<nLoop; iLoop++){
5067 nTo = 0;
5068 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5069 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5070 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
5071 LogEst rCost; /* Cost of path (pFrom+pWLoop) */
5072 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
5073 i8 isOrdered; /* isOrdered for (pFrom+pWLoop) */
5074 Bitmask maskNew; /* Mask of src visited by (..) */
5075 Bitmask revMask; /* Mask of rev-order loops for (..) */
5077 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5078 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
5079 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
5080 /* Do not use an automatic index if the this loop is expected
5081 ** to run less than 1.25 times. It is tempting to also exclude
5082 ** automatic index usage on an outer loop, but sometimes an automatic
5083 ** index is useful in the outer loop of a correlated subquery. */
5084 assert( 10==sqlite3LogEst(2) );
5085 continue;
5088 /* At this point, pWLoop is a candidate to be the next loop.
5089 ** Compute its cost */
5090 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5091 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
5092 nOut = pFrom->nRow + pWLoop->nOut;
5093 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
5094 isOrdered = pFrom->isOrdered;
5095 if( isOrdered<0 ){
5096 revMask = 0;
5097 isOrdered = wherePathSatisfiesOrderBy(pWInfo,
5098 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
5099 iLoop, pWLoop, &revMask);
5100 }else{
5101 revMask = pFrom->revLoop;
5103 if( isOrdered>=0 && isOrdered<nOrderBy ){
5104 if( aSortCost[isOrdered]==0 ){
5105 aSortCost[isOrdered] = whereSortingCost(
5106 pWInfo, nRowEst, nOrderBy, isOrdered
5109 /* TUNING: Add a small extra penalty (3) to sorting as an
5110 ** extra encouragement to the query planner to select a plan
5111 ** where the rows emerge in the correct order without any sorting
5112 ** required. */
5113 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 3;
5115 WHERETRACE(0x002,
5116 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
5117 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
5118 rUnsorted, rCost));
5119 }else{
5120 rCost = rUnsorted;
5121 rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
5124 /* TUNING: A full-scan of a VIEW or subquery in the outer loop
5125 ** is not so bad. */
5126 if( iLoop==0 && (pWLoop->wsFlags & WHERE_VIEWSCAN)!=0 && nLoop>1 ){
5127 rCost += -10;
5128 nOut += -30;
5129 WHERETRACE(0x80,("VIEWSCAN cost reduction for %c\n",pWLoop->cId));
5132 /* Check to see if pWLoop should be added to the set of
5133 ** mxChoice best-so-far paths.
5135 ** First look for an existing path among best-so-far paths
5136 ** that covers the same set of loops and has the same isOrdered
5137 ** setting as the current path candidate.
5139 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
5140 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
5141 ** of legal values for isOrdered, -1..64.
5143 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5144 if( pTo->maskLoop==maskNew
5145 && ((pTo->isOrdered^isOrdered)&0x80)==0
5147 testcase( jj==nTo-1 );
5148 break;
5151 if( jj>=nTo ){
5152 /* None of the existing best-so-far paths match the candidate. */
5153 if( nTo>=mxChoice
5154 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
5156 /* The current candidate is no better than any of the mxChoice
5157 ** paths currently in the best-so-far buffer. So discard
5158 ** this candidate as not viable. */
5159 #ifdef WHERETRACE_ENABLED /* 0x4 */
5160 if( sqlite3WhereTrace&0x4 ){
5161 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
5162 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5163 isOrdered>=0 ? isOrdered+'0' : '?');
5165 #endif
5166 continue;
5168 /* If we reach this points it means that the new candidate path
5169 ** needs to be added to the set of best-so-far paths. */
5170 if( nTo<mxChoice ){
5171 /* Increase the size of the aTo set by one */
5172 jj = nTo++;
5173 }else{
5174 /* New path replaces the prior worst to keep count below mxChoice */
5175 jj = mxI;
5177 pTo = &aTo[jj];
5178 #ifdef WHERETRACE_ENABLED /* 0x4 */
5179 if( sqlite3WhereTrace&0x4 ){
5180 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
5181 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5182 isOrdered>=0 ? isOrdered+'0' : '?');
5184 #endif
5185 }else{
5186 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
5187 ** same set of loops and has the same isOrdered setting as the
5188 ** candidate path. Check to see if the candidate should replace
5189 ** pTo or if the candidate should be skipped.
5191 ** The conditional is an expanded vector comparison equivalent to:
5192 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
5194 if( pTo->rCost<rCost
5195 || (pTo->rCost==rCost
5196 && (pTo->nRow<nOut
5197 || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
5201 #ifdef WHERETRACE_ENABLED /* 0x4 */
5202 if( sqlite3WhereTrace&0x4 ){
5203 sqlite3DebugPrintf(
5204 "Skip %s cost=%-3d,%3d,%3d order=%c",
5205 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5206 isOrdered>=0 ? isOrdered+'0' : '?');
5207 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
5208 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5209 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5211 #endif
5212 /* Discard the candidate path from further consideration */
5213 testcase( pTo->rCost==rCost );
5214 continue;
5216 testcase( pTo->rCost==rCost+1 );
5217 /* Control reaches here if the candidate path is better than the
5218 ** pTo path. Replace pTo with the candidate. */
5219 #ifdef WHERETRACE_ENABLED /* 0x4 */
5220 if( sqlite3WhereTrace&0x4 ){
5221 sqlite3DebugPrintf(
5222 "Update %s cost=%-3d,%3d,%3d order=%c",
5223 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
5224 isOrdered>=0 ? isOrdered+'0' : '?');
5225 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
5226 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5227 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5229 #endif
5231 /* pWLoop is a winner. Add it to the set of best so far */
5232 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
5233 pTo->revLoop = revMask;
5234 pTo->nRow = nOut;
5235 pTo->rCost = rCost;
5236 pTo->rUnsorted = rUnsorted;
5237 pTo->isOrdered = isOrdered;
5238 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5239 pTo->aLoop[iLoop] = pWLoop;
5240 if( nTo>=mxChoice ){
5241 mxI = 0;
5242 mxCost = aTo[0].rCost;
5243 mxUnsorted = aTo[0].nRow;
5244 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5245 if( pTo->rCost>mxCost
5246 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
5248 mxCost = pTo->rCost;
5249 mxUnsorted = pTo->rUnsorted;
5250 mxI = jj;
5257 #ifdef WHERETRACE_ENABLED /* >=2 */
5258 if( sqlite3WhereTrace & 0x02 ){
5259 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
5260 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
5261 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
5262 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
5263 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
5264 if( pTo->isOrdered>0 ){
5265 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5266 }else{
5267 sqlite3DebugPrintf("\n");
5271 #endif
5273 /* Swap the roles of aFrom and aTo for the next generation */
5274 pFrom = aTo;
5275 aTo = aFrom;
5276 aFrom = pFrom;
5277 nFrom = nTo;
5280 if( nFrom==0 ){
5281 sqlite3ErrorMsg(pParse, "no query solution");
5282 sqlite3StackFreeNN(pParse->db, pSpace);
5283 return SQLITE_ERROR;
5286 /* Find the lowest cost path. pFrom will be left pointing to that path */
5287 pFrom = aFrom;
5288 for(ii=1; ii<nFrom; ii++){
5289 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5291 assert( pWInfo->nLevel==nLoop );
5292 /* Load the lowest cost path into pWInfo */
5293 for(iLoop=0; iLoop<nLoop; iLoop++){
5294 WhereLevel *pLevel = pWInfo->a + iLoop;
5295 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
5296 pLevel->iFrom = pWLoop->iTab;
5297 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
5299 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5300 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5301 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
5302 && nRowEst
5304 Bitmask notUsed;
5305 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
5306 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
5307 if( rc==pWInfo->pResultSet->nExpr ){
5308 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5311 pWInfo->bOrderedInnerLoop = 0;
5312 if( pWInfo->pOrderBy ){
5313 pWInfo->nOBSat = pFrom->isOrdered;
5314 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5315 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
5316 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5318 if( pWInfo->pSelect->pOrderBy
5319 && pWInfo->nOBSat > pWInfo->pSelect->pOrderBy->nExpr ){
5320 pWInfo->nOBSat = pWInfo->pSelect->pOrderBy->nExpr;
5322 }else{
5323 pWInfo->revMask = pFrom->revLoop;
5324 if( pWInfo->nOBSat<=0 ){
5325 pWInfo->nOBSat = 0;
5326 if( nLoop>0 ){
5327 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
5328 if( (wsFlags & WHERE_ONEROW)==0
5329 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
5331 Bitmask m = 0;
5332 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
5333 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
5334 testcase( wsFlags & WHERE_IPK );
5335 testcase( wsFlags & WHERE_COLUMN_IN );
5336 if( rc==pWInfo->pOrderBy->nExpr ){
5337 pWInfo->bOrderedInnerLoop = 1;
5338 pWInfo->revMask = m;
5342 }else if( nLoop
5343 && pWInfo->nOBSat==1
5344 && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
5346 pWInfo->bOrderedInnerLoop = 1;
5349 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
5350 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
5352 Bitmask revMask = 0;
5353 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
5354 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
5356 assert( pWInfo->sorted==0 );
5357 if( nOrder==pWInfo->pOrderBy->nExpr ){
5358 pWInfo->sorted = 1;
5359 pWInfo->revMask = revMask;
5365 pWInfo->nRowOut = pFrom->nRow;
5367 /* Free temporary memory and return success */
5368 sqlite3StackFreeNN(pParse->db, pSpace);
5369 return SQLITE_OK;
5373 ** Most queries use only a single table (they are not joins) and have
5374 ** simple == constraints against indexed fields. This routine attempts
5375 ** to plan those simple cases using much less ceremony than the
5376 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5377 ** times for the common case.
5379 ** Return non-zero on success, if this query can be handled by this
5380 ** no-frills query planner. Return zero if this query needs the
5381 ** general-purpose query planner.
5383 static int whereShortCut(WhereLoopBuilder *pBuilder){
5384 WhereInfo *pWInfo;
5385 SrcItem *pItem;
5386 WhereClause *pWC;
5387 WhereTerm *pTerm;
5388 WhereLoop *pLoop;
5389 int iCur;
5390 int j;
5391 Table *pTab;
5392 Index *pIdx;
5393 WhereScan scan;
5395 pWInfo = pBuilder->pWInfo;
5396 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
5397 assert( pWInfo->pTabList->nSrc>=1 );
5398 pItem = pWInfo->pTabList->a;
5399 pTab = pItem->pTab;
5400 if( IsVirtual(pTab) ) return 0;
5401 if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){
5402 testcase( pItem->fg.isIndexedBy );
5403 testcase( pItem->fg.notIndexed );
5404 return 0;
5406 iCur = pItem->iCursor;
5407 pWC = &pWInfo->sWC;
5408 pLoop = pBuilder->pNew;
5409 pLoop->wsFlags = 0;
5410 pLoop->nSkip = 0;
5411 pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
5412 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5413 if( pTerm ){
5414 testcase( pTerm->eOperator & WO_IS );
5415 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5416 pLoop->aLTerm[0] = pTerm;
5417 pLoop->nLTerm = 1;
5418 pLoop->u.btree.nEq = 1;
5419 /* TUNING: Cost of a rowid lookup is 10 */
5420 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
5421 }else{
5422 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5423 int opMask;
5424 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5425 if( !IsUniqueIndex(pIdx)
5426 || pIdx->pPartIdxWhere!=0
5427 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
5428 ) continue;
5429 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
5430 for(j=0; j<pIdx->nKeyCol; j++){
5431 pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx);
5432 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
5433 if( pTerm==0 ) break;
5434 testcase( pTerm->eOperator & WO_IS );
5435 pLoop->aLTerm[j] = pTerm;
5437 if( j!=pIdx->nKeyCol ) continue;
5438 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
5439 if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
5440 pLoop->wsFlags |= WHERE_IDX_ONLY;
5442 pLoop->nLTerm = j;
5443 pLoop->u.btree.nEq = j;
5444 pLoop->u.btree.pIndex = pIdx;
5445 /* TUNING: Cost of a unique index lookup is 15 */
5446 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
5447 break;
5450 if( pLoop->wsFlags ){
5451 pLoop->nOut = (LogEst)1;
5452 pWInfo->a[0].pWLoop = pLoop;
5453 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
5454 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
5455 pWInfo->a[0].iTabCur = iCur;
5456 pWInfo->nRowOut = 1;
5457 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
5458 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5459 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5461 if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
5462 #ifdef SQLITE_DEBUG
5463 pLoop->cId = '0';
5464 #endif
5465 #ifdef WHERETRACE_ENABLED
5466 if( sqlite3WhereTrace & 0x02 ){
5467 sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
5469 #endif
5470 return 1;
5472 return 0;
5476 ** Helper function for exprIsDeterministic().
5478 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
5479 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
5480 pWalker->eCode = 0;
5481 return WRC_Abort;
5483 return WRC_Continue;
5487 ** Return true if the expression contains no non-deterministic SQL
5488 ** functions. Do not consider non-deterministic SQL functions that are
5489 ** part of sub-select statements.
5491 static int exprIsDeterministic(Expr *p){
5492 Walker w;
5493 memset(&w, 0, sizeof(w));
5494 w.eCode = 1;
5495 w.xExprCallback = exprNodeIsDeterministic;
5496 w.xSelectCallback = sqlite3SelectWalkFail;
5497 sqlite3WalkExpr(&w, p);
5498 return w.eCode;
5502 #ifdef WHERETRACE_ENABLED
5504 ** Display all WhereLoops in pWInfo
5506 static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
5507 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
5508 WhereLoop *p;
5509 int i;
5510 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5511 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5512 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5513 p->cId = zLabel[i%(sizeof(zLabel)-1)];
5514 sqlite3WhereLoopPrint(p, pWC);
5518 # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
5519 #else
5520 # define WHERETRACE_ALL_LOOPS(W,C)
5521 #endif
5523 /* Attempt to omit tables from a join that do not affect the result.
5524 ** For a table to not affect the result, the following must be true:
5526 ** 1) The query must not be an aggregate.
5527 ** 2) The table must be the RHS of a LEFT JOIN.
5528 ** 3) Either the query must be DISTINCT, or else the ON or USING clause
5529 ** must contain a constraint that limits the scan of the table to
5530 ** at most a single row.
5531 ** 4) The table must not be referenced by any part of the query apart
5532 ** from its own USING or ON clause.
5533 ** 5) The table must not have an inner-join ON or USING clause if there is
5534 ** a RIGHT JOIN anywhere in the query. Otherwise the ON/USING clause
5535 ** might move from the right side to the left side of the RIGHT JOIN.
5536 ** Note: Due to (2), this condition can only arise if the table is
5537 ** the right-most table of a subquery that was flattened into the
5538 ** main query and that subquery was the right-hand operand of an
5539 ** inner join that held an ON or USING clause.
5541 ** For example, given:
5543 ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
5544 ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
5545 ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
5547 ** then table t2 can be omitted from the following:
5549 ** SELECT v1, v3 FROM t1
5550 ** LEFT JOIN t2 ON (t1.ipk=t2.ipk)
5551 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5553 ** or from:
5555 ** SELECT DISTINCT v1, v3 FROM t1
5556 ** LEFT JOIN t2
5557 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
5559 static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
5560 WhereInfo *pWInfo,
5561 Bitmask notReady
5563 int i;
5564 Bitmask tabUsed;
5565 int hasRightJoin;
5567 /* Preconditions checked by the caller */
5568 assert( pWInfo->nLevel>=2 );
5569 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
5571 /* These two preconditions checked by the caller combine to guarantee
5572 ** condition (1) of the header comment */
5573 assert( pWInfo->pResultSet!=0 );
5574 assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
5576 tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
5577 if( pWInfo->pOrderBy ){
5578 tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
5580 hasRightJoin = (pWInfo->pTabList->a[0].fg.jointype & JT_LTORJ)!=0;
5581 for(i=pWInfo->nLevel-1; i>=1; i--){
5582 WhereTerm *pTerm, *pEnd;
5583 SrcItem *pItem;
5584 WhereLoop *pLoop;
5585 pLoop = pWInfo->a[i].pWLoop;
5586 pItem = &pWInfo->pTabList->a[pLoop->iTab];
5587 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
5588 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
5589 && (pLoop->wsFlags & WHERE_ONEROW)==0
5591 continue;
5593 if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
5594 pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
5595 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5596 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5597 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
5598 || pTerm->pExpr->w.iJoin!=pItem->iCursor
5600 break;
5603 if( hasRightJoin
5604 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
5605 && pTerm->pExpr->w.iJoin==pItem->iCursor
5607 break; /* restriction (5) */
5610 if( pTerm<pEnd ) continue;
5611 WHERETRACE(0xffffffff, ("-> drop loop %c not used\n", pLoop->cId));
5612 notReady &= ~pLoop->maskSelf;
5613 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
5614 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
5615 pTerm->wtFlags |= TERM_CODED;
5618 if( i!=pWInfo->nLevel-1 ){
5619 int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
5620 memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
5622 pWInfo->nLevel--;
5623 assert( pWInfo->nLevel>0 );
5625 return notReady;
5629 ** Check to see if there are any SEARCH loops that might benefit from
5630 ** using a Bloom filter. Consider a Bloom filter if:
5632 ** (1) The SEARCH happens more than N times where N is the number
5633 ** of rows in the table that is being considered for the Bloom
5634 ** filter.
5635 ** (2) Some searches are expected to find zero rows. (This is determined
5636 ** by the WHERE_SELFCULL flag on the term.)
5637 ** (3) Bloom-filter processing is not disabled. (Checked by the
5638 ** caller.)
5639 ** (4) The size of the table being searched is known by ANALYZE.
5641 ** This block of code merely checks to see if a Bloom filter would be
5642 ** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
5643 ** WhereLoop. The implementation of the Bloom filter comes further
5644 ** down where the code for each WhereLoop is generated.
5646 static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
5647 const WhereInfo *pWInfo
5649 int i;
5650 LogEst nSearch = 0;
5652 assert( pWInfo->nLevel>=2 );
5653 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
5654 for(i=0; i<pWInfo->nLevel; i++){
5655 WhereLoop *pLoop = pWInfo->a[i].pWLoop;
5656 const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ);
5657 SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
5658 Table *pTab = pItem->pTab;
5659 if( (pTab->tabFlags & TF_HasStat1)==0 ) break;
5660 pTab->tabFlags |= TF_StatsUsed;
5661 if( i>=1
5662 && (pLoop->wsFlags & reqFlags)==reqFlags
5663 /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
5664 && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
5666 if( nSearch > pTab->nRowLogEst ){
5667 testcase( pItem->fg.jointype & JT_LEFT );
5668 pLoop->wsFlags |= WHERE_BLOOMFILTER;
5669 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
5670 WHERETRACE(0xffffffff, (
5671 "-> use Bloom-filter on loop %c because there are ~%.1e "
5672 "lookups into %s which has only ~%.1e rows\n",
5673 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
5674 (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
5677 nSearch += pLoop->nOut;
5682 ** This is an sqlite3ParserAddCleanup() callback that is invoked to
5683 ** free the Parse->pIdxEpr list when the Parse object is destroyed.
5685 static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){
5686 Parse *pParse = (Parse*)pObject;
5687 while( pParse->pIdxEpr!=0 ){
5688 IndexedExpr *p = pParse->pIdxEpr;
5689 pParse->pIdxEpr = p->pIENext;
5690 sqlite3ExprDelete(db, p->pExpr);
5691 sqlite3DbFreeNN(db, p);
5696 ** The index pIdx is used by a query and contains one or more expressions.
5697 ** In other words pIdx is an index on an expression. iIdxCur is the cursor
5698 ** number for the index and iDataCur is the cursor number for the corresponding
5699 ** table.
5701 ** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for
5702 ** each of the expressions in the index so that the expression code generator
5703 ** will know to replace occurrences of the indexed expression with
5704 ** references to the corresponding column of the index.
5706 static SQLITE_NOINLINE void whereAddIndexedExpr(
5707 Parse *pParse, /* Add IndexedExpr entries to pParse->pIdxEpr */
5708 Index *pIdx, /* The index-on-expression that contains the expressions */
5709 int iIdxCur, /* Cursor number for pIdx */
5710 SrcItem *pTabItem /* The FROM clause entry for the table */
5712 int i;
5713 IndexedExpr *p;
5714 Table *pTab;
5715 assert( pIdx->bHasExpr );
5716 pTab = pIdx->pTable;
5717 for(i=0; i<pIdx->nColumn; i++){
5718 Expr *pExpr;
5719 int j = pIdx->aiColumn[i];
5720 int bMaybeNullRow;
5721 if( j==XN_EXPR ){
5722 pExpr = pIdx->aColExpr->a[i].pExpr;
5723 testcase( pTabItem->fg.jointype & JT_LEFT );
5724 testcase( pTabItem->fg.jointype & JT_RIGHT );
5725 testcase( pTabItem->fg.jointype & JT_LTORJ );
5726 bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0;
5727 }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
5728 pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
5729 bMaybeNullRow = 0;
5730 }else{
5731 continue;
5733 if( sqlite3ExprIsConstant(pExpr) ) continue;
5734 p = sqlite3DbMallocRaw(pParse->db, sizeof(IndexedExpr));
5735 if( p==0 ) break;
5736 p->pIENext = pParse->pIdxEpr;
5737 #ifdef WHERETRACE_ENABLED
5738 if( sqlite3WhereTrace & 0x200 ){
5739 sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i);
5740 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr);
5742 #endif
5743 p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5744 p->iDataCur = pTabItem->iCursor;
5745 p->iIdxCur = iIdxCur;
5746 p->iIdxCol = i;
5747 p->bMaybeNullRow = bMaybeNullRow;
5748 if( sqlite3IndexAffinityStr(pParse->db, pIdx) ){
5749 p->aff = pIdx->zColAff[i];
5751 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
5752 p->zIdxName = pIdx->zName;
5753 #endif
5754 pParse->pIdxEpr = p;
5755 if( p->pIENext==0 ){
5756 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pParse);
5762 ** Set the reverse-scan order mask to one for all tables in the query
5763 ** with the exception of MATERIALIZED common table expressions that have
5764 ** their own internal ORDER BY clauses.
5766 ** This implements the PRAGMA reverse_unordered_selects=ON setting.
5767 ** (Also SQLITE_DBCONFIG_REVERSE_SCANORDER).
5769 static SQLITE_NOINLINE void whereReverseScanOrder(WhereInfo *pWInfo){
5770 int ii;
5771 for(ii=0; ii<pWInfo->pTabList->nSrc; ii++){
5772 SrcItem *pItem = &pWInfo->pTabList->a[ii];
5773 if( !pItem->fg.isCte
5774 || pItem->u2.pCteUse->eM10d!=M10d_Yes
5775 || NEVER(pItem->pSelect==0)
5776 || pItem->pSelect->pOrderBy==0
5778 pWInfo->revMask |= MASKBIT(ii);
5784 ** Generate the beginning of the loop used for WHERE clause processing.
5785 ** The return value is a pointer to an opaque structure that contains
5786 ** information needed to terminate the loop. Later, the calling routine
5787 ** should invoke sqlite3WhereEnd() with the return value of this function
5788 ** in order to complete the WHERE clause processing.
5790 ** If an error occurs, this routine returns NULL.
5792 ** The basic idea is to do a nested loop, one loop for each table in
5793 ** the FROM clause of a select. (INSERT and UPDATE statements are the
5794 ** same as a SELECT with only a single table in the FROM clause.) For
5795 ** example, if the SQL is this:
5797 ** SELECT * FROM t1, t2, t3 WHERE ...;
5799 ** Then the code generated is conceptually like the following:
5801 ** foreach row1 in t1 do \ Code generated
5802 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
5803 ** foreach row3 in t3 do /
5804 ** ...
5805 ** end \ Code generated
5806 ** end |-- by sqlite3WhereEnd()
5807 ** end /
5809 ** Note that the loops might not be nested in the order in which they
5810 ** appear in the FROM clause if a different order is better able to make
5811 ** use of indices. Note also that when the IN operator appears in
5812 ** the WHERE clause, it might result in additional nested loops for
5813 ** scanning through all values on the right-hand side of the IN.
5815 ** There are Btree cursors associated with each table. t1 uses cursor
5816 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5817 ** And so forth. This routine generates code to open those VDBE cursors
5818 ** and sqlite3WhereEnd() generates the code to close them.
5820 ** The code that sqlite3WhereBegin() generates leaves the cursors named
5821 ** in pTabList pointing at their appropriate entries. The [...] code
5822 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
5823 ** data from the various tables of the loop.
5825 ** If the WHERE clause is empty, the foreach loops must each scan their
5826 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
5827 ** the tables have indices and there are terms in the WHERE clause that
5828 ** refer to those indices, a complete table scan can be avoided and the
5829 ** code will run much faster. Most of the work of this routine is checking
5830 ** to see if there are indices that can be used to speed up the loop.
5832 ** Terms of the WHERE clause are also used to limit which rows actually
5833 ** make it to the "..." in the middle of the loop. After each "foreach",
5834 ** terms of the WHERE clause that use only terms in that loop and outer
5835 ** loops are evaluated and if false a jump is made around all subsequent
5836 ** inner loops (or around the "..." if the test occurs within the inner-
5837 ** most loop)
5839 ** OUTER JOINS
5841 ** An outer join of tables t1 and t2 is conceptually coded as follows:
5843 ** foreach row1 in t1 do
5844 ** flag = 0
5845 ** foreach row2 in t2 do
5846 ** start:
5847 ** ...
5848 ** flag = 1
5849 ** end
5850 ** if flag==0 then
5851 ** move the row2 cursor to a null row
5852 ** goto start
5853 ** fi
5854 ** end
5856 ** ORDER BY CLAUSE PROCESSING
5858 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5859 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
5860 ** if there is one. If there is no ORDER BY clause or if this routine
5861 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
5863 ** The iIdxCur parameter is the cursor number of an index. If
5864 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
5865 ** to use for OR clause processing. The WHERE clause should use this
5866 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5867 ** the first cursor in an array of cursors for all indices. iIdxCur should
5868 ** be used to compute the appropriate cursor depending on which index is
5869 ** used.
5871 WhereInfo *sqlite3WhereBegin(
5872 Parse *pParse, /* The parser context */
5873 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
5874 Expr *pWhere, /* The WHERE clause */
5875 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
5876 ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
5877 Select *pSelect, /* The entire SELECT statement */
5878 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
5879 int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
5880 ** If WHERE_USE_LIMIT, then the limit amount */
5882 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
5883 int nTabList; /* Number of elements in pTabList */
5884 WhereInfo *pWInfo; /* Will become the return value of this function */
5885 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
5886 Bitmask notReady; /* Cursors that are not yet positioned */
5887 WhereLoopBuilder sWLB; /* The WhereLoop builder */
5888 WhereMaskSet *pMaskSet; /* The expression mask set */
5889 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
5890 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
5891 int ii; /* Loop counter */
5892 sqlite3 *db; /* Database connection */
5893 int rc; /* Return code */
5894 u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
5896 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
5897 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5898 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
5901 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
5902 assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
5903 || (wctrlFlags & WHERE_USE_LIMIT)==0 );
5905 /* Variable initialization */
5906 db = pParse->db;
5907 memset(&sWLB, 0, sizeof(sWLB));
5909 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
5910 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
5911 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
5913 /* The number of tables in the FROM clause is limited by the number of
5914 ** bits in a Bitmask
5916 testcase( pTabList->nSrc==BMS );
5917 if( pTabList->nSrc>BMS ){
5918 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
5919 return 0;
5922 /* This function normally generates a nested loop for all tables in
5923 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
5924 ** only generate code for the first table in pTabList and assume that
5925 ** any cursors associated with subsequent tables are uninitialized.
5927 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
5929 /* Allocate and initialize the WhereInfo structure that will become the
5930 ** return value. A single allocation is used to store the WhereInfo
5931 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5932 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5933 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5934 ** some architectures. Hence the ROUND8() below.
5936 nByteWInfo = ROUND8P(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
5937 pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
5938 if( db->mallocFailed ){
5939 sqlite3DbFree(db, pWInfo);
5940 pWInfo = 0;
5941 goto whereBeginError;
5943 pWInfo->pParse = pParse;
5944 pWInfo->pTabList = pTabList;
5945 pWInfo->pOrderBy = pOrderBy;
5946 #if WHERETRACE_ENABLED
5947 pWInfo->pWhere = pWhere;
5948 #endif
5949 pWInfo->pResultSet = pResultSet;
5950 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
5951 pWInfo->nLevel = nTabList;
5952 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
5953 pWInfo->wctrlFlags = wctrlFlags;
5954 pWInfo->iLimit = iAuxArg;
5955 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
5956 pWInfo->pSelect = pSelect;
5957 memset(&pWInfo->nOBSat, 0,
5958 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
5959 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
5960 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
5961 pMaskSet = &pWInfo->sMaskSet;
5962 pMaskSet->n = 0;
5963 pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
5964 ** a valid cursor number, to avoid an initial
5965 ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
5966 sWLB.pWInfo = pWInfo;
5967 sWLB.pWC = &pWInfo->sWC;
5968 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5969 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
5970 whereLoopInit(sWLB.pNew);
5971 #ifdef SQLITE_DEBUG
5972 sWLB.pNew->cId = '*';
5973 #endif
5975 /* Split the WHERE clause into separate subexpressions where each
5976 ** subexpression is separated by an AND operator.
5978 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
5979 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
5981 /* Special case: No FROM clause
5983 if( nTabList==0 ){
5984 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
5985 if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0
5986 && OptimizationEnabled(db, SQLITE_DistinctOpt)
5988 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5990 ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
5991 }else{
5992 /* Assign a bit from the bitmask to every term in the FROM clause.
5994 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
5996 ** The rule of the previous sentence ensures that if X is the bitmask for
5997 ** a table T, then X-1 is the bitmask for all other tables to the left of T.
5998 ** Knowing the bitmask for all tables to the left of a left join is
5999 ** important. Ticket #3015.
6001 ** Note that bitmasks are created for all pTabList->nSrc tables in
6002 ** pTabList, not just the first nTabList tables. nTabList is normally
6003 ** equal to pTabList->nSrc but might be shortened to 1 if the
6004 ** WHERE_OR_SUBCLAUSE flag is set.
6006 ii = 0;
6008 createMask(pMaskSet, pTabList->a[ii].iCursor);
6009 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
6010 }while( (++ii)<pTabList->nSrc );
6011 #ifdef SQLITE_DEBUG
6013 Bitmask mx = 0;
6014 for(ii=0; ii<pTabList->nSrc; ii++){
6015 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
6016 assert( m>=mx );
6017 mx = m;
6020 #endif
6023 /* Analyze all of the subexpressions. */
6024 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
6025 if( pSelect && pSelect->pLimit ){
6026 sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
6028 if( pParse->nErr ) goto whereBeginError;
6030 /* The False-WHERE-Term-Bypass optimization:
6032 ** If there are WHERE terms that are false, then no rows will be output,
6033 ** so skip over all of the code generated here.
6035 ** Conditions:
6037 ** (1) The WHERE term must not refer to any tables in the join.
6038 ** (2) The term must not come from an ON clause on the
6039 ** right-hand side of a LEFT or FULL JOIN.
6040 ** (3) The term must not come from an ON clause, or there must be
6041 ** no RIGHT or FULL OUTER joins in pTabList.
6042 ** (4) If the expression contains non-deterministic functions
6043 ** that are not within a sub-select. This is not required
6044 ** for correctness but rather to preserves SQLite's legacy
6045 ** behaviour in the following two cases:
6047 ** WHERE random()>0; -- eval random() once per row
6048 ** WHERE (SELECT random())>0; -- eval random() just once overall
6050 ** Note that the Where term need not be a constant in order for this
6051 ** optimization to apply, though it does need to be constant relative to
6052 ** the current subquery (condition 1). The term might include variables
6053 ** from outer queries so that the value of the term changes from one
6054 ** invocation of the current subquery to the next.
6056 for(ii=0; ii<sWLB.pWC->nBase; ii++){
6057 WhereTerm *pT = &sWLB.pWC->a[ii]; /* A term of the WHERE clause */
6058 Expr *pX; /* The expression of pT */
6059 if( pT->wtFlags & TERM_VIRTUAL ) continue;
6060 pX = pT->pExpr;
6061 assert( pX!=0 );
6062 assert( pT->prereqAll!=0 || !ExprHasProperty(pX, EP_OuterON) );
6063 if( pT->prereqAll==0 /* Conditions (1) and (2) */
6064 && (nTabList==0 || exprIsDeterministic(pX)) /* Condition (4) */
6065 && !(ExprHasProperty(pX, EP_InnerON) /* Condition (3) */
6066 && (pTabList->a[0].fg.jointype & JT_LTORJ)!=0 )
6068 sqlite3ExprIfFalse(pParse, pX, pWInfo->iBreak, SQLITE_JUMPIFNULL);
6069 pT->wtFlags |= TERM_CODED;
6073 if( wctrlFlags & WHERE_WANT_DISTINCT ){
6074 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
6075 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
6076 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
6077 wctrlFlags &= ~WHERE_WANT_DISTINCT;
6078 pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
6079 }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
6080 /* The DISTINCT marking is pointless. Ignore it. */
6081 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
6082 }else if( pOrderBy==0 ){
6083 /* Try to ORDER BY the result set to make distinct processing easier */
6084 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
6085 pWInfo->pOrderBy = pResultSet;
6089 /* Construct the WhereLoop objects */
6090 #if defined(WHERETRACE_ENABLED)
6091 if( sqlite3WhereTrace & 0xffffffff ){
6092 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
6093 if( wctrlFlags & WHERE_USE_LIMIT ){
6094 sqlite3DebugPrintf(", limit: %d", iAuxArg);
6096 sqlite3DebugPrintf(")\n");
6097 if( sqlite3WhereTrace & 0x8000 ){
6098 Select sSelect;
6099 memset(&sSelect, 0, sizeof(sSelect));
6100 sSelect.selFlags = SF_WhereBegin;
6101 sSelect.pSrc = pTabList;
6102 sSelect.pWhere = pWhere;
6103 sSelect.pOrderBy = pOrderBy;
6104 sSelect.pEList = pResultSet;
6105 sqlite3TreeViewSelect(0, &sSelect, 0);
6107 if( sqlite3WhereTrace & 0x4000 ){ /* Display all WHERE clause terms */
6108 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
6109 sqlite3WhereClausePrint(sWLB.pWC);
6112 #endif
6114 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
6115 rc = whereLoopAddAll(&sWLB);
6116 if( rc ) goto whereBeginError;
6118 #ifdef SQLITE_ENABLE_STAT4
6119 /* If one or more WhereTerm.truthProb values were used in estimating
6120 ** loop parameters, but then those truthProb values were subsequently
6121 ** changed based on STAT4 information while computing subsequent loops,
6122 ** then we need to rerun the whole loop building process so that all
6123 ** loops will be built using the revised truthProb values. */
6124 if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
6125 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6126 WHERETRACE(0xffffffff,
6127 ("**** Redo all loop computations due to"
6128 " TERM_HIGHTRUTH changes ****\n"));
6129 while( pWInfo->pLoops ){
6130 WhereLoop *p = pWInfo->pLoops;
6131 pWInfo->pLoops = p->pNextLoop;
6132 whereLoopDelete(db, p);
6134 rc = whereLoopAddAll(&sWLB);
6135 if( rc ) goto whereBeginError;
6137 #endif
6138 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
6140 wherePathSolver(pWInfo, 0);
6141 if( db->mallocFailed ) goto whereBeginError;
6142 if( pWInfo->pOrderBy ){
6143 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
6144 if( db->mallocFailed ) goto whereBeginError;
6147 assert( pWInfo->pTabList!=0 );
6148 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
6149 whereReverseScanOrder(pWInfo);
6151 if( pParse->nErr ){
6152 goto whereBeginError;
6154 assert( db->mallocFailed==0 );
6155 #ifdef WHERETRACE_ENABLED
6156 if( sqlite3WhereTrace ){
6157 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
6158 if( pWInfo->nOBSat>0 ){
6159 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
6161 switch( pWInfo->eDistinct ){
6162 case WHERE_DISTINCT_UNIQUE: {
6163 sqlite3DebugPrintf(" DISTINCT=unique");
6164 break;
6166 case WHERE_DISTINCT_ORDERED: {
6167 sqlite3DebugPrintf(" DISTINCT=ordered");
6168 break;
6170 case WHERE_DISTINCT_UNORDERED: {
6171 sqlite3DebugPrintf(" DISTINCT=unordered");
6172 break;
6175 sqlite3DebugPrintf("\n");
6176 for(ii=0; ii<pWInfo->nLevel; ii++){
6177 sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
6180 #endif
6182 /* Attempt to omit tables from a join that do not affect the result.
6183 ** See the comment on whereOmitNoopJoin() for further information.
6185 ** This query optimization is factored out into a separate "no-inline"
6186 ** procedure to keep the sqlite3WhereBegin() procedure from becoming
6187 ** too large. If sqlite3WhereBegin() becomes too large, that prevents
6188 ** some C-compiler optimizers from in-lining the
6189 ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
6190 ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
6192 notReady = ~(Bitmask)0;
6193 if( pWInfo->nLevel>=2
6194 && pResultSet!=0 /* these two combine to guarantee */
6195 && 0==(wctrlFlags & WHERE_AGG_DISTINCT) /* condition (1) above */
6196 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
6198 notReady = whereOmitNoopJoin(pWInfo, notReady);
6199 nTabList = pWInfo->nLevel;
6200 assert( nTabList>0 );
6203 /* Check to see if there are any SEARCH loops that might benefit from
6204 ** using a Bloom filter.
6206 if( pWInfo->nLevel>=2
6207 && OptimizationEnabled(db, SQLITE_BloomFilter)
6209 whereCheckIfBloomFilterIsUseful(pWInfo);
6212 #if defined(WHERETRACE_ENABLED)
6213 if( sqlite3WhereTrace & 0x4000 ){ /* Display all terms of the WHERE clause */
6214 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
6215 sqlite3WhereClausePrint(sWLB.pWC);
6217 WHERETRACE(0xffffffff,("*** Optimizer Finished ***\n"));
6218 #endif
6219 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
6221 /* If the caller is an UPDATE or DELETE statement that is requesting
6222 ** to use a one-pass algorithm, determine if this is appropriate.
6224 ** A one-pass approach can be used if the caller has requested one
6225 ** and either (a) the scan visits at most one row or (b) each
6226 ** of the following are true:
6228 ** * the caller has indicated that a one-pass approach can be used
6229 ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
6230 ** * the table is not a virtual table, and
6231 ** * either the scan does not use the OR optimization or the caller
6232 ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
6233 ** for DELETE).
6235 ** The last qualification is because an UPDATE statement uses
6236 ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
6237 ** use a one-pass approach, and this is not set accurately for scans
6238 ** that use the OR optimization.
6240 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
6241 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
6242 int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
6243 int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
6244 assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
6245 if( bOnerow || (
6246 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
6247 && !IsVirtual(pTabList->a[0].pTab)
6248 && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
6249 && OptimizationEnabled(db, SQLITE_OnePass)
6251 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
6252 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
6253 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
6254 bFordelete = OPFLAG_FORDELETE;
6256 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
6261 /* Open all tables in the pTabList and any indices selected for
6262 ** searching those tables.
6264 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
6265 Table *pTab; /* Table to open */
6266 int iDb; /* Index of database containing table/index */
6267 SrcItem *pTabItem;
6269 pTabItem = &pTabList->a[pLevel->iFrom];
6270 pTab = pTabItem->pTab;
6271 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6272 pLoop = pLevel->pWLoop;
6273 if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
6274 /* Do nothing */
6275 }else
6276 #ifndef SQLITE_OMIT_VIRTUALTABLE
6277 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
6278 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
6279 int iCur = pTabItem->iCursor;
6280 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
6281 }else if( IsVirtual(pTab) ){
6282 /* noop */
6283 }else
6284 #endif
6285 if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0
6286 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0)
6287 || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0
6289 int op = OP_OpenRead;
6290 if( pWInfo->eOnePass!=ONEPASS_OFF ){
6291 op = OP_OpenWrite;
6292 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6294 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
6295 assert( pTabItem->iCursor==pLevel->iTabCur );
6296 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
6297 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
6298 if( pWInfo->eOnePass==ONEPASS_OFF
6299 && pTab->nCol<BMS
6300 && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
6301 && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
6303 /* If we know that only a prefix of the record will be used,
6304 ** it is advantageous to reduce the "column count" field in
6305 ** the P4 operand of the OP_OpenRead/Write opcode. */
6306 Bitmask b = pTabItem->colUsed;
6307 int n = 0;
6308 for(; b; b=b>>1, n++){}
6309 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
6310 assert( n<=pTab->nCol );
6312 #ifdef SQLITE_ENABLE_CURSOR_HINTS
6313 if( pLoop->u.btree.pIndex!=0 && (pTab->tabFlags & TF_WithoutRowid)==0 ){
6314 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
6315 }else
6316 #endif
6318 sqlite3VdbeChangeP5(v, bFordelete);
6320 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6321 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
6322 (const u8*)&pTabItem->colUsed, P4_INT64);
6323 #endif
6324 }else{
6325 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
6327 if( pLoop->wsFlags & WHERE_INDEXED ){
6328 Index *pIx = pLoop->u.btree.pIndex;
6329 int iIndexCur;
6330 int op = OP_OpenRead;
6331 /* iAuxArg is always set to a positive value if ONEPASS is possible */
6332 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
6333 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
6334 && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
6336 /* This is one term of an OR-optimization using the PRIMARY KEY of a
6337 ** WITHOUT ROWID table. No need for a separate index */
6338 iIndexCur = pLevel->iTabCur;
6339 op = 0;
6340 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
6341 Index *pJ = pTabItem->pTab->pIndex;
6342 iIndexCur = iAuxArg;
6343 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6344 while( ALWAYS(pJ) && pJ!=pIx ){
6345 iIndexCur++;
6346 pJ = pJ->pNext;
6348 op = OP_OpenWrite;
6349 pWInfo->aiCurOnePass[1] = iIndexCur;
6350 }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
6351 iIndexCur = iAuxArg;
6352 op = OP_ReopenIdx;
6353 }else{
6354 iIndexCur = pParse->nTab++;
6355 if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
6356 whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem);
6359 pLevel->iIdxCur = iIndexCur;
6360 assert( pIx!=0 );
6361 assert( pIx->pSchema==pTab->pSchema );
6362 assert( iIndexCur>=0 );
6363 if( op ){
6364 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
6365 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6366 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
6367 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
6368 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
6369 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
6370 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
6371 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
6373 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
6375 VdbeComment((v, "%s", pIx->zName));
6376 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
6378 u64 colUsed = 0;
6379 int ii, jj;
6380 for(ii=0; ii<pIx->nColumn; ii++){
6381 jj = pIx->aiColumn[ii];
6382 if( jj<0 ) continue;
6383 if( jj>63 ) jj = 63;
6384 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
6385 colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
6387 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
6388 (u8*)&colUsed, P4_INT64);
6390 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
6393 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
6394 if( (pTabItem->fg.jointype & JT_RIGHT)!=0
6395 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
6397 WhereRightJoin *pRJ = pLevel->pRJ;
6398 pRJ->iMatch = pParse->nTab++;
6399 pRJ->regBloom = ++pParse->nMem;
6400 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
6401 pRJ->regReturn = ++pParse->nMem;
6402 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
6403 assert( pTab==pTabItem->pTab );
6404 if( HasRowid(pTab) ){
6405 KeyInfo *pInfo;
6406 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
6407 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
6408 if( pInfo ){
6409 pInfo->aColl[0] = 0;
6410 pInfo->aSortFlags[0] = 0;
6411 sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
6413 }else{
6414 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6415 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
6416 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
6418 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
6419 /* The nature of RIGHT JOIN processing is such that it messes up
6420 ** the output order. So omit any ORDER BY/GROUP BY elimination
6421 ** optimizations. We need to do an actual sort for RIGHT JOIN. */
6422 pWInfo->nOBSat = 0;
6423 pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED;
6426 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
6427 if( db->mallocFailed ) goto whereBeginError;
6429 /* Generate the code to do the search. Each iteration of the for
6430 ** loop below generates code for a single nested loop of the VM
6431 ** program.
6433 for(ii=0; ii<nTabList; ii++){
6434 int addrExplain;
6435 int wsFlags;
6436 SrcItem *pSrc;
6437 if( pParse->nErr ) goto whereBeginError;
6438 pLevel = &pWInfo->a[ii];
6439 wsFlags = pLevel->pWLoop->wsFlags;
6440 pSrc = &pTabList->a[pLevel->iFrom];
6441 if( pSrc->fg.isMaterialized ){
6442 if( pSrc->fg.isCorrelated ){
6443 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6444 }else{
6445 int iOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
6446 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
6447 sqlite3VdbeJumpHere(v, iOnce);
6450 assert( pTabList == pWInfo->pTabList );
6451 if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
6452 if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
6453 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6454 constructAutomaticIndex(pParse, &pWInfo->sWC, notReady, pLevel);
6455 #endif
6456 }else{
6457 sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
6459 if( db->mallocFailed ) goto whereBeginError;
6461 addrExplain = sqlite3WhereExplainOneScan(
6462 pParse, pTabList, pLevel, wctrlFlags
6464 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
6465 notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
6466 pWInfo->iContinue = pLevel->addrCont;
6467 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
6468 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
6472 /* Done. */
6473 VdbeModuleComment((v, "Begin WHERE-core"));
6474 pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
6475 return pWInfo;
6477 /* Jump here if malloc fails */
6478 whereBeginError:
6479 if( pWInfo ){
6480 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6481 whereInfoFree(db, pWInfo);
6483 return 0;
6487 ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
6488 ** index rather than the main table. In SQLITE_DEBUG mode, we want
6489 ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
6490 ** does that.
6492 #ifndef SQLITE_DEBUG
6493 # define OpcodeRewriteTrace(D,K,P) /* no-op */
6494 #else
6495 # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
6496 static void sqlite3WhereOpcodeRewriteTrace(
6497 sqlite3 *db,
6498 int pc,
6499 VdbeOp *pOp
6501 if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
6502 sqlite3VdbePrintOp(0, pc, pOp);
6504 #endif
6506 #ifdef SQLITE_DEBUG
6508 ** Return true if cursor iCur is opened by instruction k of the
6509 ** bytecode. Used inside of assert() only.
6511 static int cursorIsOpen(Vdbe *v, int iCur, int k){
6512 while( k>=0 ){
6513 VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
6514 if( pOp->p1!=iCur ) continue;
6515 if( pOp->opcode==OP_Close ) return 0;
6516 if( pOp->opcode==OP_OpenRead ) return 1;
6517 if( pOp->opcode==OP_OpenWrite ) return 1;
6518 if( pOp->opcode==OP_OpenDup ) return 1;
6519 if( pOp->opcode==OP_OpenAutoindex ) return 1;
6520 if( pOp->opcode==OP_OpenEphemeral ) return 1;
6522 return 0;
6524 #endif /* SQLITE_DEBUG */
6527 ** Generate the end of the WHERE loop. See comments on
6528 ** sqlite3WhereBegin() for additional information.
6530 void sqlite3WhereEnd(WhereInfo *pWInfo){
6531 Parse *pParse = pWInfo->pParse;
6532 Vdbe *v = pParse->pVdbe;
6533 int i;
6534 WhereLevel *pLevel;
6535 WhereLoop *pLoop;
6536 SrcList *pTabList = pWInfo->pTabList;
6537 sqlite3 *db = pParse->db;
6538 int iEnd = sqlite3VdbeCurrentAddr(v);
6539 int nRJ = 0;
6541 /* Generate loop termination code.
6543 VdbeModuleComment((v, "End WHERE-core"));
6544 for(i=pWInfo->nLevel-1; i>=0; i--){
6545 int addr;
6546 pLevel = &pWInfo->a[i];
6547 if( pLevel->pRJ ){
6548 /* Terminate the subroutine that forms the interior of the loop of
6549 ** the RIGHT JOIN table */
6550 WhereRightJoin *pRJ = pLevel->pRJ;
6551 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6552 pLevel->addrCont = 0;
6553 pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);
6554 sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);
6555 VdbeCoverage(v);
6556 nRJ++;
6558 pLoop = pLevel->pWLoop;
6559 if( pLevel->op!=OP_Noop ){
6560 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6561 int addrSeek = 0;
6562 Index *pIdx;
6563 int n;
6564 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
6565 && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
6566 && (pLoop->wsFlags & WHERE_INDEXED)!=0
6567 && (pIdx = pLoop->u.btree.pIndex)->hasStat1
6568 && (n = pLoop->u.btree.nDistinctCol)>0
6569 && pIdx->aiRowLogEst[n]>=36
6571 int r1 = pParse->nMem+1;
6572 int j, op;
6573 for(j=0; j<n; j++){
6574 sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
6576 pParse->nMem += n+1;
6577 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
6578 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
6579 VdbeCoverageIf(v, op==OP_SeekLT);
6580 VdbeCoverageIf(v, op==OP_SeekGT);
6581 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
6583 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
6584 /* The common case: Advance to the next row */
6585 if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6586 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
6587 sqlite3VdbeChangeP5(v, pLevel->p5);
6588 VdbeCoverage(v);
6589 VdbeCoverageIf(v, pLevel->op==OP_Next);
6590 VdbeCoverageIf(v, pLevel->op==OP_Prev);
6591 VdbeCoverageIf(v, pLevel->op==OP_VNext);
6592 if( pLevel->regBignull ){
6593 sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
6594 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
6595 VdbeCoverage(v);
6597 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6598 if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
6599 #endif
6600 }else if( pLevel->addrCont ){
6601 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6603 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
6604 struct InLoop *pIn;
6605 int j;
6606 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
6607 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
6608 assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
6609 || pParse->db->mallocFailed );
6610 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6611 if( pIn->eEndLoopOp!=OP_Noop ){
6612 if( pIn->nPrefix ){
6613 int bEarlyOut =
6614 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
6615 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
6616 if( pLevel->iLeftJoin ){
6617 /* For LEFT JOIN queries, cursor pIn->iCur may not have been
6618 ** opened yet. This occurs for WHERE clauses such as
6619 ** "a = ? AND b IN (...)", where the index is on (a, b). If
6620 ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
6621 ** never have been coded, but the body of the loop run to
6622 ** return the null-row. So, if the cursor is not open yet,
6623 ** jump over the OP_Next or OP_Prev instruction about to
6624 ** be coded. */
6625 sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
6626 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
6627 VdbeCoverage(v);
6629 if( bEarlyOut ){
6630 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
6631 sqlite3VdbeCurrentAddr(v)+2,
6632 pIn->iBase, pIn->nPrefix);
6633 VdbeCoverage(v);
6634 /* Retarget the OP_IsNull against the left operand of IN so
6635 ** it jumps past the OP_IfNoHope. This is because the
6636 ** OP_IsNull also bypasses the OP_Affinity opcode that is
6637 ** required by OP_IfNoHope. */
6638 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
6641 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
6642 VdbeCoverage(v);
6643 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
6644 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
6646 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
6649 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
6650 if( pLevel->pRJ ){
6651 sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1);
6652 VdbeCoverage(v);
6654 if( pLevel->addrSkip ){
6655 sqlite3VdbeGoto(v, pLevel->addrSkip);
6656 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
6657 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
6658 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
6660 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
6661 if( pLevel->addrLikeRep ){
6662 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
6663 pLevel->addrLikeRep);
6664 VdbeCoverage(v);
6666 #endif
6667 if( pLevel->iLeftJoin ){
6668 int ws = pLoop->wsFlags;
6669 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
6670 assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
6671 if( (ws & WHERE_IDX_ONLY)==0 ){
6672 assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
6673 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
6675 if( (ws & WHERE_INDEXED)
6676 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
6678 if( ws & WHERE_MULTI_OR ){
6679 Index *pIx = pLevel->u.pCoveringIdx;
6680 int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
6681 sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
6682 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6684 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
6686 if( pLevel->op==OP_Return ){
6687 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6688 }else{
6689 sqlite3VdbeGoto(v, pLevel->addrFirst);
6691 sqlite3VdbeJumpHere(v, addr);
6693 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
6694 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
6697 assert( pWInfo->nLevel<=pTabList->nSrc );
6698 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
6699 int k, last;
6700 VdbeOp *pOp, *pLastOp;
6701 Index *pIdx = 0;
6702 SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
6703 Table *pTab = pTabItem->pTab;
6704 assert( pTab!=0 );
6705 pLoop = pLevel->pWLoop;
6707 /* Do RIGHT JOIN processing. Generate code that will output the
6708 ** unmatched rows of the right operand of the RIGHT JOIN with
6709 ** all of the columns of the left operand set to NULL.
6711 if( pLevel->pRJ ){
6712 sqlite3WhereRightJoinLoop(pWInfo, i, pLevel);
6713 continue;
6716 /* For a co-routine, change all OP_Column references to the table of
6717 ** the co-routine into OP_Copy of result contained in a register.
6718 ** OP_Rowid becomes OP_Null.
6720 if( pTabItem->fg.viaCoroutine ){
6721 testcase( pParse->db->mallocFailed );
6722 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
6723 pTabItem->regResult, 0);
6724 continue;
6727 /* If this scan uses an index, make VDBE code substitutions to read data
6728 ** from the index instead of from the table where possible. In some cases
6729 ** this optimization prevents the table from ever being read, which can
6730 ** yield a significant performance boost.
6732 ** Calls to the code generator in between sqlite3WhereBegin and
6733 ** sqlite3WhereEnd will have created code that references the table
6734 ** directly. This loop scans all that code looking for opcodes
6735 ** that reference the table and converts them into opcodes that
6736 ** reference the index.
6738 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6739 pIdx = pLoop->u.btree.pIndex;
6740 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
6741 pIdx = pLevel->u.pCoveringIdx;
6743 if( pIdx
6744 && !db->mallocFailed
6746 if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
6747 last = iEnd;
6748 }else{
6749 last = pWInfo->iEndWhere;
6751 if( pIdx->bHasExpr ){
6752 IndexedExpr *p = pParse->pIdxEpr;
6753 while( p ){
6754 if( p->iIdxCur==pLevel->iIdxCur ){
6755 #ifdef WHERETRACE_ENABLED
6756 if( sqlite3WhereTrace & 0x200 ){
6757 sqlite3DebugPrintf("Disable pParse->pIdxEpr term {%d,%d}\n",
6758 p->iIdxCur, p->iIdxCol);
6759 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(p->pExpr);
6761 #endif
6762 p->iDataCur = -1;
6763 p->iIdxCur = -1;
6765 p = p->pIENext;
6768 k = pLevel->addrBody + 1;
6769 #ifdef SQLITE_DEBUG
6770 if( db->flags & SQLITE_VdbeAddopTrace ){
6771 printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n",
6772 pLevel->iTabCur, pLevel->iIdxCur, k, last-1);
6774 /* Proof that the "+1" on the k value above is safe */
6775 pOp = sqlite3VdbeGetOp(v, k - 1);
6776 assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
6777 assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur );
6778 assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
6779 #endif
6780 pOp = sqlite3VdbeGetOp(v, k);
6781 pLastOp = pOp + (last - k);
6782 assert( pOp<=pLastOp );
6784 if( pOp->p1!=pLevel->iTabCur ){
6785 /* no-op */
6786 }else if( pOp->opcode==OP_Column
6787 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6788 || pOp->opcode==OP_Offset
6789 #endif
6791 int x = pOp->p2;
6792 assert( pIdx->pTable==pTab );
6793 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6794 if( pOp->opcode==OP_Offset ){
6795 /* Do not need to translate the column number */
6796 }else
6797 #endif
6798 if( !HasRowid(pTab) ){
6799 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6800 x = pPk->aiColumn[x];
6801 assert( x>=0 );
6802 }else{
6803 testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
6804 x = sqlite3StorageColumnToTable(pTab,x);
6806 x = sqlite3TableColumnToIndex(pIdx, x);
6807 if( x>=0 ){
6808 pOp->p2 = x;
6809 pOp->p1 = pLevel->iIdxCur;
6810 OpcodeRewriteTrace(db, k, pOp);
6811 }else{
6812 /* Unable to translate the table reference into an index
6813 ** reference. Verify that this is harmless - that the
6814 ** table being referenced really is open.
6816 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6817 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6818 || cursorIsOpen(v,pOp->p1,k)
6819 || pOp->opcode==OP_Offset
6821 #else
6822 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6823 || cursorIsOpen(v,pOp->p1,k)
6825 #endif
6827 }else if( pOp->opcode==OP_Rowid ){
6828 pOp->p1 = pLevel->iIdxCur;
6829 pOp->opcode = OP_IdxRowid;
6830 OpcodeRewriteTrace(db, k, pOp);
6831 }else if( pOp->opcode==OP_IfNullRow ){
6832 pOp->p1 = pLevel->iIdxCur;
6833 OpcodeRewriteTrace(db, k, pOp);
6835 #ifdef SQLITE_DEBUG
6836 k++;
6837 #endif
6838 }while( (++pOp)<pLastOp );
6839 #ifdef SQLITE_DEBUG
6840 if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
6841 #endif
6845 /* The "break" point is here, just past the end of the outer loop.
6846 ** Set it.
6848 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
6850 /* Final cleanup
6852 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6853 whereInfoFree(db, pWInfo);
6854 pParse->withinRJSubrtn -= nRJ;
6855 return;