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. 10 ** 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". 18 */ 19 #include "sqliteInt.h" 20 #include "whereInt.h" 21 22 /* 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. 26 ** 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. 30 */ 31 typedef struct HiddenIndexInfo HiddenIndexInfo; 32 struct HiddenIndexInfo { 33 WhereClause *pWC; /* The Where clause being analyzed */ 34 Parse *pParse; /* The parsing context */ 35 }; 36 37 /* Forward declaration of methods */ 38 static int whereLoopResize(sqlite3*, WhereLoop*, int); 39 40 /* 41 ** Return the estimated number of output rows from a WHERE clause 42 */ 43 LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ 44 return pWInfo->nRowOut; 45 } 46 47 /* 48 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this 49 ** WHERE clause returns outputs for DISTINCT processing. 50 */ 51 int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ 52 return pWInfo->eDistinct; 53 } 54 55 /* 56 ** Return the number of ORDER BY terms that are satisfied by the 57 ** WHERE clause. A return of 0 means that the output must be 58 ** completely sorted. A return equal to the number of ORDER BY 59 ** terms means that no sorting is needed at all. A return that 60 ** is positive but less than the number of ORDER BY terms means that 61 ** block sorting is required. 62 */ 63 int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ 64 return pWInfo->nOBSat; 65 } 66 67 /* 68 ** In the ORDER BY LIMIT optimization, if the inner-most loop is known 69 ** to emit rows in increasing order, and if the last row emitted by the 70 ** inner-most loop did not fit within the sorter, then we can skip all 71 ** subsequent rows for the current iteration of the inner loop (because they 72 ** will not fit in the sorter either) and continue with the second inner 73 ** loop - the loop immediately outside the inner-most. 74 ** 75 ** When a row does not fit in the sorter (because the sorter already 76 ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the 77 ** label returned by this function. 78 ** 79 ** If the ORDER BY LIMIT optimization applies, the jump destination should 80 ** be the continuation for the second-inner-most loop. If the ORDER BY 81 ** LIMIT optimization does not apply, then the jump destination should 82 ** be the continuation for the inner-most loop. 83 ** 84 ** It is always safe for this routine to return the continuation of the 85 ** inner-most loop, in the sense that a correct answer will result. 86 ** Returning the continuation the second inner loop is an optimization 87 ** that might make the code run a little faster, but should not change 88 ** the final answer. 89 */ 90 int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){ 91 WhereLevel *pInner; 92 if( !pWInfo->bOrderedInnerLoop ){ 93 /* The ORDER BY LIMIT optimization does not apply. Jump to the 94 ** continuation of the inner-most loop. */ 95 return pWInfo->iContinue; 96 } 97 pInner = &pWInfo->a[pWInfo->nLevel-1]; 98 assert( pInner->addrNxt!=0 ); 99 return pInner->addrNxt; 100 } 101 102 /* 103 ** Return the VDBE address or label to jump to in order to continue 104 ** immediately with the next row of a WHERE clause. 105 */ 106 int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ 107 assert( pWInfo->iContinue!=0 ); 108 return pWInfo->iContinue; 109 } 110 111 /* 112 ** Return the VDBE address or label to jump to in order to break 113 ** out of a WHERE loop. 114 */ 115 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ 116 return pWInfo->iBreak; 117 } 118 119 /* 120 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to 121 ** operate directly on the rowids returned by a WHERE clause. Return 122 ** ONEPASS_SINGLE (1) if the statement can operation directly because only 123 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass 124 ** optimization can be used on multiple 125 ** 126 ** If the ONEPASS optimization is used (if this routine returns true) 127 ** then also write the indices of open cursors used by ONEPASS 128 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data 129 ** table and iaCur[1] gets the cursor used by an auxiliary index. 130 ** Either value may be -1, indicating that cursor is not used. 131 ** Any cursors returned will have been opened for writing. 132 ** 133 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is 134 ** unable to use the ONEPASS optimization. 135 */ 136 int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ 137 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); 138 #ifdef WHERETRACE_ENABLED 139 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ 140 sqlite3DebugPrintf("%s cursors: %d %d\n", 141 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI", 142 aiCur[0], aiCur[1]); 143 } 144 #endif 145 return pWInfo->eOnePass; 146 } 147 148 /* 149 ** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move 150 ** the data cursor to the row selected by the index cursor. 151 */ 152 int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){ 153 return pWInfo->bDeferredSeek; 154 } 155 156 /* 157 ** Move the content of pSrc into pDest 158 */ 159 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ 160 pDest->n = pSrc->n; 161 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); 162 } 163 164 /* 165 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. 166 ** 167 ** The new entry might overwrite an existing entry, or it might be 168 ** appended, or it might be discarded. Do whatever is the right thing 169 ** so that pSet keeps the N_OR_COST best entries seen so far. 170 */ 171 static int whereOrInsert( 172 WhereOrSet *pSet, /* The WhereOrSet to be updated */ 173 Bitmask prereq, /* Prerequisites of the new entry */ 174 LogEst rRun, /* Run-cost of the new entry */ 175 LogEst nOut /* Number of outputs for the new entry */ 176 ){ 177 u16 i; 178 WhereOrCost *p; 179 for(i=pSet->n, p=pSet->a; i>0; i--, p++){ 180 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ 181 goto whereOrInsert_done; 182 } 183 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ 184 return 0; 185 } 186 } 187 if( pSet->n<N_OR_COST ){ 188 p = &pSet->a[pSet->n++]; 189 p->nOut = nOut; 190 }else{ 191 p = pSet->a; 192 for(i=1; i<pSet->n; i++){ 193 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i; 194 } 195 if( p->rRun<=rRun ) return 0; 196 } 197 whereOrInsert_done: 198 p->prereq = prereq; 199 p->rRun = rRun; 200 if( p->nOut>nOut ) p->nOut = nOut; 201 return 1; 202 } 203 204 /* 205 ** Return the bitmask for the given cursor number. Return 0 if 206 ** iCursor is not in the set. 207 */ 208 Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ 209 int i; 210 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); 211 for(i=0; i<pMaskSet->n; i++){ 212 if( pMaskSet->ix[i]==iCursor ){ 213 return MASKBIT(i); 214 } 215 } 216 return 0; 217 } 218 219 /* 220 ** Create a new mask for cursor iCursor. 221 ** 222 ** There is one cursor per table in the FROM clause. The number of 223 ** tables in the FROM clause is limited by a test early in the 224 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] 225 ** array will never overflow. 226 */ 227 static void createMask(WhereMaskSet *pMaskSet, int iCursor){ 228 assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); 229 pMaskSet->ix[pMaskSet->n++] = iCursor; 230 } 231 232 /* 233 ** If the right-hand branch of the expression is a TK_COLUMN, then return 234 ** a pointer to the right-hand branch. Otherwise, return NULL. 235 */ 236 static Expr *whereRightSubexprIsColumn(Expr *p){ 237 p = sqlite3ExprSkipCollateAndLikely(p->pRight); 238 if( ALWAYS(p!=0) && p->op==TK_COLUMN ) return p; 239 return 0; 240 } 241 242 /* 243 ** Advance to the next WhereTerm that matches according to the criteria 244 ** established when the pScan object was initialized by whereScanInit(). 245 ** Return NULL if there are no more matching WhereTerms. 246 */ 247 static WhereTerm *whereScanNext(WhereScan *pScan){ 248 int iCur; /* The cursor on the LHS of the term */ 249 i16 iColumn; /* The column on the LHS of the term. -1 for IPK */ 250 Expr *pX; /* An expression being tested */ 251 WhereClause *pWC; /* Shorthand for pScan->pWC */ 252 WhereTerm *pTerm; /* The term being tested */ 253 int k = pScan->k; /* Where to start scanning */ 254 255 assert( pScan->iEquiv<=pScan->nEquiv ); 256 pWC = pScan->pWC; 257 while(1){ 258 iColumn = pScan->aiColumn[pScan->iEquiv-1]; 259 iCur = pScan->aiCur[pScan->iEquiv-1]; 260 assert( pWC!=0 ); 261 do{ 262 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){ 263 if( pTerm->leftCursor==iCur 264 && pTerm->u.x.leftColumn==iColumn 265 && (iColumn!=XN_EXPR 266 || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft, 267 pScan->pIdxExpr,iCur)==0) 268 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 269 ){ 270 if( (pTerm->eOperator & WO_EQUIV)!=0 271 && pScan->nEquiv<ArraySize(pScan->aiCur) 272 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0 273 ){ 274 int j; 275 for(j=0; j<pScan->nEquiv; j++){ 276 if( pScan->aiCur[j]==pX->iTable 277 && pScan->aiColumn[j]==pX->iColumn ){ 278 break; 279 } 280 } 281 if( j==pScan->nEquiv ){ 282 pScan->aiCur[j] = pX->iTable; 283 pScan->aiColumn[j] = pX->iColumn; 284 pScan->nEquiv++; 285 } 286 } 287 if( (pTerm->eOperator & pScan->opMask)!=0 ){ 288 /* Verify the affinity and collating sequence match */ 289 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ 290 CollSeq *pColl; 291 Parse *pParse = pWC->pWInfo->pParse; 292 pX = pTerm->pExpr; 293 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ 294 continue; 295 } 296 assert(pX->pLeft); 297 pColl = sqlite3ExprCompareCollSeq(pParse, pX); 298 if( pColl==0 ) pColl = pParse->db->pDfltColl; 299 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ 300 continue; 301 } 302 } 303 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0 304 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN 305 && pX->iTable==pScan->aiCur[0] 306 && pX->iColumn==pScan->aiColumn[0] 307 ){ 308 testcase( pTerm->eOperator & WO_IS ); 309 continue; 310 } 311 pScan->pWC = pWC; 312 pScan->k = k+1; 313 return pTerm; 314 } 315 } 316 } 317 pWC = pWC->pOuter; 318 k = 0; 319 }while( pWC!=0 ); 320 if( pScan->iEquiv>=pScan->nEquiv ) break; 321 pWC = pScan->pOrigWC; 322 k = 0; 323 pScan->iEquiv++; 324 } 325 return 0; 326 } 327 328 /* 329 ** This is whereScanInit() for the case of an index on an expression. 330 ** It is factored out into a separate tail-recursion subroutine so that 331 ** the normal whereScanInit() routine, which is a high-runner, does not 332 ** need to push registers onto the stack as part of its prologue. 333 */ 334 static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){ 335 pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr); 336 return whereScanNext(pScan); 337 } 338 339 /* 340 ** Initialize a WHERE clause scanner object. Return a pointer to the 341 ** first match. Return NULL if there are no matches. 342 ** 343 ** The scanner will be searching the WHERE clause pWC. It will look 344 ** for terms of the form "X <op> <expr>" where X is column iColumn of table 345 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx 346 ** must be one of the indexes of table iCur. 347 ** 348 ** The <op> must be one of the operators described by opMask. 349 ** 350 ** If the search is for X and the WHERE clause contains terms of the 351 ** form X=Y then this routine might also return terms of the form 352 ** "Y <op> <expr>". The number of levels of transitivity is limited, 353 ** but is enough to handle most commonly occurring SQL statements. 354 ** 355 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with 356 ** index pIdx. 357 */ 358 static WhereTerm *whereScanInit( 359 WhereScan *pScan, /* The WhereScan object being initialized */ 360 WhereClause *pWC, /* The WHERE clause to be scanned */ 361 int iCur, /* Cursor to scan for */ 362 int iColumn, /* Column to scan for */ 363 u32 opMask, /* Operator(s) to scan for */ 364 Index *pIdx /* Must be compatible with this index */ 365 ){ 366 pScan->pOrigWC = pWC; 367 pScan->pWC = pWC; 368 pScan->pIdxExpr = 0; 369 pScan->idxaff = 0; 370 pScan->zCollName = 0; 371 pScan->opMask = opMask; 372 pScan->k = 0; 373 pScan->aiCur[0] = iCur; 374 pScan->nEquiv = 1; 375 pScan->iEquiv = 1; 376 if( pIdx ){ 377 int j = iColumn; 378 iColumn = pIdx->aiColumn[j]; 379 if( iColumn==XN_EXPR ){ 380 pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; 381 pScan->zCollName = pIdx->azColl[j]; 382 pScan->aiColumn[0] = XN_EXPR; 383 return whereScanInitIndexExpr(pScan); 384 }else if( iColumn==pIdx->pTable->iPKey ){ 385 iColumn = XN_ROWID; 386 }else if( iColumn>=0 ){ 387 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; 388 pScan->zCollName = pIdx->azColl[j]; 389 } 390 }else if( iColumn==XN_EXPR ){ 391 return 0; 392 } 393 pScan->aiColumn[0] = iColumn; 394 return whereScanNext(pScan); 395 } 396 397 /* 398 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>" 399 ** where X is a reference to the iColumn of table iCur or of index pIdx 400 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by 401 ** the op parameter. Return a pointer to the term. Return 0 if not found. 402 ** 403 ** If pIdx!=0 then it must be one of the indexes of table iCur. 404 ** Search for terms matching the iColumn-th column of pIdx 405 ** rather than the iColumn-th column of table iCur. 406 ** 407 ** The term returned might by Y=<expr> if there is another constraint in 408 ** the WHERE clause that specifies that X=Y. Any such constraints will be 409 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The 410 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11 411 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10 412 ** other equivalent values. Hence a search for X will return <expr> if X=A1 413 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>. 414 ** 415 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>" 416 ** then try for the one with no dependencies on <expr> - in other words where 417 ** <expr> is a constant expression of some kind. Only return entries of 418 ** the form "X <op> Y" where Y is a column in another table if no terms of 419 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS 420 ** exist, try to return a term that does not use WO_EQUIV. 421 */ 422 WhereTerm *sqlite3WhereFindTerm( 423 WhereClause *pWC, /* The WHERE clause to be searched */ 424 int iCur, /* Cursor number of LHS */ 425 int iColumn, /* Column number of LHS */ 426 Bitmask notReady, /* RHS must not overlap with this mask */ 427 u32 op, /* Mask of WO_xx values describing operator */ 428 Index *pIdx /* Must be compatible with this index, if not NULL */ 429 ){ 430 WhereTerm *pResult = 0; 431 WhereTerm *p; 432 WhereScan scan; 433 434 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); 435 op &= WO_EQ|WO_IS; 436 while( p ){ 437 if( (p->prereqRight & notReady)==0 ){ 438 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){ 439 testcase( p->eOperator & WO_IS ); 440 return p; 441 } 442 if( pResult==0 ) pResult = p; 443 } 444 p = whereScanNext(&scan); 445 } 446 return pResult; 447 } 448 449 /* 450 ** This function searches pList for an entry that matches the iCol-th column 451 ** of index pIdx. 452 ** 453 ** If such an expression is found, its index in pList->a[] is returned. If 454 ** no expression is found, -1 is returned. 455 */ 456 static int findIndexCol( 457 Parse *pParse, /* Parse context */ 458 ExprList *pList, /* Expression list to search */ 459 int iBase, /* Cursor for table associated with pIdx */ 460 Index *pIdx, /* Index to match column of */ 461 int iCol /* Column of index to match */ 462 ){ 463 int i; 464 const char *zColl = pIdx->azColl[iCol]; 465 466 for(i=0; i<pList->nExpr; i++){ 467 Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr); 468 if( ALWAYS(p!=0) 469 && p->op==TK_COLUMN 470 && p->iColumn==pIdx->aiColumn[iCol] 471 && p->iTable==iBase 472 ){ 473 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr); 474 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){ 475 return i; 476 } 477 } 478 } 479 480 return -1; 481 } 482 483 /* 484 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL 485 */ 486 static int indexColumnNotNull(Index *pIdx, int iCol){ 487 int j; 488 assert( pIdx!=0 ); 489 assert( iCol>=0 && iCol<pIdx->nColumn ); 490 j = pIdx->aiColumn[iCol]; 491 if( j>=0 ){ 492 return pIdx->pTable->aCol[j].notNull; 493 }else if( j==(-1) ){ 494 return 1; 495 }else{ 496 assert( j==(-2) ); 497 return 0; /* Assume an indexed expression can always yield a NULL */ 498 499 } 500 } 501 502 /* 503 ** Return true if the DISTINCT expression-list passed as the third argument 504 ** is redundant. 505 ** 506 ** A DISTINCT list is redundant if any subset of the columns in the 507 ** DISTINCT list are collectively unique and individually non-null. 508 */ 509 static int isDistinctRedundant( 510 Parse *pParse, /* Parsing context */ 511 SrcList *pTabList, /* The FROM clause */ 512 WhereClause *pWC, /* The WHERE clause */ 513 ExprList *pDistinct /* The result set that needs to be DISTINCT */ 514 ){ 515 Table *pTab; 516 Index *pIdx; 517 int i; 518 int iBase; 519 520 /* If there is more than one table or sub-select in the FROM clause of 521 ** this query, then it will not be possible to show that the DISTINCT 522 ** clause is redundant. */ 523 if( pTabList->nSrc!=1 ) return 0; 524 iBase = pTabList->a[0].iCursor; 525 pTab = pTabList->a[0].pTab; 526 527 /* If any of the expressions is an IPK column on table iBase, then return 528 ** true. Note: The (p->iTable==iBase) part of this test may be false if the 529 ** current SELECT is a correlated sub-query. 530 */ 531 for(i=0; i<pDistinct->nExpr; i++){ 532 Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr); 533 if( NEVER(p==0) ) continue; 534 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1; 535 } 536 537 /* Loop through all indices on the table, checking each to see if it makes 538 ** the DISTINCT qualifier redundant. It does so if: 539 ** 540 ** 1. The index is itself UNIQUE, and 541 ** 542 ** 2. All of the columns in the index are either part of the pDistinct 543 ** list, or else the WHERE clause contains a term of the form "col=X", 544 ** where X is a constant value. The collation sequences of the 545 ** comparison and select-list expressions must match those of the index. 546 ** 547 ** 3. All of those index columns for which the WHERE clause does not 548 ** contain a "col=X" term are subject to a NOT NULL constraint. 549 */ 550 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 551 if( !IsUniqueIndex(pIdx) ) continue; 552 for(i=0; i<pIdx->nKeyCol; i++){ 553 if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ 554 if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break; 555 if( indexColumnNotNull(pIdx, i)==0 ) break; 556 } 557 } 558 if( i==pIdx->nKeyCol ){ 559 /* This index implies that the DISTINCT qualifier is redundant. */ 560 return 1; 561 } 562 } 563 564 return 0; 565 } 566 567 568 /* 569 ** Estimate the logarithm of the input value to base 2. 570 */ 571 static LogEst estLog(LogEst N){ 572 return N<=10 ? 0 : sqlite3LogEst(N) - 33; 573 } 574 575 /* 576 ** Convert OP_Column opcodes to OP_Copy in previously generated code. 577 ** 578 ** This routine runs over generated VDBE code and translates OP_Column 579 ** opcodes into OP_Copy when the table is being accessed via co-routine 580 ** instead of via table lookup. 581 ** 582 ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on 583 ** cursor iTabCur are transformed into OP_Sequence opcode for the 584 ** iAutoidxCur cursor, in order to generate unique rowids for the 585 ** automatic index being generated. 586 */ 587 static void translateColumnToCopy( 588 Parse *pParse, /* Parsing context */ 589 int iStart, /* Translate from this opcode to the end */ 590 int iTabCur, /* OP_Column/OP_Rowid references to this table */ 591 int iRegister, /* The first column is in this register */ 592 int iAutoidxCur /* If non-zero, cursor of autoindex being generated */ 593 ){ 594 Vdbe *v = pParse->pVdbe; 595 VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart); 596 int iEnd = sqlite3VdbeCurrentAddr(v); 597 if( pParse->db->mallocFailed ) return; 598 for(; iStart<iEnd; iStart++, pOp++){ 599 if( pOp->p1!=iTabCur ) continue; 600 if( pOp->opcode==OP_Column ){ 601 pOp->opcode = OP_Copy; 602 pOp->p1 = pOp->p2 + iRegister; 603 pOp->p2 = pOp->p3; 604 pOp->p3 = 0; 605 }else if( pOp->opcode==OP_Rowid ){ 606 if( iAutoidxCur ){ 607 pOp->opcode = OP_Sequence; 608 pOp->p1 = iAutoidxCur; 609 }else{ 610 pOp->opcode = OP_Null; 611 pOp->p1 = 0; 612 pOp->p3 = 0; 613 } 614 } 615 } 616 } 617 618 /* 619 ** Two routines for printing the content of an sqlite3_index_info 620 ** structure. Used for testing and debugging only. If neither 621 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines 622 ** are no-ops. 623 */ 624 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) 625 static void whereTraceIndexInfoInputs(sqlite3_index_info *p){ 626 int i; 627 if( !sqlite3WhereTrace ) return; 628 for(i=0; i<p->nConstraint; i++){ 629 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", 630 i, 631 p->aConstraint[i].iColumn, 632 p->aConstraint[i].iTermOffset, 633 p->aConstraint[i].op, 634 p->aConstraint[i].usable); 635 } 636 for(i=0; i<p->nOrderBy; i++){ 637 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", 638 i, 639 p->aOrderBy[i].iColumn, 640 p->aOrderBy[i].desc); 641 } 642 } 643 static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){ 644 int i; 645 if( !sqlite3WhereTrace ) return; 646 for(i=0; i<p->nConstraint; i++){ 647 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", 648 i, 649 p->aConstraintUsage[i].argvIndex, 650 p->aConstraintUsage[i].omit); 651 } 652 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); 653 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); 654 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); 655 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); 656 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); 657 } 658 #else 659 #define whereTraceIndexInfoInputs(A) 660 #define whereTraceIndexInfoOutputs(A) 661 #endif 662 663 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 664 /* 665 ** Return TRUE if the WHERE clause term pTerm is of a form where it 666 ** could be used with an index to access pSrc, assuming an appropriate 667 ** index existed. 668 */ 669 static int termCanDriveIndex( 670 WhereTerm *pTerm, /* WHERE clause term to check */ 671 struct SrcList_item *pSrc, /* Table we are trying to access */ 672 Bitmask notReady /* Tables in outer loops of the join */ 673 ){ 674 char aff; 675 if( pTerm->leftCursor!=pSrc->iCursor ) return 0; 676 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0; 677 if( (pSrc->fg.jointype & JT_LEFT) 678 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) 679 && (pTerm->eOperator & WO_IS) 680 ){ 681 /* Cannot use an IS term from the WHERE clause as an index driver for 682 ** the RHS of a LEFT JOIN. Such a term can only be used if it is from 683 ** the ON clause. */ 684 return 0; 685 } 686 if( (pTerm->prereqRight & notReady)!=0 ) return 0; 687 if( pTerm->u.x.leftColumn<0 ) return 0; 688 aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity; 689 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; 690 testcase( pTerm->pExpr->op==TK_IS ); 691 return 1; 692 } 693 #endif 694 695 696 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 697 /* 698 ** Generate code to construct the Index object for an automatic index 699 ** and to set up the WhereLevel object pLevel so that the code generator 700 ** makes use of the automatic index. 701 */ 702 static void constructAutomaticIndex( 703 Parse *pParse, /* The parsing context */ 704 WhereClause *pWC, /* The WHERE clause */ 705 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ 706 Bitmask notReady, /* Mask of cursors that are not available */ 707 WhereLevel *pLevel /* Write new index here */ 708 ){ 709 int nKeyCol; /* Number of columns in the constructed index */ 710 WhereTerm *pTerm; /* A single term of the WHERE clause */ 711 WhereTerm *pWCEnd; /* End of pWC->a[] */ 712 Index *pIdx; /* Object describing the transient index */ 713 Vdbe *v; /* Prepared statement under construction */ 714 int addrInit; /* Address of the initialization bypass jump */ 715 Table *pTable; /* The table being indexed */ 716 int addrTop; /* Top of the index fill loop */ 717 int regRecord; /* Register holding an index record */ 718 int n; /* Column counter */ 719 int i; /* Loop counter */ 720 int mxBitCol; /* Maximum column in pSrc->colUsed */ 721 CollSeq *pColl; /* Collating sequence to on a column */ 722 WhereLoop *pLoop; /* The Loop object */ 723 char *zNotUsed; /* Extra space on the end of pIdx */ 724 Bitmask idxCols; /* Bitmap of columns used for indexing */ 725 Bitmask extraCols; /* Bitmap of additional columns */ 726 u8 sentWarning = 0; /* True if a warnning has been issued */ 727 Expr *pPartial = 0; /* Partial Index Expression */ 728 int iContinue = 0; /* Jump here to skip excluded rows */ 729 struct SrcList_item *pTabItem; /* FROM clause term being indexed */ 730 int addrCounter = 0; /* Address where integer counter is initialized */ 731 int regBase; /* Array of registers where record is assembled */ 732 733 /* Generate code to skip over the creation and initialization of the 734 ** transient index on 2nd and subsequent iterations of the loop. */ 735 v = pParse->pVdbe; 736 assert( v!=0 ); 737 addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 738 739 /* Count the number of columns that will be added to the index 740 ** and used to match WHERE clause constraints */ 741 nKeyCol = 0; 742 pTable = pSrc->pTab; 743 pWCEnd = &pWC->a[pWC->nTerm]; 744 pLoop = pLevel->pWLoop; 745 idxCols = 0; 746 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ 747 Expr *pExpr = pTerm->pExpr; 748 assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */ 749 || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */ 750 || pLoop->prereq!=0 ); /* table of a LEFT JOIN */ 751 if( pLoop->prereq==0 752 && (pTerm->wtFlags & TERM_VIRTUAL)==0 753 && !ExprHasProperty(pExpr, EP_FromJoin) 754 && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){ 755 pPartial = sqlite3ExprAnd(pParse, pPartial, 756 sqlite3ExprDup(pParse->db, pExpr, 0)); 757 } 758 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ 759 int iCol = pTerm->u.x.leftColumn; 760 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); 761 testcase( iCol==BMS ); 762 testcase( iCol==BMS-1 ); 763 if( !sentWarning ){ 764 sqlite3_log(SQLITE_WARNING_AUTOINDEX, 765 "automatic index on %s(%s)", pTable->zName, 766 pTable->aCol[iCol].zName); 767 sentWarning = 1; 768 } 769 if( (idxCols & cMask)==0 ){ 770 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){ 771 goto end_auto_index_create; 772 } 773 pLoop->aLTerm[nKeyCol++] = pTerm; 774 idxCols |= cMask; 775 } 776 } 777 } 778 assert( nKeyCol>0 ); 779 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; 780 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED 781 | WHERE_AUTO_INDEX; 782 783 /* Count the number of additional columns needed to create a 784 ** covering index. A "covering index" is an index that contains all 785 ** columns that are needed by the query. With a covering index, the 786 ** original table never needs to be accessed. Automatic indices must 787 ** be a covering index because the index will not be updated if the 788 ** original table changes and the index and table cannot both be used 789 ** if they go out of sync. 790 */ 791 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); 792 mxBitCol = MIN(BMS-1,pTable->nCol); 793 testcase( pTable->nCol==BMS-1 ); 794 testcase( pTable->nCol==BMS-2 ); 795 for(i=0; i<mxBitCol; i++){ 796 if( extraCols & MASKBIT(i) ) nKeyCol++; 797 } 798 if( pSrc->colUsed & MASKBIT(BMS-1) ){ 799 nKeyCol += pTable->nCol - BMS + 1; 800 } 801 802 /* Construct the Index object to describe this index */ 803 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); 804 if( pIdx==0 ) goto end_auto_index_create; 805 pLoop->u.btree.pIndex = pIdx; 806 pIdx->zName = "auto-index"; 807 pIdx->pTable = pTable; 808 n = 0; 809 idxCols = 0; 810 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ 811 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ 812 int iCol = pTerm->u.x.leftColumn; 813 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); 814 testcase( iCol==BMS-1 ); 815 testcase( iCol==BMS ); 816 if( (idxCols & cMask)==0 ){ 817 Expr *pX = pTerm->pExpr; 818 idxCols |= cMask; 819 pIdx->aiColumn[n] = pTerm->u.x.leftColumn; 820 pColl = sqlite3ExprCompareCollSeq(pParse, pX); 821 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */ 822 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; 823 n++; 824 } 825 } 826 } 827 assert( (u32)n==pLoop->u.btree.nEq ); 828 829 /* Add additional columns needed to make the automatic index into 830 ** a covering index */ 831 for(i=0; i<mxBitCol; i++){ 832 if( extraCols & MASKBIT(i) ){ 833 pIdx->aiColumn[n] = i; 834 pIdx->azColl[n] = sqlite3StrBINARY; 835 n++; 836 } 837 } 838 if( pSrc->colUsed & MASKBIT(BMS-1) ){ 839 for(i=BMS-1; i<pTable->nCol; i++){ 840 pIdx->aiColumn[n] = i; 841 pIdx->azColl[n] = sqlite3StrBINARY; 842 n++; 843 } 844 } 845 assert( n==nKeyCol ); 846 pIdx->aiColumn[n] = XN_ROWID; 847 pIdx->azColl[n] = sqlite3StrBINARY; 848 849 /* Create the automatic index */ 850 assert( pLevel->iIdxCur>=0 ); 851 pLevel->iIdxCur = pParse->nTab++; 852 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); 853 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 854 VdbeComment((v, "for %s", pTable->zName)); 855 856 /* Fill the automatic index with content */ 857 pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom]; 858 if( pTabItem->fg.viaCoroutine ){ 859 int regYield = pTabItem->regReturn; 860 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0); 861 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); 862 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield); 863 VdbeCoverage(v); 864 VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); 865 }else{ 866 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); 867 } 868 if( pPartial ){ 869 iContinue = sqlite3VdbeMakeLabel(pParse); 870 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); 871 pLoop->wsFlags |= WHERE_PARTIALIDX; 872 } 873 regRecord = sqlite3GetTempReg(pParse); 874 regBase = sqlite3GenerateIndexKey( 875 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 876 ); 877 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); 878 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 879 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue); 880 if( pTabItem->fg.viaCoroutine ){ 881 sqlite3VdbeChangeP2(v, addrCounter, regBase+n); 882 testcase( pParse->db->mallocFailed ); 883 assert( pLevel->iIdxCur>0 ); 884 translateColumnToCopy(pParse, addrTop, pLevel->iTabCur, 885 pTabItem->regResult, pLevel->iIdxCur); 886 sqlite3VdbeGoto(v, addrTop); 887 pTabItem->fg.viaCoroutine = 0; 888 }else{ 889 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); 890 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); 891 } 892 sqlite3VdbeJumpHere(v, addrTop); 893 sqlite3ReleaseTempReg(pParse, regRecord); 894 895 /* Jump here when skipping the initialization */ 896 sqlite3VdbeJumpHere(v, addrInit); 897 898 end_auto_index_create: 899 sqlite3ExprDelete(pParse->db, pPartial); 900 } 901 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 902 903 #ifndef SQLITE_OMIT_VIRTUALTABLE 904 /* 905 ** Allocate and populate an sqlite3_index_info structure. It is the 906 ** responsibility of the caller to eventually release the structure 907 ** by passing the pointer returned by this function to sqlite3_free(). 908 */ 909 static sqlite3_index_info *allocateIndexInfo( 910 Parse *pParse, /* The parsing context */ 911 WhereClause *pWC, /* The WHERE clause being analyzed */ 912 Bitmask mUnusable, /* Ignore terms with these prereqs */ 913 struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */ 914 ExprList *pOrderBy, /* The ORDER BY clause */ 915 u16 *pmNoOmit /* Mask of terms not to omit */ 916 ){ 917 int i, j; 918 int nTerm; 919 struct sqlite3_index_constraint *pIdxCons; 920 struct sqlite3_index_orderby *pIdxOrderBy; 921 struct sqlite3_index_constraint_usage *pUsage; 922 struct HiddenIndexInfo *pHidden; 923 WhereTerm *pTerm; 924 int nOrderBy; 925 sqlite3_index_info *pIdxInfo; 926 u16 mNoOmit = 0; 927 928 /* Count the number of possible WHERE clause constraints referring 929 ** to this virtual table */ 930 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 931 if( pTerm->leftCursor != pSrc->iCursor ) continue; 932 if( pTerm->prereqRight & mUnusable ) continue; 933 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); 934 testcase( pTerm->eOperator & WO_IN ); 935 testcase( pTerm->eOperator & WO_ISNULL ); 936 testcase( pTerm->eOperator & WO_IS ); 937 testcase( pTerm->eOperator & WO_ALL ); 938 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue; 939 if( pTerm->wtFlags & TERM_VNULL ) continue; 940 assert( pTerm->u.x.leftColumn>=(-1) ); 941 nTerm++; 942 } 943 944 /* If the ORDER BY clause contains only columns in the current 945 ** virtual table then allocate space for the aOrderBy part of 946 ** the sqlite3_index_info structure. 947 */ 948 nOrderBy = 0; 949 if( pOrderBy ){ 950 int n = pOrderBy->nExpr; 951 for(i=0; i<n; i++){ 952 Expr *pExpr = pOrderBy->a[i].pExpr; 953 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; 954 if( pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL ) break; 955 } 956 if( i==n){ 957 nOrderBy = n; 958 } 959 } 960 961 /* Allocate the sqlite3_index_info structure 962 */ 963 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) 964 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm 965 + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) ); 966 if( pIdxInfo==0 ){ 967 sqlite3ErrorMsg(pParse, "out of memory"); 968 return 0; 969 } 970 pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1]; 971 pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1]; 972 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; 973 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; 974 pIdxInfo->nOrderBy = nOrderBy; 975 pIdxInfo->aConstraint = pIdxCons; 976 pIdxInfo->aOrderBy = pIdxOrderBy; 977 pIdxInfo->aConstraintUsage = pUsage; 978 pHidden->pWC = pWC; 979 pHidden->pParse = pParse; 980 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 981 u16 op; 982 if( pTerm->leftCursor != pSrc->iCursor ) continue; 983 if( pTerm->prereqRight & mUnusable ) continue; 984 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); 985 testcase( pTerm->eOperator & WO_IN ); 986 testcase( pTerm->eOperator & WO_IS ); 987 testcase( pTerm->eOperator & WO_ISNULL ); 988 testcase( pTerm->eOperator & WO_ALL ); 989 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue; 990 if( pTerm->wtFlags & TERM_VNULL ) continue; 991 992 /* tag-20191211-002: WHERE-clause constraints are not useful to the 993 ** right-hand table of a LEFT JOIN. See tag-20191211-001 for the 994 ** equivalent restriction for ordinary tables. */ 995 if( (pSrc->fg.jointype & JT_LEFT)!=0 996 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) 997 ){ 998 continue; 999 } 1000 assert( pTerm->u.x.leftColumn>=(-1) ); 1001 pIdxCons[j].iColumn = pTerm->u.x.leftColumn; 1002 pIdxCons[j].iTermOffset = i; 1003 op = pTerm->eOperator & WO_ALL; 1004 if( op==WO_IN ) op = WO_EQ; 1005 if( op==WO_AUX ){ 1006 pIdxCons[j].op = pTerm->eMatchOp; 1007 }else if( op & (WO_ISNULL|WO_IS) ){ 1008 if( op==WO_ISNULL ){ 1009 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL; 1010 }else{ 1011 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS; 1012 } 1013 }else{ 1014 pIdxCons[j].op = (u8)op; 1015 /* The direct assignment in the previous line is possible only because 1016 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The 1017 ** following asserts verify this fact. */ 1018 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); 1019 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); 1020 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); 1021 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); 1022 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); 1023 assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) ); 1024 1025 if( op & (WO_LT|WO_LE|WO_GT|WO_GE) 1026 && sqlite3ExprIsVector(pTerm->pExpr->pRight) 1027 ){ 1028 testcase( j!=i ); 1029 if( j<16 ) mNoOmit |= (1 << j); 1030 if( op==WO_LT ) pIdxCons[j].op = WO_LE; 1031 if( op==WO_GT ) pIdxCons[j].op = WO_GE; 1032 } 1033 } 1034 1035 j++; 1036 } 1037 pIdxInfo->nConstraint = j; 1038 for(i=0; i<nOrderBy; i++){ 1039 Expr *pExpr = pOrderBy->a[i].pExpr; 1040 pIdxOrderBy[i].iColumn = pExpr->iColumn; 1041 pIdxOrderBy[i].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC; 1042 } 1043 1044 *pmNoOmit = mNoOmit; 1045 return pIdxInfo; 1046 } 1047 1048 /* 1049 ** The table object reference passed as the second argument to this function 1050 ** must represent a virtual table. This function invokes the xBestIndex() 1051 ** method of the virtual table with the sqlite3_index_info object that 1052 ** comes in as the 3rd argument to this function. 1053 ** 1054 ** If an error occurs, pParse is populated with an error message and an 1055 ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from 1056 ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that 1057 ** the current configuration of "unusable" flags in sqlite3_index_info can 1058 ** not result in a valid plan. 1059 ** 1060 ** Whether or not an error is returned, it is the responsibility of the 1061 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates 1062 ** that this is required. 1063 */ 1064 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ 1065 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; 1066 int rc; 1067 1068 whereTraceIndexInfoInputs(p); 1069 rc = pVtab->pModule->xBestIndex(pVtab, p); 1070 whereTraceIndexInfoOutputs(p); 1071 1072 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){ 1073 if( rc==SQLITE_NOMEM ){ 1074 sqlite3OomFault(pParse->db); 1075 }else if( !pVtab->zErrMsg ){ 1076 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); 1077 }else{ 1078 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); 1079 } 1080 } 1081 sqlite3_free(pVtab->zErrMsg); 1082 pVtab->zErrMsg = 0; 1083 return rc; 1084 } 1085 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ 1086 1087 #ifdef SQLITE_ENABLE_STAT4 1088 /* 1089 ** Estimate the location of a particular key among all keys in an 1090 ** index. Store the results in aStat as follows: 1091 ** 1092 ** aStat[0] Est. number of rows less than pRec 1093 ** aStat[1] Est. number of rows equal to pRec 1094 ** 1095 ** Return the index of the sample that is the smallest sample that 1096 ** is greater than or equal to pRec. Note that this index is not an index 1097 ** into the aSample[] array - it is an index into a virtual set of samples 1098 ** based on the contents of aSample[] and the number of fields in record 1099 ** pRec. 1100 */ 1101 static int whereKeyStats( 1102 Parse *pParse, /* Database connection */ 1103 Index *pIdx, /* Index to consider domain of */ 1104 UnpackedRecord *pRec, /* Vector of values to consider */ 1105 int roundUp, /* Round up if true. Round down if false */ 1106 tRowcnt *aStat /* OUT: stats written here */ 1107 ){ 1108 IndexSample *aSample = pIdx->aSample; 1109 int iCol; /* Index of required stats in anEq[] etc. */ 1110 int i; /* Index of first sample >= pRec */ 1111 int iSample; /* Smallest sample larger than or equal to pRec */ 1112 int iMin = 0; /* Smallest sample not yet tested */ 1113 int iTest; /* Next sample to test */ 1114 int res; /* Result of comparison operation */ 1115 int nField; /* Number of fields in pRec */ 1116 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */ 1117 1118 #ifndef SQLITE_DEBUG 1119 UNUSED_PARAMETER( pParse ); 1120 #endif 1121 assert( pRec!=0 ); 1122 assert( pIdx->nSample>0 ); 1123 assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol ); 1124 1125 /* Do a binary search to find the first sample greater than or equal 1126 ** to pRec. If pRec contains a single field, the set of samples to search 1127 ** is simply the aSample[] array. If the samples in aSample[] contain more 1128 ** than one fields, all fields following the first are ignored. 1129 ** 1130 ** If pRec contains N fields, where N is more than one, then as well as the 1131 ** samples in aSample[] (truncated to N fields), the search also has to 1132 ** consider prefixes of those samples. For example, if the set of samples 1133 ** in aSample is: 1134 ** 1135 ** aSample[0] = (a, 5) 1136 ** aSample[1] = (a, 10) 1137 ** aSample[2] = (b, 5) 1138 ** aSample[3] = (c, 100) 1139 ** aSample[4] = (c, 105) 1140 ** 1141 ** Then the search space should ideally be the samples above and the 1142 ** unique prefixes [a], [b] and [c]. But since that is hard to organize, 1143 ** the code actually searches this set: 1144 ** 1145 ** 0: (a) 1146 ** 1: (a, 5) 1147 ** 2: (a, 10) 1148 ** 3: (a, 10) 1149 ** 4: (b) 1150 ** 5: (b, 5) 1151 ** 6: (c) 1152 ** 7: (c, 100) 1153 ** 8: (c, 105) 1154 ** 9: (c, 105) 1155 ** 1156 ** For each sample in the aSample[] array, N samples are present in the 1157 ** effective sample array. In the above, samples 0 and 1 are based on 1158 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc. 1159 ** 1160 ** Often, sample i of each block of N effective samples has (i+1) fields. 1161 ** Except, each sample may be extended to ensure that it is greater than or 1162 ** equal to the previous sample in the array. For example, in the above, 1163 ** sample 2 is the first sample of a block of N samples, so at first it 1164 ** appears that it should be 1 field in size. However, that would make it 1165 ** smaller than sample 1, so the binary search would not work. As a result, 1166 ** it is extended to two fields. The duplicates that this creates do not 1167 ** cause any problems. 1168 */ 1169 nField = pRec->nField; 1170 iCol = 0; 1171 iSample = pIdx->nSample * nField; 1172 do{ 1173 int iSamp; /* Index in aSample[] of test sample */ 1174 int n; /* Number of fields in test sample */ 1175 1176 iTest = (iMin+iSample)/2; 1177 iSamp = iTest / nField; 1178 if( iSamp>0 ){ 1179 /* The proposed effective sample is a prefix of sample aSample[iSamp]. 1180 ** Specifically, the shortest prefix of at least (1 + iTest%nField) 1181 ** fields that is greater than the previous effective sample. */ 1182 for(n=(iTest % nField) + 1; n<nField; n++){ 1183 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break; 1184 } 1185 }else{ 1186 n = iTest + 1; 1187 } 1188 1189 pRec->nField = n; 1190 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); 1191 if( res<0 ){ 1192 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1]; 1193 iMin = iTest+1; 1194 }else if( res==0 && n<nField ){ 1195 iLower = aSample[iSamp].anLt[n-1]; 1196 iMin = iTest+1; 1197 res = -1; 1198 }else{ 1199 iSample = iTest; 1200 iCol = n-1; 1201 } 1202 }while( res && iMin<iSample ); 1203 i = iSample / nField; 1204 1205 #ifdef SQLITE_DEBUG 1206 /* The following assert statements check that the binary search code 1207 ** above found the right answer. This block serves no purpose other 1208 ** than to invoke the asserts. */ 1209 if( pParse->db->mallocFailed==0 ){ 1210 if( res==0 ){ 1211 /* If (res==0) is true, then pRec must be equal to sample i. */ 1212 assert( i<pIdx->nSample ); 1213 assert( iCol==nField-1 ); 1214 pRec->nField = nField; 1215 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) 1216 || pParse->db->mallocFailed 1217 ); 1218 }else{ 1219 /* Unless i==pIdx->nSample, indicating that pRec is larger than 1220 ** all samples in the aSample[] array, pRec must be smaller than the 1221 ** (iCol+1) field prefix of sample i. */ 1222 assert( i<=pIdx->nSample && i>=0 ); 1223 pRec->nField = iCol+1; 1224 assert( i==pIdx->nSample 1225 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 1226 || pParse->db->mallocFailed ); 1227 1228 /* if i==0 and iCol==0, then record pRec is smaller than all samples 1229 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must 1230 ** be greater than or equal to the (iCol) field prefix of sample i. 1231 ** If (i>0), then pRec must also be greater than sample (i-1). */ 1232 if( iCol>0 ){ 1233 pRec->nField = iCol; 1234 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 1235 || pParse->db->mallocFailed ); 1236 } 1237 if( i>0 ){ 1238 pRec->nField = nField; 1239 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 1240 || pParse->db->mallocFailed ); 1241 } 1242 } 1243 } 1244 #endif /* ifdef SQLITE_DEBUG */ 1245 1246 if( res==0 ){ 1247 /* Record pRec is equal to sample i */ 1248 assert( iCol==nField-1 ); 1249 aStat[0] = aSample[i].anLt[iCol]; 1250 aStat[1] = aSample[i].anEq[iCol]; 1251 }else{ 1252 /* At this point, the (iCol+1) field prefix of aSample[i] is the first 1253 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec 1254 ** is larger than all samples in the array. */ 1255 tRowcnt iUpper, iGap; 1256 if( i>=pIdx->nSample ){ 1257 iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]); 1258 }else{ 1259 iUpper = aSample[i].anLt[iCol]; 1260 } 1261 1262 if( iLower>=iUpper ){ 1263 iGap = 0; 1264 }else{ 1265 iGap = iUpper - iLower; 1266 } 1267 if( roundUp ){ 1268 iGap = (iGap*2)/3; 1269 }else{ 1270 iGap = iGap/3; 1271 } 1272 aStat[0] = iLower + iGap; 1273 aStat[1] = pIdx->aAvgEq[nField-1]; 1274 } 1275 1276 /* Restore the pRec->nField value before returning. */ 1277 pRec->nField = nField; 1278 return i; 1279 } 1280 #endif /* SQLITE_ENABLE_STAT4 */ 1281 1282 /* 1283 ** If it is not NULL, pTerm is a term that provides an upper or lower 1284 ** bound on a range scan. Without considering pTerm, it is estimated 1285 ** that the scan will visit nNew rows. This function returns the number 1286 ** estimated to be visited after taking pTerm into account. 1287 ** 1288 ** If the user explicitly specified a likelihood() value for this term, 1289 ** then the return value is the likelihood multiplied by the number of 1290 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term 1291 ** has a likelihood of 0.50, and any other term a likelihood of 0.25. 1292 */ 1293 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ 1294 LogEst nRet = nNew; 1295 if( pTerm ){ 1296 if( pTerm->truthProb<=0 ){ 1297 nRet += pTerm->truthProb; 1298 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ 1299 nRet -= 20; assert( 20==sqlite3LogEst(4) ); 1300 } 1301 } 1302 return nRet; 1303 } 1304 1305 1306 #ifdef SQLITE_ENABLE_STAT4 1307 /* 1308 ** Return the affinity for a single column of an index. 1309 */ 1310 char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){ 1311 assert( iCol>=0 && iCol<pIdx->nColumn ); 1312 if( !pIdx->zColAff ){ 1313 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; 1314 } 1315 assert( pIdx->zColAff[iCol]!=0 ); 1316 return pIdx->zColAff[iCol]; 1317 } 1318 #endif 1319 1320 1321 #ifdef SQLITE_ENABLE_STAT4 1322 /* 1323 ** This function is called to estimate the number of rows visited by a 1324 ** range-scan on a skip-scan index. For example: 1325 ** 1326 ** CREATE INDEX i1 ON t1(a, b, c); 1327 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; 1328 ** 1329 ** Value pLoop->nOut is currently set to the estimated number of rows 1330 ** visited for scanning (a=? AND b=?). This function reduces that estimate 1331 ** by some factor to account for the (c BETWEEN ? AND ?) expression based 1332 ** on the stat4 data for the index. this scan will be peformed multiple 1333 ** times (once for each (a,b) combination that matches a=?) is dealt with 1334 ** by the caller. 1335 ** 1336 ** It does this by scanning through all stat4 samples, comparing values 1337 ** extracted from pLower and pUpper with the corresponding column in each 1338 ** sample. If L and U are the number of samples found to be less than or 1339 ** equal to the values extracted from pLower and pUpper respectively, and 1340 ** N is the total number of samples, the pLoop->nOut value is adjusted 1341 ** as follows: 1342 ** 1343 ** nOut = nOut * ( min(U - L, 1) / N ) 1344 ** 1345 ** If pLower is NULL, or a value cannot be extracted from the term, L is 1346 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it, 1347 ** U is set to N. 1348 ** 1349 ** Normally, this function sets *pbDone to 1 before returning. However, 1350 ** if no value can be extracted from either pLower or pUpper (and so the 1351 ** estimate of the number of rows delivered remains unchanged), *pbDone 1352 ** is left as is. 1353 ** 1354 ** If an error occurs, an SQLite error code is returned. Otherwise, 1355 ** SQLITE_OK. 1356 */ 1357 static int whereRangeSkipScanEst( 1358 Parse *pParse, /* Parsing & code generating context */ 1359 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ 1360 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ 1361 WhereLoop *pLoop, /* Update the .nOut value of this loop */ 1362 int *pbDone /* Set to true if at least one expr. value extracted */ 1363 ){ 1364 Index *p = pLoop->u.btree.pIndex; 1365 int nEq = pLoop->u.btree.nEq; 1366 sqlite3 *db = pParse->db; 1367 int nLower = -1; 1368 int nUpper = p->nSample+1; 1369 int rc = SQLITE_OK; 1370 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); 1371 CollSeq *pColl; 1372 1373 sqlite3_value *p1 = 0; /* Value extracted from pLower */ 1374 sqlite3_value *p2 = 0; /* Value extracted from pUpper */ 1375 sqlite3_value *pVal = 0; /* Value extracted from record */ 1376 1377 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); 1378 if( pLower ){ 1379 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); 1380 nLower = 0; 1381 } 1382 if( pUpper && rc==SQLITE_OK ){ 1383 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); 1384 nUpper = p2 ? 0 : p->nSample; 1385 } 1386 1387 if( p1 || p2 ){ 1388 int i; 1389 int nDiff; 1390 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){ 1391 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); 1392 if( rc==SQLITE_OK && p1 ){ 1393 int res = sqlite3MemCompare(p1, pVal, pColl); 1394 if( res>=0 ) nLower++; 1395 } 1396 if( rc==SQLITE_OK && p2 ){ 1397 int res = sqlite3MemCompare(p2, pVal, pColl); 1398 if( res>=0 ) nUpper++; 1399 } 1400 } 1401 nDiff = (nUpper - nLower); 1402 if( nDiff<=0 ) nDiff = 1; 1403 1404 /* If there is both an upper and lower bound specified, and the 1405 ** comparisons indicate that they are close together, use the fallback 1406 ** method (assume that the scan visits 1/64 of the rows) for estimating 1407 ** the number of rows visited. Otherwise, estimate the number of rows 1408 ** using the method described in the header comment for this function. */ 1409 if( nDiff!=1 || pUpper==0 || pLower==0 ){ 1410 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); 1411 pLoop->nOut -= nAdjust; 1412 *pbDone = 1; 1413 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", 1414 nLower, nUpper, nAdjust*-1, pLoop->nOut)); 1415 } 1416 1417 }else{ 1418 assert( *pbDone==0 ); 1419 } 1420 1421 sqlite3ValueFree(p1); 1422 sqlite3ValueFree(p2); 1423 sqlite3ValueFree(pVal); 1424 1425 return rc; 1426 } 1427 #endif /* SQLITE_ENABLE_STAT4 */ 1428 1429 /* 1430 ** This function is used to estimate the number of rows that will be visited 1431 ** by scanning an index for a range of values. The range may have an upper 1432 ** bound, a lower bound, or both. The WHERE clause terms that set the upper 1433 ** and lower bounds are represented by pLower and pUpper respectively. For 1434 ** example, assuming that index p is on t1(a): 1435 ** 1436 ** ... FROM t1 WHERE a > ? AND a < ? ... 1437 ** |_____| |_____| 1438 ** | | 1439 ** pLower pUpper 1440 ** 1441 ** If either of the upper or lower bound is not present, then NULL is passed in 1442 ** place of the corresponding WhereTerm. 1443 ** 1444 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index 1445 ** column subject to the range constraint. Or, equivalently, the number of 1446 ** equality constraints optimized by the proposed index scan. For example, 1447 ** assuming index p is on t1(a, b), and the SQL query is: 1448 ** 1449 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... 1450 ** 1451 ** then nEq is set to 1 (as the range restricted column, b, is the second 1452 ** left-most column of the index). Or, if the query is: 1453 ** 1454 ** ... FROM t1 WHERE a > ? AND a < ? ... 1455 ** 1456 ** then nEq is set to 0. 1457 ** 1458 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the 1459 ** number of rows that the index scan is expected to visit without 1460 ** considering the range constraints. If nEq is 0, then *pnOut is the number of 1461 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) 1462 ** to account for the range constraints pLower and pUpper. 1463 ** 1464 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be 1465 ** used, a single range inequality reduces the search space by a factor of 4. 1466 ** and a pair of constraints (x>? AND x<?) reduces the expected number of 1467 ** rows visited by a factor of 64. 1468 */ 1469 static int whereRangeScanEst( 1470 Parse *pParse, /* Parsing & code generating context */ 1471 WhereLoopBuilder *pBuilder, 1472 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ 1473 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ 1474 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ 1475 ){ 1476 int rc = SQLITE_OK; 1477 int nOut = pLoop->nOut; 1478 LogEst nNew; 1479 1480 #ifdef SQLITE_ENABLE_STAT4 1481 Index *p = pLoop->u.btree.pIndex; 1482 int nEq = pLoop->u.btree.nEq; 1483 1484 if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol) 1485 && OptimizationEnabled(pParse->db, SQLITE_Stat4) 1486 ){ 1487 if( nEq==pBuilder->nRecValid ){ 1488 UnpackedRecord *pRec = pBuilder->pRec; 1489 tRowcnt a[2]; 1490 int nBtm = pLoop->u.btree.nBtm; 1491 int nTop = pLoop->u.btree.nTop; 1492 1493 /* Variable iLower will be set to the estimate of the number of rows in 1494 ** the index that are less than the lower bound of the range query. The 1495 ** lower bound being the concatenation of $P and $L, where $P is the 1496 ** key-prefix formed by the nEq values matched against the nEq left-most 1497 ** columns of the index, and $L is the value in pLower. 1498 ** 1499 ** Or, if pLower is NULL or $L cannot be extracted from it (because it 1500 ** is not a simple variable or literal value), the lower bound of the 1501 ** range is $P. Due to a quirk in the way whereKeyStats() works, even 1502 ** if $L is available, whereKeyStats() is called for both ($P) and 1503 ** ($P:$L) and the larger of the two returned values is used. 1504 ** 1505 ** Similarly, iUpper is to be set to the estimate of the number of rows 1506 ** less than the upper bound of the range query. Where the upper bound 1507 ** is either ($P) or ($P:$U). Again, even if $U is available, both values 1508 ** of iUpper are requested of whereKeyStats() and the smaller used. 1509 ** 1510 ** The number of rows between the two bounds is then just iUpper-iLower. 1511 */ 1512 tRowcnt iLower; /* Rows less than the lower bound */ 1513 tRowcnt iUpper; /* Rows less than the upper bound */ 1514 int iLwrIdx = -2; /* aSample[] for the lower bound */ 1515 int iUprIdx = -1; /* aSample[] for the upper bound */ 1516 1517 if( pRec ){ 1518 testcase( pRec->nField!=pBuilder->nRecValid ); 1519 pRec->nField = pBuilder->nRecValid; 1520 } 1521 /* Determine iLower and iUpper using ($P) only. */ 1522 if( nEq==0 ){ 1523 iLower = 0; 1524 iUpper = p->nRowEst0; 1525 }else{ 1526 /* Note: this call could be optimized away - since the same values must 1527 ** have been requested when testing key $P in whereEqualScanEst(). */ 1528 whereKeyStats(pParse, p, pRec, 0, a); 1529 iLower = a[0]; 1530 iUpper = a[0] + a[1]; 1531 } 1532 1533 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); 1534 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); 1535 assert( p->aSortOrder!=0 ); 1536 if( p->aSortOrder[nEq] ){ 1537 /* The roles of pLower and pUpper are swapped for a DESC index */ 1538 SWAP(WhereTerm*, pLower, pUpper); 1539 SWAP(int, nBtm, nTop); 1540 } 1541 1542 /* If possible, improve on the iLower estimate using ($P:$L). */ 1543 if( pLower ){ 1544 int n; /* Values extracted from pExpr */ 1545 Expr *pExpr = pLower->pExpr->pRight; 1546 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); 1547 if( rc==SQLITE_OK && n ){ 1548 tRowcnt iNew; 1549 u16 mask = WO_GT|WO_LE; 1550 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); 1551 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); 1552 iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0); 1553 if( iNew>iLower ) iLower = iNew; 1554 nOut--; 1555 pLower = 0; 1556 } 1557 } 1558 1559 /* If possible, improve on the iUpper estimate using ($P:$U). */ 1560 if( pUpper ){ 1561 int n; /* Values extracted from pExpr */ 1562 Expr *pExpr = pUpper->pExpr->pRight; 1563 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); 1564 if( rc==SQLITE_OK && n ){ 1565 tRowcnt iNew; 1566 u16 mask = WO_GT|WO_LE; 1567 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); 1568 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); 1569 iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0); 1570 if( iNew<iUpper ) iUpper = iNew; 1571 nOut--; 1572 pUpper = 0; 1573 } 1574 } 1575 1576 pBuilder->pRec = pRec; 1577 if( rc==SQLITE_OK ){ 1578 if( iUpper>iLower ){ 1579 nNew = sqlite3LogEst(iUpper - iLower); 1580 /* TUNING: If both iUpper and iLower are derived from the same 1581 ** sample, then assume they are 4x more selective. This brings 1582 ** the estimated selectivity more in line with what it would be 1583 ** if estimated without the use of STAT4 tables. */ 1584 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) ); 1585 }else{ 1586 nNew = 10; assert( 10==sqlite3LogEst(2) ); 1587 } 1588 if( nNew<nOut ){ 1589 nOut = nNew; 1590 } 1591 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n", 1592 (u32)iLower, (u32)iUpper, nOut)); 1593 } 1594 }else{ 1595 int bDone = 0; 1596 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone); 1597 if( bDone ) return rc; 1598 } 1599 } 1600 #else 1601 UNUSED_PARAMETER(pParse); 1602 UNUSED_PARAMETER(pBuilder); 1603 assert( pLower || pUpper ); 1604 #endif 1605 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 ); 1606 nNew = whereRangeAdjust(pLower, nOut); 1607 nNew = whereRangeAdjust(pUpper, nNew); 1608 1609 /* TUNING: If there is both an upper and lower limit and neither limit 1610 ** has an application-defined likelihood(), assume the range is 1611 ** reduced by an additional 75%. This means that, by default, an open-ended 1612 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the 1613 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to 1614 ** match 1/64 of the index. */ 1615 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){ 1616 nNew -= 20; 1617 } 1618 1619 nOut -= (pLower!=0) + (pUpper!=0); 1620 if( nNew<10 ) nNew = 10; 1621 if( nNew<nOut ) nOut = nNew; 1622 #if defined(WHERETRACE_ENABLED) 1623 if( pLoop->nOut>nOut ){ 1624 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n", 1625 pLoop->nOut, nOut)); 1626 } 1627 #endif 1628 pLoop->nOut = (LogEst)nOut; 1629 return rc; 1630 } 1631 1632 #ifdef SQLITE_ENABLE_STAT4 1633 /* 1634 ** Estimate the number of rows that will be returned based on 1635 ** an equality constraint x=VALUE and where that VALUE occurs in 1636 ** the histogram data. This only works when x is the left-most 1637 ** column of an index and sqlite_stat4 histogram data is available 1638 ** for that index. When pExpr==NULL that means the constraint is 1639 ** "x IS NULL" instead of "x=VALUE". 1640 ** 1641 ** Write the estimated row count into *pnRow and return SQLITE_OK. 1642 ** If unable to make an estimate, leave *pnRow unchanged and return 1643 ** non-zero. 1644 ** 1645 ** This routine can fail if it is unable to load a collating sequence 1646 ** required for string comparison, or if unable to allocate memory 1647 ** for a UTF conversion required for comparison. The error is stored 1648 ** in the pParse structure. 1649 */ 1650 static int whereEqualScanEst( 1651 Parse *pParse, /* Parsing & code generating context */ 1652 WhereLoopBuilder *pBuilder, 1653 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ 1654 tRowcnt *pnRow /* Write the revised row estimate here */ 1655 ){ 1656 Index *p = pBuilder->pNew->u.btree.pIndex; 1657 int nEq = pBuilder->pNew->u.btree.nEq; 1658 UnpackedRecord *pRec = pBuilder->pRec; 1659 int rc; /* Subfunction return code */ 1660 tRowcnt a[2]; /* Statistics */ 1661 int bOk; 1662 1663 assert( nEq>=1 ); 1664 assert( nEq<=p->nColumn ); 1665 assert( p->aSample!=0 ); 1666 assert( p->nSample>0 ); 1667 assert( pBuilder->nRecValid<nEq ); 1668 1669 /* If values are not available for all fields of the index to the left 1670 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */ 1671 if( pBuilder->nRecValid<(nEq-1) ){ 1672 return SQLITE_NOTFOUND; 1673 } 1674 1675 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() 1676 ** below would return the same value. */ 1677 if( nEq>=p->nColumn ){ 1678 *pnRow = 1; 1679 return SQLITE_OK; 1680 } 1681 1682 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk); 1683 pBuilder->pRec = pRec; 1684 if( rc!=SQLITE_OK ) return rc; 1685 if( bOk==0 ) return SQLITE_NOTFOUND; 1686 pBuilder->nRecValid = nEq; 1687 1688 whereKeyStats(pParse, p, pRec, 0, a); 1689 WHERETRACE(0x10,("equality scan regions %s(%d): %d\n", 1690 p->zName, nEq-1, (int)a[1])); 1691 *pnRow = a[1]; 1692 1693 return rc; 1694 } 1695 #endif /* SQLITE_ENABLE_STAT4 */ 1696 1697 #ifdef SQLITE_ENABLE_STAT4 1698 /* 1699 ** Estimate the number of rows that will be returned based on 1700 ** an IN constraint where the right-hand side of the IN operator 1701 ** is a list of values. Example: 1702 ** 1703 ** WHERE x IN (1,2,3,4) 1704 ** 1705 ** Write the estimated row count into *pnRow and return SQLITE_OK. 1706 ** If unable to make an estimate, leave *pnRow unchanged and return 1707 ** non-zero. 1708 ** 1709 ** This routine can fail if it is unable to load a collating sequence 1710 ** required for string comparison, or if unable to allocate memory 1711 ** for a UTF conversion required for comparison. The error is stored 1712 ** in the pParse structure. 1713 */ 1714 static int whereInScanEst( 1715 Parse *pParse, /* Parsing & code generating context */ 1716 WhereLoopBuilder *pBuilder, 1717 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ 1718 tRowcnt *pnRow /* Write the revised row estimate here */ 1719 ){ 1720 Index *p = pBuilder->pNew->u.btree.pIndex; 1721 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]); 1722 int nRecValid = pBuilder->nRecValid; 1723 int rc = SQLITE_OK; /* Subfunction return code */ 1724 tRowcnt nEst; /* Number of rows for a single term */ 1725 tRowcnt nRowEst = 0; /* New estimate of the number of rows */ 1726 int i; /* Loop counter */ 1727 1728 assert( p->aSample!=0 ); 1729 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){ 1730 nEst = nRow0; 1731 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); 1732 nRowEst += nEst; 1733 pBuilder->nRecValid = nRecValid; 1734 } 1735 1736 if( rc==SQLITE_OK ){ 1737 if( nRowEst > nRow0 ) nRowEst = nRow0; 1738 *pnRow = nRowEst; 1739 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst)); 1740 } 1741 assert( pBuilder->nRecValid==nRecValid ); 1742 return rc; 1743 } 1744 #endif /* SQLITE_ENABLE_STAT4 */ 1745 1746 1747 #ifdef WHERETRACE_ENABLED 1748 /* 1749 ** Print the content of a WhereTerm object 1750 */ 1751 void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){ 1752 if( pTerm==0 ){ 1753 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); 1754 }else{ 1755 char zType[8]; 1756 char zLeft[50]; 1757 memcpy(zType, "....", 5); 1758 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; 1759 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; 1760 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; 1761 if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C'; 1762 if( pTerm->eOperator & WO_SINGLE ){ 1763 sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", 1764 pTerm->leftCursor, pTerm->u.x.leftColumn); 1765 }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){ 1766 sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx", 1767 pTerm->u.pOrInfo->indexable); 1768 }else{ 1769 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); 1770 } 1771 sqlite3DebugPrintf( 1772 "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x", 1773 iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags); 1774 /* The 0x10000 .wheretrace flag causes extra information to be 1775 ** shown about each Term */ 1776 if( sqlite3WhereTrace & 0x10000 ){ 1777 sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx", 1778 pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight); 1779 } 1780 if( pTerm->u.x.iField ){ 1781 sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField); 1782 } 1783 if( pTerm->iParent>=0 ){ 1784 sqlite3DebugPrintf(" iParent=%d", pTerm->iParent); 1785 } 1786 sqlite3DebugPrintf("\n"); 1787 sqlite3TreeViewExpr(0, pTerm->pExpr, 0); 1788 } 1789 } 1790 #endif 1791 1792 #ifdef WHERETRACE_ENABLED 1793 /* 1794 ** Show the complete content of a WhereClause 1795 */ 1796 void sqlite3WhereClausePrint(WhereClause *pWC){ 1797 int i; 1798 for(i=0; i<pWC->nTerm; i++){ 1799 sqlite3WhereTermPrint(&pWC->a[i], i); 1800 } 1801 } 1802 #endif 1803 1804 #ifdef WHERETRACE_ENABLED 1805 /* 1806 ** Print a WhereLoop object for debugging purposes 1807 */ 1808 void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){ 1809 WhereInfo *pWInfo = pWC->pWInfo; 1810 int nb = 1+(pWInfo->pTabList->nSrc+3)/4; 1811 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab; 1812 Table *pTab = pItem->pTab; 1813 Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1; 1814 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, 1815 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); 1816 sqlite3DebugPrintf(" %12s", 1817 pItem->zAlias ? pItem->zAlias : pTab->zName); 1818 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ 1819 const char *zName; 1820 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ 1821 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ 1822 int i = sqlite3Strlen30(zName) - 1; 1823 while( zName[i]!='_' ) i--; 1824 zName += i; 1825 } 1826 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); 1827 }else{ 1828 sqlite3DebugPrintf("%20s",""); 1829 } 1830 }else{ 1831 char *z; 1832 if( p->u.vtab.idxStr ){ 1833 z = sqlite3_mprintf("(%d,\"%s\",%#x)", 1834 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); 1835 }else{ 1836 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); 1837 } 1838 sqlite3DebugPrintf(" %-19s", z); 1839 sqlite3_free(z); 1840 } 1841 if( p->wsFlags & WHERE_SKIPSCAN ){ 1842 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); 1843 }else{ 1844 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); 1845 } 1846 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); 1847 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ 1848 int i; 1849 for(i=0; i<p->nLTerm; i++){ 1850 sqlite3WhereTermPrint(p->aLTerm[i], i); 1851 } 1852 } 1853 } 1854 #endif 1855 1856 /* 1857 ** Convert bulk memory into a valid WhereLoop that can be passed 1858 ** to whereLoopClear harmlessly. 1859 */ 1860 static void whereLoopInit(WhereLoop *p){ 1861 p->aLTerm = p->aLTermSpace; 1862 p->nLTerm = 0; 1863 p->nLSlot = ArraySize(p->aLTermSpace); 1864 p->wsFlags = 0; 1865 } 1866 1867 /* 1868 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. 1869 */ 1870 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ 1871 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ 1872 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ 1873 sqlite3_free(p->u.vtab.idxStr); 1874 p->u.vtab.needFree = 0; 1875 p->u.vtab.idxStr = 0; 1876 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ 1877 sqlite3DbFree(db, p->u.btree.pIndex->zColAff); 1878 sqlite3DbFreeNN(db, p->u.btree.pIndex); 1879 p->u.btree.pIndex = 0; 1880 } 1881 } 1882 } 1883 1884 /* 1885 ** Deallocate internal memory used by a WhereLoop object 1886 */ 1887 static void whereLoopClear(sqlite3 *db, WhereLoop *p){ 1888 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm); 1889 whereLoopClearUnion(db, p); 1890 whereLoopInit(p); 1891 } 1892 1893 /* 1894 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n. 1895 */ 1896 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ 1897 WhereTerm **paNew; 1898 if( p->nLSlot>=n ) return SQLITE_OK; 1899 n = (n+7)&~7; 1900 paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); 1901 if( paNew==0 ) return SQLITE_NOMEM_BKPT; 1902 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); 1903 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm); 1904 p->aLTerm = paNew; 1905 p->nLSlot = n; 1906 return SQLITE_OK; 1907 } 1908 1909 /* 1910 ** Transfer content from the second pLoop into the first. 1911 */ 1912 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ 1913 whereLoopClearUnion(db, pTo); 1914 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ 1915 memset(&pTo->u, 0, sizeof(pTo->u)); 1916 return SQLITE_NOMEM_BKPT; 1917 } 1918 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); 1919 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); 1920 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ 1921 pFrom->u.vtab.needFree = 0; 1922 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ 1923 pFrom->u.btree.pIndex = 0; 1924 } 1925 return SQLITE_OK; 1926 } 1927 1928 /* 1929 ** Delete a WhereLoop object 1930 */ 1931 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ 1932 whereLoopClear(db, p); 1933 sqlite3DbFreeNN(db, p); 1934 } 1935 1936 /* 1937 ** Free a WhereInfo structure 1938 */ 1939 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ 1940 int i; 1941 assert( pWInfo!=0 ); 1942 for(i=0; i<pWInfo->nLevel; i++){ 1943 WhereLevel *pLevel = &pWInfo->a[i]; 1944 if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){ 1945 sqlite3DbFree(db, pLevel->u.in.aInLoop); 1946 } 1947 } 1948 sqlite3WhereClauseClear(&pWInfo->sWC); 1949 while( pWInfo->pLoops ){ 1950 WhereLoop *p = pWInfo->pLoops; 1951 pWInfo->pLoops = p->pNextLoop; 1952 whereLoopDelete(db, p); 1953 } 1954 assert( pWInfo->pExprMods==0 ); 1955 sqlite3DbFreeNN(db, pWInfo); 1956 } 1957 1958 /* 1959 ** Return TRUE if all of the following are true: 1960 ** 1961 ** (1) X has the same or lower cost that Y 1962 ** (2) X uses fewer WHERE clause terms than Y 1963 ** (3) Every WHERE clause term used by X is also used by Y 1964 ** (4) X skips at least as many columns as Y 1965 ** (5) If X is a covering index, than Y is too 1966 ** 1967 ** Conditions (2) and (3) mean that X is a "proper subset" of Y. 1968 ** If X is a proper subset of Y then Y is a better choice and ought 1969 ** to have a lower cost. This routine returns TRUE when that cost 1970 ** relationship is inverted and needs to be adjusted. Constraint (4) 1971 ** was added because if X uses skip-scan less than Y it still might 1972 ** deserve a lower cost even if it is a proper subset of Y. Constraint (5) 1973 ** was added because a covering index probably deserves to have a lower cost 1974 ** than a non-covering index even if it is a proper subset. 1975 */ 1976 static int whereLoopCheaperProperSubset( 1977 const WhereLoop *pX, /* First WhereLoop to compare */ 1978 const WhereLoop *pY /* Compare against this WhereLoop */ 1979 ){ 1980 int i, j; 1981 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){ 1982 return 0; /* X is not a subset of Y */ 1983 } 1984 if( pY->nSkip > pX->nSkip ) return 0; 1985 if( pX->rRun >= pY->rRun ){ 1986 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */ 1987 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */ 1988 } 1989 for(i=pX->nLTerm-1; i>=0; i--){ 1990 if( pX->aLTerm[i]==0 ) continue; 1991 for(j=pY->nLTerm-1; j>=0; j--){ 1992 if( pY->aLTerm[j]==pX->aLTerm[i] ) break; 1993 } 1994 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ 1995 } 1996 if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 1997 && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){ 1998 return 0; /* Constraint (5) */ 1999 } 2000 return 1; /* All conditions meet */ 2001 } 2002 2003 /* 2004 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so 2005 ** that: 2006 ** 2007 ** (1) pTemplate costs less than any other WhereLoops that are a proper 2008 ** subset of pTemplate 2009 ** 2010 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate 2011 ** is a proper subset. 2012 ** 2013 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer 2014 ** WHERE clause terms than Y and that every WHERE clause term used by X is 2015 ** also used by Y. 2016 */ 2017 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ 2018 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; 2019 for(; p; p=p->pNextLoop){ 2020 if( p->iTab!=pTemplate->iTab ) continue; 2021 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; 2022 if( whereLoopCheaperProperSubset(p, pTemplate) ){ 2023 /* Adjust pTemplate cost downward so that it is cheaper than its 2024 ** subset p. */ 2025 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", 2026 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1)); 2027 pTemplate->rRun = p->rRun; 2028 pTemplate->nOut = p->nOut - 1; 2029 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ 2030 /* Adjust pTemplate cost upward so that it is costlier than p since 2031 ** pTemplate is a proper subset of p */ 2032 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", 2033 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1)); 2034 pTemplate->rRun = p->rRun; 2035 pTemplate->nOut = p->nOut + 1; 2036 } 2037 } 2038 } 2039 2040 /* 2041 ** Search the list of WhereLoops in *ppPrev looking for one that can be 2042 ** replaced by pTemplate. 2043 ** 2044 ** Return NULL if pTemplate does not belong on the WhereLoop list. 2045 ** In other words if pTemplate ought to be dropped from further consideration. 2046 ** 2047 ** If pX is a WhereLoop that pTemplate can replace, then return the 2048 ** link that points to pX. 2049 ** 2050 ** If pTemplate cannot replace any existing element of the list but needs 2051 ** to be added to the list as a new entry, then return a pointer to the 2052 ** tail of the list. 2053 */ 2054 static WhereLoop **whereLoopFindLesser( 2055 WhereLoop **ppPrev, 2056 const WhereLoop *pTemplate 2057 ){ 2058 WhereLoop *p; 2059 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){ 2060 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ 2061 /* If either the iTab or iSortIdx values for two WhereLoop are different 2062 ** then those WhereLoops need to be considered separately. Neither is 2063 ** a candidate to replace the other. */ 2064 continue; 2065 } 2066 /* In the current implementation, the rSetup value is either zero 2067 ** or the cost of building an automatic index (NlogN) and the NlogN 2068 ** is the same for compatible WhereLoops. */ 2069 assert( p->rSetup==0 || pTemplate->rSetup==0 2070 || p->rSetup==pTemplate->rSetup ); 2071 2072 /* whereLoopAddBtree() always generates and inserts the automatic index 2073 ** case first. Hence compatible candidate WhereLoops never have a larger 2074 ** rSetup. Call this SETUP-INVARIANT */ 2075 assert( p->rSetup>=pTemplate->rSetup ); 2076 2077 /* Any loop using an appliation-defined index (or PRIMARY KEY or 2078 ** UNIQUE constraint) with one or more == constraints is better 2079 ** than an automatic index. Unless it is a skip-scan. */ 2080 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 2081 && (pTemplate->nSkip)==0 2082 && (pTemplate->wsFlags & WHERE_INDEXED)!=0 2083 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 2084 && (p->prereq & pTemplate->prereq)==pTemplate->prereq 2085 ){ 2086 break; 2087 } 2088 2089 /* If existing WhereLoop p is better than pTemplate, pTemplate can be 2090 ** discarded. WhereLoop p is better if: 2091 ** (1) p has no more dependencies than pTemplate, and 2092 ** (2) p has an equal or lower cost than pTemplate 2093 */ 2094 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */ 2095 && p->rSetup<=pTemplate->rSetup /* (2a) */ 2096 && p->rRun<=pTemplate->rRun /* (2b) */ 2097 && p->nOut<=pTemplate->nOut /* (2c) */ 2098 ){ 2099 return 0; /* Discard pTemplate */ 2100 } 2101 2102 /* If pTemplate is always better than p, then cause p to be overwritten 2103 ** with pTemplate. pTemplate is better than p if: 2104 ** (1) pTemplate has no more dependences than p, and 2105 ** (2) pTemplate has an equal or lower cost than p. 2106 */ 2107 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */ 2108 && p->rRun>=pTemplate->rRun /* (2a) */ 2109 && p->nOut>=pTemplate->nOut /* (2b) */ 2110 ){ 2111 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ 2112 break; /* Cause p to be overwritten by pTemplate */ 2113 } 2114 } 2115 return ppPrev; 2116 } 2117 2118 /* 2119 ** Insert or replace a WhereLoop entry using the template supplied. 2120 ** 2121 ** An existing WhereLoop entry might be overwritten if the new template 2122 ** is better and has fewer dependencies. Or the template will be ignored 2123 ** and no insert will occur if an existing WhereLoop is faster and has 2124 ** fewer dependencies than the template. Otherwise a new WhereLoop is 2125 ** added based on the template. 2126 ** 2127 ** If pBuilder->pOrSet is not NULL then we care about only the 2128 ** prerequisites and rRun and nOut costs of the N best loops. That 2129 ** information is gathered in the pBuilder->pOrSet object. This special 2130 ** processing mode is used only for OR clause processing. 2131 ** 2132 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we 2133 ** still might overwrite similar loops with the new template if the 2134 ** new template is better. Loops may be overwritten if the following 2135 ** conditions are met: 2136 ** 2137 ** (1) They have the same iTab. 2138 ** (2) They have the same iSortIdx. 2139 ** (3) The template has same or fewer dependencies than the current loop 2140 ** (4) The template has the same or lower cost than the current loop 2141 */ 2142 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ 2143 WhereLoop **ppPrev, *p; 2144 WhereInfo *pWInfo = pBuilder->pWInfo; 2145 sqlite3 *db = pWInfo->pParse->db; 2146 int rc; 2147 2148 /* Stop the search once we hit the query planner search limit */ 2149 if( pBuilder->iPlanLimit==0 ){ 2150 WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n")); 2151 if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0; 2152 return SQLITE_DONE; 2153 } 2154 pBuilder->iPlanLimit--; 2155 2156 whereLoopAdjustCost(pWInfo->pLoops, pTemplate); 2157 2158 /* If pBuilder->pOrSet is defined, then only keep track of the costs 2159 ** and prereqs. 2160 */ 2161 if( pBuilder->pOrSet!=0 ){ 2162 if( pTemplate->nLTerm ){ 2163 #if WHERETRACE_ENABLED 2164 u16 n = pBuilder->pOrSet->n; 2165 int x = 2166 #endif 2167 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, 2168 pTemplate->nOut); 2169 #if WHERETRACE_ENABLED /* 0x8 */ 2170 if( sqlite3WhereTrace & 0x8 ){ 2171 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); 2172 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); 2173 } 2174 #endif 2175 } 2176 return SQLITE_OK; 2177 } 2178 2179 /* Look for an existing WhereLoop to replace with pTemplate 2180 */ 2181 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); 2182 2183 if( ppPrev==0 ){ 2184 /* There already exists a WhereLoop on the list that is better 2185 ** than pTemplate, so just ignore pTemplate */ 2186 #if WHERETRACE_ENABLED /* 0x8 */ 2187 if( sqlite3WhereTrace & 0x8 ){ 2188 sqlite3DebugPrintf(" skip: "); 2189 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); 2190 } 2191 #endif 2192 return SQLITE_OK; 2193 }else{ 2194 p = *ppPrev; 2195 } 2196 2197 /* If we reach this point it means that either p[] should be overwritten 2198 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new 2199 ** WhereLoop and insert it. 2200 */ 2201 #if WHERETRACE_ENABLED /* 0x8 */ 2202 if( sqlite3WhereTrace & 0x8 ){ 2203 if( p!=0 ){ 2204 sqlite3DebugPrintf("replace: "); 2205 sqlite3WhereLoopPrint(p, pBuilder->pWC); 2206 sqlite3DebugPrintf(" with: "); 2207 }else{ 2208 sqlite3DebugPrintf(" add: "); 2209 } 2210 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); 2211 } 2212 #endif 2213 if( p==0 ){ 2214 /* Allocate a new WhereLoop to add to the end of the list */ 2215 *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop)); 2216 if( p==0 ) return SQLITE_NOMEM_BKPT; 2217 whereLoopInit(p); 2218 p->pNextLoop = 0; 2219 }else{ 2220 /* We will be overwriting WhereLoop p[]. But before we do, first 2221 ** go through the rest of the list and delete any other entries besides 2222 ** p[] that are also supplated by pTemplate */ 2223 WhereLoop **ppTail = &p->pNextLoop; 2224 WhereLoop *pToDel; 2225 while( *ppTail ){ 2226 ppTail = whereLoopFindLesser(ppTail, pTemplate); 2227 if( ppTail==0 ) break; 2228 pToDel = *ppTail; 2229 if( pToDel==0 ) break; 2230 *ppTail = pToDel->pNextLoop; 2231 #if WHERETRACE_ENABLED /* 0x8 */ 2232 if( sqlite3WhereTrace & 0x8 ){ 2233 sqlite3DebugPrintf(" delete: "); 2234 sqlite3WhereLoopPrint(pToDel, pBuilder->pWC); 2235 } 2236 #endif 2237 whereLoopDelete(db, pToDel); 2238 } 2239 } 2240 rc = whereLoopXfer(db, p, pTemplate); 2241 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ 2242 Index *pIndex = p->u.btree.pIndex; 2243 if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){ 2244 p->u.btree.pIndex = 0; 2245 } 2246 } 2247 return rc; 2248 } 2249 2250 /* 2251 ** Adjust the WhereLoop.nOut value downward to account for terms of the 2252 ** WHERE clause that reference the loop but which are not used by an 2253 ** index. 2254 * 2255 ** For every WHERE clause term that is not used by the index 2256 ** and which has a truth probability assigned by one of the likelihood(), 2257 ** likely(), or unlikely() SQL functions, reduce the estimated number 2258 ** of output rows by the probability specified. 2259 ** 2260 ** TUNING: For every WHERE clause term that is not used by the index 2261 ** and which does not have an assigned truth probability, heuristics 2262 ** described below are used to try to estimate the truth probability. 2263 ** TODO --> Perhaps this is something that could be improved by better 2264 ** table statistics. 2265 ** 2266 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75% 2267 ** value corresponds to -1 in LogEst notation, so this means decrement 2268 ** the WhereLoop.nOut field for every such WHERE clause term. 2269 ** 2270 ** Heuristic 2: If there exists one or more WHERE clause terms of the 2271 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the 2272 ** final output row estimate is no greater than 1/4 of the total number 2273 ** of rows in the table. In other words, assume that x==EXPR will filter 2274 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the 2275 ** "x" column is boolean or else -1 or 0 or 1 is a common default value 2276 ** on the "x" column and so in that case only cap the output row estimate 2277 ** at 1/2 instead of 1/4. 2278 */ 2279 static void whereLoopOutputAdjust( 2280 WhereClause *pWC, /* The WHERE clause */ 2281 WhereLoop *pLoop, /* The loop to adjust downward */ 2282 LogEst nRow /* Number of rows in the entire table */ 2283 ){ 2284 WhereTerm *pTerm, *pX; 2285 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); 2286 int i, j; 2287 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ 2288 2289 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 2290 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ 2291 assert( pTerm!=0 ); 2292 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; 2293 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; 2294 if( (pTerm->prereqAll & notAllowed)!=0 ) continue; 2295 for(j=pLoop->nLTerm-1; j>=0; j--){ 2296 pX = pLoop->aLTerm[j]; 2297 if( pX==0 ) continue; 2298 if( pX==pTerm ) break; 2299 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; 2300 } 2301 if( j<0 ){ 2302 if( pTerm->truthProb<=0 ){ 2303 /* If a truth probability is specified using the likelihood() hints, 2304 ** then use the probability provided by the application. */ 2305 pLoop->nOut += pTerm->truthProb; 2306 }else{ 2307 /* In the absence of explicit truth probabilities, use heuristics to 2308 ** guess a reasonable truth probability. */ 2309 pLoop->nOut--; 2310 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 2311 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */ 2312 ){ 2313 Expr *pRight = pTerm->pExpr->pRight; 2314 int k = 0; 2315 testcase( pTerm->pExpr->op==TK_IS ); 2316 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ 2317 k = 10; 2318 }else{ 2319 k = 20; 2320 } 2321 if( iReduce<k ){ 2322 pTerm->wtFlags |= TERM_HEURTRUTH; 2323 iReduce = k; 2324 } 2325 } 2326 } 2327 } 2328 } 2329 if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce; 2330 } 2331 2332 /* 2333 ** Term pTerm is a vector range comparison operation. The first comparison 2334 ** in the vector can be optimized using column nEq of the index. This 2335 ** function returns the total number of vector elements that can be used 2336 ** as part of the range comparison. 2337 ** 2338 ** For example, if the query is: 2339 ** 2340 ** WHERE a = ? AND (b, c, d) > (?, ?, ?) 2341 ** 2342 ** and the index: 2343 ** 2344 ** CREATE INDEX ... ON (a, b, c, d, e) 2345 ** 2346 ** then this function would be invoked with nEq=1. The value returned in 2347 ** this case is 3. 2348 */ 2349 static int whereRangeVectorLen( 2350 Parse *pParse, /* Parsing context */ 2351 int iCur, /* Cursor open on pIdx */ 2352 Index *pIdx, /* The index to be used for a inequality constraint */ 2353 int nEq, /* Number of prior equality constraints on same index */ 2354 WhereTerm *pTerm /* The vector inequality constraint */ 2355 ){ 2356 int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft); 2357 int i; 2358 2359 nCmp = MIN(nCmp, (pIdx->nColumn - nEq)); 2360 for(i=1; i<nCmp; i++){ 2361 /* Test if comparison i of pTerm is compatible with column (i+nEq) 2362 ** of the index. If not, exit the loop. */ 2363 char aff; /* Comparison affinity */ 2364 char idxaff = 0; /* Indexed columns affinity */ 2365 CollSeq *pColl; /* Comparison collation sequence */ 2366 Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr; 2367 Expr *pRhs = pTerm->pExpr->pRight; 2368 if( pRhs->flags & EP_xIsSelect ){ 2369 pRhs = pRhs->x.pSelect->pEList->a[i].pExpr; 2370 }else{ 2371 pRhs = pRhs->x.pList->a[i].pExpr; 2372 } 2373 2374 /* Check that the LHS of the comparison is a column reference to 2375 ** the right column of the right source table. And that the sort 2376 ** order of the index column is the same as the sort order of the 2377 ** leftmost index column. */ 2378 if( pLhs->op!=TK_COLUMN 2379 || pLhs->iTable!=iCur 2380 || pLhs->iColumn!=pIdx->aiColumn[i+nEq] 2381 || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq] 2382 ){ 2383 break; 2384 } 2385 2386 testcase( pLhs->iColumn==XN_ROWID ); 2387 aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs)); 2388 idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); 2389 if( aff!=idxaff ) break; 2390 2391 pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); 2392 if( pColl==0 ) break; 2393 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; 2394 } 2395 return i; 2396 } 2397 2398 /* 2399 ** Adjust the cost C by the costMult facter T. This only occurs if 2400 ** compiled with -DSQLITE_ENABLE_COSTMULT 2401 */ 2402 #ifdef SQLITE_ENABLE_COSTMULT 2403 # define ApplyCostMultiplier(C,T) C += T 2404 #else 2405 # define ApplyCostMultiplier(C,T) 2406 #endif 2407 2408 /* 2409 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 2410 ** index pIndex. Try to match one more. 2411 ** 2412 ** When this function is called, pBuilder->pNew->nOut contains the 2413 ** number of rows expected to be visited by filtering using the nEq 2414 ** terms only. If it is modified, this value is restored before this 2415 ** function returns. 2416 ** 2417 ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is 2418 ** a fake index used for the INTEGER PRIMARY KEY. 2419 */ 2420 static int whereLoopAddBtreeIndex( 2421 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ 2422 struct SrcList_item *pSrc, /* FROM clause term being analyzed */ 2423 Index *pProbe, /* An index on pSrc */ 2424 LogEst nInMul /* log(Number of iterations due to IN) */ 2425 ){ 2426 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ 2427 Parse *pParse = pWInfo->pParse; /* Parsing context */ 2428 sqlite3 *db = pParse->db; /* Database connection malloc context */ 2429 WhereLoop *pNew; /* Template WhereLoop under construction */ 2430 WhereTerm *pTerm; /* A WhereTerm under consideration */ 2431 int opMask; /* Valid operators for constraints */ 2432 WhereScan scan; /* Iterator for WHERE terms */ 2433 Bitmask saved_prereq; /* Original value of pNew->prereq */ 2434 u16 saved_nLTerm; /* Original value of pNew->nLTerm */ 2435 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ 2436 u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */ 2437 u16 saved_nTop; /* Original value of pNew->u.btree.nTop */ 2438 u16 saved_nSkip; /* Original value of pNew->nSkip */ 2439 u32 saved_wsFlags; /* Original value of pNew->wsFlags */ 2440 LogEst saved_nOut; /* Original value of pNew->nOut */ 2441 int rc = SQLITE_OK; /* Return code */ 2442 LogEst rSize; /* Number of rows in the table */ 2443 LogEst rLogSize; /* Logarithm of table size */ 2444 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ 2445 2446 pNew = pBuilder->pNew; 2447 if( db->mallocFailed ) return SQLITE_NOMEM_BKPT; 2448 WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n", 2449 pProbe->pTable->zName,pProbe->zName, 2450 pNew->u.btree.nEq, pNew->nSkip, pNew->rRun)); 2451 2452 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); 2453 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); 2454 if( pNew->wsFlags & WHERE_BTM_LIMIT ){ 2455 opMask = WO_LT|WO_LE; 2456 }else{ 2457 assert( pNew->u.btree.nBtm==0 ); 2458 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS; 2459 } 2460 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); 2461 2462 assert( pNew->u.btree.nEq<pProbe->nColumn ); 2463 2464 saved_nEq = pNew->u.btree.nEq; 2465 saved_nBtm = pNew->u.btree.nBtm; 2466 saved_nTop = pNew->u.btree.nTop; 2467 saved_nSkip = pNew->nSkip; 2468 saved_nLTerm = pNew->nLTerm; 2469 saved_wsFlags = pNew->wsFlags; 2470 saved_prereq = pNew->prereq; 2471 saved_nOut = pNew->nOut; 2472 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq, 2473 opMask, pProbe); 2474 pNew->rSetup = 0; 2475 rSize = pProbe->aiRowLogEst[0]; 2476 rLogSize = estLog(rSize); 2477 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ 2478 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ 2479 LogEst rCostIdx; 2480 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ 2481 int nIn = 0; 2482 #ifdef SQLITE_ENABLE_STAT4 2483 int nRecValid = pBuilder->nRecValid; 2484 #endif 2485 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) 2486 && indexColumnNotNull(pProbe, saved_nEq) 2487 ){ 2488 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ 2489 } 2490 if( pTerm->prereqRight & pNew->maskSelf ) continue; 2491 2492 /* Do not allow the upper bound of a LIKE optimization range constraint 2493 ** to mix with a lower range bound from some other source */ 2494 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue; 2495 2496 /* tag-20191211-001: Do not allow constraints from the WHERE clause to 2497 ** be used by the right table of a LEFT JOIN. Only constraints in the 2498 ** ON clause are allowed. See tag-20191211-002 for the vtab equivalent. */ 2499 if( (pSrc->fg.jointype & JT_LEFT)!=0 2500 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) 2501 ){ 2502 continue; 2503 } 2504 2505 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){ 2506 pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE; 2507 }else{ 2508 pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED; 2509 } 2510 pNew->wsFlags = saved_wsFlags; 2511 pNew->u.btree.nEq = saved_nEq; 2512 pNew->u.btree.nBtm = saved_nBtm; 2513 pNew->u.btree.nTop = saved_nTop; 2514 pNew->nLTerm = saved_nLTerm; 2515 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ 2516 pNew->aLTerm[pNew->nLTerm++] = pTerm; 2517 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; 2518 2519 assert( nInMul==0 2520 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 2521 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 2522 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 2523 ); 2524 2525 if( eOp & WO_IN ){ 2526 Expr *pExpr = pTerm->pExpr; 2527 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2528 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ 2529 int i; 2530 nIn = 46; assert( 46==sqlite3LogEst(25) ); 2531 2532 /* The expression may actually be of the form (x, y) IN (SELECT...). 2533 ** In this case there is a separate term for each of (x) and (y). 2534 ** However, the nIn multiplier should only be applied once, not once 2535 ** for each such term. The following loop checks that pTerm is the 2536 ** first such term in use, and sets nIn back to 0 if it is not. */ 2537 for(i=0; i<pNew->nLTerm-1; i++){ 2538 if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0; 2539 } 2540 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ 2541 /* "x IN (value, value, ...)" */ 2542 nIn = sqlite3LogEst(pExpr->x.pList->nExpr); 2543 } 2544 if( pProbe->hasStat1 && rLogSize>=10 ){ 2545 LogEst M, logK, safetyMargin; 2546 /* Let: 2547 ** N = the total number of rows in the table 2548 ** K = the number of entries on the RHS of the IN operator 2549 ** M = the number of rows in the table that match terms to the 2550 ** to the left in the same index. If the IN operator is on 2551 ** the left-most index column, M==N. 2552 ** 2553 ** Given the definitions above, it is better to omit the IN operator 2554 ** from the index lookup and instead do a scan of the M elements, 2555 ** testing each scanned row against the IN operator separately, if: 2556 ** 2557 ** M*log(K) < K*log(N) 2558 ** 2559 ** Our estimates for M, K, and N might be inaccurate, so we build in 2560 ** a safety margin of 2 (LogEst: 10) that favors using the IN operator 2561 ** with the index, as using an index has better worst-case behavior. 2562 ** If we do not have real sqlite_stat1 data, always prefer to use 2563 ** the index. Do not bother with this optimization on very small 2564 ** tables (less than 2 rows) as it is pointless in that case. 2565 */ 2566 M = pProbe->aiRowLogEst[saved_nEq]; 2567 logK = estLog(nIn); 2568 safetyMargin = 10; /* TUNING: extra weight for indexed IN */ 2569 if( M + logK + safetyMargin < nIn + rLogSize ){ 2570 WHERETRACE(0x40, 2571 ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n", 2572 saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize)); 2573 pNew->wsFlags |= WHERE_IN_SEEKSCAN; 2574 }else{ 2575 WHERETRACE(0x40, 2576 ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n", 2577 saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize)); 2578 } 2579 } 2580 pNew->wsFlags |= WHERE_COLUMN_IN; 2581 }else if( eOp & (WO_EQ|WO_IS) ){ 2582 int iCol = pProbe->aiColumn[saved_nEq]; 2583 pNew->wsFlags |= WHERE_COLUMN_EQ; 2584 assert( saved_nEq==pNew->u.btree.nEq ); 2585 if( iCol==XN_ROWID 2586 || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) 2587 ){ 2588 if( iCol==XN_ROWID || pProbe->uniqNotNull 2589 || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ) 2590 ){ 2591 pNew->wsFlags |= WHERE_ONEROW; 2592 }else{ 2593 pNew->wsFlags |= WHERE_UNQ_WANTED; 2594 } 2595 } 2596 }else if( eOp & WO_ISNULL ){ 2597 pNew->wsFlags |= WHERE_COLUMN_NULL; 2598 }else if( eOp & (WO_GT|WO_GE) ){ 2599 testcase( eOp & WO_GT ); 2600 testcase( eOp & WO_GE ); 2601 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; 2602 pNew->u.btree.nBtm = whereRangeVectorLen( 2603 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm 2604 ); 2605 pBtm = pTerm; 2606 pTop = 0; 2607 if( pTerm->wtFlags & TERM_LIKEOPT ){ 2608 /* Range contraints that come from the LIKE optimization are 2609 ** always used in pairs. */ 2610 pTop = &pTerm[1]; 2611 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm ); 2612 assert( pTop->wtFlags & TERM_LIKEOPT ); 2613 assert( pTop->eOperator==WO_LT ); 2614 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ 2615 pNew->aLTerm[pNew->nLTerm++] = pTop; 2616 pNew->wsFlags |= WHERE_TOP_LIMIT; 2617 pNew->u.btree.nTop = 1; 2618 } 2619 }else{ 2620 assert( eOp & (WO_LT|WO_LE) ); 2621 testcase( eOp & WO_LT ); 2622 testcase( eOp & WO_LE ); 2623 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; 2624 pNew->u.btree.nTop = whereRangeVectorLen( 2625 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm 2626 ); 2627 pTop = pTerm; 2628 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? 2629 pNew->aLTerm[pNew->nLTerm-2] : 0; 2630 } 2631 2632 /* At this point pNew->nOut is set to the number of rows expected to 2633 ** be visited by the index scan before considering term pTerm, or the 2634 ** values of nIn and nInMul. In other words, assuming that all 2635 ** "x IN(...)" terms are replaced with "x = ?". This block updates 2636 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ 2637 assert( pNew->nOut==saved_nOut ); 2638 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ 2639 /* Adjust nOut using stat4 data. Or, if there is no stat4 2640 ** data, using some other estimate. */ 2641 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); 2642 }else{ 2643 int nEq = ++pNew->u.btree.nEq; 2644 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) ); 2645 2646 assert( pNew->nOut==saved_nOut ); 2647 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){ 2648 assert( (eOp & WO_IN) || nIn==0 ); 2649 testcase( eOp & WO_IN ); 2650 pNew->nOut += pTerm->truthProb; 2651 pNew->nOut -= nIn; 2652 }else{ 2653 #ifdef SQLITE_ENABLE_STAT4 2654 tRowcnt nOut = 0; 2655 if( nInMul==0 2656 && pProbe->nSample 2657 && pNew->u.btree.nEq<=pProbe->nSampleCol 2658 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) 2659 && OptimizationEnabled(db, SQLITE_Stat4) 2660 ){ 2661 Expr *pExpr = pTerm->pExpr; 2662 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){ 2663 testcase( eOp & WO_EQ ); 2664 testcase( eOp & WO_IS ); 2665 testcase( eOp & WO_ISNULL ); 2666 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); 2667 }else{ 2668 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); 2669 } 2670 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; 2671 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ 2672 if( nOut ){ 2673 pNew->nOut = sqlite3LogEst(nOut); 2674 if( nEq==1 2675 /* TUNING: Mark terms as "low selectivity" if they seem likely 2676 ** to be true for half or more of the rows in the table. 2677 ** See tag-202002240-1 */ 2678 && pNew->nOut+10 > pProbe->aiRowLogEst[0] 2679 ){ 2680 #if WHERETRACE_ENABLED /* 0x01 */ 2681 if( sqlite3WhereTrace & 0x01 ){ 2682 sqlite3DebugPrintf( 2683 "STAT4 determines term has low selectivity:\n"); 2684 sqlite3WhereTermPrint(pTerm, 999); 2685 } 2686 #endif 2687 pTerm->wtFlags |= TERM_HIGHTRUTH; 2688 if( pTerm->wtFlags & TERM_HEURTRUTH ){ 2689 /* If the term has previously been used with an assumption of 2690 ** higher selectivity, then set the flag to rerun the 2691 ** loop computations. */ 2692 pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS; 2693 } 2694 } 2695 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; 2696 pNew->nOut -= nIn; 2697 } 2698 } 2699 if( nOut==0 ) 2700 #endif 2701 { 2702 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]); 2703 if( eOp & WO_ISNULL ){ 2704 /* TUNING: If there is no likelihood() value, assume that a 2705 ** "col IS NULL" expression matches twice as many rows 2706 ** as (col=?). */ 2707 pNew->nOut += 10; 2708 } 2709 } 2710 } 2711 } 2712 2713 /* Set rCostIdx to the cost of visiting selected rows in index. Add 2714 ** it to pNew->rRun, which is currently set to the cost of the index 2715 ** seek only. Then, if this is a non-covering index, add the cost of 2716 ** visiting the rows in the main table. */ 2717 assert( pSrc->pTab->szTabRow>0 ); 2718 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow; 2719 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx); 2720 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ 2721 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); 2722 } 2723 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); 2724 2725 nOutUnadjusted = pNew->nOut; 2726 pNew->rRun += nInMul + nIn; 2727 pNew->nOut += nInMul + nIn; 2728 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize); 2729 rc = whereLoopInsert(pBuilder, pNew); 2730 2731 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ 2732 pNew->nOut = saved_nOut; 2733 }else{ 2734 pNew->nOut = nOutUnadjusted; 2735 } 2736 2737 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 2738 && pNew->u.btree.nEq<pProbe->nColumn 2739 ){ 2740 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); 2741 } 2742 pNew->nOut = saved_nOut; 2743 #ifdef SQLITE_ENABLE_STAT4 2744 pBuilder->nRecValid = nRecValid; 2745 #endif 2746 } 2747 pNew->prereq = saved_prereq; 2748 pNew->u.btree.nEq = saved_nEq; 2749 pNew->u.btree.nBtm = saved_nBtm; 2750 pNew->u.btree.nTop = saved_nTop; 2751 pNew->nSkip = saved_nSkip; 2752 pNew->wsFlags = saved_wsFlags; 2753 pNew->nOut = saved_nOut; 2754 pNew->nLTerm = saved_nLTerm; 2755 2756 /* Consider using a skip-scan if there are no WHERE clause constraints 2757 ** available for the left-most terms of the index, and if the average 2758 ** number of repeats in the left-most terms is at least 18. 2759 ** 2760 ** The magic number 18 is selected on the basis that scanning 17 rows 2761 ** is almost always quicker than an index seek (even though if the index 2762 ** contains fewer than 2^17 rows we assume otherwise in other parts of 2763 ** the code). And, even if it is not, it should not be too much slower. 2764 ** On the other hand, the extra seeks could end up being significantly 2765 ** more expensive. */ 2766 assert( 42==sqlite3LogEst(18) ); 2767 if( saved_nEq==saved_nSkip 2768 && saved_nEq+1<pProbe->nKeyCol 2769 && saved_nEq==pNew->nLTerm 2770 && pProbe->noSkipScan==0 2771 && pProbe->hasStat1!=0 2772 && OptimizationEnabled(db, SQLITE_SkipScan) 2773 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ 2774 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK 2775 ){ 2776 LogEst nIter; 2777 pNew->u.btree.nEq++; 2778 pNew->nSkip++; 2779 pNew->aLTerm[pNew->nLTerm++] = 0; 2780 pNew->wsFlags |= WHERE_SKIPSCAN; 2781 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; 2782 pNew->nOut -= nIter; 2783 /* TUNING: Because uncertainties in the estimates for skip-scan queries, 2784 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */ 2785 nIter += 5; 2786 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); 2787 pNew->nOut = saved_nOut; 2788 pNew->u.btree.nEq = saved_nEq; 2789 pNew->nSkip = saved_nSkip; 2790 pNew->wsFlags = saved_wsFlags; 2791 } 2792 2793 WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n", 2794 pProbe->pTable->zName, pProbe->zName, saved_nEq, rc)); 2795 return rc; 2796 } 2797 2798 /* 2799 ** Return True if it is possible that pIndex might be useful in 2800 ** implementing the ORDER BY clause in pBuilder. 2801 ** 2802 ** Return False if pBuilder does not contain an ORDER BY clause or 2803 ** if there is no way for pIndex to be useful in implementing that 2804 ** ORDER BY clause. 2805 */ 2806 static int indexMightHelpWithOrderBy( 2807 WhereLoopBuilder *pBuilder, 2808 Index *pIndex, 2809 int iCursor 2810 ){ 2811 ExprList *pOB; 2812 ExprList *aColExpr; 2813 int ii, jj; 2814 2815 if( pIndex->bUnordered ) return 0; 2816 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; 2817 for(ii=0; ii<pOB->nExpr; ii++){ 2818 Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr); 2819 if( NEVER(pExpr==0) ) continue; 2820 if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){ 2821 if( pExpr->iColumn<0 ) return 1; 2822 for(jj=0; jj<pIndex->nKeyCol; jj++){ 2823 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; 2824 } 2825 }else if( (aColExpr = pIndex->aColExpr)!=0 ){ 2826 for(jj=0; jj<pIndex->nKeyCol; jj++){ 2827 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue; 2828 if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ 2829 return 1; 2830 } 2831 } 2832 } 2833 } 2834 return 0; 2835 } 2836 2837 /* Check to see if a partial index with pPartIndexWhere can be used 2838 ** in the current query. Return true if it can be and false if not. 2839 */ 2840 static int whereUsablePartialIndex( 2841 int iTab, /* The table for which we want an index */ 2842 int isLeft, /* True if iTab is the right table of a LEFT JOIN */ 2843 WhereClause *pWC, /* The WHERE clause of the query */ 2844 Expr *pWhere /* The WHERE clause from the partial index */ 2845 ){ 2846 int i; 2847 WhereTerm *pTerm; 2848 Parse *pParse = pWC->pWInfo->pParse; 2849 while( pWhere->op==TK_AND ){ 2850 if( !whereUsablePartialIndex(iTab,isLeft,pWC,pWhere->pLeft) ) return 0; 2851 pWhere = pWhere->pRight; 2852 } 2853 if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0; 2854 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 2855 Expr *pExpr; 2856 pExpr = pTerm->pExpr; 2857 if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) 2858 && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin)) 2859 && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) 2860 ){ 2861 return 1; 2862 } 2863 } 2864 return 0; 2865 } 2866 2867 /* 2868 ** Add all WhereLoop objects for a single table of the join where the table 2869 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be 2870 ** a b-tree table, not a virtual table. 2871 ** 2872 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function 2873 ** are calculated as follows: 2874 ** 2875 ** For a full scan, assuming the table (or index) contains nRow rows: 2876 ** 2877 ** cost = nRow * 3.0 // full-table scan 2878 ** cost = nRow * K // scan of covering index 2879 ** cost = nRow * (K+3.0) // scan of non-covering index 2880 ** 2881 ** where K is a value between 1.1 and 3.0 set based on the relative 2882 ** estimated average size of the index and table records. 2883 ** 2884 ** For an index scan, where nVisit is the number of index rows visited 2885 ** by the scan, and nSeek is the number of seek operations required on 2886 ** the index b-tree: 2887 ** 2888 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index 2889 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index 2890 ** 2891 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the 2892 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 2893 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans. 2894 ** 2895 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount 2896 ** of uncertainty. For this reason, scoring is designed to pick plans that 2897 ** "do the least harm" if the estimates are inaccurate. For example, a 2898 ** log(nRow) factor is omitted from a non-covering index scan in order to 2899 ** bias the scoring in favor of using an index, since the worst-case 2900 ** performance of using an index is far better than the worst-case performance 2901 ** of a full table scan. 2902 */ 2903 static int whereLoopAddBtree( 2904 WhereLoopBuilder *pBuilder, /* WHERE clause information */ 2905 Bitmask mPrereq /* Extra prerequesites for using this table */ 2906 ){ 2907 WhereInfo *pWInfo; /* WHERE analysis context */ 2908 Index *pProbe; /* An index we are evaluating */ 2909 Index sPk; /* A fake index object for the primary key */ 2910 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */ 2911 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */ 2912 SrcList *pTabList; /* The FROM clause */ 2913 struct SrcList_item *pSrc; /* The FROM clause btree term to add */ 2914 WhereLoop *pNew; /* Template WhereLoop object */ 2915 int rc = SQLITE_OK; /* Return code */ 2916 int iSortIdx = 1; /* Index number */ 2917 int b; /* A boolean value */ 2918 LogEst rSize; /* number of rows in the table */ 2919 LogEst rLogSize; /* Logarithm of the number of rows in the table */ 2920 WhereClause *pWC; /* The parsed WHERE clause */ 2921 Table *pTab; /* Table being queried */ 2922 2923 pNew = pBuilder->pNew; 2924 pWInfo = pBuilder->pWInfo; 2925 pTabList = pWInfo->pTabList; 2926 pSrc = pTabList->a + pNew->iTab; 2927 pTab = pSrc->pTab; 2928 pWC = pBuilder->pWC; 2929 assert( !IsVirtual(pSrc->pTab) ); 2930 2931 if( pSrc->pIBIndex ){ 2932 /* An INDEXED BY clause specifies a particular index to use */ 2933 pProbe = pSrc->pIBIndex; 2934 }else if( !HasRowid(pTab) ){ 2935 pProbe = pTab->pIndex; 2936 }else{ 2937 /* There is no INDEXED BY clause. Create a fake Index object in local 2938 ** variable sPk to represent the rowid primary key index. Make this 2939 ** fake index the first in a chain of Index objects with all of the real 2940 ** indices to follow */ 2941 Index *pFirst; /* First of real indices on the table */ 2942 memset(&sPk, 0, sizeof(Index)); 2943 sPk.nKeyCol = 1; 2944 sPk.nColumn = 1; 2945 sPk.aiColumn = &aiColumnPk; 2946 sPk.aiRowLogEst = aiRowEstPk; 2947 sPk.onError = OE_Replace; 2948 sPk.pTable = pTab; 2949 sPk.szIdxRow = pTab->szTabRow; 2950 sPk.idxType = SQLITE_IDXTYPE_IPK; 2951 aiRowEstPk[0] = pTab->nRowLogEst; 2952 aiRowEstPk[1] = 0; 2953 pFirst = pSrc->pTab->pIndex; 2954 if( pSrc->fg.notIndexed==0 ){ 2955 /* The real indices of the table are only considered if the 2956 ** NOT INDEXED qualifier is omitted from the FROM clause */ 2957 sPk.pNext = pFirst; 2958 } 2959 pProbe = &sPk; 2960 } 2961 rSize = pTab->nRowLogEst; 2962 rLogSize = estLog(rSize); 2963 2964 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 2965 /* Automatic indexes */ 2966 if( !pBuilder->pOrSet /* Not part of an OR optimization */ 2967 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 2968 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 2969 && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */ 2970 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */ 2971 && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */ 2972 && !pSrc->fg.isCorrelated /* Not a correlated subquery */ 2973 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */ 2974 ){ 2975 /* Generate auto-index WhereLoops */ 2976 WhereTerm *pTerm; 2977 WhereTerm *pWCEnd = pWC->a + pWC->nTerm; 2978 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){ 2979 if( pTerm->prereqRight & pNew->maskSelf ) continue; 2980 if( termCanDriveIndex(pTerm, pSrc, 0) ){ 2981 pNew->u.btree.nEq = 1; 2982 pNew->nSkip = 0; 2983 pNew->u.btree.pIndex = 0; 2984 pNew->nLTerm = 1; 2985 pNew->aLTerm[0] = pTerm; 2986 /* TUNING: One-time cost for computing the automatic index is 2987 ** estimated to be X*N*log2(N) where N is the number of rows in 2988 ** the table being indexed and where X is 7 (LogEst=28) for normal 2989 ** tables or 0.5 (LogEst=-10) for views and subqueries. The value 2990 ** of X is smaller for views and subqueries so that the query planner 2991 ** will be more aggressive about generating automatic indexes for 2992 ** those objects, since there is no opportunity to add schema 2993 ** indexes on subqueries and views. */ 2994 pNew->rSetup = rLogSize + rSize; 2995 if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){ 2996 pNew->rSetup += 28; 2997 }else{ 2998 pNew->rSetup -= 10; 2999 } 3000 ApplyCostMultiplier(pNew->rSetup, pTab->costMult); 3001 if( pNew->rSetup<0 ) pNew->rSetup = 0; 3002 /* TUNING: Each index lookup yields 20 rows in the table. This 3003 ** is more than the usual guess of 10 rows, since we have no way 3004 ** of knowing how selective the index will ultimately be. It would 3005 ** not be unreasonable to make this value much larger. */ 3006 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); 3007 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); 3008 pNew->wsFlags = WHERE_AUTO_INDEX; 3009 pNew->prereq = mPrereq | pTerm->prereqRight; 3010 rc = whereLoopInsert(pBuilder, pNew); 3011 } 3012 } 3013 } 3014 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 3015 3016 /* Loop over all indices. If there was an INDEXED BY clause, then only 3017 ** consider index pProbe. */ 3018 for(; rc==SQLITE_OK && pProbe; 3019 pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++ 3020 ){ 3021 int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0; 3022 if( pProbe->pPartIdxWhere!=0 3023 && !whereUsablePartialIndex(pSrc->iCursor, isLeft, pWC, 3024 pProbe->pPartIdxWhere) 3025 ){ 3026 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ 3027 continue; /* Partial index inappropriate for this query */ 3028 } 3029 if( pProbe->bNoQuery ) continue; 3030 rSize = pProbe->aiRowLogEst[0]; 3031 pNew->u.btree.nEq = 0; 3032 pNew->u.btree.nBtm = 0; 3033 pNew->u.btree.nTop = 0; 3034 pNew->nSkip = 0; 3035 pNew->nLTerm = 0; 3036 pNew->iSortIdx = 0; 3037 pNew->rSetup = 0; 3038 pNew->prereq = mPrereq; 3039 pNew->nOut = rSize; 3040 pNew->u.btree.pIndex = pProbe; 3041 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); 3042 3043 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ 3044 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); 3045 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){ 3046 /* Integer primary key index */ 3047 pNew->wsFlags = WHERE_IPK; 3048 3049 /* Full table scan */ 3050 pNew->iSortIdx = b ? iSortIdx : 0; 3051 /* TUNING: Cost of full table scan is 3.0*N. The 3.0 factor is an 3052 ** extra cost designed to discourage the use of full table scans, 3053 ** since index lookups have better worst-case performance if our 3054 ** stat guesses are wrong. Reduce the 3.0 penalty slightly 3055 ** (to 2.75) if we have valid STAT4 information for the table. 3056 ** At 2.75, a full table scan is preferred over using an index on 3057 ** a column with just two distinct values where each value has about 3058 ** an equal number of appearances. Without STAT4 data, we still want 3059 ** to use an index in that case, since the constraint might be for 3060 ** the scarcer of the two values, and in that case an index lookup is 3061 ** better. 3062 */ 3063 #ifdef SQLITE_ENABLE_STAT4 3064 pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0); 3065 #else 3066 pNew->rRun = rSize + 16; 3067 #endif 3068 ApplyCostMultiplier(pNew->rRun, pTab->costMult); 3069 whereLoopOutputAdjust(pWC, pNew, rSize); 3070 rc = whereLoopInsert(pBuilder, pNew); 3071 pNew->nOut = rSize; 3072 if( rc ) break; 3073 }else{ 3074 Bitmask m; 3075 if( pProbe->isCovering ){ 3076 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; 3077 m = 0; 3078 }else{ 3079 m = pSrc->colUsed & pProbe->colNotIdxed; 3080 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; 3081 } 3082 3083 /* Full scan via index */ 3084 if( b 3085 || !HasRowid(pTab) 3086 || pProbe->pPartIdxWhere!=0 3087 || pSrc->fg.isIndexedBy 3088 || ( m==0 3089 && pProbe->bUnordered==0 3090 && (pProbe->szIdxRow<pTab->szTabRow) 3091 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 3092 && sqlite3GlobalConfig.bUseCis 3093 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) 3094 ) 3095 ){ 3096 pNew->iSortIdx = b ? iSortIdx : 0; 3097 3098 /* The cost of visiting the index rows is N*K, where K is 3099 ** between 1.1 and 3.0, depending on the relative sizes of the 3100 ** index and table rows. */ 3101 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; 3102 if( m!=0 ){ 3103 /* If this is a non-covering index scan, add in the cost of 3104 ** doing table lookups. The cost will be 3x the number of 3105 ** lookups. Take into account WHERE clause terms that can be 3106 ** satisfied using just the index, and that do not require a 3107 ** table lookup. */ 3108 LogEst nLookup = rSize + 16; /* Base cost: N*3 */ 3109 int ii; 3110 int iCur = pSrc->iCursor; 3111 WhereClause *pWC2 = &pWInfo->sWC; 3112 for(ii=0; ii<pWC2->nTerm; ii++){ 3113 WhereTerm *pTerm = &pWC2->a[ii]; 3114 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ 3115 break; 3116 } 3117 /* pTerm can be evaluated using just the index. So reduce 3118 ** the expected number of table lookups accordingly */ 3119 if( pTerm->truthProb<=0 ){ 3120 nLookup += pTerm->truthProb; 3121 }else{ 3122 nLookup--; 3123 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19; 3124 } 3125 } 3126 3127 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup); 3128 } 3129 ApplyCostMultiplier(pNew->rRun, pTab->costMult); 3130 whereLoopOutputAdjust(pWC, pNew, rSize); 3131 rc = whereLoopInsert(pBuilder, pNew); 3132 pNew->nOut = rSize; 3133 if( rc ) break; 3134 } 3135 } 3136 3137 pBuilder->bldFlags1 = 0; 3138 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); 3139 if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){ 3140 /* If a non-unique index is used, or if a prefix of the key for 3141 ** unique index is used (making the index functionally non-unique) 3142 ** then the sqlite_stat1 data becomes important for scoring the 3143 ** plan */ 3144 pTab->tabFlags |= TF_StatsUsed; 3145 } 3146 #ifdef SQLITE_ENABLE_STAT4 3147 sqlite3Stat4ProbeFree(pBuilder->pRec); 3148 pBuilder->nRecValid = 0; 3149 pBuilder->pRec = 0; 3150 #endif 3151 } 3152 return rc; 3153 } 3154 3155 #ifndef SQLITE_OMIT_VIRTUALTABLE 3156 3157 /* 3158 ** Argument pIdxInfo is already populated with all constraints that may 3159 ** be used by the virtual table identified by pBuilder->pNew->iTab. This 3160 ** function marks a subset of those constraints usable, invokes the 3161 ** xBestIndex method and adds the returned plan to pBuilder. 3162 ** 3163 ** A constraint is marked usable if: 3164 ** 3165 ** * Argument mUsable indicates that its prerequisites are available, and 3166 ** 3167 ** * It is not one of the operators specified in the mExclude mask passed 3168 ** as the fourth argument (which in practice is either WO_IN or 0). 3169 ** 3170 ** Argument mPrereq is a mask of tables that must be scanned before the 3171 ** virtual table in question. These are added to the plans prerequisites 3172 ** before it is added to pBuilder. 3173 ** 3174 ** Output parameter *pbIn is set to true if the plan added to pBuilder 3175 ** uses one or more WO_IN terms, or false otherwise. 3176 */ 3177 static int whereLoopAddVirtualOne( 3178 WhereLoopBuilder *pBuilder, 3179 Bitmask mPrereq, /* Mask of tables that must be used. */ 3180 Bitmask mUsable, /* Mask of usable tables */ 3181 u16 mExclude, /* Exclude terms using these operators */ 3182 sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ 3183 u16 mNoOmit, /* Do not omit these constraints */ 3184 int *pbIn /* OUT: True if plan uses an IN(...) op */ 3185 ){ 3186 WhereClause *pWC = pBuilder->pWC; 3187 struct sqlite3_index_constraint *pIdxCons; 3188 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; 3189 int i; 3190 int mxTerm; 3191 int rc = SQLITE_OK; 3192 WhereLoop *pNew = pBuilder->pNew; 3193 Parse *pParse = pBuilder->pWInfo->pParse; 3194 struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab]; 3195 int nConstraint = pIdxInfo->nConstraint; 3196 3197 assert( (mUsable & mPrereq)==mPrereq ); 3198 *pbIn = 0; 3199 pNew->prereq = mPrereq; 3200 3201 /* Set the usable flag on the subset of constraints identified by 3202 ** arguments mUsable and mExclude. */ 3203 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 3204 for(i=0; i<nConstraint; i++, pIdxCons++){ 3205 WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset]; 3206 pIdxCons->usable = 0; 3207 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight 3208 && (pTerm->eOperator & mExclude)==0 3209 ){ 3210 pIdxCons->usable = 1; 3211 } 3212 } 3213 3214 /* Initialize the output fields of the sqlite3_index_info structure */ 3215 memset(pUsage, 0, sizeof(pUsage[0])*nConstraint); 3216 assert( pIdxInfo->needToFreeIdxStr==0 ); 3217 pIdxInfo->idxStr = 0; 3218 pIdxInfo->idxNum = 0; 3219 pIdxInfo->orderByConsumed = 0; 3220 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; 3221 pIdxInfo->estimatedRows = 25; 3222 pIdxInfo->idxFlags = 0; 3223 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; 3224 3225 /* Invoke the virtual table xBestIndex() method */ 3226 rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo); 3227 if( rc ){ 3228 if( rc==SQLITE_CONSTRAINT ){ 3229 /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means 3230 ** that the particular combination of parameters provided is unusable. 3231 ** Make no entries in the loop table. 3232 */ 3233 WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n")); 3234 return SQLITE_OK; 3235 } 3236 return rc; 3237 } 3238 3239 mxTerm = -1; 3240 assert( pNew->nLSlot>=nConstraint ); 3241 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0; 3242 pNew->u.vtab.omitMask = 0; 3243 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 3244 for(i=0; i<nConstraint; i++, pIdxCons++){ 3245 int iTerm; 3246 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){ 3247 WhereTerm *pTerm; 3248 int j = pIdxCons->iTermOffset; 3249 if( iTerm>=nConstraint 3250 || j<0 3251 || j>=pWC->nTerm 3252 || pNew->aLTerm[iTerm]!=0 3253 || pIdxCons->usable==0 3254 ){ 3255 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); 3256 testcase( pIdxInfo->needToFreeIdxStr ); 3257 return SQLITE_ERROR; 3258 } 3259 testcase( iTerm==nConstraint-1 ); 3260 testcase( j==0 ); 3261 testcase( j==pWC->nTerm-1 ); 3262 pTerm = &pWC->a[j]; 3263 pNew->prereq |= pTerm->prereqRight; 3264 assert( iTerm<pNew->nLSlot ); 3265 pNew->aLTerm[iTerm] = pTerm; 3266 if( iTerm>mxTerm ) mxTerm = iTerm; 3267 testcase( iTerm==15 ); 3268 testcase( iTerm==16 ); 3269 if( pUsage[i].omit ){ 3270 if( i<16 && ((1<<i)&mNoOmit)==0 ){ 3271 testcase( i!=iTerm ); 3272 pNew->u.vtab.omitMask |= 1<<iTerm; 3273 }else{ 3274 testcase( i!=iTerm ); 3275 } 3276 } 3277 if( (pTerm->eOperator & WO_IN)!=0 ){ 3278 /* A virtual table that is constrained by an IN clause may not 3279 ** consume the ORDER BY clause because (1) the order of IN terms 3280 ** is not necessarily related to the order of output terms and 3281 ** (2) Multiple outputs from a single IN value will not merge 3282 ** together. */ 3283 pIdxInfo->orderByConsumed = 0; 3284 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE; 3285 *pbIn = 1; assert( (mExclude & WO_IN)==0 ); 3286 } 3287 } 3288 } 3289 3290 pNew->nLTerm = mxTerm+1; 3291 for(i=0; i<=mxTerm; i++){ 3292 if( pNew->aLTerm[i]==0 ){ 3293 /* The non-zero argvIdx values must be contiguous. Raise an 3294 ** error if they are not */ 3295 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); 3296 testcase( pIdxInfo->needToFreeIdxStr ); 3297 return SQLITE_ERROR; 3298 } 3299 } 3300 assert( pNew->nLTerm<=pNew->nLSlot ); 3301 pNew->u.vtab.idxNum = pIdxInfo->idxNum; 3302 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; 3303 pIdxInfo->needToFreeIdxStr = 0; 3304 pNew->u.vtab.idxStr = pIdxInfo->idxStr; 3305 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? 3306 pIdxInfo->nOrderBy : 0); 3307 pNew->rSetup = 0; 3308 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); 3309 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); 3310 3311 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated 3312 ** that the scan will visit at most one row. Clear it otherwise. */ 3313 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){ 3314 pNew->wsFlags |= WHERE_ONEROW; 3315 }else{ 3316 pNew->wsFlags &= ~WHERE_ONEROW; 3317 } 3318 rc = whereLoopInsert(pBuilder, pNew); 3319 if( pNew->u.vtab.needFree ){ 3320 sqlite3_free(pNew->u.vtab.idxStr); 3321 pNew->u.vtab.needFree = 0; 3322 } 3323 WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n", 3324 *pbIn, (sqlite3_uint64)mPrereq, 3325 (sqlite3_uint64)(pNew->prereq & ~mPrereq))); 3326 3327 return rc; 3328 } 3329 3330 /* 3331 ** If this function is invoked from within an xBestIndex() callback, it 3332 ** returns a pointer to a buffer containing the name of the collation 3333 ** sequence associated with element iCons of the sqlite3_index_info.aConstraint 3334 ** array. Or, if iCons is out of range or there is no active xBestIndex 3335 ** call, return NULL. 3336 */ 3337 const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){ 3338 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; 3339 const char *zRet = 0; 3340 if( iCons>=0 && iCons<pIdxInfo->nConstraint ){ 3341 CollSeq *pC = 0; 3342 int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset; 3343 Expr *pX = pHidden->pWC->a[iTerm].pExpr; 3344 if( pX->pLeft ){ 3345 pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX); 3346 } 3347 zRet = (pC ? pC->zName : sqlite3StrBINARY); 3348 } 3349 return zRet; 3350 } 3351 3352 /* 3353 ** Add all WhereLoop objects for a table of the join identified by 3354 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. 3355 ** 3356 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and 3357 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause 3358 ** entries that occur before the virtual table in the FROM clause and are 3359 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the 3360 ** mUnusable mask contains all FROM clause entries that occur after the 3361 ** virtual table and are separated from it by at least one LEFT or 3362 ** CROSS JOIN. 3363 ** 3364 ** For example, if the query were: 3365 ** 3366 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6; 3367 ** 3368 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6). 3369 ** 3370 ** All the tables in mPrereq must be scanned before the current virtual 3371 ** table. So any terms for which all prerequisites are satisfied by 3372 ** mPrereq may be specified as "usable" in all calls to xBestIndex. 3373 ** Conversely, all tables in mUnusable must be scanned after the current 3374 ** virtual table, so any terms for which the prerequisites overlap with 3375 ** mUnusable should always be configured as "not-usable" for xBestIndex. 3376 */ 3377 static int whereLoopAddVirtual( 3378 WhereLoopBuilder *pBuilder, /* WHERE clause information */ 3379 Bitmask mPrereq, /* Tables that must be scanned before this one */ 3380 Bitmask mUnusable /* Tables that must be scanned after this one */ 3381 ){ 3382 int rc = SQLITE_OK; /* Return code */ 3383 WhereInfo *pWInfo; /* WHERE analysis context */ 3384 Parse *pParse; /* The parsing context */ 3385 WhereClause *pWC; /* The WHERE clause */ 3386 struct SrcList_item *pSrc; /* The FROM clause term to search */ 3387 sqlite3_index_info *p; /* Object to pass to xBestIndex() */ 3388 int nConstraint; /* Number of constraints in p */ 3389 int bIn; /* True if plan uses IN(...) operator */ 3390 WhereLoop *pNew; 3391 Bitmask mBest; /* Tables used by best possible plan */ 3392 u16 mNoOmit; 3393 3394 assert( (mPrereq & mUnusable)==0 ); 3395 pWInfo = pBuilder->pWInfo; 3396 pParse = pWInfo->pParse; 3397 pWC = pBuilder->pWC; 3398 pNew = pBuilder->pNew; 3399 pSrc = &pWInfo->pTabList->a[pNew->iTab]; 3400 assert( IsVirtual(pSrc->pTab) ); 3401 p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, 3402 &mNoOmit); 3403 if( p==0 ) return SQLITE_NOMEM_BKPT; 3404 pNew->rSetup = 0; 3405 pNew->wsFlags = WHERE_VIRTUALTABLE; 3406 pNew->nLTerm = 0; 3407 pNew->u.vtab.needFree = 0; 3408 nConstraint = p->nConstraint; 3409 if( whereLoopResize(pParse->db, pNew, nConstraint) ){ 3410 sqlite3DbFree(pParse->db, p); 3411 return SQLITE_NOMEM_BKPT; 3412 } 3413 3414 /* First call xBestIndex() with all constraints usable. */ 3415 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName)); 3416 WHERETRACE(0x40, (" VirtualOne: all usable\n")); 3417 rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn); 3418 3419 /* If the call to xBestIndex() with all terms enabled produced a plan 3420 ** that does not require any source tables (IOW: a plan with mBest==0) 3421 ** and does not use an IN(...) operator, then there is no point in making 3422 ** any further calls to xBestIndex() since they will all return the same 3423 ** result (if the xBestIndex() implementation is sane). */ 3424 if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){ 3425 int seenZero = 0; /* True if a plan with no prereqs seen */ 3426 int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */ 3427 Bitmask mPrev = 0; 3428 Bitmask mBestNoIn = 0; 3429 3430 /* If the plan produced by the earlier call uses an IN(...) term, call 3431 ** xBestIndex again, this time with IN(...) terms disabled. */ 3432 if( bIn ){ 3433 WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n")); 3434 rc = whereLoopAddVirtualOne( 3435 pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn); 3436 assert( bIn==0 ); 3437 mBestNoIn = pNew->prereq & ~mPrereq; 3438 if( mBestNoIn==0 ){ 3439 seenZero = 1; 3440 seenZeroNoIN = 1; 3441 } 3442 } 3443 3444 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) 3445 ** in the set of terms that apply to the current virtual table. */ 3446 while( rc==SQLITE_OK ){ 3447 int i; 3448 Bitmask mNext = ALLBITS; 3449 assert( mNext>0 ); 3450 for(i=0; i<nConstraint; i++){ 3451 Bitmask mThis = ( 3452 pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq 3453 ); 3454 if( mThis>mPrev && mThis<mNext ) mNext = mThis; 3455 } 3456 mPrev = mNext; 3457 if( mNext==ALLBITS ) break; 3458 if( mNext==mBest || mNext==mBestNoIn ) continue; 3459 WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n", 3460 (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext)); 3461 rc = whereLoopAddVirtualOne( 3462 pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn); 3463 if( pNew->prereq==mPrereq ){ 3464 seenZero = 1; 3465 if( bIn==0 ) seenZeroNoIN = 1; 3466 } 3467 } 3468 3469 /* If the calls to xBestIndex() in the above loop did not find a plan 3470 ** that requires no source tables at all (i.e. one guaranteed to be 3471 ** usable), make a call here with all source tables disabled */ 3472 if( rc==SQLITE_OK && seenZero==0 ){ 3473 WHERETRACE(0x40, (" VirtualOne: all disabled\n")); 3474 rc = whereLoopAddVirtualOne( 3475 pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn); 3476 if( bIn==0 ) seenZeroNoIN = 1; 3477 } 3478 3479 /* If the calls to xBestIndex() have so far failed to find a plan 3480 ** that requires no source tables at all and does not use an IN(...) 3481 ** operator, make a final call to obtain one here. */ 3482 if( rc==SQLITE_OK && seenZeroNoIN==0 ){ 3483 WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n")); 3484 rc = whereLoopAddVirtualOne( 3485 pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn); 3486 } 3487 } 3488 3489 if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr); 3490 sqlite3DbFreeNN(pParse->db, p); 3491 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc)); 3492 return rc; 3493 } 3494 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 3495 3496 /* 3497 ** Add WhereLoop entries to handle OR terms. This works for either 3498 ** btrees or virtual tables. 3499 */ 3500 static int whereLoopAddOr( 3501 WhereLoopBuilder *pBuilder, 3502 Bitmask mPrereq, 3503 Bitmask mUnusable 3504 ){ 3505 WhereInfo *pWInfo = pBuilder->pWInfo; 3506 WhereClause *pWC; 3507 WhereLoop *pNew; 3508 WhereTerm *pTerm, *pWCEnd; 3509 int rc = SQLITE_OK; 3510 int iCur; 3511 WhereClause tempWC; 3512 WhereLoopBuilder sSubBuild; 3513 WhereOrSet sSum, sCur; 3514 struct SrcList_item *pItem; 3515 3516 pWC = pBuilder->pWC; 3517 pWCEnd = pWC->a + pWC->nTerm; 3518 pNew = pBuilder->pNew; 3519 memset(&sSum, 0, sizeof(sSum)); 3520 pItem = pWInfo->pTabList->a + pNew->iTab; 3521 iCur = pItem->iCursor; 3522 3523 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){ 3524 if( (pTerm->eOperator & WO_OR)!=0 3525 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 3526 ){ 3527 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; 3528 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; 3529 WhereTerm *pOrTerm; 3530 int once = 1; 3531 int i, j; 3532 3533 sSubBuild = *pBuilder; 3534 sSubBuild.pOrderBy = 0; 3535 sSubBuild.pOrSet = &sCur; 3536 3537 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm)); 3538 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){ 3539 if( (pOrTerm->eOperator & WO_AND)!=0 ){ 3540 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; 3541 }else if( pOrTerm->leftCursor==iCur ){ 3542 tempWC.pWInfo = pWC->pWInfo; 3543 tempWC.pOuter = pWC; 3544 tempWC.op = TK_AND; 3545 tempWC.nTerm = 1; 3546 tempWC.a = pOrTerm; 3547 sSubBuild.pWC = &tempWC; 3548 }else{ 3549 continue; 3550 } 3551 sCur.n = 0; 3552 #ifdef WHERETRACE_ENABLED 3553 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", 3554 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); 3555 if( sqlite3WhereTrace & 0x400 ){ 3556 sqlite3WhereClausePrint(sSubBuild.pWC); 3557 } 3558 #endif 3559 #ifndef SQLITE_OMIT_VIRTUALTABLE 3560 if( IsVirtual(pItem->pTab) ){ 3561 rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable); 3562 }else 3563 #endif 3564 { 3565 rc = whereLoopAddBtree(&sSubBuild, mPrereq); 3566 } 3567 if( rc==SQLITE_OK ){ 3568 rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable); 3569 } 3570 assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 ); 3571 testcase( rc==SQLITE_DONE ); 3572 if( sCur.n==0 ){ 3573 sSum.n = 0; 3574 break; 3575 }else if( once ){ 3576 whereOrMove(&sSum, &sCur); 3577 once = 0; 3578 }else{ 3579 WhereOrSet sPrev; 3580 whereOrMove(&sPrev, &sSum); 3581 sSum.n = 0; 3582 for(i=0; i<sPrev.n; i++){ 3583 for(j=0; j<sCur.n; j++){ 3584 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq, 3585 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun), 3586 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut)); 3587 } 3588 } 3589 } 3590 } 3591 pNew->nLTerm = 1; 3592 pNew->aLTerm[0] = pTerm; 3593 pNew->wsFlags = WHERE_MULTI_OR; 3594 pNew->rSetup = 0; 3595 pNew->iSortIdx = 0; 3596 memset(&pNew->u, 0, sizeof(pNew->u)); 3597 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){ 3598 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs 3599 ** of all sub-scans required by the OR-scan. However, due to rounding 3600 ** errors, it may be that the cost of the OR-scan is equal to its 3601 ** most expensive sub-scan. Add the smallest possible penalty 3602 ** (equivalent to multiplying the cost by 1.07) to ensure that 3603 ** this does not happen. Otherwise, for WHERE clauses such as the 3604 ** following where there is an index on "y": 3605 ** 3606 ** WHERE likelihood(x=?, 0.99) OR y=? 3607 ** 3608 ** the planner may elect to "OR" together a full-table scan and an 3609 ** index lookup. And other similarly odd results. */ 3610 pNew->rRun = sSum.a[i].rRun + 1; 3611 pNew->nOut = sSum.a[i].nOut; 3612 pNew->prereq = sSum.a[i].prereq; 3613 rc = whereLoopInsert(pBuilder, pNew); 3614 } 3615 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm)); 3616 } 3617 } 3618 return rc; 3619 } 3620 3621 /* 3622 ** Add all WhereLoop objects for all tables 3623 */ 3624 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ 3625 WhereInfo *pWInfo = pBuilder->pWInfo; 3626 Bitmask mPrereq = 0; 3627 Bitmask mPrior = 0; 3628 int iTab; 3629 SrcList *pTabList = pWInfo->pTabList; 3630 struct SrcList_item *pItem; 3631 struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel]; 3632 sqlite3 *db = pWInfo->pParse->db; 3633 int rc = SQLITE_OK; 3634 WhereLoop *pNew; 3635 3636 /* Loop over the tables in the join, from left to right */ 3637 pNew = pBuilder->pNew; 3638 whereLoopInit(pNew); 3639 pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT; 3640 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){ 3641 Bitmask mUnusable = 0; 3642 pNew->iTab = iTab; 3643 pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR; 3644 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); 3645 if( (pItem->fg.jointype & (JT_LEFT|JT_CROSS))!=0 ){ 3646 /* This condition is true when pItem is the FROM clause term on the 3647 ** right-hand-side of a LEFT or CROSS JOIN. */ 3648 mPrereq = mPrior; 3649 }else{ 3650 mPrereq = 0; 3651 } 3652 #ifndef SQLITE_OMIT_VIRTUALTABLE 3653 if( IsVirtual(pItem->pTab) ){ 3654 struct SrcList_item *p; 3655 for(p=&pItem[1]; p<pEnd; p++){ 3656 if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){ 3657 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); 3658 } 3659 } 3660 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable); 3661 }else 3662 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 3663 { 3664 rc = whereLoopAddBtree(pBuilder, mPrereq); 3665 } 3666 if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){ 3667 rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); 3668 } 3669 mPrior |= pNew->maskSelf; 3670 if( rc || db->mallocFailed ){ 3671 if( rc==SQLITE_DONE ){ 3672 /* We hit the query planner search limit set by iPlanLimit */ 3673 sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search"); 3674 rc = SQLITE_OK; 3675 }else{ 3676 break; 3677 } 3678 } 3679 } 3680 3681 whereLoopClear(db, pNew); 3682 return rc; 3683 } 3684 3685 /* 3686 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th 3687 ** parameters) to see if it outputs rows in the requested ORDER BY 3688 ** (or GROUP BY) without requiring a separate sort operation. Return N: 3689 ** 3690 ** N>0: N terms of the ORDER BY clause are satisfied 3691 ** N==0: No terms of the ORDER BY clause are satisfied 3692 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied. 3693 ** 3694 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as 3695 ** strict. With GROUP BY and DISTINCT the only requirement is that 3696 ** equivalent rows appear immediately adjacent to one another. GROUP BY 3697 ** and DISTINCT do not require rows to appear in any particular order as long 3698 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT 3699 ** the pOrderBy terms can be matched in any order. With ORDER BY, the 3700 ** pOrderBy terms must be matched in strict left-to-right order. 3701 */ 3702 static i8 wherePathSatisfiesOrderBy( 3703 WhereInfo *pWInfo, /* The WHERE clause */ 3704 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ 3705 WherePath *pPath, /* The WherePath to check */ 3706 u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ 3707 u16 nLoop, /* Number of entries in pPath->aLoop[] */ 3708 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ 3709 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ 3710 ){ 3711 u8 revSet; /* True if rev is known */ 3712 u8 rev; /* Composite sort order */ 3713 u8 revIdx; /* Index sort order */ 3714 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ 3715 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ 3716 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ 3717 u16 eqOpMask; /* Allowed equality operators */ 3718 u16 nKeyCol; /* Number of key columns in pIndex */ 3719 u16 nColumn; /* Total number of ordered columns in the index */ 3720 u16 nOrderBy; /* Number terms in the ORDER BY clause */ 3721 int iLoop; /* Index of WhereLoop in pPath being processed */ 3722 int i, j; /* Loop counters */ 3723 int iCur; /* Cursor number for current WhereLoop */ 3724 int iColumn; /* A column number within table iCur */ 3725 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ 3726 WhereTerm *pTerm; /* A single term of the WHERE clause */ 3727 Expr *pOBExpr; /* An expression from the ORDER BY clause */ 3728 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ 3729 Index *pIndex; /* The index associated with pLoop */ 3730 sqlite3 *db = pWInfo->pParse->db; /* Database connection */ 3731 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ 3732 Bitmask obDone; /* Mask of all ORDER BY terms */ 3733 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ 3734 Bitmask ready; /* Mask of inner loops */ 3735 3736 /* 3737 ** We say the WhereLoop is "one-row" if it generates no more than one 3738 ** row of output. A WhereLoop is one-row if all of the following are true: 3739 ** (a) All index columns match with WHERE_COLUMN_EQ. 3740 ** (b) The index is unique 3741 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. 3742 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. 3743 ** 3744 ** We say the WhereLoop is "order-distinct" if the set of columns from 3745 ** that WhereLoop that are in the ORDER BY clause are different for every 3746 ** row of the WhereLoop. Every one-row WhereLoop is automatically 3747 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause 3748 ** is not order-distinct. To be order-distinct is not quite the same as being 3749 ** UNIQUE since a UNIQUE column or index can have multiple rows that 3750 ** are NULL and NULL values are equivalent for the purpose of order-distinct. 3751 ** To be order-distinct, the columns must be UNIQUE and NOT NULL. 3752 ** 3753 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the 3754 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is 3755 ** automatically order-distinct. 3756 */ 3757 3758 assert( pOrderBy!=0 ); 3759 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; 3760 3761 nOrderBy = pOrderBy->nExpr; 3762 testcase( nOrderBy==BMS-1 ); 3763 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ 3764 isOrderDistinct = 1; 3765 obDone = MASKBIT(nOrderBy)-1; 3766 orderDistinctMask = 0; 3767 ready = 0; 3768 eqOpMask = WO_EQ | WO_IS | WO_ISNULL; 3769 if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){ 3770 eqOpMask |= WO_IN; 3771 } 3772 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){ 3773 if( iLoop>0 ) ready |= pLoop->maskSelf; 3774 if( iLoop<nLoop ){ 3775 pLoop = pPath->aLoop[iLoop]; 3776 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue; 3777 }else{ 3778 pLoop = pLast; 3779 } 3780 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ 3781 if( pLoop->u.vtab.isOrdered && (wctrlFlags & WHERE_DISTINCTBY)==0 ){ 3782 obSat = obDone; 3783 } 3784 break; 3785 }else if( wctrlFlags & WHERE_DISTINCTBY ){ 3786 pLoop->u.btree.nDistinctCol = 0; 3787 } 3788 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; 3789 3790 /* Mark off any ORDER BY term X that is a column in the table of 3791 ** the current loop for which there is term in the WHERE 3792 ** clause of the form X IS NULL or X=? that reference only outer 3793 ** loops. 3794 */ 3795 for(i=0; i<nOrderBy; i++){ 3796 if( MASKBIT(i) & obSat ) continue; 3797 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr); 3798 if( NEVER(pOBExpr==0) ) continue; 3799 if( pOBExpr->op!=TK_COLUMN ) continue; 3800 if( pOBExpr->iTable!=iCur ) continue; 3801 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, 3802 ~ready, eqOpMask, 0); 3803 if( pTerm==0 ) continue; 3804 if( pTerm->eOperator==WO_IN ){ 3805 /* IN terms are only valid for sorting in the ORDER BY LIMIT 3806 ** optimization, and then only if they are actually used 3807 ** by the query plan */ 3808 assert( wctrlFlags & 3809 (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ); 3810 for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){} 3811 if( j>=pLoop->nLTerm ) continue; 3812 } 3813 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ 3814 Parse *pParse = pWInfo->pParse; 3815 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr); 3816 CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr); 3817 assert( pColl1 ); 3818 if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){ 3819 continue; 3820 } 3821 testcase( pTerm->pExpr->op==TK_IS ); 3822 } 3823 obSat |= MASKBIT(i); 3824 } 3825 3826 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ 3827 if( pLoop->wsFlags & WHERE_IPK ){ 3828 pIndex = 0; 3829 nKeyCol = 0; 3830 nColumn = 1; 3831 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ 3832 return 0; 3833 }else{ 3834 nKeyCol = pIndex->nKeyCol; 3835 nColumn = pIndex->nColumn; 3836 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); 3837 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID 3838 || !HasRowid(pIndex->pTable)); 3839 isOrderDistinct = IsUniqueIndex(pIndex) 3840 && (pLoop->wsFlags & WHERE_SKIPSCAN)==0; 3841 } 3842 3843 /* Loop through all columns of the index and deal with the ones 3844 ** that are not constrained by == or IN. 3845 */ 3846 rev = revSet = 0; 3847 distinctColumns = 0; 3848 for(j=0; j<nColumn; j++){ 3849 u8 bOnce = 1; /* True to run the ORDER BY search loop */ 3850 3851 assert( j>=pLoop->u.btree.nEq 3852 || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip) 3853 ); 3854 if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){ 3855 u16 eOp = pLoop->aLTerm[j]->eOperator; 3856 3857 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when 3858 ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL 3859 ** terms imply that the index is not UNIQUE NOT NULL in which case 3860 ** the loop need to be marked as not order-distinct because it can 3861 ** have repeated NULL rows. 3862 ** 3863 ** If the current term is a column of an ((?,?) IN (SELECT...)) 3864 ** expression for which the SELECT returns more than one column, 3865 ** check that it is the only column used by this loop. Otherwise, 3866 ** if it is one of two or more, none of the columns can be 3867 ** considered to match an ORDER BY term. 3868 */ 3869 if( (eOp & eqOpMask)!=0 ){ 3870 if( eOp & (WO_ISNULL|WO_IS) ){ 3871 testcase( eOp & WO_ISNULL ); 3872 testcase( eOp & WO_IS ); 3873 testcase( isOrderDistinct ); 3874 isOrderDistinct = 0; 3875 } 3876 continue; 3877 }else if( ALWAYS(eOp & WO_IN) ){ 3878 /* ALWAYS() justification: eOp is an equality operator due to the 3879 ** j<pLoop->u.btree.nEq constraint above. Any equality other 3880 ** than WO_IN is captured by the previous "if". So this one 3881 ** always has to be WO_IN. */ 3882 Expr *pX = pLoop->aLTerm[j]->pExpr; 3883 for(i=j+1; i<pLoop->u.btree.nEq; i++){ 3884 if( pLoop->aLTerm[i]->pExpr==pX ){ 3885 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) ); 3886 bOnce = 0; 3887 break; 3888 } 3889 } 3890 } 3891 } 3892 3893 /* Get the column number in the table (iColumn) and sort order 3894 ** (revIdx) for the j-th column of the index. 3895 */ 3896 if( pIndex ){ 3897 iColumn = pIndex->aiColumn[j]; 3898 revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC; 3899 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID; 3900 }else{ 3901 iColumn = XN_ROWID; 3902 revIdx = 0; 3903 } 3904 3905 /* An unconstrained column that might be NULL means that this 3906 ** WhereLoop is not well-ordered 3907 */ 3908 if( isOrderDistinct 3909 && iColumn>=0 3910 && j>=pLoop->u.btree.nEq 3911 && pIndex->pTable->aCol[iColumn].notNull==0 3912 ){ 3913 isOrderDistinct = 0; 3914 } 3915 3916 /* Find the ORDER BY term that corresponds to the j-th column 3917 ** of the index and mark that ORDER BY term off 3918 */ 3919 isMatch = 0; 3920 for(i=0; bOnce && i<nOrderBy; i++){ 3921 if( MASKBIT(i) & obSat ) continue; 3922 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr); 3923 testcase( wctrlFlags & WHERE_GROUPBY ); 3924 testcase( wctrlFlags & WHERE_DISTINCTBY ); 3925 if( NEVER(pOBExpr==0) ) continue; 3926 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; 3927 if( iColumn>=XN_ROWID ){ 3928 if( pOBExpr->op!=TK_COLUMN ) continue; 3929 if( pOBExpr->iTable!=iCur ) continue; 3930 if( pOBExpr->iColumn!=iColumn ) continue; 3931 }else{ 3932 Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr; 3933 if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){ 3934 continue; 3935 } 3936 } 3937 if( iColumn!=XN_ROWID ){ 3938 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); 3939 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; 3940 } 3941 if( wctrlFlags & WHERE_DISTINCTBY ){ 3942 pLoop->u.btree.nDistinctCol = j+1; 3943 } 3944 isMatch = 1; 3945 break; 3946 } 3947 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ 3948 /* Make sure the sort order is compatible in an ORDER BY clause. 3949 ** Sort order is irrelevant for a GROUP BY clause. */ 3950 if( revSet ){ 3951 if( (rev ^ revIdx)!=(pOrderBy->a[i].sortFlags&KEYINFO_ORDER_DESC) ){ 3952 isMatch = 0; 3953 } 3954 }else{ 3955 rev = revIdx ^ (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC); 3956 if( rev ) *pRevMask |= MASKBIT(iLoop); 3957 revSet = 1; 3958 } 3959 } 3960 if( isMatch && (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL) ){ 3961 if( j==pLoop->u.btree.nEq ){ 3962 pLoop->wsFlags |= WHERE_BIGNULL_SORT; 3963 }else{ 3964 isMatch = 0; 3965 } 3966 } 3967 if( isMatch ){ 3968 if( iColumn==XN_ROWID ){ 3969 testcase( distinctColumns==0 ); 3970 distinctColumns = 1; 3971 } 3972 obSat |= MASKBIT(i); 3973 }else{ 3974 /* No match found */ 3975 if( j==0 || j<nKeyCol ){ 3976 testcase( isOrderDistinct!=0 ); 3977 isOrderDistinct = 0; 3978 } 3979 break; 3980 } 3981 } /* end Loop over all index columns */ 3982 if( distinctColumns ){ 3983 testcase( isOrderDistinct==0 ); 3984 isOrderDistinct = 1; 3985 } 3986 } /* end-if not one-row */ 3987 3988 /* Mark off any other ORDER BY terms that reference pLoop */ 3989 if( isOrderDistinct ){ 3990 orderDistinctMask |= pLoop->maskSelf; 3991 for(i=0; i<nOrderBy; i++){ 3992 Expr *p; 3993 Bitmask mTerm; 3994 if( MASKBIT(i) & obSat ) continue; 3995 p = pOrderBy->a[i].pExpr; 3996 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); 3997 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; 3998 if( (mTerm&~orderDistinctMask)==0 ){ 3999 obSat |= MASKBIT(i); 4000 } 4001 } 4002 } 4003 } /* End the loop over all WhereLoops from outer-most down to inner-most */ 4004 if( obSat==obDone ) return (i8)nOrderBy; 4005 if( !isOrderDistinct ){ 4006 for(i=nOrderBy-1; i>0; i--){ 4007 Bitmask m = MASKBIT(i) - 1; 4008 if( (obSat&m)==m ) return i; 4009 } 4010 return 0; 4011 } 4012 return -1; 4013 } 4014 4015 4016 /* 4017 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(), 4018 ** the planner assumes that the specified pOrderBy list is actually a GROUP 4019 ** BY clause - and so any order that groups rows as required satisfies the 4020 ** request. 4021 ** 4022 ** Normally, in this case it is not possible for the caller to determine 4023 ** whether or not the rows are really being delivered in sorted order, or 4024 ** just in some other order that provides the required grouping. However, 4025 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then 4026 ** this function may be called on the returned WhereInfo object. It returns 4027 ** true if the rows really will be sorted in the specified order, or false 4028 ** otherwise. 4029 ** 4030 ** For example, assuming: 4031 ** 4032 ** CREATE INDEX i1 ON t1(x, Y); 4033 ** 4034 ** then 4035 ** 4036 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1 4037 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0 4038 */ 4039 int sqlite3WhereIsSorted(WhereInfo *pWInfo){ 4040 assert( pWInfo->wctrlFlags & WHERE_GROUPBY ); 4041 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); 4042 return pWInfo->sorted; 4043 } 4044 4045 #ifdef WHERETRACE_ENABLED 4046 /* For debugging use only: */ 4047 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ 4048 static char zName[65]; 4049 int i; 4050 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; } 4051 if( pLast ) zName[i++] = pLast->cId; 4052 zName[i] = 0; 4053 return zName; 4054 } 4055 #endif 4056 4057 /* 4058 ** Return the cost of sorting nRow rows, assuming that the keys have 4059 ** nOrderby columns and that the first nSorted columns are already in 4060 ** order. 4061 */ 4062 static LogEst whereSortingCost( 4063 WhereInfo *pWInfo, 4064 LogEst nRow, 4065 int nOrderBy, 4066 int nSorted 4067 ){ 4068 /* TUNING: Estimated cost of a full external sort, where N is 4069 ** the number of rows to sort is: 4070 ** 4071 ** cost = (3.0 * N * log(N)). 4072 ** 4073 ** Or, if the order-by clause has X terms but only the last Y 4074 ** terms are out of order, then block-sorting will reduce the 4075 ** sorting cost to: 4076 ** 4077 ** cost = (3.0 * N * log(N)) * (Y/X) 4078 ** 4079 ** The (Y/X) term is implemented using stack variable rScale 4080 ** below. 4081 */ 4082 LogEst rScale, rSortCost; 4083 assert( nOrderBy>0 && 66==sqlite3LogEst(100) ); 4084 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; 4085 rSortCost = nRow + rScale + 16; 4086 4087 /* Multiple by log(M) where M is the number of output rows. 4088 ** Use the LIMIT for M if it is smaller. Or if this sort is for 4089 ** a DISTINCT operator, M will be the number of distinct output 4090 ** rows, so fudge it downwards a bit. 4091 */ 4092 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){ 4093 nRow = pWInfo->iLimit; 4094 }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){ 4095 /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT 4096 ** reduces the number of output rows by a factor of 2 */ 4097 if( nRow>10 ) nRow -= 10; assert( 10==sqlite3LogEst(2) ); 4098 } 4099 rSortCost += estLog(nRow); 4100 return rSortCost; 4101 } 4102 4103 /* 4104 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine 4105 ** attempts to find the lowest cost path that visits each WhereLoop 4106 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields. 4107 ** 4108 ** Assume that the total number of output rows that will need to be sorted 4109 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting 4110 ** costs if nRowEst==0. 4111 ** 4112 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation 4113 ** error occurs. 4114 */ 4115 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ 4116 int mxChoice; /* Maximum number of simultaneous paths tracked */ 4117 int nLoop; /* Number of terms in the join */ 4118 Parse *pParse; /* Parsing context */ 4119 sqlite3 *db; /* The database connection */ 4120 int iLoop; /* Loop counter over the terms of the join */ 4121 int ii, jj; /* Loop counters */ 4122 int mxI = 0; /* Index of next entry to replace */ 4123 int nOrderBy; /* Number of ORDER BY clause terms */ 4124 LogEst mxCost = 0; /* Maximum cost of a set of paths */ 4125 LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */ 4126 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ 4127 WherePath *aFrom; /* All nFrom paths at the previous level */ 4128 WherePath *aTo; /* The nTo best paths at the current level */ 4129 WherePath *pFrom; /* An element of aFrom[] that we are working on */ 4130 WherePath *pTo; /* An element of aTo[] that we are working on */ 4131 WhereLoop *pWLoop; /* One of the WhereLoop objects */ 4132 WhereLoop **pX; /* Used to divy up the pSpace memory */ 4133 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */ 4134 char *pSpace; /* Temporary memory used by this routine */ 4135 int nSpace; /* Bytes of space allocated at pSpace */ 4136 4137 pParse = pWInfo->pParse; 4138 db = pParse->db; 4139 nLoop = pWInfo->nLevel; 4140 /* TUNING: For simple queries, only the best path is tracked. 4141 ** For 2-way joins, the 5 best paths are followed. 4142 ** For joins of 3 or more tables, track the 10 best paths */ 4143 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10); 4144 assert( nLoop<=pWInfo->pTabList->nSrc ); 4145 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst)); 4146 4147 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this 4148 ** case the purpose of this call is to estimate the number of rows returned 4149 ** by the overall query. Once this estimate has been obtained, the caller 4150 ** will invoke this function a second time, passing the estimate as the 4151 ** nRowEst parameter. */ 4152 if( pWInfo->pOrderBy==0 || nRowEst==0 ){ 4153 nOrderBy = 0; 4154 }else{ 4155 nOrderBy = pWInfo->pOrderBy->nExpr; 4156 } 4157 4158 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */ 4159 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; 4160 nSpace += sizeof(LogEst) * nOrderBy; 4161 pSpace = sqlite3DbMallocRawNN(db, nSpace); 4162 if( pSpace==0 ) return SQLITE_NOMEM_BKPT; 4163 aTo = (WherePath*)pSpace; 4164 aFrom = aTo+mxChoice; 4165 memset(aFrom, 0, sizeof(aFrom[0])); 4166 pX = (WhereLoop**)(aFrom+mxChoice); 4167 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ 4168 pFrom->aLoop = pX; 4169 } 4170 if( nOrderBy ){ 4171 /* If there is an ORDER BY clause and it is not being ignored, set up 4172 ** space for the aSortCost[] array. Each element of the aSortCost array 4173 ** is either zero - meaning it has not yet been initialized - or the 4174 ** cost of sorting nRowEst rows of data where the first X terms of 4175 ** the ORDER BY clause are already in order, where X is the array 4176 ** index. */ 4177 aSortCost = (LogEst*)pX; 4178 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); 4179 } 4180 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); 4181 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); 4182 4183 /* Seed the search with a single WherePath containing zero WhereLoops. 4184 ** 4185 ** TUNING: Do not let the number of iterations go above 28. If the cost 4186 ** of computing an automatic index is not paid back within the first 28 4187 ** rows, then do not use the automatic index. */ 4188 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) ); 4189 nFrom = 1; 4190 assert( aFrom[0].isOrdered==0 ); 4191 if( nOrderBy ){ 4192 /* If nLoop is zero, then there are no FROM terms in the query. Since 4193 ** in this case the query may return a maximum of one row, the results 4194 ** are already in the requested order. Set isOrdered to nOrderBy to 4195 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to 4196 ** -1, indicating that the result set may or may not be ordered, 4197 ** depending on the loops added to the current plan. */ 4198 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; 4199 } 4200 4201 /* Compute successively longer WherePaths using the previous generation 4202 ** of WherePaths as the basis for the next. Keep track of the mxChoice 4203 ** best paths at each generation */ 4204 for(iLoop=0; iLoop<nLoop; iLoop++){ 4205 nTo = 0; 4206 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){ 4207 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ 4208 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */ 4209 LogEst rCost; /* Cost of path (pFrom+pWLoop) */ 4210 LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */ 4211 i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */ 4212 Bitmask maskNew; /* Mask of src visited by (..) */ 4213 Bitmask revMask = 0; /* Mask of rev-order loops for (..) */ 4214 4215 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; 4216 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; 4217 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){ 4218 /* Do not use an automatic index if the this loop is expected 4219 ** to run less than 1.25 times. It is tempting to also exclude 4220 ** automatic index usage on an outer loop, but sometimes an automatic 4221 ** index is useful in the outer loop of a correlated subquery. */ 4222 assert( 10==sqlite3LogEst(2) ); 4223 continue; 4224 } 4225 4226 /* At this point, pWLoop is a candidate to be the next loop. 4227 ** Compute its cost */ 4228 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); 4229 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted); 4230 nOut = pFrom->nRow + pWLoop->nOut; 4231 maskNew = pFrom->maskLoop | pWLoop->maskSelf; 4232 if( isOrdered<0 ){ 4233 isOrdered = wherePathSatisfiesOrderBy(pWInfo, 4234 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, 4235 iLoop, pWLoop, &revMask); 4236 }else{ 4237 revMask = pFrom->revLoop; 4238 } 4239 if( isOrdered>=0 && isOrdered<nOrderBy ){ 4240 if( aSortCost[isOrdered]==0 ){ 4241 aSortCost[isOrdered] = whereSortingCost( 4242 pWInfo, nRowEst, nOrderBy, isOrdered 4243 ); 4244 } 4245 /* TUNING: Add a small extra penalty (5) to sorting as an 4246 ** extra encouragment to the query planner to select a plan 4247 ** where the rows emerge in the correct order without any sorting 4248 ** required. */ 4249 rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5; 4250 4251 WHERETRACE(0x002, 4252 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n", 4253 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, 4254 rUnsorted, rCost)); 4255 }else{ 4256 rCost = rUnsorted; 4257 rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */ 4258 } 4259 4260 /* Check to see if pWLoop should be added to the set of 4261 ** mxChoice best-so-far paths. 4262 ** 4263 ** First look for an existing path among best-so-far paths 4264 ** that covers the same set of loops and has the same isOrdered 4265 ** setting as the current path candidate. 4266 ** 4267 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent 4268 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range 4269 ** of legal values for isOrdered, -1..64. 4270 */ 4271 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){ 4272 if( pTo->maskLoop==maskNew 4273 && ((pTo->isOrdered^isOrdered)&0x80)==0 4274 ){ 4275 testcase( jj==nTo-1 ); 4276 break; 4277 } 4278 } 4279 if( jj>=nTo ){ 4280 /* None of the existing best-so-far paths match the candidate. */ 4281 if( nTo>=mxChoice 4282 && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted)) 4283 ){ 4284 /* The current candidate is no better than any of the mxChoice 4285 ** paths currently in the best-so-far buffer. So discard 4286 ** this candidate as not viable. */ 4287 #ifdef WHERETRACE_ENABLED /* 0x4 */ 4288 if( sqlite3WhereTrace&0x4 ){ 4289 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n", 4290 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, 4291 isOrdered>=0 ? isOrdered+'0' : '?'); 4292 } 4293 #endif 4294 continue; 4295 } 4296 /* If we reach this points it means that the new candidate path 4297 ** needs to be added to the set of best-so-far paths. */ 4298 if( nTo<mxChoice ){ 4299 /* Increase the size of the aTo set by one */ 4300 jj = nTo++; 4301 }else{ 4302 /* New path replaces the prior worst to keep count below mxChoice */ 4303 jj = mxI; 4304 } 4305 pTo = &aTo[jj]; 4306 #ifdef WHERETRACE_ENABLED /* 0x4 */ 4307 if( sqlite3WhereTrace&0x4 ){ 4308 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n", 4309 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, 4310 isOrdered>=0 ? isOrdered+'0' : '?'); 4311 } 4312 #endif 4313 }else{ 4314 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the 4315 ** same set of loops and has the same isOrdered setting as the 4316 ** candidate path. Check to see if the candidate should replace 4317 ** pTo or if the candidate should be skipped. 4318 ** 4319 ** The conditional is an expanded vector comparison equivalent to: 4320 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted) 4321 */ 4322 if( pTo->rCost<rCost 4323 || (pTo->rCost==rCost 4324 && (pTo->nRow<nOut 4325 || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted) 4326 ) 4327 ) 4328 ){ 4329 #ifdef WHERETRACE_ENABLED /* 0x4 */ 4330 if( sqlite3WhereTrace&0x4 ){ 4331 sqlite3DebugPrintf( 4332 "Skip %s cost=%-3d,%3d,%3d order=%c", 4333 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, 4334 isOrdered>=0 ? isOrdered+'0' : '?'); 4335 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n", 4336 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 4337 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); 4338 } 4339 #endif 4340 /* Discard the candidate path from further consideration */ 4341 testcase( pTo->rCost==rCost ); 4342 continue; 4343 } 4344 testcase( pTo->rCost==rCost+1 ); 4345 /* Control reaches here if the candidate path is better than the 4346 ** pTo path. Replace pTo with the candidate. */ 4347 #ifdef WHERETRACE_ENABLED /* 0x4 */ 4348 if( sqlite3WhereTrace&0x4 ){ 4349 sqlite3DebugPrintf( 4350 "Update %s cost=%-3d,%3d,%3d order=%c", 4351 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted, 4352 isOrdered>=0 ? isOrdered+'0' : '?'); 4353 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n", 4354 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 4355 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); 4356 } 4357 #endif 4358 } 4359 /* pWLoop is a winner. Add it to the set of best so far */ 4360 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; 4361 pTo->revLoop = revMask; 4362 pTo->nRow = nOut; 4363 pTo->rCost = rCost; 4364 pTo->rUnsorted = rUnsorted; 4365 pTo->isOrdered = isOrdered; 4366 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); 4367 pTo->aLoop[iLoop] = pWLoop; 4368 if( nTo>=mxChoice ){ 4369 mxI = 0; 4370 mxCost = aTo[0].rCost; 4371 mxUnsorted = aTo[0].nRow; 4372 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){ 4373 if( pTo->rCost>mxCost 4374 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) 4375 ){ 4376 mxCost = pTo->rCost; 4377 mxUnsorted = pTo->rUnsorted; 4378 mxI = jj; 4379 } 4380 } 4381 } 4382 } 4383 } 4384 4385 #ifdef WHERETRACE_ENABLED /* >=2 */ 4386 if( sqlite3WhereTrace & 0x02 ){ 4387 sqlite3DebugPrintf("---- after round %d ----\n", iLoop); 4388 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){ 4389 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", 4390 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 4391 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); 4392 if( pTo->isOrdered>0 ){ 4393 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); 4394 }else{ 4395 sqlite3DebugPrintf("\n"); 4396 } 4397 } 4398 } 4399 #endif 4400 4401 /* Swap the roles of aFrom and aTo for the next generation */ 4402 pFrom = aTo; 4403 aTo = aFrom; 4404 aFrom = pFrom; 4405 nFrom = nTo; 4406 } 4407 4408 if( nFrom==0 ){ 4409 sqlite3ErrorMsg(pParse, "no query solution"); 4410 sqlite3DbFreeNN(db, pSpace); 4411 return SQLITE_ERROR; 4412 } 4413 4414 /* Find the lowest cost path. pFrom will be left pointing to that path */ 4415 pFrom = aFrom; 4416 for(ii=1; ii<nFrom; ii++){ 4417 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; 4418 } 4419 assert( pWInfo->nLevel==nLoop ); 4420 /* Load the lowest cost path into pWInfo */ 4421 for(iLoop=0; iLoop<nLoop; iLoop++){ 4422 WhereLevel *pLevel = pWInfo->a + iLoop; 4423 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; 4424 pLevel->iFrom = pWLoop->iTab; 4425 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; 4426 } 4427 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 4428 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 4429 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP 4430 && nRowEst 4431 ){ 4432 Bitmask notUsed; 4433 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom, 4434 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); 4435 if( rc==pWInfo->pResultSet->nExpr ){ 4436 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; 4437 } 4438 } 4439 pWInfo->bOrderedInnerLoop = 0; 4440 if( pWInfo->pOrderBy ){ 4441 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ 4442 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ 4443 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; 4444 } 4445 }else{ 4446 pWInfo->nOBSat = pFrom->isOrdered; 4447 pWInfo->revMask = pFrom->revLoop; 4448 if( pWInfo->nOBSat<=0 ){ 4449 pWInfo->nOBSat = 0; 4450 if( nLoop>0 ){ 4451 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags; 4452 if( (wsFlags & WHERE_ONEROW)==0 4453 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN) 4454 ){ 4455 Bitmask m = 0; 4456 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, 4457 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m); 4458 testcase( wsFlags & WHERE_IPK ); 4459 testcase( wsFlags & WHERE_COLUMN_IN ); 4460 if( rc==pWInfo->pOrderBy->nExpr ){ 4461 pWInfo->bOrderedInnerLoop = 1; 4462 pWInfo->revMask = m; 4463 } 4464 } 4465 } 4466 }else if( nLoop 4467 && pWInfo->nOBSat==1 4468 && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0 4469 ){ 4470 pWInfo->bOrderedInnerLoop = 1; 4471 } 4472 } 4473 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) 4474 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0 4475 ){ 4476 Bitmask revMask = 0; 4477 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 4478 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask 4479 ); 4480 assert( pWInfo->sorted==0 ); 4481 if( nOrder==pWInfo->pOrderBy->nExpr ){ 4482 pWInfo->sorted = 1; 4483 pWInfo->revMask = revMask; 4484 } 4485 } 4486 } 4487 4488 4489 pWInfo->nRowOut = pFrom->nRow; 4490 4491 /* Free temporary memory and return success */ 4492 sqlite3DbFreeNN(db, pSpace); 4493 return SQLITE_OK; 4494 } 4495 4496 /* 4497 ** Most queries use only a single table (they are not joins) and have 4498 ** simple == constraints against indexed fields. This routine attempts 4499 ** to plan those simple cases using much less ceremony than the 4500 ** general-purpose query planner, and thereby yield faster sqlite3_prepare() 4501 ** times for the common case. 4502 ** 4503 ** Return non-zero on success, if this query can be handled by this 4504 ** no-frills query planner. Return zero if this query needs the 4505 ** general-purpose query planner. 4506 */ 4507 static int whereShortCut(WhereLoopBuilder *pBuilder){ 4508 WhereInfo *pWInfo; 4509 struct SrcList_item *pItem; 4510 WhereClause *pWC; 4511 WhereTerm *pTerm; 4512 WhereLoop *pLoop; 4513 int iCur; 4514 int j; 4515 Table *pTab; 4516 Index *pIdx; 4517 4518 pWInfo = pBuilder->pWInfo; 4519 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0; 4520 assert( pWInfo->pTabList->nSrc>=1 ); 4521 pItem = pWInfo->pTabList->a; 4522 pTab = pItem->pTab; 4523 if( IsVirtual(pTab) ) return 0; 4524 if( pItem->fg.isIndexedBy ) return 0; 4525 iCur = pItem->iCursor; 4526 pWC = &pWInfo->sWC; 4527 pLoop = pBuilder->pNew; 4528 pLoop->wsFlags = 0; 4529 pLoop->nSkip = 0; 4530 pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0); 4531 if( pTerm ){ 4532 testcase( pTerm->eOperator & WO_IS ); 4533 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; 4534 pLoop->aLTerm[0] = pTerm; 4535 pLoop->nLTerm = 1; 4536 pLoop->u.btree.nEq = 1; 4537 /* TUNING: Cost of a rowid lookup is 10 */ 4538 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ 4539 }else{ 4540 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 4541 int opMask; 4542 assert( pLoop->aLTermSpace==pLoop->aLTerm ); 4543 if( !IsUniqueIndex(pIdx) 4544 || pIdx->pPartIdxWhere!=0 4545 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 4546 ) continue; 4547 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ; 4548 for(j=0; j<pIdx->nKeyCol; j++){ 4549 pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx); 4550 if( pTerm==0 ) break; 4551 testcase( pTerm->eOperator & WO_IS ); 4552 pLoop->aLTerm[j] = pTerm; 4553 } 4554 if( j!=pIdx->nKeyCol ) continue; 4555 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; 4556 if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){ 4557 pLoop->wsFlags |= WHERE_IDX_ONLY; 4558 } 4559 pLoop->nLTerm = j; 4560 pLoop->u.btree.nEq = j; 4561 pLoop->u.btree.pIndex = pIdx; 4562 /* TUNING: Cost of a unique index lookup is 15 */ 4563 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ 4564 break; 4565 } 4566 } 4567 if( pLoop->wsFlags ){ 4568 pLoop->nOut = (LogEst)1; 4569 pWInfo->a[0].pWLoop = pLoop; 4570 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] ); 4571 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */ 4572 pWInfo->a[0].iTabCur = iCur; 4573 pWInfo->nRowOut = 1; 4574 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; 4575 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ 4576 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 4577 } 4578 #ifdef SQLITE_DEBUG 4579 pLoop->cId = '0'; 4580 #endif 4581 return 1; 4582 } 4583 return 0; 4584 } 4585 4586 /* 4587 ** Helper function for exprIsDeterministic(). 4588 */ 4589 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){ 4590 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){ 4591 pWalker->eCode = 0; 4592 return WRC_Abort; 4593 } 4594 return WRC_Continue; 4595 } 4596 4597 /* 4598 ** Return true if the expression contains no non-deterministic SQL 4599 ** functions. Do not consider non-deterministic SQL functions that are 4600 ** part of sub-select statements. 4601 */ 4602 static int exprIsDeterministic(Expr *p){ 4603 Walker w; 4604 memset(&w, 0, sizeof(w)); 4605 w.eCode = 1; 4606 w.xExprCallback = exprNodeIsDeterministic; 4607 w.xSelectCallback = sqlite3SelectWalkFail; 4608 sqlite3WalkExpr(&w, p); 4609 return w.eCode; 4610 } 4611 4612 4613 #ifdef WHERETRACE_ENABLED 4614 /* 4615 ** Display all WhereLoops in pWInfo 4616 */ 4617 static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){ 4618 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ 4619 WhereLoop *p; 4620 int i; 4621 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" 4622 "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; 4623 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ 4624 p->cId = zLabel[i%(sizeof(zLabel)-1)]; 4625 sqlite3WhereLoopPrint(p, pWC); 4626 } 4627 } 4628 } 4629 # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C) 4630 #else 4631 # define WHERETRACE_ALL_LOOPS(W,C) 4632 #endif 4633 4634 /* 4635 ** Generate the beginning of the loop used for WHERE clause processing. 4636 ** The return value is a pointer to an opaque structure that contains 4637 ** information needed to terminate the loop. Later, the calling routine 4638 ** should invoke sqlite3WhereEnd() with the return value of this function 4639 ** in order to complete the WHERE clause processing. 4640 ** 4641 ** If an error occurs, this routine returns NULL. 4642 ** 4643 ** The basic idea is to do a nested loop, one loop for each table in 4644 ** the FROM clause of a select. (INSERT and UPDATE statements are the 4645 ** same as a SELECT with only a single table in the FROM clause.) For 4646 ** example, if the SQL is this: 4647 ** 4648 ** SELECT * FROM t1, t2, t3 WHERE ...; 4649 ** 4650 ** Then the code generated is conceptually like the following: 4651 ** 4652 ** foreach row1 in t1 do \ Code generated 4653 ** foreach row2 in t2 do |-- by sqlite3WhereBegin() 4654 ** foreach row3 in t3 do / 4655 ** ... 4656 ** end \ Code generated 4657 ** end |-- by sqlite3WhereEnd() 4658 ** end / 4659 ** 4660 ** Note that the loops might not be nested in the order in which they 4661 ** appear in the FROM clause if a different order is better able to make 4662 ** use of indices. Note also that when the IN operator appears in 4663 ** the WHERE clause, it might result in additional nested loops for 4664 ** scanning through all values on the right-hand side of the IN. 4665 ** 4666 ** There are Btree cursors associated with each table. t1 uses cursor 4667 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. 4668 ** And so forth. This routine generates code to open those VDBE cursors 4669 ** and sqlite3WhereEnd() generates the code to close them. 4670 ** 4671 ** The code that sqlite3WhereBegin() generates leaves the cursors named 4672 ** in pTabList pointing at their appropriate entries. The [...] code 4673 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract 4674 ** data from the various tables of the loop. 4675 ** 4676 ** If the WHERE clause is empty, the foreach loops must each scan their 4677 ** entire tables. Thus a three-way join is an O(N^3) operation. But if 4678 ** the tables have indices and there are terms in the WHERE clause that 4679 ** refer to those indices, a complete table scan can be avoided and the 4680 ** code will run much faster. Most of the work of this routine is checking 4681 ** to see if there are indices that can be used to speed up the loop. 4682 ** 4683 ** Terms of the WHERE clause are also used to limit which rows actually 4684 ** make it to the "..." in the middle of the loop. After each "foreach", 4685 ** terms of the WHERE clause that use only terms in that loop and outer 4686 ** loops are evaluated and if false a jump is made around all subsequent 4687 ** inner loops (or around the "..." if the test occurs within the inner- 4688 ** most loop) 4689 ** 4690 ** OUTER JOINS 4691 ** 4692 ** An outer join of tables t1 and t2 is conceptally coded as follows: 4693 ** 4694 ** foreach row1 in t1 do 4695 ** flag = 0 4696 ** foreach row2 in t2 do 4697 ** start: 4698 ** ... 4699 ** flag = 1 4700 ** end 4701 ** if flag==0 then 4702 ** move the row2 cursor to a null row 4703 ** goto start 4704 ** fi 4705 ** end 4706 ** 4707 ** ORDER BY CLAUSE PROCESSING 4708 ** 4709 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause 4710 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement 4711 ** if there is one. If there is no ORDER BY clause or if this routine 4712 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. 4713 ** 4714 ** The iIdxCur parameter is the cursor number of an index. If 4715 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index 4716 ** to use for OR clause processing. The WHERE clause should use this 4717 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is 4718 ** the first cursor in an array of cursors for all indices. iIdxCur should 4719 ** be used to compute the appropriate cursor depending on which index is 4720 ** used. 4721 */ 4722 WhereInfo *sqlite3WhereBegin( 4723 Parse *pParse, /* The parser context */ 4724 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ 4725 Expr *pWhere, /* The WHERE clause */ 4726 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ 4727 ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */ 4728 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */ 4729 int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number 4730 ** If WHERE_USE_LIMIT, then the limit amount */ 4731 ){ 4732 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ 4733 int nTabList; /* Number of elements in pTabList */ 4734 WhereInfo *pWInfo; /* Will become the return value of this function */ 4735 Vdbe *v = pParse->pVdbe; /* The virtual database engine */ 4736 Bitmask notReady; /* Cursors that are not yet positioned */ 4737 WhereLoopBuilder sWLB; /* The WhereLoop builder */ 4738 WhereMaskSet *pMaskSet; /* The expression mask set */ 4739 WhereLevel *pLevel; /* A single level in pWInfo->a[] */ 4740 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ 4741 int ii; /* Loop counter */ 4742 sqlite3 *db; /* Database connection */ 4743 int rc; /* Return code */ 4744 u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */ 4745 4746 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || ( 4747 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 4748 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 4749 )); 4750 4751 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */ 4752 assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 4753 || (wctrlFlags & WHERE_USE_LIMIT)==0 ); 4754 4755 /* Variable initialization */ 4756 db = pParse->db; 4757 memset(&sWLB, 0, sizeof(sWLB)); 4758 4759 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ 4760 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); 4761 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; 4762 sWLB.pOrderBy = pOrderBy; 4763 4764 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via 4765 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ 4766 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ 4767 wctrlFlags &= ~WHERE_WANT_DISTINCT; 4768 } 4769 4770 /* The number of tables in the FROM clause is limited by the number of 4771 ** bits in a Bitmask 4772 */ 4773 testcase( pTabList->nSrc==BMS ); 4774 if( pTabList->nSrc>BMS ){ 4775 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); 4776 return 0; 4777 } 4778 4779 /* This function normally generates a nested loop for all tables in 4780 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should 4781 ** only generate code for the first table in pTabList and assume that 4782 ** any cursors associated with subsequent tables are uninitialized. 4783 */ 4784 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc; 4785 4786 /* Allocate and initialize the WhereInfo structure that will become the 4787 ** return value. A single allocation is used to store the WhereInfo 4788 ** struct, the contents of WhereInfo.a[], the WhereClause structure 4789 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte 4790 ** field (type Bitmask) it must be aligned on an 8-byte boundary on 4791 ** some architectures. Hence the ROUND8() below. 4792 */ 4793 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); 4794 pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); 4795 if( db->mallocFailed ){ 4796 sqlite3DbFree(db, pWInfo); 4797 pWInfo = 0; 4798 goto whereBeginError; 4799 } 4800 pWInfo->pParse = pParse; 4801 pWInfo->pTabList = pTabList; 4802 pWInfo->pOrderBy = pOrderBy; 4803 pWInfo->pWhere = pWhere; 4804 pWInfo->pResultSet = pResultSet; 4805 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; 4806 pWInfo->nLevel = nTabList; 4807 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse); 4808 pWInfo->wctrlFlags = wctrlFlags; 4809 pWInfo->iLimit = iAuxArg; 4810 pWInfo->savedNQueryLoop = pParse->nQueryLoop; 4811 memset(&pWInfo->nOBSat, 0, 4812 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat)); 4813 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel)); 4814 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */ 4815 pMaskSet = &pWInfo->sMaskSet; 4816 sWLB.pWInfo = pWInfo; 4817 sWLB.pWC = &pWInfo->sWC; 4818 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); 4819 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); 4820 whereLoopInit(sWLB.pNew); 4821 #ifdef SQLITE_DEBUG 4822 sWLB.pNew->cId = '*'; 4823 #endif 4824 4825 /* Split the WHERE clause into separate subexpressions where each 4826 ** subexpression is separated by an AND operator. 4827 */ 4828 initMaskSet(pMaskSet); 4829 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); 4830 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); 4831 4832 /* Special case: No FROM clause 4833 */ 4834 if( nTabList==0 ){ 4835 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; 4836 if( wctrlFlags & WHERE_WANT_DISTINCT ){ 4837 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 4838 } 4839 ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW")); 4840 }else{ 4841 /* Assign a bit from the bitmask to every term in the FROM clause. 4842 ** 4843 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N. 4844 ** 4845 ** The rule of the previous sentence ensures thta if X is the bitmask for 4846 ** a table T, then X-1 is the bitmask for all other tables to the left of T. 4847 ** Knowing the bitmask for all tables to the left of a left join is 4848 ** important. Ticket #3015. 4849 ** 4850 ** Note that bitmasks are created for all pTabList->nSrc tables in 4851 ** pTabList, not just the first nTabList tables. nTabList is normally 4852 ** equal to pTabList->nSrc but might be shortened to 1 if the 4853 ** WHERE_OR_SUBCLAUSE flag is set. 4854 */ 4855 ii = 0; 4856 do{ 4857 createMask(pMaskSet, pTabList->a[ii].iCursor); 4858 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); 4859 }while( (++ii)<pTabList->nSrc ); 4860 #ifdef SQLITE_DEBUG 4861 { 4862 Bitmask mx = 0; 4863 for(ii=0; ii<pTabList->nSrc; ii++){ 4864 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); 4865 assert( m>=mx ); 4866 mx = m; 4867 } 4868 } 4869 #endif 4870 } 4871 4872 /* Analyze all of the subexpressions. */ 4873 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); 4874 if( db->mallocFailed ) goto whereBeginError; 4875 4876 /* Special case: WHERE terms that do not refer to any tables in the join 4877 ** (constant expressions). Evaluate each such term, and jump over all the 4878 ** generated code if the result is not true. 4879 ** 4880 ** Do not do this if the expression contains non-deterministic functions 4881 ** that are not within a sub-select. This is not strictly required, but 4882 ** preserves SQLite's legacy behaviour in the following two cases: 4883 ** 4884 ** FROM ... WHERE random()>0; -- eval random() once per row 4885 ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall 4886 */ 4887 for(ii=0; ii<sWLB.pWC->nTerm; ii++){ 4888 WhereTerm *pT = &sWLB.pWC->a[ii]; 4889 if( pT->wtFlags & TERM_VIRTUAL ) continue; 4890 if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){ 4891 sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL); 4892 pT->wtFlags |= TERM_CODED; 4893 } 4894 } 4895 4896 if( wctrlFlags & WHERE_WANT_DISTINCT ){ 4897 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ 4898 /* The DISTINCT marking is pointless. Ignore it. */ 4899 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 4900 }else if( pOrderBy==0 ){ 4901 /* Try to ORDER BY the result set to make distinct processing easier */ 4902 pWInfo->wctrlFlags |= WHERE_DISTINCTBY; 4903 pWInfo->pOrderBy = pResultSet; 4904 } 4905 } 4906 4907 /* Construct the WhereLoop objects */ 4908 #if defined(WHERETRACE_ENABLED) 4909 if( sqlite3WhereTrace & 0xffff ){ 4910 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); 4911 if( wctrlFlags & WHERE_USE_LIMIT ){ 4912 sqlite3DebugPrintf(", limit: %d", iAuxArg); 4913 } 4914 sqlite3DebugPrintf(")\n"); 4915 if( sqlite3WhereTrace & 0x100 ){ 4916 Select sSelect; 4917 memset(&sSelect, 0, sizeof(sSelect)); 4918 sSelect.selFlags = SF_WhereBegin; 4919 sSelect.pSrc = pTabList; 4920 sSelect.pWhere = pWhere; 4921 sSelect.pOrderBy = pOrderBy; 4922 sSelect.pEList = pResultSet; 4923 sqlite3TreeViewSelect(0, &sSelect, 0); 4924 } 4925 } 4926 if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ 4927 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n"); 4928 sqlite3WhereClausePrint(sWLB.pWC); 4929 } 4930 #endif 4931 4932 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ 4933 rc = whereLoopAddAll(&sWLB); 4934 if( rc ) goto whereBeginError; 4935 4936 #ifdef SQLITE_ENABLE_STAT4 4937 /* If one or more WhereTerm.truthProb values were used in estimating 4938 ** loop parameters, but then those truthProb values were subsequently 4939 ** changed based on STAT4 information while computing subsequent loops, 4940 ** then we need to rerun the whole loop building process so that all 4941 ** loops will be built using the revised truthProb values. */ 4942 if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){ 4943 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC); 4944 WHERETRACE(0xffff, 4945 ("**** Redo all loop computations due to" 4946 " TERM_HIGHTRUTH changes ****\n")); 4947 while( pWInfo->pLoops ){ 4948 WhereLoop *p = pWInfo->pLoops; 4949 pWInfo->pLoops = p->pNextLoop; 4950 whereLoopDelete(db, p); 4951 } 4952 rc = whereLoopAddAll(&sWLB); 4953 if( rc ) goto whereBeginError; 4954 } 4955 #endif 4956 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC); 4957 4958 wherePathSolver(pWInfo, 0); 4959 if( db->mallocFailed ) goto whereBeginError; 4960 if( pWInfo->pOrderBy ){ 4961 wherePathSolver(pWInfo, pWInfo->nRowOut+1); 4962 if( db->mallocFailed ) goto whereBeginError; 4963 } 4964 } 4965 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ 4966 pWInfo->revMask = ALLBITS; 4967 } 4968 if( pParse->nErr || NEVER(db->mallocFailed) ){ 4969 goto whereBeginError; 4970 } 4971 #ifdef WHERETRACE_ENABLED 4972 if( sqlite3WhereTrace ){ 4973 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); 4974 if( pWInfo->nOBSat>0 ){ 4975 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); 4976 } 4977 switch( pWInfo->eDistinct ){ 4978 case WHERE_DISTINCT_UNIQUE: { 4979 sqlite3DebugPrintf(" DISTINCT=unique"); 4980 break; 4981 } 4982 case WHERE_DISTINCT_ORDERED: { 4983 sqlite3DebugPrintf(" DISTINCT=ordered"); 4984 break; 4985 } 4986 case WHERE_DISTINCT_UNORDERED: { 4987 sqlite3DebugPrintf(" DISTINCT=unordered"); 4988 break; 4989 } 4990 } 4991 sqlite3DebugPrintf("\n"); 4992 for(ii=0; ii<pWInfo->nLevel; ii++){ 4993 sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); 4994 } 4995 } 4996 #endif 4997 4998 /* Attempt to omit tables from the join that do not affect the result. 4999 ** For a table to not affect the result, the following must be true: 5000 ** 5001 ** 1) The query must not be an aggregate. 5002 ** 2) The table must be the RHS of a LEFT JOIN. 5003 ** 3) Either the query must be DISTINCT, or else the ON or USING clause 5004 ** must contain a constraint that limits the scan of the table to 5005 ** at most a single row. 5006 ** 4) The table must not be referenced by any part of the query apart 5007 ** from its own USING or ON clause. 5008 ** 5009 ** For example, given: 5010 ** 5011 ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1); 5012 ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2); 5013 ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3); 5014 ** 5015 ** then table t2 can be omitted from the following: 5016 ** 5017 ** SELECT v1, v3 FROM t1 5018 ** LEFT JOIN t2 ON (t1.ipk=t2.ipk) 5019 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) 5020 ** 5021 ** or from: 5022 ** 5023 ** SELECT DISTINCT v1, v3 FROM t1 5024 ** LEFT JOIN t2 5025 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) 5026 */ 5027 notReady = ~(Bitmask)0; 5028 if( pWInfo->nLevel>=2 5029 && pResultSet!=0 /* guarantees condition (1) above */ 5030 && OptimizationEnabled(db, SQLITE_OmitNoopJoin) 5031 ){ 5032 int i; 5033 Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet); 5034 if( sWLB.pOrderBy ){ 5035 tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); 5036 } 5037 for(i=pWInfo->nLevel-1; i>=1; i--){ 5038 WhereTerm *pTerm, *pEnd; 5039 struct SrcList_item *pItem; 5040 pLoop = pWInfo->a[i].pWLoop; 5041 pItem = &pWInfo->pTabList->a[pLoop->iTab]; 5042 if( (pItem->fg.jointype & JT_LEFT)==0 ) continue; 5043 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 5044 && (pLoop->wsFlags & WHERE_ONEROW)==0 5045 ){ 5046 continue; 5047 } 5048 if( (tabUsed & pLoop->maskSelf)!=0 ) continue; 5049 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; 5050 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ 5051 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){ 5052 if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin) 5053 || pTerm->pExpr->iRightJoinTable!=pItem->iCursor 5054 ){ 5055 break; 5056 } 5057 } 5058 } 5059 if( pTerm<pEnd ) continue; 5060 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId)); 5061 notReady &= ~pLoop->maskSelf; 5062 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ 5063 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){ 5064 pTerm->wtFlags |= TERM_CODED; 5065 } 5066 } 5067 if( i!=pWInfo->nLevel-1 ){ 5068 int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel); 5069 memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte); 5070 } 5071 pWInfo->nLevel--; 5072 nTabList--; 5073 } 5074 } 5075 #if defined(WHERETRACE_ENABLED) 5076 if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ 5077 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n"); 5078 sqlite3WhereClausePrint(sWLB.pWC); 5079 } 5080 WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); 5081 #endif 5082 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; 5083 5084 /* If the caller is an UPDATE or DELETE statement that is requesting 5085 ** to use a one-pass algorithm, determine if this is appropriate. 5086 ** 5087 ** A one-pass approach can be used if the caller has requested one 5088 ** and either (a) the scan visits at most one row or (b) each 5089 ** of the following are true: 5090 ** 5091 ** * the caller has indicated that a one-pass approach can be used 5092 ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and 5093 ** * the table is not a virtual table, and 5094 ** * either the scan does not use the OR optimization or the caller 5095 ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified 5096 ** for DELETE). 5097 ** 5098 ** The last qualification is because an UPDATE statement uses 5099 ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can 5100 ** use a one-pass approach, and this is not set accurately for scans 5101 ** that use the OR optimization. 5102 */ 5103 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); 5104 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){ 5105 int wsFlags = pWInfo->a[0].pWLoop->wsFlags; 5106 int bOnerow = (wsFlags & WHERE_ONEROW)!=0; 5107 assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) ); 5108 if( bOnerow || ( 5109 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW) 5110 && !IsVirtual(pTabList->a[0].pTab) 5111 && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK)) 5112 )){ 5113 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI; 5114 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){ 5115 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){ 5116 bFordelete = OPFLAG_FORDELETE; 5117 } 5118 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY); 5119 } 5120 } 5121 } 5122 5123 /* Open all tables in the pTabList and any indices selected for 5124 ** searching those tables. 5125 */ 5126 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){ 5127 Table *pTab; /* Table to open */ 5128 int iDb; /* Index of database containing table/index */ 5129 struct SrcList_item *pTabItem; 5130 5131 pTabItem = &pTabList->a[pLevel->iFrom]; 5132 pTab = pTabItem->pTab; 5133 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 5134 pLoop = pLevel->pWLoop; 5135 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ 5136 /* Do nothing */ 5137 }else 5138 #ifndef SQLITE_OMIT_VIRTUALTABLE 5139 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 5140 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 5141 int iCur = pTabItem->iCursor; 5142 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); 5143 }else if( IsVirtual(pTab) ){ 5144 /* noop */ 5145 }else 5146 #endif 5147 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 5148 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ 5149 int op = OP_OpenRead; 5150 if( pWInfo->eOnePass!=ONEPASS_OFF ){ 5151 op = OP_OpenWrite; 5152 pWInfo->aiCurOnePass[0] = pTabItem->iCursor; 5153 }; 5154 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); 5155 assert( pTabItem->iCursor==pLevel->iTabCur ); 5156 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 ); 5157 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS ); 5158 if( pWInfo->eOnePass==ONEPASS_OFF 5159 && pTab->nCol<BMS 5160 && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0 5161 ){ 5162 /* If we know that only a prefix of the record will be used, 5163 ** it is advantageous to reduce the "column count" field in 5164 ** the P4 operand of the OP_OpenRead/Write opcode. */ 5165 Bitmask b = pTabItem->colUsed; 5166 int n = 0; 5167 for(; b; b=b>>1, n++){} 5168 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32); 5169 assert( n<=pTab->nCol ); 5170 } 5171 #ifdef SQLITE_ENABLE_CURSOR_HINTS 5172 if( pLoop->u.btree.pIndex!=0 ){ 5173 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); 5174 }else 5175 #endif 5176 { 5177 sqlite3VdbeChangeP5(v, bFordelete); 5178 } 5179 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 5180 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, 5181 (const u8*)&pTabItem->colUsed, P4_INT64); 5182 #endif 5183 }else{ 5184 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 5185 } 5186 if( pLoop->wsFlags & WHERE_INDEXED ){ 5187 Index *pIx = pLoop->u.btree.pIndex; 5188 int iIndexCur; 5189 int op = OP_OpenRead; 5190 /* iAuxArg is always set to a positive value if ONEPASS is possible */ 5191 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); 5192 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) 5193 && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 5194 ){ 5195 /* This is one term of an OR-optimization using the PRIMARY KEY of a 5196 ** WITHOUT ROWID table. No need for a separate index */ 5197 iIndexCur = pLevel->iTabCur; 5198 op = 0; 5199 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){ 5200 Index *pJ = pTabItem->pTab->pIndex; 5201 iIndexCur = iAuxArg; 5202 assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); 5203 while( ALWAYS(pJ) && pJ!=pIx ){ 5204 iIndexCur++; 5205 pJ = pJ->pNext; 5206 } 5207 op = OP_OpenWrite; 5208 pWInfo->aiCurOnePass[1] = iIndexCur; 5209 }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ 5210 iIndexCur = iAuxArg; 5211 op = OP_ReopenIdx; 5212 }else{ 5213 iIndexCur = pParse->nTab++; 5214 } 5215 pLevel->iIdxCur = iIndexCur; 5216 assert( pIx->pSchema==pTab->pSchema ); 5217 assert( iIndexCur>=0 ); 5218 if( op ){ 5219 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); 5220 sqlite3VdbeSetP4KeyInfo(pParse, pIx); 5221 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0 5222 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0 5223 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0 5224 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 5225 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 5226 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED 5227 ){ 5228 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); 5229 } 5230 VdbeComment((v, "%s", pIx->zName)); 5231 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 5232 { 5233 u64 colUsed = 0; 5234 int ii, jj; 5235 for(ii=0; ii<pIx->nColumn; ii++){ 5236 jj = pIx->aiColumn[ii]; 5237 if( jj<0 ) continue; 5238 if( jj>63 ) jj = 63; 5239 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; 5240 colUsed |= ((u64)1)<<(ii<63 ? ii : 63); 5241 } 5242 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, 5243 (u8*)&colUsed, P4_INT64); 5244 } 5245 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ 5246 } 5247 } 5248 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); 5249 } 5250 pWInfo->iTop = sqlite3VdbeCurrentAddr(v); 5251 if( db->mallocFailed ) goto whereBeginError; 5252 5253 /* Generate the code to do the search. Each iteration of the for 5254 ** loop below generates code for a single nested loop of the VM 5255 ** program. 5256 */ 5257 for(ii=0; ii<nTabList; ii++){ 5258 int addrExplain; 5259 int wsFlags; 5260 pLevel = &pWInfo->a[ii]; 5261 wsFlags = pLevel->pWLoop->wsFlags; 5262 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 5263 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ 5264 constructAutomaticIndex(pParse, &pWInfo->sWC, 5265 &pTabList->a[pLevel->iFrom], notReady, pLevel); 5266 if( db->mallocFailed ) goto whereBeginError; 5267 } 5268 #endif 5269 addrExplain = sqlite3WhereExplainOneScan( 5270 pParse, pTabList, pLevel, wctrlFlags 5271 ); 5272 pLevel->addrBody = sqlite3VdbeCurrentAddr(v); 5273 notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady); 5274 pWInfo->iContinue = pLevel->addrCont; 5275 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){ 5276 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); 5277 } 5278 } 5279 5280 /* Done. */ 5281 VdbeModuleComment((v, "Begin WHERE-core")); 5282 pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v); 5283 return pWInfo; 5284 5285 /* Jump here if malloc fails */ 5286 whereBeginError: 5287 if( pWInfo ){ 5288 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 5289 whereInfoFree(db, pWInfo); 5290 } 5291 return 0; 5292 } 5293 5294 /* 5295 ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the 5296 ** index rather than the main table. In SQLITE_DEBUG mode, we want 5297 ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine 5298 ** does that. 5299 */ 5300 #ifndef SQLITE_DEBUG 5301 # define OpcodeRewriteTrace(D,K,P) /* no-op */ 5302 #else 5303 # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P) 5304 static void sqlite3WhereOpcodeRewriteTrace( 5305 sqlite3 *db, 5306 int pc, 5307 VdbeOp *pOp 5308 ){ 5309 if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return; 5310 sqlite3VdbePrintOp(0, pc, pOp); 5311 } 5312 #endif 5313 5314 /* 5315 ** Generate the end of the WHERE loop. See comments on 5316 ** sqlite3WhereBegin() for additional information. 5317 */ 5318 void sqlite3WhereEnd(WhereInfo *pWInfo){ 5319 Parse *pParse = pWInfo->pParse; 5320 Vdbe *v = pParse->pVdbe; 5321 int i; 5322 WhereLevel *pLevel; 5323 WhereLoop *pLoop; 5324 SrcList *pTabList = pWInfo->pTabList; 5325 sqlite3 *db = pParse->db; 5326 int iEnd = sqlite3VdbeCurrentAddr(v); 5327 5328 /* Generate loop termination code. 5329 */ 5330 VdbeModuleComment((v, "End WHERE-core")); 5331 for(i=pWInfo->nLevel-1; i>=0; i--){ 5332 int addr; 5333 pLevel = &pWInfo->a[i]; 5334 pLoop = pLevel->pWLoop; 5335 if( pLevel->op!=OP_Noop ){ 5336 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT 5337 int addrSeek = 0; 5338 Index *pIdx; 5339 int n; 5340 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 5341 && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */ 5342 && (pLoop->wsFlags & WHERE_INDEXED)!=0 5343 && (pIdx = pLoop->u.btree.pIndex)->hasStat1 5344 && (n = pLoop->u.btree.nDistinctCol)>0 5345 && pIdx->aiRowLogEst[n]>=36 5346 ){ 5347 int r1 = pParse->nMem+1; 5348 int j, op; 5349 for(j=0; j<n; j++){ 5350 sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j); 5351 } 5352 pParse->nMem += n+1; 5353 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT; 5354 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n); 5355 VdbeCoverageIf(v, op==OP_SeekLT); 5356 VdbeCoverageIf(v, op==OP_SeekGT); 5357 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2); 5358 } 5359 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */ 5360 /* The common case: Advance to the next row */ 5361 sqlite3VdbeResolveLabel(v, pLevel->addrCont); 5362 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); 5363 sqlite3VdbeChangeP5(v, pLevel->p5); 5364 VdbeCoverage(v); 5365 VdbeCoverageIf(v, pLevel->op==OP_Next); 5366 VdbeCoverageIf(v, pLevel->op==OP_Prev); 5367 VdbeCoverageIf(v, pLevel->op==OP_VNext); 5368 if( pLevel->regBignull ){ 5369 sqlite3VdbeResolveLabel(v, pLevel->addrBignull); 5370 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1); 5371 VdbeCoverage(v); 5372 } 5373 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT 5374 if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek); 5375 #endif 5376 }else{ 5377 sqlite3VdbeResolveLabel(v, pLevel->addrCont); 5378 } 5379 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ 5380 struct InLoop *pIn; 5381 int j; 5382 sqlite3VdbeResolveLabel(v, pLevel->addrNxt); 5383 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ 5384 sqlite3VdbeJumpHere(v, pIn->addrInTop+1); 5385 if( pIn->eEndLoopOp!=OP_Noop ){ 5386 if( pIn->nPrefix ){ 5387 int bEarlyOut = 5388 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 5389 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0; 5390 if( pLevel->iLeftJoin ){ 5391 /* For LEFT JOIN queries, cursor pIn->iCur may not have been 5392 ** opened yet. This occurs for WHERE clauses such as 5393 ** "a = ? AND b IN (...)", where the index is on (a, b). If 5394 ** the RHS of the (a=?) is NULL, then the "b IN (...)" may 5395 ** never have been coded, but the body of the loop run to 5396 ** return the null-row. So, if the cursor is not open yet, 5397 ** jump over the OP_Next or OP_Prev instruction about to 5398 ** be coded. */ 5399 sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur, 5400 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut); 5401 VdbeCoverage(v); 5402 } 5403 if( bEarlyOut ){ 5404 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur, 5405 sqlite3VdbeCurrentAddr(v)+2, 5406 pIn->iBase, pIn->nPrefix); 5407 VdbeCoverage(v); 5408 } 5409 } 5410 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); 5411 VdbeCoverage(v); 5412 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev); 5413 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next); 5414 } 5415 sqlite3VdbeJumpHere(v, pIn->addrInTop-1); 5416 } 5417 } 5418 sqlite3VdbeResolveLabel(v, pLevel->addrBrk); 5419 if( pLevel->addrSkip ){ 5420 sqlite3VdbeGoto(v, pLevel->addrSkip); 5421 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); 5422 sqlite3VdbeJumpHere(v, pLevel->addrSkip); 5423 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); 5424 } 5425 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 5426 if( pLevel->addrLikeRep ){ 5427 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), 5428 pLevel->addrLikeRep); 5429 VdbeCoverage(v); 5430 } 5431 #endif 5432 if( pLevel->iLeftJoin ){ 5433 int ws = pLoop->wsFlags; 5434 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); 5435 assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 ); 5436 if( (ws & WHERE_IDX_ONLY)==0 ){ 5437 assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor ); 5438 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur); 5439 } 5440 if( (ws & WHERE_INDEXED) 5441 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) 5442 ){ 5443 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); 5444 } 5445 if( pLevel->op==OP_Return ){ 5446 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); 5447 }else{ 5448 sqlite3VdbeGoto(v, pLevel->addrFirst); 5449 } 5450 sqlite3VdbeJumpHere(v, addr); 5451 } 5452 VdbeModuleComment((v, "End WHERE-loop%d: %s", i, 5453 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); 5454 } 5455 5456 /* The "break" point is here, just past the end of the outer loop. 5457 ** Set it. 5458 */ 5459 sqlite3VdbeResolveLabel(v, pWInfo->iBreak); 5460 5461 assert( pWInfo->nLevel<=pTabList->nSrc ); 5462 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ 5463 int k, last; 5464 VdbeOp *pOp, *pLastOp; 5465 Index *pIdx = 0; 5466 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; 5467 Table *pTab = pTabItem->pTab; 5468 assert( pTab!=0 ); 5469 pLoop = pLevel->pWLoop; 5470 5471 /* For a co-routine, change all OP_Column references to the table of 5472 ** the co-routine into OP_Copy of result contained in a register. 5473 ** OP_Rowid becomes OP_Null. 5474 */ 5475 if( pTabItem->fg.viaCoroutine ){ 5476 testcase( pParse->db->mallocFailed ); 5477 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur, 5478 pTabItem->regResult, 0); 5479 continue; 5480 } 5481 5482 #ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE 5483 /* Close all of the cursors that were opened by sqlite3WhereBegin. 5484 ** Except, do not close cursors that will be reused by the OR optimization 5485 ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors 5486 ** created for the ONEPASS optimization. 5487 */ 5488 if( (pTab->tabFlags & TF_Ephemeral)==0 5489 && pTab->pSelect==0 5490 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 5491 ){ 5492 int ws = pLoop->wsFlags; 5493 if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){ 5494 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); 5495 } 5496 if( (ws & WHERE_INDEXED)!=0 5497 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 5498 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] 5499 ){ 5500 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); 5501 } 5502 } 5503 #endif 5504 5505 /* If this scan uses an index, make VDBE code substitutions to read data 5506 ** from the index instead of from the table where possible. In some cases 5507 ** this optimization prevents the table from ever being read, which can 5508 ** yield a significant performance boost. 5509 ** 5510 ** Calls to the code generator in between sqlite3WhereBegin and 5511 ** sqlite3WhereEnd will have created code that references the table 5512 ** directly. This loop scans all that code looking for opcodes 5513 ** that reference the table and converts them into opcodes that 5514 ** reference the index. 5515 */ 5516 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ 5517 pIdx = pLoop->u.btree.pIndex; 5518 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ 5519 pIdx = pLevel->u.pCovidx; 5520 } 5521 if( pIdx 5522 && !db->mallocFailed 5523 ){ 5524 if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){ 5525 last = iEnd; 5526 }else{ 5527 last = pWInfo->iEndWhere; 5528 } 5529 k = pLevel->addrBody + 1; 5530 #ifdef SQLITE_DEBUG 5531 if( db->flags & SQLITE_VdbeAddopTrace ){ 5532 printf("TRANSLATE opcodes in range %d..%d\n", k, last-1); 5533 } 5534 /* Proof that the "+1" on the k value above is safe */ 5535 pOp = sqlite3VdbeGetOp(v, k - 1); 5536 assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur ); 5537 assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur ); 5538 assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur ); 5539 #endif 5540 pOp = sqlite3VdbeGetOp(v, k); 5541 pLastOp = pOp + (last - k); 5542 assert( pOp<pLastOp ); 5543 do{ 5544 if( pOp->p1!=pLevel->iTabCur ){ 5545 /* no-op */ 5546 }else if( pOp->opcode==OP_Column 5547 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 5548 || pOp->opcode==OP_Offset 5549 #endif 5550 ){ 5551 int x = pOp->p2; 5552 assert( pIdx->pTable==pTab ); 5553 if( !HasRowid(pTab) ){ 5554 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 5555 x = pPk->aiColumn[x]; 5556 assert( x>=0 ); 5557 }else{ 5558 testcase( x!=sqlite3StorageColumnToTable(pTab,x) ); 5559 x = sqlite3StorageColumnToTable(pTab,x); 5560 } 5561 x = sqlite3TableColumnToIndex(pIdx, x); 5562 if( x>=0 ){ 5563 pOp->p2 = x; 5564 pOp->p1 = pLevel->iIdxCur; 5565 OpcodeRewriteTrace(db, k, pOp); 5566 } 5567 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 5568 || pWInfo->eOnePass ); 5569 }else if( pOp->opcode==OP_Rowid ){ 5570 pOp->p1 = pLevel->iIdxCur; 5571 pOp->opcode = OP_IdxRowid; 5572 OpcodeRewriteTrace(db, k, pOp); 5573 }else if( pOp->opcode==OP_IfNullRow ){ 5574 pOp->p1 = pLevel->iIdxCur; 5575 OpcodeRewriteTrace(db, k, pOp); 5576 } 5577 #ifdef SQLITE_DEBUG 5578 k++; 5579 #endif 5580 }while( (++pOp)<pLastOp ); 5581 #ifdef SQLITE_DEBUG 5582 if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n"); 5583 #endif 5584 } 5585 } 5586 5587 /* Undo all Expr node modifications */ 5588 while( pWInfo->pExprMods ){ 5589 WhereExprMod *p = pWInfo->pExprMods; 5590 pWInfo->pExprMods = p->pNext; 5591 memcpy(p->pExpr, &p->orig, sizeof(p->orig)); 5592 sqlite3DbFree(db, p); 5593 } 5594 5595 /* Final cleanup 5596 */ 5597 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 5598 whereInfoFree(db, pWInfo); 5599 return; 5600 } 5601