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