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