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