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