Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/src/where.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / src / where.c` 8088 lines ยท 305611 bytes Raw Blame History 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 u32 mIn; /* Mask of terms that are IN (...) */ 37 u32 mHandleIn; /* Terms that vtab will handle as IN (...) */ 38 sqlite3_value *aRhs[FLEXARRAY]; /* RHS values for constraints. MUST BE LAST 39 ** Extra space is allocated to hold up 40 ** to nTerm such values */ 41 }; 42 43 /* Size (in bytes) of a HiddenIndeInfo object sufficient to hold as 44 ** many as N constraints */ 45 #define SZ_HIDDENINDEXINFO(N) \ 46 (offsetof(HiddenIndexInfo,aRhs) + (N)*sizeof(sqlite3_value*)) 47 48 /* Forward declaration of methods */ 49 static int whereLoopResize(sqlite3*, WhereLoop*, int); 50 51 /* 52 ** Return the estimated number of output rows from a WHERE clause 53 */ 54 LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ 55 return pWInfo->nRowOut; 56 } 57 58 /* 59 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this 60 ** WHERE clause returns outputs for DISTINCT processing. 61 */ 62 int sqlite3WhereIsDistinct(WhereInfo *pWInfo){ 63 return pWInfo->eDistinct; 64 } 65 66 /* 67 ** Return the number of ORDER BY terms that are satisfied by the 68 ** WHERE clause. A return of 0 means that the output must be 69 ** completely sorted. A return equal to the number of ORDER BY 70 ** terms means that no sorting is needed at all. A return that 71 ** is positive but less than the number of ORDER BY terms means that 72 ** block sorting is required. 73 */ 74 int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ 75 return pWInfo->nOBSat<0 ? 0 : pWInfo->nOBSat; 76 } 77 78 /* 79 ** In the ORDER BY LIMIT optimization, if the inner-most loop is known 80 ** to emit rows in increasing order, and if the last row emitted by the 81 ** inner-most loop did not fit within the sorter, then we can skip all 82 ** subsequent rows for the current iteration of the inner loop (because they 83 ** will not fit in the sorter either) and continue with the second inner 84 ** loop - the loop immediately outside the inner-most. 85 ** 86 ** When a row does not fit in the sorter (because the sorter already 87 ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the 88 ** label returned by this function. 89 ** 90 ** If the ORDER BY LIMIT optimization applies, the jump destination should 91 ** be the continuation for the second-inner-most loop. If the ORDER BY 92 ** LIMIT optimization does not apply, then the jump destination should 93 ** be the continuation for the inner-most loop. 94 ** 95 ** It is always safe for this routine to return the continuation of the 96 ** inner-most loop, in the sense that a correct answer will result. 97 ** Returning the continuation the second inner loop is an optimization 98 ** that might make the code run a little faster, but should not change 99 ** the final answer. 100 */ 101 int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){ 102 WhereLevel *pInner; 103 if( !pWInfo->bOrderedInnerLoop ){ 104 /* The ORDER BY LIMIT optimization does not apply. Jump to the 105 ** continuation of the inner-most loop. */ 106 return pWInfo->iContinue; 107 } 108 pInner = &pWInfo->a[pWInfo->nLevel-1]; 109 assert( pInner->addrNxt!=0 ); 110 return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt; 111 } 112 113 /* 114 ** While generating code for the min/max optimization, after handling 115 ** the aggregate-step call to min() or max(), check to see if any 116 ** additional looping is required. If the output order is such that 117 ** we are certain that the correct answer has already been found, then 118 ** code an OP_Goto to by pass subsequent processing. 119 ** 120 ** Any extra OP_Goto that is coded here is an optimization. The 121 ** correct answer should be obtained regardless. This OP_Goto just 122 ** makes the answer appear faster. 123 */ 124 void sqlite3WhereMinMaxOptEarlyOut(Vdbe *v, WhereInfo *pWInfo){ 125 WhereLevel *pInner; 126 int i; 127 if( !pWInfo->bOrderedInnerLoop ) return; 128 if( pWInfo->nOBSat==0 ) return; 129 for(i=pWInfo->nLevel-1; i>=0; i--){ 130 pInner = &pWInfo->a[i]; 131 if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){ 132 sqlite3VdbeGoto(v, pInner->addrNxt); 133 return; 134 } 135 } 136 sqlite3VdbeGoto(v, pWInfo->iBreak); 137 } 138 139 /* 140 ** Return the VDBE address or label to jump to in order to continue 141 ** immediately with the next row of a WHERE clause. 142 */ 143 int sqlite3WhereContinueLabel(WhereInfo *pWInfo){ 144 assert( pWInfo->iContinue!=0 ); 145 return pWInfo->iContinue; 146 } 147 148 /* 149 ** Return the VDBE address or label to jump to in order to break 150 ** out of a WHERE loop. 151 */ 152 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ 153 return pWInfo->iBreak; 154 } 155 156 /* 157 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to 158 ** operate directly on the rowids returned by a WHERE clause. Return 159 ** ONEPASS_SINGLE (1) if the statement can operation directly because only 160 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass 161 ** optimization can be used on multiple 162 ** 163 ** If the ONEPASS optimization is used (if this routine returns true) 164 ** then also write the indices of open cursors used by ONEPASS 165 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data 166 ** table and aiCur[1] gets the cursor used by an auxiliary index. 167 ** Either value may be -1, indicating that cursor is not used. 168 ** Any cursors returned will have been opened for writing. 169 ** 170 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is 171 ** unable to use the ONEPASS optimization. 172 */ 173 int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ 174 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); 175 #ifdef WHERETRACE_ENABLED 176 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ 177 sqlite3DebugPrintf("%s cursors: %d %d\n", 178 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI", 179 aiCur[0], aiCur[1]); 180 } 181 #endif 182 return pWInfo->eOnePass; 183 } 184 185 /* 186 ** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move 187 ** the data cursor to the row selected by the index cursor. 188 */ 189 int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){ 190 return pWInfo->bDeferredSeek; 191 } 192 193 /* 194 ** Move the content of pSrc into pDest 195 */ 196 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ 197 pDest->n = pSrc->n; 198 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); 199 } 200 201 /* 202 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet. 203 ** 204 ** The new entry might overwrite an existing entry, or it might be 205 ** appended, or it might be discarded. Do whatever is the right thing 206 ** so that pSet keeps the N_OR_COST best entries seen so far. 207 */ 208 static int whereOrInsert( 209 WhereOrSet *pSet, /* The WhereOrSet to be updated */ 210 Bitmask prereq, /* Prerequisites of the new entry */ 211 LogEst rRun, /* Run-cost of the new entry */ 212 LogEst nOut /* Number of outputs for the new entry */ 213 ){ 214 u16 i; 215 WhereOrCost *p; 216 for(i=pSet->n, p=pSet->a; i>0; i--, p++){ 217 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){ 218 goto whereOrInsert_done; 219 } 220 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){ 221 return 0; 222 } 223 } 224 if( pSet->na[pSet->n++]; 226 }else{ 227 /* The set is full. Replace the most expensive entry, but only if the 228 ** new entry is less expensive than it. */ 229 p = pSet->a; 230 for(i=1; in; i++){ 231 if( p->rRuna[i].rRun ) p = pSet->a + i; 232 } 233 if( p->rRun<=rRun ) return 0; 234 } 235 p->nOut = nOut; 236 whereOrInsert_done: 237 p->prereq = prereq; 238 p->rRun = rRun; 239 if( p->nOut>nOut ) p->nOut = nOut; 240 return 1; 241 } 242 243 /* 244 ** Return the bitmask for the given cursor number. Return 0 if 245 ** iCursor is not in the set. 246 */ 247 Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ 248 int i; 249 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); 250 assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 ); 251 assert( iCursor>=-1 ); 252 if( pMaskSet->ix[0]==iCursor ){ 253 return 1; 254 } 255 for(i=1; in; i++){ 256 if( pMaskSet->ix[i]==iCursor ){ 257 return MASKBIT(i); 258 } 259 } 260 return 0; 261 } 262 263 /* Allocate memory that is automatically freed when pWInfo is freed. 264 */ 265 void *sqlite3WhereMalloc(WhereInfo *pWInfo, u64 nByte){ 266 WhereMemBlock *pBlock; 267 pBlock = sqlite3DbMallocRawNN(pWInfo->pParse->db, nByte+sizeof(*pBlock)); 268 if( pBlock ){ 269 pBlock->pNext = pWInfo->pMemToFree; 270 pBlock->sz = nByte; 271 pWInfo->pMemToFree = pBlock; 272 pBlock++; 273 } 274 return (void*)pBlock; 275 } 276 void *sqlite3WhereRealloc(WhereInfo *pWInfo, void *pOld, u64 nByte){ 277 void *pNew = sqlite3WhereMalloc(pWInfo, nByte); 278 if( pNew && pOld ){ 279 WhereMemBlock *pOldBlk = (WhereMemBlock*)pOld; 280 pOldBlk--; 281 assert( pOldBlk->szsz); 283 } 284 return pNew; 285 } 286 287 /* 288 ** Create a new mask for cursor iCursor. 289 ** 290 ** There is one cursor per table in the FROM clause. The number of 291 ** tables in the FROM clause is limited by a test early in the 292 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] 293 ** array will never overflow. 294 */ 295 static void createMask(WhereMaskSet *pMaskSet, int iCursor){ 296 assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); 297 pMaskSet->ix[pMaskSet->n++] = iCursor; 298 } 299 300 /* 301 ** If the right-hand branch of the expression is a TK_COLUMN, then return 302 ** a pointer to the right-hand branch. Otherwise, return NULL. 303 */ 304 static Expr *whereRightSubexprIsColumn(Expr *p){ 305 p = sqlite3ExprSkipCollateAndLikely(p->pRight); 306 if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){ 307 return p; 308 } 309 return 0; 310 } 311 312 /* 313 ** Term pTerm is guaranteed to be a WO_IN term. It may be a component term 314 ** of a vector IN expression of the form "(x, y, ...) IN (SELECT ...)". 315 ** This function checks to see if the term is compatible with an index 316 ** column with affinity idxaff (one of the SQLITE_AFF_XYZ values). If so, 317 ** it returns a pointer to the name of the collation sequence (e.g. "BINARY" 318 ** or "NOCASE") used by the comparison in pTerm. If it is not compatible 319 ** with affinity idxaff, NULL is returned. 320 */ 321 static SQLITE_NOINLINE const char *indexInAffinityOk( 322 Parse *pParse, 323 WhereTerm *pTerm, 324 u8 idxaff 325 ){ 326 Expr *pX = pTerm->pExpr; 327 Expr inexpr; 328 329 assert( pTerm->eOperator & WO_IN ); 330 331 if( ExprUseXSelect(pX) ){ 332 int iField = 0; 333 inexpr.flags = 0; 334 inexpr.op = TK_EQ; 335 if( sqlite3ExprIsVector(pX->pLeft) ){ 336 iField = pTerm->u.x.iField - 1; 337 inexpr.pLeft = pX->pLeft->x.pList->a[iField].pExpr; 338 }else{ 339 inexpr.pLeft = pX->pLeft; 340 } 341 inexpr.pRight = pX->x.pSelect->pEList->a[iField].pExpr; 342 pX = &inexpr; 343 } 344 345 if( sqlite3IndexAffinityOk(pX, idxaff) ){ 346 CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX); 347 return pRet ? pRet->zName : sqlite3StrBINARY; 348 } 349 return 0; 350 } 351 352 /* 353 ** pTerm is a WO_EQUIV term "X=Y" that whereScanNext() might use to add 354 ** Y to the equivalence class of X. Return true if any of the following 355 ** are true: 356 ** 357 ** * Parameter zCollName is NULL, 358 ** * The collation sequence of pTerm is BINARY, or 359 ** * The collation sequence of pTerm is zCollName. 360 ** 361 ** Otherwise return false. 362 */ 363 static int whereScanEquivCollOk( 364 Parse *pParse, 365 WhereTerm *pTerm, 366 const char *zCollName 367 ){ 368 CollSeq *pColl; 369 if( zCollName==0 ) return 1; 370 pColl = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr); 371 if( sqlite3IsBinary(pColl) ) return 1; 372 return sqlite3StrICmp(pColl->zName, zCollName)==0; 373 } 374 375 /* 376 ** Advance to the next WhereTerm that matches according to the criteria 377 ** established when the pScan object was initialized by whereScanInit(). 378 ** Return NULL if there are no more matching WhereTerms. 379 */ 380 static WhereTerm *whereScanNext(WhereScan *pScan){ 381 int iCur; /* The cursor on the LHS of the term */ 382 i16 iColumn; /* The column on the LHS of the term. -1 for IPK */ 383 Expr *pX; /* An expression being tested */ 384 WhereClause *pWC; /* Shorthand for pScan->pWC */ 385 WhereTerm *pTerm; /* The term being tested */ 386 int k = pScan->k; /* Where to start scanning */ 387 388 assert( pScan->iEquiv<=pScan->nEquiv ); 389 pWC = pScan->pWC; 390 while(1){ 391 iColumn = pScan->aiColumn[pScan->iEquiv-1]; 392 iCur = pScan->aiCur[pScan->iEquiv-1]; 393 assert( pWC!=0 ); 394 assert( iCur>=0 ); 395 do{ 396 for(pTerm=pWC->a+k; knTerm; k++, pTerm++){ 397 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 || pTerm->leftCursor<0 ); 398 if( pTerm->leftCursor==iCur 399 && pTerm->u.x.leftColumn==iColumn 400 && (iColumn!=XN_EXPR 401 || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft, 402 pScan->pIdxExpr,iCur)==0) 403 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON)) 404 ){ 405 if( (pTerm->eOperator & WO_EQUIV)!=0 406 && pScan->nEquivaiCur) 407 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0 408 && whereScanEquivCollOk(pWC->pWInfo->pParse, pTerm, pScan->zCollName) 409 ){ 410 int j; 411 for(j=0; jnEquiv; j++){ 412 if( pScan->aiCur[j]==pX->iTable 413 && pScan->aiColumn[j]==pX->iColumn ){ 414 break; 415 } 416 } 417 if( j==pScan->nEquiv ){ 418 pScan->aiCur[j] = pX->iTable; 419 pScan->aiColumn[j] = pX->iColumn; 420 pScan->nEquiv++; 421 } 422 } 423 if( (pTerm->eOperator & pScan->opMask)!=0 ){ 424 /* Verify the affinity and collating sequence match */ 425 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ 426 const char *zCollName; 427 Parse *pParse = pWC->pWInfo->pParse; 428 pX = pTerm->pExpr; 429 430 if( (pTerm->eOperator & WO_IN) ){ 431 zCollName = indexInAffinityOk(pParse, pTerm, pScan->idxaff); 432 if( !zCollName ) continue; 433 }else{ 434 CollSeq *pColl; 435 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ 436 continue; 437 } 438 assert(pX->pLeft); 439 pColl = sqlite3ExprCompareCollSeq(pParse, pX); 440 zCollName = pColl ? pColl->zName : sqlite3StrBINARY; 441 } 442 443 if( sqlite3StrICmp(zCollName, pScan->zCollName) ){ 444 continue; 445 } 446 } 447 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0 448 && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0)) 449 && pX->op==TK_COLUMN 450 && pX->iTable==pScan->aiCur[0] 451 && pX->iColumn==pScan->aiColumn[0] 452 ){ 453 testcase( pTerm->eOperator & WO_IS ); 454 continue; 455 } 456 pScan->pWC = pWC; 457 pScan->k = k+1; 458 #ifdef WHERETRACE_ENABLED 459 if( (sqlite3WhereTrace & 0x20000)!=0 && pScan->nEquiv>1 ){ 460 int ii; 461 sqlite3DebugPrintf("EQUIVALENT TO {%d:%d} (due to TERM-%d):", 462 pScan->aiCur[0], pScan->aiColumn[0], pTerm->iTerm); 463 for(ii=1; iinEquiv; ii++){ 464 sqlite3DebugPrintf(" {%d:%d}", 465 pScan->aiCur[ii], pScan->aiColumn[ii]); 466 } 467 sqlite3DebugPrintf("\n"); 468 } 469 #endif 470 return pTerm; 471 } 472 } 473 } 474 pWC = pWC->pOuter; 475 k = 0; 476 }while( pWC!=0 ); 477 if( pScan->iEquiv>=pScan->nEquiv ) break; 478 pWC = pScan->pOrigWC; 479 k = 0; 480 pScan->iEquiv++; 481 } 482 return 0; 483 } 484 485 /* 486 ** This is whereScanInit() for the case of an index on an expression. 487 ** It is factored out into a separate tail-recursion subroutine so that 488 ** the normal whereScanInit() routine, which is a high-runner, does not 489 ** need to push registers onto the stack as part of its prologue. 490 */ 491 static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){ 492 pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr); 493 return whereScanNext(pScan); 494 } 495 496 /* 497 ** Initialize a WHERE clause scanner object. Return a pointer to the 498 ** first match. Return NULL if there are no matches. 499 ** 500 ** The scanner will be searching the WHERE clause pWC. It will look 501 ** for terms of the form "X " where X is column iColumn of table 502 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx 503 ** must be one of the indexes of table iCur. 504 ** 505 ** The must be one of the operators described by opMask. 506 ** 507 ** If the search is for X and the WHERE clause contains terms of the 508 ** form X=Y then this routine might also return terms of the form 509 ** "Y ". The number of levels of transitivity is limited, 510 ** but is enough to handle most commonly occurring SQL statements. 511 ** 512 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with 513 ** index pIdx. 514 */ 515 static WhereTerm *whereScanInit( 516 WhereScan *pScan, /* The WhereScan object being initialized */ 517 WhereClause *pWC, /* The WHERE clause to be scanned */ 518 int iCur, /* Cursor to scan for */ 519 int iColumn, /* Column to scan for */ 520 u32 opMask, /* Operator(s) to scan for */ 521 Index *pIdx /* Must be compatible with this index */ 522 ){ 523 pScan->pOrigWC = pWC; 524 pScan->pWC = pWC; 525 pScan->pIdxExpr = 0; 526 pScan->idxaff = 0; 527 pScan->zCollName = 0; 528 pScan->opMask = opMask; 529 pScan->k = 0; 530 pScan->aiCur[0] = iCur; 531 pScan->nEquiv = 1; 532 pScan->iEquiv = 1; 533 if( pIdx ){ 534 int j = iColumn; 535 iColumn = pIdx->aiColumn[j]; 536 if( iColumn==pIdx->pTable->iPKey ){ 537 iColumn = XN_ROWID; 538 }else if( iColumn>=0 ){ 539 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; 540 pScan->zCollName = pIdx->azColl[j]; 541 }else if( iColumn==XN_EXPR ){ 542 pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; 543 pScan->zCollName = pIdx->azColl[j]; 544 pScan->aiColumn[0] = XN_EXPR; 545 return whereScanInitIndexExpr(pScan); 546 } 547 }else if( iColumn==XN_EXPR ){ 548 return 0; 549 } 550 pScan->aiColumn[0] = iColumn; 551 return whereScanNext(pScan); 552 } 553 554 /* 555 ** Search for a term in the WHERE clause that is of the form "X " 556 ** where X is a reference to the iColumn of table iCur or of index pIdx 557 ** if pIdx!=0 and is one of the WO_xx operator codes specified by 558 ** the op parameter. Return a pointer to the term. Return 0 if not found. 559 ** 560 ** If pIdx!=0 then it must be one of the indexes of table iCur. 561 ** Search for terms matching the iColumn-th column of pIdx 562 ** rather than the iColumn-th column of table iCur. 563 ** 564 ** The term returned might by Y= if there is another constraint in 565 ** the WHERE clause that specifies that X=Y. Any such constraints will be 566 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The 567 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11 568 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10 569 ** other equivalent values. Hence a search for X will return if X=A1 570 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=. 571 ** 572 ** If there are multiple terms in the WHERE clause of the form "X " 573 ** then try for the one with no dependencies on - in other words where 574 ** is a constant expression of some kind. Only return entries of 575 ** the form "X Y" where Y is a column in another table if no terms of 576 ** the form "X " exist. If no terms with a constant RHS 577 ** exist, try to return a term that does not use WO_EQUIV. 578 */ 579 WhereTerm *sqlite3WhereFindTerm( 580 WhereClause *pWC, /* The WHERE clause to be searched */ 581 int iCur, /* Cursor number of LHS */ 582 int iColumn, /* Column number of LHS */ 583 Bitmask notReady, /* RHS must not overlap with this mask */ 584 u32 op, /* Mask of WO_xx values describing operator */ 585 Index *pIdx /* Must be compatible with this index, if not NULL */ 586 ){ 587 WhereTerm *pResult = 0; 588 WhereTerm *p; 589 WhereScan scan; 590 591 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); 592 op &= WO_EQ|WO_IS; 593 while( p ){ 594 if( (p->prereqRight & notReady)==0 ){ 595 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){ 596 testcase( p->eOperator & WO_IS ); 597 return p; 598 } 599 if( pResult==0 ) pResult = p; 600 } 601 p = whereScanNext(&scan); 602 } 603 return pResult; 604 } 605 606 /* 607 ** This function searches pList for an entry that matches the iCol-th column 608 ** of index pIdx. 609 ** 610 ** If such an expression is found, its index in pList->a[] is returned. If 611 ** no expression is found, -1 is returned. 612 */ 613 static int findIndexCol( 614 Parse *pParse, /* Parse context */ 615 ExprList *pList, /* Expression list to search */ 616 int iBase, /* Cursor for table associated with pIdx */ 617 Index *pIdx, /* Index to match column of */ 618 int iCol /* Column of index to match */ 619 ){ 620 int i; 621 const char *zColl = pIdx->azColl[iCol]; 622 623 for(i=0; inExpr; i++){ 624 Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr); 625 if( ALWAYS(p!=0) 626 && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) 627 && p->iColumn==pIdx->aiColumn[iCol] 628 && p->iTable==iBase 629 ){ 630 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr); 631 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){ 632 return i; 633 } 634 } 635 } 636 637 return -1; 638 } 639 640 /* 641 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL 642 */ 643 static int indexColumnNotNull(Index *pIdx, int iCol){ 644 int j; 645 assert( pIdx!=0 ); 646 assert( iCol>=0 && iColnColumn ); 647 j = pIdx->aiColumn[iCol]; 648 if( j>=0 ){ 649 return pIdx->pTable->aCol[j].notNull; 650 }else if( j==(-1) ){ 651 return 1; 652 }else{ 653 assert( j==(-2) ); 654 return 0; /* Assume an indexed expression can always yield a NULL */ 655 656 } 657 } 658 659 /* 660 ** Return true if the DISTINCT expression-list passed as the third argument 661 ** is redundant. 662 ** 663 ** A DISTINCT list is redundant if any subset of the columns in the 664 ** DISTINCT list are collectively unique and individually non-null. 665 */ 666 static int isDistinctRedundant( 667 Parse *pParse, /* Parsing context */ 668 SrcList *pTabList, /* The FROM clause */ 669 WhereClause *pWC, /* The WHERE clause */ 670 ExprList *pDistinct /* The result set that needs to be DISTINCT */ 671 ){ 672 Table *pTab; 673 Index *pIdx; 674 int i; 675 int iBase; 676 677 /* If there is more than one table or sub-select in the FROM clause of 678 ** this query, then it will not be possible to show that the DISTINCT 679 ** clause is redundant. */ 680 if( pTabList->nSrc!=1 ) return 0; 681 iBase = pTabList->a[0].iCursor; 682 pTab = pTabList->a[0].pSTab; 683 684 /* If any of the expressions is an IPK column on table iBase, then return 685 ** true. Note: The (p->iTable==iBase) part of this test may be false if the 686 ** current SELECT is a correlated sub-query. 687 */ 688 for(i=0; inExpr; i++){ 689 Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr); 690 if( NEVER(p==0) ) continue; 691 if( p->op!=TK_COLUMN && p->op!=TK_AGG_COLUMN ) continue; 692 if( p->iTable==iBase && p->iColumn<0 ) return 1; 693 } 694 695 /* Loop through all indices on the table, checking each to see if it makes 696 ** the DISTINCT qualifier redundant. It does so if: 697 ** 698 ** 1. The index is itself UNIQUE, and 699 ** 700 ** 2. All of the columns in the index are either part of the pDistinct 701 ** list, or else the WHERE clause contains a term of the form "col=X", 702 ** where X is a constant value. The collation sequences of the 703 ** comparison and select-list expressions must match those of the index. 704 ** 705 ** 3. All of those index columns for which the WHERE clause does not 706 ** contain a "col=X" term are subject to a NOT NULL constraint. 707 */ 708 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 709 if( !IsUniqueIndex(pIdx) ) continue; 710 if( pIdx->pPartIdxWhere ) continue; 711 for(i=0; inKeyCol; i++){ 712 if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ 713 if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break; 714 if( indexColumnNotNull(pIdx, i)==0 ) break; 715 } 716 } 717 if( i==pIdx->nKeyCol ){ 718 /* This index implies that the DISTINCT qualifier is redundant. */ 719 return 1; 720 } 721 } 722 723 return 0; 724 } 725 726 727 /* 728 ** Estimate the logarithm of the input value to base 2. 729 */ 730 static LogEst estLog(LogEst N){ 731 return N<=10 ? 0 : sqlite3LogEst(N) - 33; 732 } 733 734 /* 735 ** Convert OP_Column opcodes to OP_Copy in previously generated code. 736 ** 737 ** This routine runs over generated VDBE code and translates OP_Column 738 ** opcodes into OP_Copy when the table is being accessed via co-routine 739 ** instead of via table lookup. 740 ** 741 ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on 742 ** cursor iTabCur are transformed into OP_Sequence opcode for the 743 ** iAutoidxCur cursor, in order to generate unique rowids for the 744 ** automatic index being generated. 745 */ 746 static void translateColumnToCopy( 747 Parse *pParse, /* Parsing context */ 748 int iStart, /* Translate from this opcode to the end */ 749 int iTabCur, /* OP_Column/OP_Rowid references to this table */ 750 int iRegister, /* The first column is in this register */ 751 int iAutoidxCur /* If non-zero, cursor of autoindex being generated */ 752 ){ 753 Vdbe *v = pParse->pVdbe; 754 VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart); 755 int iEnd = sqlite3VdbeCurrentAddr(v); 756 if( pParse->db->mallocFailed ) return; 757 #ifdef SQLITE_DEBUG 758 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ 759 printf("CHECKING for column-to-copy on cursor %d for %d..%d\n", 760 iTabCur, iStart, iEnd); 761 } 762 #endif 763 for(; iStartp1!=iTabCur ) continue; 765 if( pOp->opcode==OP_Column ){ 766 #ifdef SQLITE_DEBUG 767 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ 768 printf("TRANSLATE OP_Column to OP_Copy at %d\n", iStart); 769 } 770 #endif 771 pOp->opcode = OP_Copy; 772 pOp->p1 = pOp->p2 + iRegister; 773 pOp->p2 = pOp->p3; 774 pOp->p3 = 0; 775 pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */ 776 }else if( pOp->opcode==OP_Rowid ){ 777 #ifdef SQLITE_DEBUG 778 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ 779 printf("TRANSLATE OP_Rowid to OP_Sequence at %d\n", iStart); 780 } 781 #endif 782 pOp->opcode = OP_Sequence; 783 pOp->p1 = iAutoidxCur; 784 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW 785 if( iAutoidxCur==0 ){ 786 pOp->opcode = OP_Null; 787 pOp->p3 = 0; 788 } 789 #endif 790 } 791 } 792 } 793 794 /* 795 ** Two routines for printing the content of an sqlite3_index_info 796 ** structure. Used for testing and debugging only. If neither 797 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines 798 ** are no-ops. 799 */ 800 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) 801 static void whereTraceIndexInfoInputs( 802 sqlite3_index_info *p, /* The IndexInfo object */ 803 Table *pTab /* The TABLE that is the virtual table */ 804 ){ 805 int i; 806 if( (sqlite3WhereTrace & 0x10)==0 ) return; 807 sqlite3DebugPrintf("sqlite3_index_info inputs for %s:\n", pTab->zName); 808 for(i=0; inConstraint; i++){ 809 sqlite3DebugPrintf( 810 " constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n", 811 i, 812 p->aConstraint[i].iColumn, 813 p->aConstraint[i].iTermOffset, 814 p->aConstraint[i].op, 815 p->aConstraint[i].usable, 816 sqlite3_vtab_collation(p,i)); 817 } 818 for(i=0; inOrderBy; i++){ 819 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", 820 i, 821 p->aOrderBy[i].iColumn, 822 p->aOrderBy[i].desc); 823 } 824 } 825 static void whereTraceIndexInfoOutputs( 826 sqlite3_index_info *p, /* The IndexInfo object */ 827 Table *pTab /* The TABLE that is the virtual table */ 828 ){ 829 int i; 830 if( (sqlite3WhereTrace & 0x10)==0 ) return; 831 sqlite3DebugPrintf("sqlite3_index_info outputs for %s:\n", pTab->zName); 832 for(i=0; inConstraint; i++){ 833 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", 834 i, 835 p->aConstraintUsage[i].argvIndex, 836 p->aConstraintUsage[i].omit); 837 } 838 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); 839 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); 840 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); 841 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); 842 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows); 843 } 844 #else 845 #define whereTraceIndexInfoInputs(A,B) 846 #define whereTraceIndexInfoOutputs(A,B) 847 #endif 848 849 /* 850 ** We know that pSrc is an operand of an outer join. Return true if 851 ** pTerm is a constraint that is compatible with that join. 852 ** 853 ** pTerm must be EP_OuterON if pSrc is the right operand of an 854 ** outer join. pTerm can be either EP_OuterON or EP_InnerON if pSrc 855 ** is the left operand of a RIGHT join. 856 ** 857 ** See https://sqlite.org/forum/forumpost/`206d99a16dd9212f` 858 ** for an example of a WHERE clause constraints that may not be used on 859 ** the right table of a RIGHT JOIN because the constraint implies a 860 ** not-NULL condition on the left table of the RIGHT JOIN. 861 */ 862 static int constraintCompatibleWithOuterJoin( 863 const WhereTerm *pTerm, /* WHERE clause term to check */ 864 const SrcItem *pSrc /* Table we are trying to access */ 865 ){ 866 assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */ 867 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT ); 868 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ ); 869 testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) 870 testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) ); 871 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON) 872 || pTerm->pExpr->w.iJoin != pSrc->iCursor 873 ){ 874 return 0; 875 } 876 if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0 877 && NEVER(ExprHasProperty(pTerm->pExpr, EP_InnerON)) 878 ){ 879 return 0; 880 } 881 return 1; 882 } 883 884 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 885 /* 886 ** Return true if column iCol of table pTab seem like it might be a 887 ** good column to use as part of a query-time index. 888 ** 889 ** Current algorithm (subject to improvement!): 890 ** 891 ** 1. If iCol is already the left-most column of some other index, 892 ** then return false. 893 ** 894 ** 2. If iCol is part of an existing index that has an aiRowLogEst of 895 ** more than 20, then return false. 896 ** 897 ** 3. If no disqualifying conditions above are found, return true. 898 ** 899 ** 2025-01-03: I experimented with a new rule that returns false if the 900 ** the datatype of the column is "BOOLEAN". This did not improve 901 ** performance on any queries at hand, but it did burn CPU cycles, so the 902 ** idea was not committed. 903 */ 904 static SQLITE_NOINLINE int columnIsGoodIndexCandidate( 905 const Table *pTab, 906 int iCol 907 ){ 908 const Index *pIdx; 909 for(pIdx = pTab->pIndex; pIdx!=0; pIdx=pIdx->pNext){ 910 int j; 911 for(j=0; jnKeyCol; j++){ 912 if( pIdx->aiColumn[j]==iCol ){ 913 if( j==0 ) return 0; 914 if( pIdx->hasStat1 && pIdx->aiRowLogEst[j+1]>20 ) return 0; 915 break; 916 } 917 } 918 } 919 return 1; 920 } 921 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 922 923 924 925 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 926 /* 927 ** Return TRUE if the WHERE clause term pTerm is of a form where it 928 ** could be used with an index to access pSrc, assuming an appropriate 929 ** index existed. 930 */ 931 static int termCanDriveIndex( 932 const WhereTerm *pTerm, /* WHERE clause term to check */ 933 const SrcItem *pSrc, /* Table we are trying to access */ 934 const Bitmask notReady /* Tables in outer loops of the join */ 935 ){ 936 char aff; 937 int leftCol; 938 939 if( pTerm->leftCursor!=pSrc->iCursor ) return 0; 940 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0; 941 assert( (pSrc->fg.jointype & JT_RIGHT)==0 ); 942 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 943 && !constraintCompatibleWithOuterJoin(pTerm,pSrc) 944 ){ 945 return 0; /* See https://sqlite.org/forum/forumpost/`51e6959f61` */ 946 } 947 if( (pTerm->prereqRight & notReady)!=0 ) return 0; 948 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 ); 949 leftCol = pTerm->u.x.leftColumn; 950 if( leftCol<0 ) return 0; 951 aff = pSrc->pSTab->aCol[leftCol].affinity; 952 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; 953 testcase( pTerm->pExpr->op==TK_IS ); 954 return columnIsGoodIndexCandidate(pSrc->pSTab, leftCol); 955 } 956 #endif 957 958 959 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 960 961 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 962 /* 963 ** Argument pIdx represents an automatic index that the current statement 964 ** will create and populate. Add an OP_Explain with text of the form: 965 ** 966 ** CREATE AUTOMATIC INDEX ON () [WHERE ] 967 ** 968 ** This is only required if sqlite3_stmt_scanstatus() is enabled, to 969 ** associate an SQLITE_SCANSTAT_NCYCLE and SQLITE_SCANSTAT_NLOOP 970 ** values with. In order to avoid breaking legacy code and test cases, 971 ** the OP_Explain is not added if this is an EXPLAIN QUERY PLAN command. 972 */ 973 static void explainAutomaticIndex( 974 Parse *pParse, 975 Index *pIdx, /* Automatic index to explain */ 976 int bPartial, /* True if pIdx is a partial index */ 977 int *pAddrExplain /* OUT: Address of OP_Explain */ 978 ){ 979 if( IS_STMT_SCANSTATUS(pParse->db) && pParse->explain!=2 ){ 980 Table *pTab = pIdx->pTable; 981 const char *zSep = ""; 982 char *zText = 0; 983 int ii = 0; 984 sqlite3_str *pStr = sqlite3_str_new(pParse->db); 985 sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName); 986 assert( pIdx->nColumn>1 ); 987 assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID || !HasRowid(pTab) ); 988 for(ii=0; ii<(pIdx->nColumn-1); ii++){ 989 const char *zName = 0; 990 int iCol = pIdx->aiColumn[ii]; 991 992 zName = pTab->aCol[iCol].zCnName; 993 sqlite3_str_appendf(pStr, "%s%s", zSep, zName); 994 zSep = ", "; 995 } 996 zText = sqlite3_str_finish(pStr); 997 if( zText==0 ){ 998 sqlite3OomFault(pParse->db); 999 }else{ 1000 *pAddrExplain = sqlite3VdbeExplain( 1001 pParse, 0, "%s)%s", zText, (bPartial ? " WHERE " : "") 1002 ); 1003 sqlite3_free(zText); 1004 } 1005 } 1006 } 1007 #else 1008 # define explainAutomaticIndex(a,b,c,d) 1009 #endif 1010 1011 /* 1012 ** Generate code to construct the Index object for an automatic index 1013 ** and to set up the WhereLevel object pLevel so that the code generator 1014 ** makes use of the automatic index. 1015 */ 1016 static SQLITE_NOINLINE void constructAutomaticIndex( 1017 Parse *pParse, /* The parsing context */ 1018 WhereClause *pWC, /* The WHERE clause */ 1019 const Bitmask notReady, /* Mask of cursors that are not available */ 1020 WhereLevel *pLevel /* Write new index here */ 1021 ){ 1022 int nKeyCol; /* Number of columns in the constructed index */ 1023 WhereTerm *pTerm; /* A single term of the WHERE clause */ 1024 WhereTerm *pWCEnd; /* End of pWC->a[] */ 1025 Index *pIdx; /* Object describing the transient index */ 1026 Vdbe *v; /* Prepared statement under construction */ 1027 int addrInit; /* Address of the initialization bypass jump */ 1028 Table *pTable; /* The table being indexed */ 1029 int addrTop; /* Top of the index fill loop */ 1030 int regRecord; /* Register holding an index record */ 1031 int n; /* Column counter */ 1032 int i; /* Loop counter */ 1033 int mxBitCol; /* Maximum column in pSrc->colUsed */ 1034 CollSeq *pColl; /* Collating sequence to on a column */ 1035 WhereLoop *pLoop; /* The Loop object */ 1036 char *zNotUsed; /* Extra space on the end of pIdx */ 1037 Bitmask idxCols; /* Bitmap of columns used for indexing */ 1038 Bitmask pkCols; /* PK cols whose key collation keeps them unique */ 1039 Bitmask extraCols; /* Bitmap of additional columns */ 1040 int bHighCols; /* True to add all columns >= BMS-1 */ 1041 u8 sentWarning = 0; /* True if a warning has been issued */ 1042 u8 useBloomFilter = 1; /* True to also add a Bloom filter */ 1043 Expr *pPartial = 0; /* Partial Index Expression */ 1044 int iContinue = 0; /* Jump here to skip excluded rows */ 1045 SrcList *pTabList; /* The complete FROM clause */ 1046 SrcItem *pSrc; /* The FROM clause term to get the next index */ 1047 int addrCounter = 0; /* Address where integer counter is initialized */ 1048 int regBase; /* Array of registers where record is assembled */ 1049 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 1050 int addrExp = 0; /* Address of OP_Explain */ 1051 #endif 1052 1053 /* Generate code to skip over the creation and initialization of the 1054 ** transient index on 2nd and subsequent iterations of the loop. */ 1055 v = pParse->pVdbe; 1056 assert( v!=0 ); 1057 addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 1058 1059 /* Count the number of columns that will be added to the index 1060 ** and used to match WHERE clause constraints */ 1061 nKeyCol = 0; 1062 pTabList = pWC->pWInfo->pTabList; 1063 pSrc = &pTabList->a[pLevel->iFrom]; 1064 pTable = pSrc->pSTab; 1065 pWCEnd = &pWC->a[pWC->nTerm]; 1066 pLoop = pLevel->pWLoop; 1067 idxCols = 0; 1068 pkCols = 0; 1069 for(pTerm=pWC->a; pTermpExpr; 1071 /* Make the automatic index a partial index if there are terms in the 1072 ** WHERE clause (or the ON clause of a LEFT join) that constrain which 1073 ** rows of the target table (pSrc) that can be used. */ 1074 if( (pTerm->wtFlags & TERM_VIRTUAL)==0 1075 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, pLevel->iFrom, 0) 1076 ){ 1077 pPartial = sqlite3ExprAnd(pParse, pPartial, 1078 sqlite3ExprDup(pParse->db, pExpr, 0)); 1079 } 1080 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ 1081 int iCol; 1082 Bitmask cMask; 1083 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 ); 1084 iCol = pTerm->u.x.leftColumn; 1085 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); 1086 testcase( iCol==BMS ); 1087 testcase( iCol==BMS-1 ); 1088 if( !sentWarning ){ 1089 sqlite3_log(SQLITE_WARNING_AUTOINDEX, 1090 "automatic index on %s(%s)", pTable->zName, 1091 pTable->aCol[iCol].zCnName); 1092 sentWarning = 1; 1093 } 1094 if( (idxCols & cMask)==0 ){ 1095 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){ 1096 goto end_auto_index_create; 1097 } 1098 pLoop->aLTerm[nKeyCol++] = pTerm; 1099 idxCols |= cMask; 1100 1101 /* For a WITHOUT ROWID table, all PRIMARY KEY columns must be 1102 ** present in the automatic index, sorted with either BINARY or 1103 ** the same collation used by the PK index itself, to guarantee each 1104 ** entry is unique. If the current field matches that criteria, 1105 ** set the corresponding bit in pkCols. */ 1106 if( !HasRowid(pTable) && iColaCol[iCol].colFlags & COLFLAG_PRIMKEY) 1108 ){ 1109 Index *pPk = sqlite3PrimaryKeyIndex(pTable); 1110 CollSeq *pX = sqlite3ExprCompareCollSeq(pParse, pExpr); 1111 int iPk = sqlite3TableColumnToIndex(pPk, iCol); 1112 assert( iPk>=0 && iPknKeyCol ); 1113 if( sqlite3IsBinary(pX) 1114 || sqlite3StrICmp(pPk->azColl[iPk], pX->zName)==0 1115 ){ 1116 pkCols |= cMask; 1117 } 1118 } 1119 } 1120 } 1121 } 1122 assert( nKeyCol>0 || pParse->db->mallocFailed ); 1123 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; 1124 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED 1125 | WHERE_AUTO_INDEX; 1126 1127 /* Count the number of additional columns needed to create a 1128 ** covering index. A "covering index" is an index that contains all 1129 ** columns that are needed by the query. With a covering index, the 1130 ** original table never needs to be accessed. Automatic indices must 1131 ** be a covering index because the index will not be updated if the 1132 ** original table changes and the index and table cannot both be used 1133 ** if they go out of sync. 1134 */ 1135 if( IsView(pTable) ){ 1136 extraCols = ALLBITS & ~idxCols; 1137 }else{ 1138 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); 1139 } 1140 bHighCols = (pSrc->colUsed & MASKBIT(BMS-1))!=0; 1141 if( !HasRowid(pTable) ){ 1142 /* For WITHOUT ROWID tables, ensure that all PRIMARY KEY columns are 1143 ** either in the pkCols mask or in the extraCols mask. A column that 1144 ** is already an index key but is not in pkCols is added a second 1145 ** time, using the BINARY collating sequence. */ 1146 for(i=0; inCol; i++){ 1147 if( (pTable->aCol[i].colFlags & COLFLAG_PRIMKEY)==0 ) continue; 1148 if( i>=BMS-1 ){ 1149 bHighCols = 1; 1150 break; 1151 } 1152 if( pkCols & MASKBIT(i) ) continue; 1153 extraCols |= MASKBIT(i); 1154 } 1155 } 1156 mxBitCol = MIN(BMS-1,pTable->nCol); 1157 testcase( pTable->nCol==BMS-1 ); 1158 testcase( pTable->nCol==BMS-2 ); 1159 for(i=0; inCol - BMS + 1; 1164 } 1165 1166 /* Construct the Index object to describe this index */ 1167 assert( nKeyCol <= pTable->nCol + MIN(pTable->nCol, BMS) ); 1168 /* ^-- This guarantees that the number of index columns will fit in the u16 */ 1169 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+HasRowid(pTable), 1170 0, &zNotUsed); 1171 if( pIdx==0 ) goto end_auto_index_create; 1172 pLoop->u.btree.pIndex = pIdx; 1173 pIdx->zName = "auto-index"; 1174 pIdx->pTable = pTable; 1175 n = 0; 1176 idxCols = 0; 1177 for(pTerm=pWC->a; pTermeOperator & (WO_OR|WO_AND))==0 ); 1182 iCol = pTerm->u.x.leftColumn; 1183 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); 1184 testcase( iCol==BMS-1 ); 1185 testcase( iCol==BMS ); 1186 if( (idxCols & cMask)==0 ){ 1187 Expr *pX = pTerm->pExpr; 1188 idxCols |= cMask; 1189 pIdx->aiColumn[n] = pTerm->u.x.leftColumn; 1190 pColl = sqlite3ExprCompareCollSeq(pParse, pX); 1191 testcase( pColl==0 && pParse->nErr==0 ); /* TH3 collate01.810 */ 1192 if( !sqlite3IsBinary(pColl) ){ 1193 /* Disallow the use of a Bloom filter if any non-BINARY collating 1194 ** sequence is involved. tag-`202607231411` */ 1195 useBloomFilter = 0; 1196 } 1197 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; 1198 n++; 1199 } 1200 } 1201 } 1202 assert( (u32)n==pLoop->u.btree.nEq ); 1203 1204 /* Add additional columns needed to make the automatic index into 1205 ** a covering index */ 1206 for(i=0; iaiColumn[n] = i; 1209 pIdx->azColl[n] = sqlite3StrBINARY; 1210 n++; 1211 } 1212 } 1213 if( bHighCols ){ 1214 for(i=BMS-1; inCol; i++){ 1215 pIdx->aiColumn[n] = i; 1216 pIdx->azColl[n] = sqlite3StrBINARY; 1217 n++; 1218 } 1219 } 1220 assert( n==nKeyCol ); 1221 if( HasRowid(pTable) ){ 1222 pIdx->aiColumn[n] = XN_ROWID; 1223 pIdx->azColl[n] = sqlite3StrBINARY; 1224 } 1225 1226 /* Create the automatic index */ 1227 explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp); 1228 assert( pLevel->iIdxCur>=0 ); 1229 pLevel->iIdxCur = pParse->nTab++; 1230 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); 1231 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 1232 VdbeComment((v, "for %s", pTable->zName)); 1233 if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) && useBloomFilter ){ 1234 sqlite3WhereExplainBloomFilter(pParse, pWC->pWInfo, pLevel); 1235 pLevel->regFilter = ++pParse->nMem; 1236 sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter); 1237 } 1238 1239 /* Fill the automatic index with content */ 1240 assert( pSrc == &pWC->pWInfo->pTabList->a[pLevel->iFrom] ); 1241 if( pSrc->fg.viaCoroutine ){ 1242 int regYield; 1243 Subquery *pSubq; 1244 assert( pSrc->fg.isSubquery ); 1245 pSubq = pSrc->u4.pSubq; 1246 assert( pSubq!=0 ); 1247 regYield = pSubq->regReturn; 1248 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0); 1249 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSubq->addrFillSub); 1250 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield); 1251 VdbeCoverage(v); 1252 VdbeComment((v, "next row of %s", pSrc->pSTab->zName)); 1253 }else{ 1254 assert( pLevel->addrHalt ); 1255 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind,pLevel->iTabCur,pLevel->addrHalt); 1256 VdbeCoverage(v); 1257 } 1258 if( pPartial ){ 1259 iContinue = sqlite3VdbeMakeLabel(pParse); 1260 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); 1261 pLoop->wsFlags |= WHERE_PARTIALIDX; 1262 } 1263 regRecord = sqlite3GetTempReg(pParse); 1264 regBase = sqlite3GenerateIndexKey( 1265 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 1266 ); 1267 if( pLevel->regFilter ){ 1268 assert( sqlite3WhereLoopBloomable(pLoop) ); 1269 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, 1270 regBase, pLoop->u.btree.nEq); 1271 } 1272 sqlite3VdbeScanStatusCounters(v, addrExp, addrExp, sqlite3VdbeCurrentAddr(v)); 1273 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); 1274 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1275 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue); 1276 if( pSrc->fg.viaCoroutine ){ 1277 assert( pSrc->fg.isSubquery && pSrc->u4.pSubq!=0 ); 1278 sqlite3VdbeChangeP2(v, addrCounter, regBase+n); 1279 testcase( pParse->db->mallocFailed ); 1280 assert( pLevel->iIdxCur>0 ); 1281 translateColumnToCopy(pParse, addrTop, pLevel->iTabCur, 1282 pSrc->u4.pSubq->regResult, pLevel->iIdxCur); 1283 sqlite3VdbeGoto(v, addrTop); 1284 pSrc->fg.viaCoroutine = 0; 1285 sqlite3VdbeJumpHere(v, addrTop); 1286 }else{ 1287 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); 1288 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); 1289 if( (pSrc->fg.jointype & JT_LEFT)!=0 ){ 1290 sqlite3VdbeJumpHere(v, addrTop); 1291 } 1292 } 1293 sqlite3ReleaseTempReg(pParse, regRecord); 1294 1295 /* Jump here when skipping the initialization */ 1296 sqlite3VdbeJumpHere(v, addrInit); 1297 sqlite3VdbeScanStatusRange(v, addrExp, addrExp, -1); 1298 1299 end_auto_index_create: 1300 sqlite3ExprDelete(pParse->db, pPartial); 1301 } 1302 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 1303 1304 /* 1305 ** Generate bytecode that will initialize a Bloom filter that is appropriate 1306 ** for pLevel. 1307 ** 1308 ** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER 1309 ** flag set, initialize a Bloomfilter for them as well. 1310 ** 1311 ** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared 1312 ** from the loop, but the regFilter value is set to a register that implements 1313 ** the Bloom filter. When regFilter is positive, the 1314 ** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter 1315 ** and skip the subsequence B-Tree seek if the Bloom filter indicates that 1316 ** no matching rows exist. 1317 ** 1318 ** This routine may only be called if it has previously been determined that 1319 ** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit 1320 ** is set. 1321 */ 1322 static SQLITE_NOINLINE void sqlite3ConstructBloomFilter( 1323 WhereInfo *pWInfo, /* The WHERE clause */ 1324 int iLevel, /* Index in pWInfo->a[] that is pLevel */ 1325 WhereLevel *pLevel, /* Make a Bloom filter for this FROM term */ 1326 Bitmask notReady /* Loops that are not ready */ 1327 ){ 1328 int addrOnce; /* Address of opening OP_Once */ 1329 int addrTop; /* Address of OP_Rewind */ 1330 int addrCont; /* Jump here to skip a row */ 1331 const WhereTerm *pTerm; /* For looping over WHERE clause terms */ 1332 const WhereTerm *pWCEnd; /* Last WHERE clause term */ 1333 Parse *pParse = pWInfo->pParse; /* Parsing context */ 1334 Vdbe *v = pParse->pVdbe; /* VDBE under construction */ 1335 WhereLoop *pLoop = pLevel->pWLoop; /* The loop being coded */ 1336 int iCur; /* Cursor for table getting the filter */ 1337 IndexedExpr *saved_pIdxEpr; /* saved copy of Parse.pIdxEpr */ 1338 IndexedExpr *saved_pIdxPartExpr; /* saved copy of Parse.pIdxPartExpr */ 1339 1340 saved_pIdxEpr = pParse->pIdxEpr; 1341 saved_pIdxPartExpr = pParse->pIdxPartExpr; 1342 pParse->pIdxEpr = 0; 1343 pParse->pIdxPartExpr = 0; 1344 1345 assert( pLoop!=0 ); 1346 assert( v!=0 ); 1347 assert( pLoop->wsFlags & WHERE_BLOOMFILTER ); 1348 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ); 1349 1350 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 1351 do{ 1352 const SrcList *pTabList; 1353 const SrcItem *pItem; 1354 const Table *pTab; 1355 u64 sz; 1356 int iSrc; 1357 sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel); 1358 addrCont = sqlite3VdbeMakeLabel(pParse); 1359 iCur = pLevel->iTabCur; 1360 pLevel->regFilter = ++pParse->nMem; 1361 1362 /* The Bloom filter is a Blob held in a register. Initialize it 1363 ** to zero-filled blob of at least 80K bits, but maybe more if the 1364 ** estimated size of the table is larger. We could actually 1365 ** measure the size of the table at run-time using OP_Count with 1366 ** P3==1 and use that value to initialize the blob. But that makes 1367 ** testing complicated. By basing the blob size on the value in the 1368 ** sqlite_stat1 table, testing is much easier. 1369 */ 1370 pTabList = pWInfo->pTabList; 1371 iSrc = pLevel->iFrom; 1372 pItem = &pTabList->a[iSrc]; 1373 assert( pItem!=0 ); 1374 pTab = pItem->pSTab; 1375 assert( pTab!=0 ); 1376 sz = sqlite3LogEstToInt(pTab->nRowLogEst); 1377 if( sz<10000 ){ 1378 sz = 10000; 1379 }else if( sz>`10000000` ){ 1380 sz = `10000000`; 1381 } 1382 assert( sqlite3WhereLoopBloomable(pLoop) ); 1383 sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter); 1384 1385 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); 1386 pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm]; 1387 for(pTerm=pWInfo->sWC.a; pTermpExpr; 1389 if( (pTerm->wtFlags & TERM_VIRTUAL)==0 1390 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, iSrc, 0) 1391 ){ 1392 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 1393 } 1394 } 1395 if( pLoop->wsFlags & WHERE_IPK ){ 1396 int r1 = sqlite3GetTempReg(pParse); 1397 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1); 1398 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1); 1399 sqlite3ReleaseTempReg(pParse, r1); 1400 }else{ 1401 Index *pIdx = pLoop->u.btree.pIndex; 1402 int n = pLoop->u.btree.nEq; 1403 int r1 = sqlite3GetTempRange(pParse, n); 1404 int jj; 1405 assert( pIdx!=0 ); 1406 for(jj=0; jjpTable==pItem->pSTab ); 1408 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iCur, jj, r1+jj); 1409 } 1410 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n); 1411 sqlite3ReleaseTempRange(pParse, r1, n); 1412 } 1413 sqlite3VdbeResolveLabel(v, addrCont); 1414 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); 1415 VdbeCoverage(v); 1416 sqlite3VdbeJumpHere(v, addrTop); 1417 pLoop->wsFlags &= ~WHERE_BLOOMFILTER; 1418 while( ++iLevel < pWInfo->nLevel ){ 1419 const SrcItem *pTabItem; 1420 pLevel = &pWInfo->a[iLevel]; 1421 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 1422 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ) ) continue; 1423 pLoop = pLevel->pWLoop; 1424 if( NEVER(pLoop==0) ) continue; 1425 if( pLoop->prereq & notReady ) continue; 1426 if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN)) 1427 ==WHERE_BLOOMFILTER 1428 ){ 1429 /* This is a candidate for bloom-filter pull-down (early evaluation). 1430 ** The test that WHERE_COLUMN_IN is omitted is important, as we are 1431 ** not able to do early evaluation of bloom filters that make use of 1432 ** the IN operator */ 1433 break; 1434 } 1435 } 1436 }while( iLevel < pWInfo->nLevel ); 1437 sqlite3VdbeJumpHere(v, addrOnce); 1438 pParse->pIdxEpr = saved_pIdxEpr; 1439 pParse->pIdxPartExpr = saved_pIdxPartExpr; 1440 } 1441 1442 1443 #ifndef SQLITE_OMIT_VIRTUALTABLE 1444 /* 1445 ** Return term iTerm of the WhereClause passed as the first argument. Terms 1446 ** are numbered from 0 upwards, starting with the terms in pWC->a[], then 1447 ** those in pWC->pOuter->a[] (if any), and so on. 1448 */ 1449 static WhereTerm *termFromWhereClause(WhereClause *pWC, int iTerm){ 1450 WhereClause *p; 1451 for(p=pWC; p; p=p->pOuter){ 1452 if( iTermnTerm ) return &p->a[iTerm]; 1453 iTerm -= p->nTerm; 1454 } 1455 return 0; 1456 } 1457 1458 /* 1459 ** Allocate and populate an sqlite3_index_info structure. It is the 1460 ** responsibility of the caller to eventually release the structure 1461 ** by passing the pointer returned by this function to freeIndexInfo(). 1462 */ 1463 static sqlite3_index_info *allocateIndexInfo( 1464 WhereInfo *pWInfo, /* The WHERE clause */ 1465 WhereClause *pWC, /* The WHERE clause being analyzed */ 1466 Bitmask mUnusable, /* Ignore terms with these prereqs */ 1467 SrcItem *pSrc, /* The FROM clause term that is the vtab */ 1468 u16 *pmNoOmit /* Mask of terms not to omit */ 1469 ){ 1470 int i, j; 1471 int nTerm; 1472 Parse *pParse = pWInfo->pParse; 1473 struct sqlite3_index_constraint *pIdxCons; 1474 struct sqlite3_index_orderby *pIdxOrderBy; 1475 struct sqlite3_index_constraint_usage *pUsage; 1476 struct HiddenIndexInfo *pHidden; 1477 WhereTerm *pTerm; 1478 int nOrderBy; 1479 sqlite3_index_info *pIdxInfo; 1480 u16 mNoOmit = 0; 1481 const Table *pTab; 1482 int eDistinct = 0; 1483 ExprList *pOrderBy = pWInfo->pOrderBy; 1484 WhereClause *p; 1485 1486 assert( pSrc!=0 ); 1487 pTab = pSrc->pSTab; 1488 assert( pTab!=0 ); 1489 assert( IsVirtual(pTab) ); 1490 1491 /* Find all WHERE clause constraints referring to this virtual table. 1492 ** Mark each term with the TERM_OK flag. Set nTerm to the number of 1493 ** terms found. 1494 */ 1495 for(p=pWC, nTerm=0; p; p=p->pOuter){ 1496 for(i=0, pTerm=p->a; inTerm; i++, pTerm++){ 1497 pTerm->wtFlags &= ~TERM_OK; 1498 if( pTerm->leftCursor != pSrc->iCursor ) continue; 1499 if( pTerm->prereqRight & mUnusable ) continue; 1500 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); 1501 testcase( pTerm->eOperator & WO_IN ); 1502 testcase( pTerm->eOperator & WO_ISNULL ); 1503 testcase( pTerm->eOperator & WO_IS ); 1504 testcase( pTerm->eOperator & WO_ALL ); 1505 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue; 1506 if( pTerm->wtFlags & TERM_VNULL ) continue; 1507 1508 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 ); 1509 assert( pTerm->u.x.leftColumn>=XN_ROWID ); 1510 assert( pTerm->u.x.leftColumnnCol ); 1511 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 1512 && !constraintCompatibleWithOuterJoin(pTerm,pSrc) 1513 ){ 1514 continue; 1515 } 1516 nTerm++; 1517 pTerm->wtFlags |= TERM_OK; 1518 } 1519 } 1520 1521 /* If the ORDER BY clause contains only columns in the current 1522 ** virtual table then allocate space for the aOrderBy part of 1523 ** the sqlite3_index_info structure. 1524 */ 1525 nOrderBy = 0; 1526 if( pOrderBy ){ 1527 int n = pOrderBy->nExpr; 1528 for(i=0; ia[i].pExpr; 1530 Expr *pE2; 1531 1532 /* Skip over constant terms in the ORDER BY clause */ 1533 if( sqlite3ExprIsConstant(0, pExpr) ){ 1534 continue; 1535 } 1536 1537 /* Virtual tables are unable to deal with NULLS FIRST */ 1538 if( pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) break; 1539 1540 /* First case - a direct column references without a COLLATE operator */ 1541 if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){ 1542 assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumnnCol ); 1543 continue; 1544 } 1545 1546 /* 2nd case - a column reference with a COLLATE operator. Only match 1547 ** of the COLLATE operator matches the collation of the column. */ 1548 if( pExpr->op==TK_COLLATE 1549 && (pE2 = pExpr->pLeft)->op==TK_COLUMN 1550 && pE2->iTable==pSrc->iCursor 1551 ){ 1552 const char *zColl; /* The collating sequence name */ 1553 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 1554 assert( pExpr->u.zToken!=0 ); 1555 assert( pE2->iColumn>=XN_ROWID && pE2->iColumnnCol ); 1556 pExpr->iColumn = pE2->iColumn; 1557 if( pE2->iColumn<0 ) continue; /* Collseq does not matter for rowid */ 1558 zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]); 1559 if( zColl==0 ) zColl = sqlite3StrBINARY; 1560 if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue; 1561 } 1562 1563 /* No matches cause a break out of the loop */ 1564 break; 1565 } 1566 if( i==n ){ 1567 int bSortByGroup = (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0; 1568 nOrderBy = n; 1569 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) && !pSrc->fg.rowidUsed ){ 1570 eDistinct = 2 + bSortByGroup; 1571 }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){ 1572 eDistinct = 1 - bSortByGroup; 1573 }else if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ 1574 eDistinct = 3; 1575 } 1576 } 1577 } 1578 1579 /* Allocate the sqlite3_index_info structure 1580 */ 1581 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) 1582 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm 1583 + sizeof(*pIdxOrderBy)*nOrderBy 1584 + SZ_HIDDENINDEXINFO(nTerm) ); 1585 if( pIdxInfo==0 ){ 1586 sqlite3ErrorMsg(pParse, "out of memory"); 1587 return 0; 1588 } 1589 pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1]; 1590 pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm]; 1591 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; 1592 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; 1593 pIdxInfo->aConstraint = pIdxCons; 1594 pIdxInfo->aOrderBy = pIdxOrderBy; 1595 pIdxInfo->aConstraintUsage = pUsage; 1596 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; 1597 if( HasRowid(pTab)==0 ){ 1598 /* Ensure that all bits associated with PK columns are set. This is to 1599 ** ensure they are available for cases like RIGHT joins or OR loops. */ 1600 Index *pPk = sqlite3PrimaryKeyIndex((Table*)pTab); 1601 assert( pPk!=0 ); 1602 for(i=0; inKeyCol; i++){ 1603 int iCol = pPk->aiColumn[i]; 1604 assert( iCol>=0 ); 1605 if( iCol>=BMS-1 ) iCol = BMS-1; 1606 pIdxInfo->colUsed |= MASKBIT(iCol); 1607 } 1608 } 1609 pHidden->pWC = pWC; 1610 pHidden->pParse = pParse; 1611 pHidden->eDistinct = eDistinct; 1612 pHidden->mIn = 0; 1613 for(p=pWC, i=j=0; p; p=p->pOuter){ 1614 int nLast = i+p->nTerm;; 1615 for(pTerm=p->a; iwtFlags & TERM_OK)==0 ) continue; 1618 pIdxCons[j].iColumn = pTerm->u.x.leftColumn; 1619 pIdxCons[j].iTermOffset = i; 1620 op = pTerm->eOperator & WO_ALL; 1621 if( op==WO_IN ){ 1622 if( (pTerm->wtFlags & TERM_SLICE)==0 ){ 1623 pHidden->mIn |= SMASKBIT32(j); 1624 } 1625 op = WO_EQ; 1626 } 1627 if( op==WO_AUX ){ 1628 pIdxCons[j].op = pTerm->eMatchOp; 1629 }else if( op & (WO_ISNULL|WO_IS) ){ 1630 if( op==WO_ISNULL ){ 1631 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL; 1632 }else{ 1633 pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS; 1634 } 1635 }else{ 1636 pIdxCons[j].op = (u8)op; 1637 /* The direct assignment in the previous line is possible only because 1638 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The 1639 ** following asserts verify this fact. */ 1640 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); 1641 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); 1642 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); 1643 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); 1644 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); 1645 assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) ); 1646 1647 if( op & (WO_LT|WO_LE|WO_GT|WO_GE) 1648 && sqlite3ExprIsVector(pTerm->pExpr->pRight) 1649 ){ 1650 testcase( j!=i ); 1651 if( j<16 ) mNoOmit |= (1 << j); 1652 if( op==WO_LT ) pIdxCons[j].op = WO_LE; 1653 if( op==WO_GT ) pIdxCons[j].op = WO_GE; 1654 } 1655 } 1656 1657 j++; 1658 } 1659 } 1660 assert( j==nTerm ); 1661 pIdxInfo->nConstraint = j; 1662 for(i=j=0; ia[i].pExpr; 1664 if( sqlite3ExprIsConstant(0, pExpr) ) continue; 1665 assert( pExpr->op==TK_COLUMN 1666 || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN 1667 && pExpr->iColumn==pExpr->pLeft->iColumn) ); 1668 pIdxOrderBy[j].iColumn = pExpr->iColumn; 1669 pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC; 1670 j++; 1671 } 1672 pIdxInfo->nOrderBy = j; 1673 1674 *pmNoOmit = mNoOmit; 1675 return pIdxInfo; 1676 } 1677 1678 /* 1679 ** Free and zero the sqlite3_index_info.idxStr value if needed. 1680 */ 1681 static void freeIdxStr(sqlite3_index_info *pIdxInfo){ 1682 if( pIdxInfo->needToFreeIdxStr ){ 1683 sqlite3_free(pIdxInfo->idxStr); 1684 pIdxInfo->idxStr = 0; 1685 pIdxInfo->needToFreeIdxStr = 0; 1686 } 1687 } 1688 1689 /* 1690 ** Free an sqlite3_index_info structure allocated by allocateIndexInfo() 1691 ** and possibly modified by xBestIndex methods. 1692 */ 1693 static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){ 1694 HiddenIndexInfo *pHidden; 1695 int i; 1696 assert( pIdxInfo!=0 ); 1697 pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; 1698 assert( pHidden->pParse!=0 ); 1699 assert( pHidden->pParse->db==db ); 1700 for(i=0; inConstraint; i++){ 1701 sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */ 1702 pHidden->aRhs[i] = 0; 1703 } 1704 freeIdxStr(pIdxInfo); 1705 sqlite3DbFree(db, pIdxInfo); 1706 } 1707 1708 /* 1709 ** The table object reference passed as the second argument to this function 1710 ** must represent a virtual table. This function invokes the xBestIndex() 1711 ** method of the virtual table with the sqlite3_index_info object that 1712 ** comes in as the 3rd argument to this function. 1713 ** 1714 ** If an error occurs, pParse is populated with an error message and an 1715 ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from 1716 ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that 1717 ** the current configuration of "unusable" flags in sqlite3_index_info can 1718 ** not result in a valid plan. 1719 ** 1720 ** Whether or not an error is returned, it is the responsibility of the 1721 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates 1722 ** that this is required. 1723 */ 1724 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ 1725 int rc; 1726 sqlite3_vtab *pVtab; 1727 1728 assert( IsVirtual(pTab) ); 1729 pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; 1730 whereTraceIndexInfoInputs(p, pTab); 1731 pParse->db->nSchemaLock++; 1732 rc = pVtab->pModule->xBestIndex(pVtab, p); 1733 pParse->db->nSchemaLock--; 1734 whereTraceIndexInfoOutputs(p, pTab); 1735 1736 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){ 1737 if( rc==SQLITE_NOMEM ){ 1738 sqlite3OomFault(pParse->db); 1739 }else if( !pVtab->zErrMsg ){ 1740 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); 1741 }else{ 1742 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); 1743 } 1744 } 1745 if( pTab->u.vtab.p->bAllSchemas ){ 1746 sqlite3VtabUsesAllSchemas(pParse); 1747 } 1748 sqlite3_free(pVtab->zErrMsg); 1749 pVtab->zErrMsg = 0; 1750 return rc; 1751 } 1752 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ 1753 1754 #ifdef SQLITE_ENABLE_STAT4 1755 /* 1756 ** Estimate the location of a particular key among all keys in an 1757 ** index. Store the results in aStat as follows: 1758 ** 1759 ** aStat[0] Est. number of rows less than pRec 1760 ** aStat[1] Est. number of rows equal to pRec 1761 ** 1762 ** Return the index of the sample that is the smallest sample that 1763 ** is greater than or equal to pRec. Note that this index is not an index 1764 ** into the aSample[] array - it is an index into a virtual set of samples 1765 ** based on the contents of aSample[] and the number of fields in record 1766 ** pRec. 1767 */ 1768 static int whereKeyStats( 1769 Parse *pParse, /* Database connection */ 1770 Index *pIdx, /* Index to consider domain of */ 1771 UnpackedRecord *pRec, /* Vector of values to consider */ 1772 int roundUp, /* Round up if true. Round down if false */ 1773 tRowcnt *aStat /* OUT: stats written here */ 1774 ){ 1775 IndexSample *aSample = pIdx->aSample; 1776 int iCol; /* Index of required stats in anEq[] etc. */ 1777 int i; /* Index of first sample >= pRec */ 1778 int iSample; /* Smallest sample larger than or equal to pRec */ 1779 int iMin = 0; /* Smallest sample not yet tested */ 1780 int iTest; /* Next sample to test */ 1781 int res; /* Result of comparison operation */ 1782 int nField; /* Number of fields in pRec */ 1783 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */ 1784 1785 #ifndef SQLITE_DEBUG 1786 UNUSED_PARAMETER( pParse ); 1787 #endif 1788 assert( pRec!=0 ); 1789 assert( pIdx->nSample>0 ); 1790 assert( pRec->nField>0 ); 1791 1792 1793 /* Do a binary search to find the first sample greater than or equal 1794 ** to pRec. If pRec contains a single field, the set of samples to search 1795 ** is simply the aSample[] array. If the samples in aSample[] contain more 1796 ** than one fields, all fields following the first are ignored. 1797 ** 1798 ** If pRec contains N fields, where N is more than one, then as well as the 1799 ** samples in aSample[] (truncated to N fields), the search also has to 1800 ** consider prefixes of those samples. For example, if the set of samples 1801 ** in aSample is: 1802 ** 1803 ** aSample[0] = (a, 5) 1804 ** aSample[1] = (a, 10) 1805 ** aSample[2] = (b, 5) 1806 ** aSample[3] = (c, 100) 1807 ** aSample[4] = (c, 105) 1808 ** 1809 ** Then the search space should ideally be the samples above and the 1810 ** unique prefixes [a], [b] and [c]. But since that is hard to organize, 1811 ** the code actually searches this set: 1812 ** 1813 ** 0: (a) 1814 ** 1: (a, 5) 1815 ** 2: (a, 10) 1816 ** 3: (a, 10) 1817 ** 4: (b) 1818 ** 5: (b, 5) 1819 ** 6: (c) 1820 ** 7: (c, 100) 1821 ** 8: (c, 105) 1822 ** 9: (c, 105) 1823 ** 1824 ** For each sample in the aSample[] array, N samples are present in the 1825 ** effective sample array. In the above, samples 0 and 1 are based on 1826 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc. 1827 ** 1828 ** Often, sample i of each block of N effective samples has (i+1) fields. 1829 ** Except, each sample may be extended to ensure that it is greater than or 1830 ** equal to the previous sample in the array. For example, in the above, 1831 ** sample 2 is the first sample of a block of N samples, so at first it 1832 ** appears that it should be 1 field in size. However, that would make it 1833 ** smaller than sample 1, so the binary search would not work. As a result, 1834 ** it is extended to two fields. The duplicates that this creates do not 1835 ** cause any problems. 1836 */ 1837 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){ 1838 nField = pIdx->nKeyCol; 1839 }else{ 1840 nField = pIdx->nColumn; 1841 } 1842 nField = MIN(pRec->nField, nField); 1843 iCol = 0; 1844 iSample = pIdx->nSample * nField; 1845 do{ 1846 int iSamp; /* Index in aSample[] of test sample */ 1847 int n; /* Number of fields in test sample */ 1848 1849 iTest = (iMin+iSample)/2; 1850 iSamp = iTest / nField; 1851 if( iSamp>0 ){ 1852 /* The proposed effective sample is a prefix of sample aSample[iSamp]. 1853 ** Specifically, the shortest prefix of at least (1 + iTest%nField) 1854 ** fields that is greater than the previous effective sample. */ 1855 for(n=(iTest % nField) + 1; nnField = n; 1863 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); 1864 if( res<0 ){ 1865 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1]; 1866 iMin = iTest+1; 1867 }else if( res==0 && ndb->mallocFailed==0 ){ 1883 if( res==0 ){ 1884 /* If (res==0) is true, then pRec must be equal to sample i. */ 1885 assert( inSample ); 1886 assert( iCol==nField-1 ); 1887 pRec->nField = nField; 1888 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) 1889 || pParse->db->mallocFailed 1890 ); 1891 }else{ 1892 /* Unless i==pIdx->nSample, indicating that pRec is larger than 1893 ** all samples in the aSample[] array, pRec must be smaller than the 1894 ** (iCol+1) field prefix of sample i. */ 1895 assert( i<=pIdx->nSample && i>=0 ); 1896 pRec->nField = iCol+1; 1897 assert( i==pIdx->nSample 1898 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 1899 || pParse->db->mallocFailed ); 1900 1901 /* if i==0 and iCol==0, then record pRec is smaller than all samples 1902 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must 1903 ** be greater than or equal to the (iCol) field prefix of sample i. 1904 ** If (i>0), then pRec must also be greater than sample (i-1). */ 1905 if( iCol>0 ){ 1906 pRec->nField = iCol; 1907 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 1908 || pParse->db->mallocFailed || CORRUPT_DB ); 1909 } 1910 if( i>0 ){ 1911 pRec->nField = nField; 1912 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 1913 || pParse->db->mallocFailed || CORRUPT_DB ); 1914 } 1915 } 1916 } 1917 #endif /* ifdef SQLITE_DEBUG */ 1918 1919 if( res==0 ){ 1920 /* Record pRec is equal to sample i */ 1921 assert( iCol==nField-1 ); 1922 aStat[0] = aSample[i].anLt[iCol]; 1923 aStat[1] = aSample[i].anEq[iCol]; 1924 }else{ 1925 /* At this point, the (iCol+1) field prefix of aSample[i] is the first 1926 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec 1927 ** is larger than all samples in the array. */ 1928 tRowcnt iUpper, iGap; 1929 if( i>=pIdx->nSample ){ 1930 iUpper = pIdx->nRowEst0; 1931 }else{ 1932 iUpper = aSample[i].anLt[iCol]; 1933 } 1934 1935 if( iLower>=iUpper ){ 1936 iGap = 0; 1937 }else{ 1938 iGap = iUpper - iLower; 1939 } 1940 if( roundUp ){ 1941 iGap = (iGap*2)/3; 1942 }else{ 1943 iGap = iGap/3; 1944 } 1945 aStat[0] = iLower + iGap; 1946 aStat[1] = pIdx->aAvgEq[nField-1]; 1947 } 1948 1949 /* Restore the pRec->nField value before returning. */ 1950 pRec->nField = nField; 1951 return i; 1952 } 1953 #endif /* SQLITE_ENABLE_STAT4 */ 1954 1955 /* 1956 ** If it is not NULL, pTerm is a term that provides an upper or lower 1957 ** bound on a range scan. Without considering pTerm, it is estimated 1958 ** that the scan will visit nNew rows. This function returns the number 1959 ** estimated to be visited after taking pTerm into account. 1960 ** 1961 ** If the user explicitly specified a likelihood() value for this term, 1962 ** then the return value is the likelihood multiplied by the number of 1963 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term 1964 ** has a likelihood of 0.50, and any other term a likelihood of 0.25. 1965 */ 1966 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ 1967 LogEst nRet = nNew; 1968 if( pTerm ){ 1969 if( pTerm->truthProb<=0 ){ 1970 nRet += pTerm->truthProb; 1971 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ 1972 nRet -= 20; assert( 20==sqlite3LogEst(4) ); 1973 } 1974 } 1975 return nRet; 1976 } 1977 1978 1979 #ifdef SQLITE_ENABLE_STAT4 1980 /* 1981 ** Return the affinity for a single column of an index. 1982 */ 1983 char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){ 1984 assert( iCol>=0 && iColnColumn ); 1985 if( !pIdx->zColAff ){ 1986 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; 1987 } 1988 assert( pIdx->zColAff[iCol]!=0 ); 1989 return pIdx->zColAff[iCol]; 1990 } 1991 #endif 1992 1993 1994 #ifdef SQLITE_ENABLE_STAT4 1995 /* 1996 ** This function is called to estimate the number of rows visited by a 1997 ** range-scan on a skip-scan index. For example: 1998 ** 1999 ** CREATE INDEX i1 ON t1(a, b, c); 2000 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; 2001 ** 2002 ** Value pLoop->nOut is currently set to the estimated number of rows 2003 ** visited for scanning (a=? AND b=?). This function reduces that estimate 2004 ** by some factor to account for the (c BETWEEN ? AND ?) expression based 2005 ** on the stat4 data for the index. this scan will be performed multiple 2006 ** times (once for each (a,b) combination that matches a=?) is dealt with 2007 ** by the caller. 2008 ** 2009 ** It does this by scanning through all stat4 samples, comparing values 2010 ** extracted from pLower and pUpper with the corresponding column in each 2011 ** sample. If L and U are the number of samples found to be less than or 2012 ** equal to the values extracted from pLower and pUpper respectively, and 2013 ** N is the total number of samples, the pLoop->nOut value is adjusted 2014 ** as follows: 2015 ** 2016 ** nOut = nOut * ( min(U - L, 1) / N ) 2017 ** 2018 ** If pLower is NULL, or a value cannot be extracted from the term, L is 2019 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it, 2020 ** U is set to N. 2021 ** 2022 ** Normally, this function sets *pbDone to 1 before returning. However, 2023 ** if no value can be extracted from either pLower or pUpper (and so the 2024 ** estimate of the number of rows delivered remains unchanged), *pbDone 2025 ** is left as is. 2026 ** 2027 ** If an error occurs, an SQLite error code is returned. Otherwise, 2028 ** SQLITE_OK. 2029 */ 2030 static int whereRangeSkipScanEst( 2031 Parse *pParse, /* Parsing & code generating context */ 2032 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ 2033 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ 2034 WhereLoop *pLoop, /* Update the .nOut value of this loop */ 2035 int *pbDone /* Set to true if at least one expr. value extracted */ 2036 ){ 2037 Index *p = pLoop->u.btree.pIndex; 2038 int nEq = pLoop->u.btree.nEq; 2039 sqlite3 *db = pParse->db; 2040 int nLower = -1; 2041 int nUpper = p->nSample+1; 2042 int rc = SQLITE_OK; 2043 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); 2044 CollSeq *pColl; 2045 2046 sqlite3_value *p1 = 0; /* Value extracted from pLower */ 2047 sqlite3_value *p2 = 0; /* Value extracted from pUpper */ 2048 sqlite3_value *pVal = 0; /* Value extracted from record */ 2049 2050 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); 2051 if( pLower ){ 2052 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); 2053 nLower = 0; 2054 } 2055 if( pUpper && rc==SQLITE_OK ){ 2056 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); 2057 nUpper = p2 ? 0 : p->nSample; 2058 } 2059 2060 if( p1 || p2 ){ 2061 int i; 2062 int nDiff; 2063 for(i=0; rc==SQLITE_OK && inSample; i++){ 2064 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); 2065 if( rc==SQLITE_OK && p1 ){ 2066 int res = sqlite3MemCompare(p1, pVal, pColl); 2067 if( res>=0 ) nLower++; 2068 } 2069 if( rc==SQLITE_OK && p2 ){ 2070 int res = sqlite3MemCompare(p2, pVal, pColl); 2071 if( res>=0 ) nUpper++; 2072 } 2073 } 2074 nDiff = (nUpper - nLower); 2075 if( nDiff<=0 ) nDiff = 1; 2076 2077 /* If there is both an upper and lower bound specified, and the 2078 ** comparisons indicate that they are close together, use the fallback 2079 ** method (assume that the scan visits 1/64 of the rows) for estimating 2080 ** the number of rows visited. Otherwise, estimate the number of rows 2081 ** using the method described in the header comment for this function. */ 2082 if( nDiff!=1 || pUpper==0 || pLower==0 ){ 2083 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); 2084 pLoop->nOut -= nAdjust; 2085 *pbDone = 1; 2086 WHERETRACE(0x20, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", 2087 nLower, nUpper, nAdjust*-1, pLoop->nOut)); 2088 } 2089 2090 }else{ 2091 assert( *pbDone==0 ); 2092 } 2093 2094 sqlite3ValueFree(p1); 2095 sqlite3ValueFree(p2); 2096 sqlite3ValueFree(pVal); 2097 2098 return rc; 2099 } 2100 #endif /* SQLITE_ENABLE_STAT4 */ 2101 2102 /* 2103 ** This function is used to estimate the number of rows that will be visited 2104 ** by scanning an index for a range of values. The range may have an upper 2105 ** bound, a lower bound, or both. The WHERE clause terms that set the upper 2106 ** and lower bounds are represented by pLower and pUpper respectively. For 2107 ** example, assuming that index p is on t1(a): 2108 ** 2109 ** ... FROM t1 WHERE a > ? AND a < ? ... 2110 ** |_____| |_____| 2111 ** | | 2112 ** pLower pUpper 2113 ** 2114 ** If either of the upper or lower bound is not present, then NULL is passed in 2115 ** place of the corresponding WhereTerm. 2116 ** 2117 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index 2118 ** column subject to the range constraint. Or, equivalently, the number of 2119 ** equality constraints optimized by the proposed index scan. For example, 2120 ** assuming index p is on t1(a, b), and the SQL query is: 2121 ** 2122 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... 2123 ** 2124 ** then nEq is set to 1 (as the range restricted column, b, is the second 2125 ** left-most column of the index). Or, if the query is: 2126 ** 2127 ** ... FROM t1 WHERE a > ? AND a < ? ... 2128 ** 2129 ** then nEq is set to 0. 2130 ** 2131 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the 2132 ** number of rows that the index scan is expected to visit without 2133 ** considering the range constraints. If nEq is 0, then *pnOut is the number of 2134 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) 2135 ** to account for the range constraints pLower and pUpper. 2136 ** 2137 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be 2138 ** used, a single range inequality reduces the search space by a factor of 4. 2139 ** and a pair of constraints (x>? AND x123" Might be NULL */ 2146 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ 2147 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ 2148 ){ 2149 int rc = SQLITE_OK; 2150 int nOut = pLoop->nOut; 2151 LogEst nNew; 2152 2153 #ifdef SQLITE_ENABLE_STAT4 2154 Index *p = pLoop->u.btree.pIndex; 2155 int nEq = pLoop->u.btree.nEq; 2156 2157 if( p->nSample>0 && ALWAYS(nEqnSampleCol) 2158 && OptimizationEnabled(pParse->db, SQLITE_Stat4) 2159 ){ 2160 if( nEq==pBuilder->nRecValid ){ 2161 UnpackedRecord *pRec = pBuilder->pRec; 2162 tRowcnt a[2]; 2163 int nBtm = pLoop->u.btree.nBtm; 2164 int nTop = pLoop->u.btree.nTop; 2165 2166 /* Variable iLower will be set to the estimate of the number of rows in 2167 ** the index that are less than the lower bound of the range query. The 2168 ** lower bound being the concatenation of $P and $L, where $P is the 2169 ** key-prefix formed by the nEq values matched against the nEq left-most 2170 ** columns of the index, and $L is the value in pLower. 2171 ** 2172 ** Or, if pLower is NULL or $L cannot be extracted from it (because it 2173 ** is not a simple variable or literal value), the lower bound of the 2174 ** range is $P. Due to a quirk in the way whereKeyStats() works, even 2175 ** if $L is available, whereKeyStats() is called for both ($P) and 2176 ** ($P:$L) and the larger of the two returned values is used. 2177 ** 2178 ** Similarly, iUpper is to be set to the estimate of the number of rows 2179 ** less than the upper bound of the range query. Where the upper bound 2180 ** is either ($P) or ($P:$U). Again, even if $U is available, both values 2181 ** of iUpper are requested of whereKeyStats() and the smaller used. 2182 ** 2183 ** The number of rows between the two bounds is then just iUpper-iLower. 2184 */ 2185 tRowcnt iLower; /* Rows less than the lower bound */ 2186 tRowcnt iUpper; /* Rows less than the upper bound */ 2187 int iLwrIdx = -2; /* aSample[] for the lower bound */ 2188 int iUprIdx = -1; /* aSample[] for the upper bound */ 2189 2190 if( pRec ){ 2191 testcase( pRec->nField!=pBuilder->nRecValid ); 2192 pRec->nField = pBuilder->nRecValid; 2193 } 2194 /* Determine iLower and iUpper using ($P) only. */ 2195 if( nEq==0 ){ 2196 iLower = 0; 2197 iUpper = p->nRowEst0; 2198 }else{ 2199 /* Note: this call could be optimized away - since the same values must 2200 ** have been requested when testing key $P in whereEqualScanEst(). */ 2201 whereKeyStats(pParse, p, pRec, 0, a); 2202 iLower = a[0]; 2203 iUpper = a[0] + a[1]; 2204 } 2205 2206 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); 2207 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); 2208 assert( p->aSortOrder!=0 ); 2209 if( p->aSortOrder[nEq] ){ 2210 /* The roles of pLower and pUpper are swapped for a DESC index */ 2211 SWAP(WhereTerm*, pLower, pUpper); 2212 SWAP(int, nBtm, nTop); 2213 } 2214 2215 /* If possible, improve on the iLower estimate using ($P:$L). */ 2216 if( pLower ){ 2217 int n; /* Values extracted from pExpr */ 2218 Expr *pExpr = pLower->pExpr->pRight; 2219 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n); 2220 if( rc==SQLITE_OK && n ){ 2221 tRowcnt iNew; 2222 u16 mask = WO_GT|WO_LE; 2223 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); 2224 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); 2225 iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0); 2226 if( iNew>iLower ) iLower = iNew; 2227 nOut--; 2228 pLower = 0; 2229 } 2230 } 2231 2232 /* If possible, improve on the iUpper estimate using ($P:$U). */ 2233 if( pUpper ){ 2234 int n; /* Values extracted from pExpr */ 2235 Expr *pExpr = pUpper->pExpr->pRight; 2236 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n); 2237 if( rc==SQLITE_OK && n ){ 2238 tRowcnt iNew; 2239 u16 mask = WO_GT|WO_LE; 2240 if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT); 2241 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); 2242 iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0); 2243 if( iNewpRec = pRec; 2250 if( rc==SQLITE_OK ){ 2251 if( iUpper>iLower ){ 2252 nNew = sqlite3LogEst(iUpper - iLower); 2253 /* TUNING: If both iUpper and iLower are derived from the same 2254 ** sample, then assume they are 4x more selective. This brings 2255 ** the estimated selectivity more in line with what it would be 2256 ** if estimated without the use of STAT4 tables. */ 2257 if( iLwrIdx==iUprIdx ){ nNew -= 20; } 2258 assert( 20==sqlite3LogEst(4) ); 2259 }else{ 2260 nNew = 10; assert( 10==sqlite3LogEst(2) ); 2261 } 2262 if( nNewwtFlags & TERM_VNULL)==0 || pParse->nErr>0 ); 2280 nNew = whereRangeAdjust(pLower, nOut); 2281 nNew = whereRangeAdjust(pUpper, nNew); 2282 2283 /* TUNING: If there is both an upper and lower limit and neither limit 2284 ** has an application-defined likelihood(), assume the range is 2285 ** reduced by an additional 75%. This means that, by default, an open-ended 2286 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the 2287 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to 2288 ** match 1/64 of the index. */ 2289 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){ 2290 nNew -= 20; 2291 } 2292 2293 nOut -= (pLower!=0) + (pUpper!=0); 2294 if( nNew<10 ) nNew = 10; 2295 if( nNewnOut>nOut ){ 2298 WHERETRACE(0x20,("Range scan lowers nOut from %d to %d\n", 2299 pLoop->nOut, nOut)); 2300 } 2301 #endif 2302 pLoop->nOut = (LogEst)nOut; 2303 return rc; 2304 } 2305 2306 #ifdef SQLITE_ENABLE_STAT4 2307 /* 2308 ** Estimate the number of rows that will be returned based on 2309 ** an equality constraint x=VALUE and where that VALUE occurs in 2310 ** the histogram data. This only works when x is the left-most 2311 ** column of an index and sqlite_stat4 histogram data is available 2312 ** for that index. When pExpr==NULL that means the constraint is 2313 ** "x IS NULL" instead of "x=VALUE". 2314 ** 2315 ** Write the estimated row count into *pnRow and return SQLITE_OK. 2316 ** If unable to make an estimate, leave *pnRow unchanged and return 2317 ** non-zero. 2318 ** 2319 ** This routine can fail if it is unable to load a collating sequence 2320 ** required for string comparison, or if unable to allocate memory 2321 ** for a UTF conversion required for comparison. The error is stored 2322 ** in the pParse structure. 2323 */ 2324 static int whereEqualScanEst( 2325 Parse *pParse, /* Parsing & code generating context */ 2326 WhereLoopBuilder *pBuilder, 2327 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ 2328 tRowcnt *pnRow /* Write the revised row estimate here */ 2329 ){ 2330 Index *p = pBuilder->pNew->u.btree.pIndex; 2331 int nEq = pBuilder->pNew->u.btree.nEq; 2332 UnpackedRecord *pRec = pBuilder->pRec; 2333 int rc; /* Subfunction return code */ 2334 tRowcnt a[2]; /* Statistics */ 2335 int bOk; 2336 2337 assert( nEq>=1 ); 2338 assert( nEq<=p->nColumn ); 2339 assert( p->aSample!=0 ); 2340 assert( p->nSample>0 ); 2341 assert( pBuilder->nRecValidnRecValid<(nEq-1) ){ 2346 return SQLITE_NOTFOUND; 2347 } 2348 2349 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() 2350 ** below would return the same value. */ 2351 if( nEq>=p->nColumn ){ 2352 *pnRow = 1; 2353 return SQLITE_OK; 2354 } 2355 2356 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk); 2357 pBuilder->pRec = pRec; 2358 if( rc!=SQLITE_OK ) return rc; 2359 if( bOk==0 ) return SQLITE_NOTFOUND; 2360 pBuilder->nRecValid = nEq; 2361 2362 whereKeyStats(pParse, p, pRec, 0, a); 2363 WHERETRACE(0x20,("equality scan regions %s(%d): %d\n", 2364 p->zName, nEq-1, (int)a[1])); 2365 *pnRow = a[1]; 2366 2367 return rc; 2368 } 2369 #endif /* SQLITE_ENABLE_STAT4 */ 2370 2371 #ifdef SQLITE_ENABLE_STAT4 2372 /* 2373 ** Estimate the number of rows that will be returned based on 2374 ** an IN constraint where the right-hand side of the IN operator 2375 ** is a list of values. Example: 2376 ** 2377 ** WHERE x IN (1,2,3,4) 2378 ** 2379 ** Write the estimated row count into *pnRow and return SQLITE_OK. 2380 ** If unable to make an estimate, leave *pnRow unchanged and return 2381 ** non-zero. 2382 ** 2383 ** This routine can fail if it is unable to load a collating sequence 2384 ** required for string comparison, or if unable to allocate memory 2385 ** for a UTF conversion required for comparison. The error is stored 2386 ** in the pParse structure. 2387 */ 2388 static int whereInScanEst( 2389 Parse *pParse, /* Parsing & code generating context */ 2390 WhereLoopBuilder *pBuilder, 2391 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ 2392 tRowcnt *pnRow /* Write the revised row estimate here */ 2393 ){ 2394 Index *p = pBuilder->pNew->u.btree.pIndex; 2395 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]); 2396 int nRecValid = pBuilder->nRecValid; 2397 int rc = SQLITE_OK; /* Subfunction return code */ 2398 tRowcnt nEst; /* Number of rows for a single term */ 2399 tRowcnt nRowEst = 0; /* New estimate of the number of rows */ 2400 int i; /* Loop counter */ 2401 2402 assert( p->aSample!=0 ); 2403 for(i=0; rc==SQLITE_OK && inExpr; i++){ 2404 nEst = nRow0; 2405 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); 2406 nRowEst += nEst; 2407 pBuilder->nRecValid = nRecValid; 2408 } 2409 2410 if( rc==SQLITE_OK ){ 2411 if( nRowEst > (tRowcnt)nRow0 ) nRowEst = nRow0; 2412 *pnRow = nRowEst; 2413 WHERETRACE(0x20,("IN row estimate: est=%d\n", nRowEst)); 2414 } 2415 assert( pBuilder->nRecValid==nRecValid ); 2416 return rc; 2417 } 2418 #endif /* SQLITE_ENABLE_STAT4 */ 2419 2420 2421 #if defined(WHERETRACE_ENABLED) || defined(SQLITE_DEBUG) 2422 /* 2423 ** Print the content of a WhereTerm object 2424 */ 2425 void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){ 2426 if( pTerm==0 ){ 2427 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); 2428 }else{ 2429 char zType[8]; 2430 char zLeft[50]; 2431 memcpy(zType, "....", 5); 2432 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; 2433 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; 2434 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) zType[2] = 'L'; 2435 if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C'; 2436 if( pTerm->eOperator & WO_SINGLE ){ 2437 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 ); 2438 sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}", 2439 pTerm->leftCursor, pTerm->u.x.leftColumn); 2440 }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){ 2441 sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx", 2442 pTerm->u.pOrInfo->indexable); 2443 }else{ 2444 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor); 2445 } 2446 iTerm = pTerm->iTerm = MAX(iTerm,pTerm->iTerm); 2447 sqlite3DebugPrintf( 2448 "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x", 2449 iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags); 2450 /* The 0x10000 .wheretrace flag causes extra information to be 2451 ** shown about each Term */ 2452 if( sqlite3WhereTrace & 0x10000 ){ 2453 sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx", 2454 pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight); 2455 } 2456 if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){ 2457 sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField); 2458 } 2459 if( pTerm->iParent>=0 ){ 2460 sqlite3DebugPrintf(" iParent=%d", pTerm->iParent); 2461 } 2462 sqlite3DebugPrintf("\n"); 2463 sqlite3TreeViewExpr(0, pTerm->pExpr, 0); 2464 } 2465 } 2466 void sqlite3ShowWhereTerm(WhereTerm *pTerm){ 2467 sqlite3WhereTermPrint(pTerm, 0); 2468 } 2469 #endif 2470 2471 #ifdef WHERETRACE_ENABLED 2472 /* 2473 ** Show the complete content of a WhereClause 2474 */ 2475 void sqlite3WhereClausePrint(WhereClause *pWC){ 2476 int i; 2477 for(i=0; inTerm; i++){ 2478 sqlite3WhereTermPrint(&pWC->a[i], i); 2479 } 2480 } 2481 #endif 2482 2483 #ifdef WHERETRACE_ENABLED 2484 /* 2485 ** Print a WhereLoop object for debugging purposes 2486 ** 2487 ** Format example: 2488 ** 2489 ** .--- Position in WHERE clause rSetup, rRun, nOut ---. 2490 ** | | 2491 ** | .--- selfMask nTerm ------. | 2492 ** | | | | 2493 ** | | .-- prereq Idx wsFlags----. | | 2494 ** | | | Name | | | 2495 ** | | | __|__ nEq ---. ___|__ | __|__ 2496 ** | / \ / \ / \ | / \ / \ / \ 2497 ** 1.002.001 t2.t2xy 2 f 010241 N 2 cost 0,56,31 2498 */ 2499 void sqlite3WhereLoopPrint(const WhereLoop *p, const WhereClause *pWC){ 2500 WhereInfo *pWInfo; 2501 if( pWC ){ 2502 int nb; 2503 SrcItem *pItem; 2504 Table *pTab; 2505 Bitmask mAll; 2506 2507 pWInfo = pWC->pWInfo; 2508 nb = 1+(pWInfo->pTabList->nSrc+3)/4; 2509 pItem = pWInfo->pTabList->a + p->iTab; 2510 pTab = pItem->pSTab; 2511 mAll = (((Bitmask)1)<<(nb*4)) - 1; 2512 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, 2513 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll); 2514 sqlite3DebugPrintf(" %12s", 2515 pItem->zAlias ? pItem->zAlias : pTab->zName); 2516 }else{ 2517 pWInfo = 0; 2518 sqlite3DebugPrintf("%c%2d.%03llx.%03llx %c%d", 2519 p->cId, p->iTab, p->maskSelf, p->prereq & 0xfff, p->cId, p->iTab); 2520 } 2521 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ 2522 const char *zName; 2523 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ 2524 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ 2525 int i = sqlite3Strlen30(zName) - 1; 2526 while( zName[i]!='_' ) i--; 2527 zName += i; 2528 } 2529 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); 2530 }else{ 2531 sqlite3DebugPrintf("%20s",""); 2532 } 2533 }else{ 2534 char *z; 2535 if( p->u.vtab.idxStr ){ 2536 z = sqlite3_mprintf("(%d,\"%s\",%#x)", 2537 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); 2538 }else{ 2539 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); 2540 } 2541 sqlite3DebugPrintf(" %-19s", z); 2542 sqlite3_free(z); 2543 } 2544 if( p->wsFlags & WHERE_SKIPSCAN ){ 2545 sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); 2546 }else{ 2547 sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm); 2548 } 2549 if( pWInfo && pWInfo->bStarUsed && p->rStarDelta!=0 ){ 2550 sqlite3DebugPrintf(" cost %d,%d,%d delta=%d\n", 2551 p->rSetup, p->rRun, p->nOut, p->rStarDelta); 2552 }else{ 2553 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); 2554 } 2555 if( p->nLTerm && (sqlite3WhereTrace & 0x4000)!=0 ){ 2556 int i; 2557 for(i=0; inLTerm; i++){ 2558 sqlite3WhereTermPrint(p->aLTerm[i], i); 2559 } 2560 } 2561 } 2562 void sqlite3ShowWhereLoop(const WhereLoop *p){ 2563 if( p ) sqlite3WhereLoopPrint(p, 0); 2564 } 2565 void sqlite3ShowWhereLoopList(const WhereLoop *p){ 2566 while( p ){ 2567 sqlite3ShowWhereLoop(p); 2568 p = p->pNextLoop; 2569 } 2570 } 2571 #endif 2572 2573 /* 2574 ** Convert bulk memory into a valid WhereLoop that can be passed 2575 ** to whereLoopClear harmlessly. 2576 */ 2577 static void whereLoopInit(WhereLoop *p){ 2578 p->aLTerm = p->aLTermSpace; 2579 p->nLTerm = 0; 2580 p->nLSlot = ArraySize(p->aLTermSpace); 2581 p->wsFlags = 0; 2582 } 2583 2584 /* 2585 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. 2586 */ 2587 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ 2588 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ 2589 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ 2590 sqlite3_free(p->u.vtab.idxStr); 2591 p->u.vtab.needFree = 0; 2592 p->u.vtab.idxStr = 0; 2593 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ 2594 sqlite3DbFree(db, p->u.btree.pIndex->zColAff); 2595 sqlite3DbFreeNN(db, p->u.btree.pIndex); 2596 p->u.btree.pIndex = 0; 2597 } 2598 } 2599 } 2600 2601 /* 2602 ** Deallocate internal memory used by a WhereLoop object. Leave the 2603 ** object in an initialized state, as if it had been newly allocated. 2604 */ 2605 static void whereLoopClear(sqlite3 *db, WhereLoop *p){ 2606 if( p->aLTerm!=p->aLTermSpace ){ 2607 sqlite3DbFreeNN(db, p->aLTerm); 2608 p->aLTerm = p->aLTermSpace; 2609 p->nLSlot = ArraySize(p->aLTermSpace); 2610 } 2611 whereLoopClearUnion(db, p); 2612 p->nLTerm = 0; 2613 p->wsFlags = 0; 2614 } 2615 2616 /* 2617 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n. 2618 */ 2619 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ 2620 WhereTerm **paNew; 2621 if( p->nLSlot>=n ) return SQLITE_OK; 2622 n = (n+7)&~7; 2623 paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n); 2624 if( paNew==0 ) return SQLITE_NOMEM_BKPT; 2625 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); 2626 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm); 2627 p->aLTerm = paNew; 2628 p->nLSlot = n; 2629 return SQLITE_OK; 2630 } 2631 2632 /* 2633 ** Transfer content from the second pLoop into the first. 2634 */ 2635 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ 2636 whereLoopClearUnion(db, pTo); 2637 if( pFrom->nLTerm > pTo->nLSlot 2638 && whereLoopResize(db, pTo, pFrom->nLTerm) 2639 ){ 2640 memset(pTo, 0, WHERE_LOOP_XFER_SZ); 2641 return SQLITE_NOMEM_BKPT; 2642 } 2643 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); 2644 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); 2645 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ 2646 pFrom->u.vtab.needFree = 0; 2647 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ 2648 pFrom->u.btree.pIndex = 0; 2649 } 2650 return SQLITE_OK; 2651 } 2652 2653 /* 2654 ** Delete a WhereLoop object 2655 */ 2656 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ 2657 assert( db!=0 ); 2658 whereLoopClear(db, p); 2659 sqlite3DbNNFreeNN(db, p); 2660 } 2661 2662 /* 2663 ** Free a WhereInfo structure 2664 */ 2665 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ 2666 assert( pWInfo!=0 ); 2667 assert( db!=0 ); 2668 sqlite3WhereClauseClear(&pWInfo->sWC); 2669 while( pWInfo->pLoops ){ 2670 WhereLoop *p = pWInfo->pLoops; 2671 pWInfo->pLoops = p->pNextLoop; 2672 whereLoopDelete(db, p); 2673 } 2674 while( pWInfo->pMemToFree ){ 2675 WhereMemBlock *pNext = pWInfo->pMemToFree->pNext; 2676 sqlite3DbNNFreeNN(db, pWInfo->pMemToFree); 2677 pWInfo->pMemToFree = pNext; 2678 } 2679 sqlite3DbNNFreeNN(db, pWInfo); 2680 } 2681 2682 /* 2683 ** Return TRUE if X is a proper subset of Y but is of equal or less cost. 2684 ** In other words, return true if all constraints of X are also part of Y 2685 ** and Y has additional constraints that might speed the search that X lacks 2686 ** but the cost of running X is not more than the cost of running Y. 2687 ** 2688 ** In other words, return true if the cost relationship between X and Y 2689 ** is inverted and needs to be adjusted. 2690 ** 2691 ** Case 1: 2692 ** 2693 ** (1a) X and Y use the same index. 2694 ** (1b) X has fewer == terms than Y 2695 ** (1c) Neither X nor Y use skip-scan 2696 ** (1d) X does not have a a greater cost than Y 2697 ** 2698 ** Case 2: 2699 ** 2700 ** (2a) X has the same or lower cost, or returns the same or fewer rows, 2701 ** than Y. 2702 ** (2b) X uses fewer WHERE clause terms than Y 2703 ** (2c) Every WHERE clause term used by X is also used by Y 2704 ** (2d) X skips at least as many columns as Y 2705 ** (2e) If X is a covering index, than Y is too 2706 */ 2707 static int whereLoopCheaperProperSubset( 2708 const WhereLoop *pX, /* First WhereLoop to compare */ 2709 const WhereLoop *pY /* Compare against this WhereLoop */ 2710 ){ 2711 int i, j; 2712 if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0; /* (1d) and (2a) */ 2713 assert( (pX->wsFlags & WHERE_VIRTUALTABLE)==0 ); 2714 assert( (pY->wsFlags & WHERE_VIRTUALTABLE)==0 ); 2715 if( pX->u.btree.nEq < pY->u.btree.nEq /* (1b) */ 2716 && pX->u.btree.pIndex==pY->u.btree.pIndex /* (1a) */ 2717 && pX->nSkip==0 && pY->nSkip==0 /* (1c) */ 2718 ){ 2719 return 1; /* Case 1 is true */ 2720 } 2721 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){ 2722 return 0; /* (2b) */ 2723 } 2724 if( pY->nSkip > pX->nSkip ) return 0; /* (2d) */ 2725 for(i=pX->nLTerm-1; i>=0; i--){ 2726 if( pX->aLTerm[i]==0 ) continue; 2727 for(j=pY->nLTerm-1; j>=0; j--){ 2728 if( pY->aLTerm[j]==pX->aLTerm[i] ) break; 2729 } 2730 if( j<0 ) return 0; /* (2c) */ 2731 } 2732 if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 2733 && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){ 2734 return 0; /* (2e) */ 2735 } 2736 return 1; /* Case 2 is true */ 2737 } 2738 2739 /* 2740 ** Try to adjust the cost and number of output rows of WhereLoop pTemplate 2741 ** upwards or downwards so that: 2742 ** 2743 ** (1) pTemplate costs less than any other WhereLoops that are a proper 2744 ** subset of pTemplate 2745 ** 2746 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate 2747 ** is a proper subset. 2748 ** 2749 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer 2750 ** WHERE clause terms than Y and that every WHERE clause term used by X is 2751 ** also used by Y. 2752 */ 2753 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ 2754 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; 2755 for(; p; p=p->pNextLoop){ 2756 if( p->iTab!=pTemplate->iTab ) continue; 2757 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; 2758 if( whereLoopCheaperProperSubset(p, pTemplate) ){ 2759 /* Adjust pTemplate cost downward so that it is cheaper than its 2760 ** subset p. */ 2761 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", 2762 pTemplate->rRun, pTemplate->nOut, 2763 MIN(p->rRun, pTemplate->rRun), 2764 MIN(p->nOut - 1, pTemplate->nOut))); 2765 pTemplate->rRun = MIN(p->rRun, pTemplate->rRun); 2766 pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut); 2767 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ 2768 /* Adjust pTemplate cost upward so that it is costlier than p since 2769 ** pTemplate is a proper subset of p */ 2770 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", 2771 pTemplate->rRun, pTemplate->nOut, 2772 MAX(p->rRun, pTemplate->rRun), 2773 MAX(p->nOut + 1, pTemplate->nOut))); 2774 pTemplate->rRun = MAX(p->rRun, pTemplate->rRun); 2775 pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut); 2776 } 2777 } 2778 } 2779 2780 /* 2781 ** Search the list of WhereLoops in *ppPrev looking for one that can be 2782 ** replaced by pTemplate. 2783 ** 2784 ** Return NULL if pTemplate does not belong on the WhereLoop list. 2785 ** In other words if pTemplate ought to be dropped from further consideration. 2786 ** 2787 ** If pX is a WhereLoop that pTemplate can replace, then return the 2788 ** link that points to pX. 2789 ** 2790 ** If pTemplate cannot replace any existing element of the list but needs 2791 ** to be added to the list as a new entry, then return a pointer to the 2792 ** tail of the list. 2793 */ 2794 static WhereLoop **whereLoopFindLesser( 2795 WhereLoop **ppPrev, 2796 const WhereLoop *pTemplate 2797 ){ 2798 WhereLoop *p; 2799 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){ 2800 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ 2801 /* If either the iTab or iSortIdx values for two WhereLoop are different 2802 ** then those WhereLoops need to be considered separately. Neither is 2803 ** a candidate to replace the other. */ 2804 continue; 2805 } 2806 /* In the current implementation, the rSetup value is either zero 2807 ** or the cost of building an automatic index (NlogN) and the NlogN 2808 ** is the same for compatible WhereLoops. */ 2809 assert( p->rSetup==0 || pTemplate->rSetup==0 2810 || p->rSetup==pTemplate->rSetup ); 2811 2812 /* whereLoopAddBtree() always generates and inserts the automatic index 2813 ** case first. Hence compatible candidate WhereLoops never have a larger 2814 ** rSetup. Call this SETUP-INVARIANT */ 2815 assert( p->rSetup>=pTemplate->rSetup ); 2816 2817 /* Any loop using an application-defined index (or PRIMARY KEY or 2818 ** UNIQUE constraint) with one or more == constraints is better 2819 ** than an automatic index. Unless it is a skip-scan. */ 2820 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 2821 && (pTemplate->nSkip)==0 2822 && (pTemplate->wsFlags & WHERE_INDEXED)!=0 2823 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 2824 && (p->prereq & pTemplate->prereq)==pTemplate->prereq 2825 ){ 2826 break; 2827 } 2828 2829 /* If existing WhereLoop p is better than pTemplate, pTemplate can be 2830 ** discarded. WhereLoop p is better if: 2831 ** (1) p has no more dependencies than pTemplate, and 2832 ** (2) p has an equal or lower cost than pTemplate 2833 */ 2834 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */ 2835 && p->rSetup<=pTemplate->rSetup /* (2a) */ 2836 && p->rRun<=pTemplate->rRun /* (2b) */ 2837 && p->nOut<=pTemplate->nOut /* (2c) */ 2838 ){ 2839 return 0; /* Discard pTemplate */ 2840 } 2841 2842 /* If pTemplate is always better than p, then cause p to be overwritten 2843 ** with pTemplate. pTemplate is better than p if: 2844 ** (1) pTemplate has no more dependencies than p, and 2845 ** (2) pTemplate has an equal or lower cost than p. 2846 */ 2847 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */ 2848 && p->rRun>=pTemplate->rRun /* (2a) */ 2849 && p->nOut>=pTemplate->nOut /* (2b) */ 2850 ){ 2851 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ 2852 break; /* Cause p to be overwritten by pTemplate */ 2853 } 2854 } 2855 return ppPrev; 2856 } 2857 2858 /* 2859 ** Insert or replace a WhereLoop entry using the template supplied. 2860 ** 2861 ** An existing WhereLoop entry might be overwritten if the new template 2862 ** is better and has fewer dependencies. Or the template will be ignored 2863 ** and no insert will occur if an existing WhereLoop is faster and has 2864 ** fewer dependencies than the template. Otherwise a new WhereLoop is 2865 ** added based on the template. 2866 ** 2867 ** If pBuilder->pOrSet is not NULL then we care about only the 2868 ** prerequisites and rRun and nOut costs of the N best loops. That 2869 ** information is gathered in the pBuilder->pOrSet object. This special 2870 ** processing mode is used only for OR clause processing. 2871 ** 2872 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we 2873 ** still might overwrite similar loops with the new template if the 2874 ** new template is better. Loops may be overwritten if the following 2875 ** conditions are met: 2876 ** 2877 ** (1) They have the same iTab. 2878 ** (2) They have the same iSortIdx. 2879 ** (3) The template has same or fewer dependencies than the current loop 2880 ** (4) The template has the same or lower cost than the current loop 2881 */ 2882 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ 2883 WhereLoop **ppPrev, *p; 2884 WhereInfo *pWInfo = pBuilder->pWInfo; 2885 sqlite3 *db = pWInfo->pParse->db; 2886 int rc; 2887 2888 /* Stop the search once we hit the query planner search limit */ 2889 if( pBuilder->iPlanLimit==0 ){ 2890 WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n")); 2891 if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0; 2892 return SQLITE_DONE; 2893 } 2894 pBuilder->iPlanLimit--; 2895 2896 whereLoopAdjustCost(pWInfo->pLoops, pTemplate); 2897 2898 /* If pBuilder->pOrSet is defined, then only keep track of the costs 2899 ** and prereqs. 2900 */ 2901 if( pBuilder->pOrSet!=0 ){ 2902 if( pTemplate->nLTerm ){ 2903 #if WHERETRACE_ENABLED 2904 u16 n = pBuilder->pOrSet->n; 2905 int x = 2906 #endif 2907 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, 2908 pTemplate->nOut); 2909 #if WHERETRACE_ENABLED /* 0x8 */ 2910 if( sqlite3WhereTrace & 0x8 ){ 2911 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); 2912 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); 2913 } 2914 #endif 2915 } 2916 return SQLITE_OK; 2917 } 2918 2919 /* Look for an existing WhereLoop to replace with pTemplate 2920 */ 2921 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); 2922 2923 if( ppPrev==0 ){ 2924 /* There already exists a WhereLoop on the list that is better 2925 ** than pTemplate, so just ignore pTemplate */ 2926 #if WHERETRACE_ENABLED /* 0x8 */ 2927 if( sqlite3WhereTrace & 0x8 ){ 2928 sqlite3DebugPrintf(" skip: "); 2929 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); 2930 } 2931 #endif 2932 return SQLITE_OK; 2933 }else{ 2934 p = *ppPrev; 2935 } 2936 2937 /* If we reach this point it means that either p[] should be overwritten 2938 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new 2939 ** WhereLoop and insert it. 2940 */ 2941 #if WHERETRACE_ENABLED /* 0x8 */ 2942 if( sqlite3WhereTrace & 0x8 ){ 2943 if( p!=0 ){ 2944 sqlite3DebugPrintf("replace: "); 2945 sqlite3WhereLoopPrint(p, pBuilder->pWC); 2946 sqlite3DebugPrintf(" with: "); 2947 }else{ 2948 sqlite3DebugPrintf(" add: "); 2949 } 2950 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC); 2951 } 2952 #endif 2953 if( p==0 ){ 2954 /* Allocate a new WhereLoop to add to the end of the list */ 2955 *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop)); 2956 if( p==0 ) return SQLITE_NOMEM_BKPT; 2957 whereLoopInit(p); 2958 p->pNextLoop = 0; 2959 }else{ 2960 /* We will be overwriting WhereLoop p[]. But before we do, first 2961 ** go through the rest of the list and delete any other entries besides 2962 ** p[] that are also supplanted by pTemplate */ 2963 WhereLoop **ppTail = &p->pNextLoop; 2964 WhereLoop *pToDel; 2965 while( *ppTail ){ 2966 ppTail = whereLoopFindLesser(ppTail, pTemplate); 2967 if( ppTail==0 ) break; 2968 pToDel = *ppTail; 2969 if( pToDel==0 ) break; 2970 *ppTail = pToDel->pNextLoop; 2971 #if WHERETRACE_ENABLED /* 0x8 */ 2972 if( sqlite3WhereTrace & 0x8 ){ 2973 sqlite3DebugPrintf(" delete: "); 2974 sqlite3WhereLoopPrint(pToDel, pBuilder->pWC); 2975 } 2976 #endif 2977 whereLoopDelete(db, pToDel); 2978 } 2979 } 2980 rc = whereLoopXfer(db, p, pTemplate); 2981 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ 2982 Index *pIndex = p->u.btree.pIndex; 2983 if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){ 2984 p->u.btree.pIndex = 0; 2985 } 2986 } 2987 return rc; 2988 } 2989 2990 /* 2991 ** Callback for estLikePatternLength(). 2992 ** 2993 ** If this node is a string literal that is longer pWalker->sz, then set 2994 ** pWalker->sz to the byte length of that string literal. 2995 ** 2996 ** pWalker->eCode indicates how to count characters: 2997 ** 2998 ** eCode==0 Count as a GLOB pattern 2999 ** eCode==1 Count as a LIKE pattern 3000 */ 3001 static int exprNodePatternLengthEst(Walker *pWalker, Expr *pExpr){ 3002 if( pExpr->op==TK_STRING ){ 3003 int sz = 0; /* Pattern size in bytes */ 3004 u8 *z = (u8*)pExpr->u.zToken; /* The pattern */ 3005 u8 c; /* Next character of the pattern */ 3006 u8 c1, c2, c3; /* Wildcards */ 3007 if( pWalker->eCode ){ 3008 c1 = '%'; 3009 c2 = '_'; 3010 c3 = 0; 3011 }else{ 3012 c1 = '*'; 3013 c2 = '?'; 3014 c3 = '['; 3015 } 3016 while( (c = *(z++))!=0 ){ 3017 if( c==c3 ){ 3018 if( *z ) z++; 3019 while( *z && *z!=']' ) z++; 3020 }else if( c!=c1 && c!=c2 ){ 3021 sz++; 3022 } 3023 } 3024 if( sz>pWalker->u.sz ) pWalker->u.sz = sz; 3025 } 3026 return WRC_Continue; 3027 } 3028 3029 /* 3030 ** Return the length of the longest string literal in the given 3031 ** expression. 3032 ** 3033 ** eCode indicates how to count characters: 3034 ** 3035 ** eCode==0 Count as a GLOB pattern 3036 ** eCode==1 Count as a LIKE pattern 3037 */ 3038 static int estLikePatternLength(Expr *p, u16 eCode){ 3039 Walker w; 3040 w.u.sz = 0; 3041 w.eCode = eCode; 3042 w.xExprCallback = exprNodePatternLengthEst; 3043 w.xSelectCallback = sqlite3SelectWalkFail; 3044 #ifdef SQLITE_DEBUG 3045 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 3046 #endif 3047 sqlite3WalkExpr(&w, p); 3048 return w.u.sz; 3049 } 3050 3051 /* 3052 ** Adjust the WhereLoop.nOut value downward to account for terms of the 3053 ** WHERE clause that reference the loop but which are not used by an 3054 ** index. 3055 * 3056 ** For every WHERE clause term that is not used by the index 3057 ** and which has a truth probability assigned by one of the likelihood(), 3058 ** likely(), or unlikely() SQL functions, reduce the estimated number 3059 ** of output rows by the probability specified. 3060 ** 3061 ** TUNING: For every WHERE clause term that is not used by the index 3062 ** and which does not have an assigned truth probability, heuristics 3063 ** described below are used to try to estimate the truth probability. 3064 ** TODO --> Perhaps this is something that could be improved by better 3065 ** table statistics. 3066 ** 3067 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75% 3068 ** value corresponds to -1 in LogEst notation, so this means decrement 3069 ** the WhereLoop.nOut field for every such WHERE clause term. 3070 ** 3071 ** Heuristic 2: If there exists one or more WHERE clause terms of the 3072 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the 3073 ** final output row estimate is no greater than 1/4 of the total number 3074 ** of rows in the table. In other words, assume that x==EXPR will filter 3075 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the 3076 ** "x" column is boolean or else -1 or 0 or 1 is a common default value 3077 ** on the "x" column and so in that case only cap the output row estimate 3078 ** at 1/2 instead of 1/4. 3079 ** 3080 ** Heuristic 3: If there is a LIKE or GLOB (or REGEXP or MATCH) operator 3081 ** with a large constant pattern, then reduce the size of the search 3082 ** space according to the length of the pattern, under the theory that 3083 ** longer patterns are less likely to match. This heuristic was added 3084 ** to give better output-row count estimates when preparing queries for 3085 ** the Join-Order Benchmarks. See forum thread 2026-01-30T09:57:54z 3086 */ 3087 static void whereLoopOutputAdjust( 3088 WhereClause *pWC, /* The WHERE clause */ 3089 WhereLoop *pLoop, /* The loop to adjust downward */ 3090 LogEst nRow /* Number of rows in the entire table */ 3091 ){ 3092 WhereTerm *pTerm, *pX; 3093 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); 3094 int i, j; 3095 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ 3096 3097 /* Skip all this if the FROM clause of the query is a single table and 3098 ** there is no ORDER BY. In this case it doesn't matter how accurate 3099 ** the WhereLoop.nOut values are. */ 3100 if( pWC->pWInfo->pTabList->nSrc<=1 && pWC->pWInfo->pOrderBy==0 ){ 3101 return; 3102 } 3103 3104 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 3105 for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){ 3106 assert( pTerm!=0 ); 3107 if( (pTerm->prereqAll & notAllowed)!=0 ) continue; 3108 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; 3109 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue; 3110 for(j=pLoop->nLTerm-1; j>=0; j--){ 3111 pX = pLoop->aLTerm[j]; 3112 if( pX==0 ) continue; 3113 if( pX==pTerm ) break; 3114 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; 3115 } 3116 if( j<0 ){ 3117 sqlite3ProgressCheck(pWC->pWInfo->pParse); 3118 if( pLoop->maskSelf==pTerm->prereqAll ){ 3119 /* If there are extra terms in the WHERE clause not used by an index 3120 ** that depend only on the table being scanned, and that will tend to 3121 ** cause many rows to be omitted, then mark that table as 3122 ** "self-culling". 3123 ** 3124 ** 2022-03-24: Self-culling only applies if either the extra terms 3125 ** are straight comparison operators that are non-true with NULL 3126 ** operand, or if the loop is not an OUTER JOIN. 3127 */ 3128 if( (pTerm->eOperator & 0x3f)!=0 3129 || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype 3130 & (JT_LEFT|JT_LTORJ))==0 3131 ){ 3132 pLoop->wsFlags |= WHERE_SELFCULL; 3133 } 3134 } 3135 if( pTerm->truthProb<=0 ){ 3136 /* If a truth probability is specified using the likelihood() hints, 3137 ** then use the probability provided by the application. */ 3138 pLoop->nOut += pTerm->truthProb; 3139 }else{ 3140 /* In the absence of explicit truth probabilities, use heuristics to 3141 ** guess a reasonable truth probability. */ 3142 Expr *pOpExpr = pTerm->pExpr; 3143 pLoop->nOut--; 3144 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 3145 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-`20200224`-1 */ 3146 ){ 3147 Expr *pRight = pOpExpr->pRight; 3148 Parse *pParse = pWC->pWInfo->pParse; 3149 int k = 0; 3150 testcase( pOpExpr->op==TK_IS ); 3151 if( sqlite3ExprIsInteger(pRight, &k, pParse, 1) && k>=(-1) && k<=1 ){ 3152 k = 10; 3153 }else{ 3154 k = 20; 3155 } 3156 if( iReducewtFlags |= TERM_HEURTRUTH; 3158 iReduce = k; 3159 } 3160 }else 3161 if( ExprHasProperty(pOpExpr, EP_InfixFunc) 3162 && pOpExpr->op==TK_FUNCTION 3163 ){ 3164 int eOp; 3165 assert( ExprUseXList(pOpExpr) ); 3166 assert( pOpExpr->x.pList->nExpr>=2 ); 3167 eOp = sqlite3ExprIsLikeOperator(pOpExpr); 3168 if( ALWAYS(eOp>0) ){ 3169 int szPattern; 3170 Expr *pRHS = pOpExpr->x.pList->a[0].pExpr; 3171 eOp = eOp==SQLITE_INDEX_CONSTRAINT_LIKE; 3172 szPattern = estLikePatternLength(pRHS, eOp); 3173 if( szPattern>0 ){ 3174 pLoop->nOut -= szPattern*2; 3175 } 3176 } 3177 } 3178 } 3179 } 3180 } 3181 if( pLoop->nOut > nRow-iReduce ){ 3182 pLoop->nOut = nRow - iReduce; 3183 } 3184 } 3185 3186 /* 3187 ** Term pTerm is a vector range comparison operation. The first comparison 3188 ** in the vector can be optimized using column nEq of the index. This 3189 ** function returns the total number of vector elements that can be used 3190 ** as part of the range comparison. 3191 ** 3192 ** For example, if the query is: 3193 ** 3194 ** WHERE a = ? AND (b, c, d) > (?, ?, ?) 3195 ** 3196 ** and the index: 3197 ** 3198 ** CREATE INDEX ... ON (a, b, c, d, e) 3199 ** 3200 ** then this function would be invoked with nEq=1. The value returned in 3201 ** this case is 3. 3202 */ 3203 static int whereRangeVectorLen( 3204 Parse *pParse, /* Parsing context */ 3205 int iCur, /* Cursor open on pIdx */ 3206 Index *pIdx, /* The index to be used for a inequality constraint */ 3207 int nEq, /* Number of prior equality constraints on same index */ 3208 WhereTerm *pTerm /* The vector inequality constraint */ 3209 ){ 3210 int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft); 3211 int i; 3212 3213 nCmp = MIN(nCmp, (pIdx->nColumn - nEq)); 3214 for(i=1; ipExpr->pLeft) ); 3223 pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr; 3224 pRhs = pTerm->pExpr->pRight; 3225 if( ExprUseXSelect(pRhs) ){ 3226 pRhs = pRhs->x.pSelect->pEList->a[i].pExpr; 3227 }else{ 3228 pRhs = pRhs->x.pList->a[i].pExpr; 3229 } 3230 3231 /* Check that the LHS of the comparison is a column reference to 3232 ** the right column of the right source table. And that the sort 3233 ** order of the index column is the same as the sort order of the 3234 ** leftmost index column. */ 3235 if( pLhs->op!=TK_COLUMN 3236 || pLhs->iTable!=iCur 3237 || pLhs->iColumn!=pIdx->aiColumn[i+nEq] 3238 || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq] 3239 ){ 3240 break; 3241 } 3242 3243 testcase( pLhs->iColumn==XN_ROWID ); 3244 aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs)); 3245 idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn); 3246 if( aff!=idxaff ) break; 3247 3248 if( ExprHasProperty(pTerm->pExpr, EP_Commuted) ) SWAP(Expr*, pRhs, pLhs); 3249 pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); 3250 if( pColl==0 ) break; 3251 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break; 3252 } 3253 return i; 3254 } 3255 3256 /* 3257 ** Adjust the cost C by the costMult factor T. This only occurs if 3258 ** compiled with -DSQLITE_ENABLE_COSTMULT 3259 */ 3260 #ifdef SQLITE_ENABLE_COSTMULT 3261 # define ApplyCostMultiplier(C,T) C += T 3262 #else 3263 # define ApplyCostMultiplier(C,T) 3264 #endif 3265 3266 /* 3267 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 3268 ** index pIndex. Try to match one more. 3269 ** 3270 ** When this function is called, pBuilder->pNew->nOut contains the 3271 ** number of rows expected to be visited by filtering using the nEq 3272 ** terms only. If it is modified, this value is restored before this 3273 ** function returns. 3274 ** 3275 ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is 3276 ** a fake index used for the INTEGER PRIMARY KEY. 3277 */ 3278 static int whereLoopAddBtreeIndex( 3279 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ 3280 SrcItem *pSrc, /* FROM clause term being analyzed */ 3281 Index *pProbe, /* An index on pSrc */ 3282 LogEst nInMul /* log(Number of iterations due to IN) */ 3283 ){ 3284 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyze context */ 3285 Parse *pParse = pWInfo->pParse; /* Parsing context */ 3286 sqlite3 *db = pParse->db; /* Database connection malloc context */ 3287 WhereLoop *pNew; /* Template WhereLoop under construction */ 3288 WhereTerm *pTerm; /* A WhereTerm under consideration */ 3289 int opMask; /* Valid operators for constraints */ 3290 WhereScan scan; /* Iterator for WHERE terms */ 3291 Bitmask saved_prereq; /* Original value of pNew->prereq */ 3292 u16 saved_nLTerm; /* Original value of pNew->nLTerm */ 3293 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ 3294 u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */ 3295 u16 saved_nTop; /* Original value of pNew->u.btree.nTop */ 3296 u16 saved_nSkip; /* Original value of pNew->nSkip */ 3297 u32 saved_wsFlags; /* Original value of pNew->wsFlags */ 3298 LogEst saved_nOut; /* Original value of pNew->nOut */ 3299 int rc = SQLITE_OK; /* Return code */ 3300 LogEst rSize; /* Number of rows in the table */ 3301 LogEst rLogSize; /* Logarithm of table size */ 3302 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ 3303 3304 pNew = pBuilder->pNew; 3305 assert( db->mallocFailed==0 || pParse->nErr>0 ); 3306 if( pParse->nErr ){ 3307 return pParse->rc; 3308 } 3309 WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n", 3310 pProbe->pTable->zName,pProbe->zName, 3311 pNew->u.btree.nEq, pNew->nSkip, pNew->rRun)); 3312 3313 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); 3314 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); 3315 if( pNew->wsFlags & WHERE_BTM_LIMIT ){ 3316 opMask = WO_LT|WO_LE; 3317 }else{ 3318 assert( pNew->u.btree.nBtm==0 ); 3319 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS; 3320 } 3321 if( pProbe->bUnordered ){ 3322 opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); 3323 } 3324 3325 assert( pNew->u.btree.nEqnColumn ); 3326 assert( pNew->u.btree.nEqnKeyCol 3327 || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY ); 3328 3329 saved_nEq = pNew->u.btree.nEq; 3330 saved_nBtm = pNew->u.btree.nBtm; 3331 saved_nTop = pNew->u.btree.nTop; 3332 saved_nSkip = pNew->nSkip; 3333 saved_nLTerm = pNew->nLTerm; 3334 saved_wsFlags = pNew->wsFlags; 3335 saved_prereq = pNew->prereq; 3336 saved_nOut = pNew->nOut; 3337 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq, 3338 opMask, pProbe); 3339 pNew->rSetup = 0; 3340 rSize = pProbe->aiRowLogEst[0]; 3341 rLogSize = estLog(rSize); 3342 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ 3343 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ 3344 LogEst rCostIdx; 3345 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ 3346 int nIn = 0; 3347 #ifdef SQLITE_ENABLE_STAT4 3348 int nRecValid = pBuilder->nRecValid; 3349 #endif 3350 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) 3351 && indexColumnNotNull(pProbe, saved_nEq) 3352 ){ 3353 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ 3354 } 3355 if( pTerm->prereqRight & pNew->maskSelf ) continue; 3356 3357 /* Do not allow the upper bound of a LIKE optimization range constraint 3358 ** to mix with a lower range bound from some other source */ 3359 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue; 3360 3361 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 3362 && !constraintCompatibleWithOuterJoin(pTerm,pSrc) 3363 ){ 3364 continue; 3365 } 3366 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){ 3367 pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE; 3368 }else{ 3369 pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED; 3370 } 3371 pNew->wsFlags = saved_wsFlags; 3372 pNew->u.btree.nEq = saved_nEq; 3373 pNew->u.btree.nBtm = saved_nBtm; 3374 pNew->u.btree.nTop = saved_nTop; 3375 pNew->nLTerm = saved_nLTerm; 3376 if( pNew->nLTerm>=pNew->nLSlot 3377 && whereLoopResize(db, pNew, pNew->nLTerm+1) 3378 ){ 3379 break; /* OOM while trying to enlarge the pNew->aLTerm array */ 3380 } 3381 pNew->aLTerm[pNew->nLTerm++] = pTerm; 3382 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; 3383 3384 assert( nInMul==0 3385 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 3386 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 3387 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 3388 ); 3389 3390 if( eOp & WO_IN ){ 3391 Expr *pExpr = pTerm->pExpr; 3392 if( ExprUseXSelect(pExpr) ){ 3393 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ 3394 int i; 3395 int bRedundant = 0; 3396 nIn = 46; assert( 46==sqlite3LogEst(25) ); 3397 3398 /* The expression may actually be of the form (x, y) IN (SELECT...). 3399 ** In this case there is a separate term for each of (x) and (y). 3400 ** However, the nIn multiplier should only be applied once, not once 3401 ** for each such term. The following loop checks that pTerm is the 3402 ** first such term in use, and sets nIn back to 0 if it is not. */ 3403 for(i=0; inLTerm-1; i++){ 3404 if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ){ 3405 nIn = 0; 3406 if( pNew->aLTerm[i]->u.x.iField == pTerm->u.x.iField ){ 3407 /* Detect when two or more columns of an index match the same 3408 ** column of a vector IN operater, and avoid adding the column 3409 ** to the WhereLoop more than once. See tag-`20250707`-01 3410 ** in test/rowvalue.test */ 3411 bRedundant = 1; 3412 } 3413 } 3414 } 3415 if( bRedundant ){ 3416 pNew->nLTerm--; 3417 continue; 3418 } 3419 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ 3420 /* "x IN (value, value, ...)" */ 3421 nIn = sqlite3LogEst(pExpr->x.pList->nExpr); 3422 } 3423 if( pProbe->hasStat1 && rLogSize>=10 ){ 3424 LogEst M, logK, x; 3425 /* Let: 3426 ** N = the total number of rows in the table 3427 ** K = the number of entries on the RHS of the IN operator 3428 ** M = the number of rows in the table that match terms to the 3429 ** to the left in the same index. If the IN operator is on 3430 ** the left-most index column, M==N. 3431 ** 3432 ** Given the definitions above, it is better to omit the IN operator 3433 ** from the index lookup and instead do a scan of the M elements, 3434 ** testing each scanned row against the IN operator separately, if: 3435 ** 3436 ** M*log(K) < K*log(N) 3437 ** 3438 ** Our estimates for M, K, and N might be inaccurate, so we build in 3439 ** a safety margin of 2 (LogEst: 10) that favors using the IN operator 3440 ** with the index, as using an index has better worst-case behavior. 3441 ** If we do not have real sqlite_stat1 data, always prefer to use 3442 ** the index. Do not bother with this optimization on very small 3443 ** tables (less than 2 rows) as it is pointless in that case. 3444 */ 3445 M = pProbe->aiRowLogEst[saved_nEq]; 3446 logK = estLog(nIn); 3447 /* TUNING v----- 10 to bias toward indexed IN */ 3448 x = M + logK + 10 - (nIn + rLogSize); 3449 if( x>=0 ){ 3450 WHERETRACE(0x40, 3451 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) " 3452 "prefers indexed lookup\n", 3453 saved_nEq, M, logK, nIn, rLogSize, x)); 3454 }else if( nInMul<2 && OptimizationEnabled(db, SQLITE_SeekScan) ){ 3455 WHERETRACE(0x40, 3456 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d" 3457 " nInMul=%d) prefers skip-scan\n", 3458 saved_nEq, M, logK, nIn, rLogSize, x, nInMul)); 3459 pNew->wsFlags |= WHERE_IN_SEEKSCAN; 3460 }else{ 3461 WHERETRACE(0x40, 3462 ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d" 3463 " nInMul=%d) prefers normal scan\n", 3464 saved_nEq, M, logK, nIn, rLogSize, x, nInMul)); 3465 continue; 3466 } 3467 } 3468 pNew->wsFlags |= WHERE_COLUMN_IN; 3469 }else if( eOp & (WO_EQ|WO_IS) ){ 3470 int iCol = pProbe->aiColumn[saved_nEq]; 3471 pNew->wsFlags |= WHERE_COLUMN_EQ; 3472 assert( saved_nEq==pNew->u.btree.nEq ); 3473 if( iCol==XN_ROWID 3474 || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) 3475 ){ 3476 if( iCol==XN_ROWID || pProbe->uniqNotNull 3477 || (pProbe->nKeyCol==1 && pProbe->onError && (eOp & WO_EQ)) 3478 ){ 3479 pNew->wsFlags |= WHERE_ONEROW; 3480 }else{ 3481 pNew->wsFlags |= WHERE_UNQ_WANTED; 3482 } 3483 } 3484 if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS; 3485 }else if( eOp & WO_ISNULL ){ 3486 pNew->wsFlags |= WHERE_COLUMN_NULL; 3487 }else{ 3488 int nVecLen = whereRangeVectorLen( 3489 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm 3490 ); 3491 if( eOp & (WO_GT|WO_GE) ){ 3492 testcase( eOp & WO_GT ); 3493 testcase( eOp & WO_GE ); 3494 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; 3495 pNew->u.btree.nBtm = nVecLen; 3496 pBtm = pTerm; 3497 pTop = 0; 3498 if( pTerm->wtFlags & TERM_LIKEOPT ){ 3499 /* Range constraints that come from the LIKE optimization are 3500 ** always used in pairs. */ 3501 pTop = &pTerm[1]; 3502 assert( (pTop-(pTerm->pWC->a))pWC->nTerm ); 3503 assert( pTop->wtFlags & TERM_LIKEOPT ); 3504 assert( pTop->eOperator==WO_LT ); 3505 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ 3506 pNew->aLTerm[pNew->nLTerm++] = pTop; 3507 pNew->wsFlags |= WHERE_TOP_LIMIT; 3508 pNew->u.btree.nTop = 1; 3509 } 3510 }else{ 3511 assert( eOp & (WO_LT|WO_LE) ); 3512 testcase( eOp & WO_LT ); 3513 testcase( eOp & WO_LE ); 3514 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; 3515 pNew->u.btree.nTop = nVecLen; 3516 pTop = pTerm; 3517 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? 3518 pNew->aLTerm[pNew->nLTerm-2] : 0; 3519 } 3520 } 3521 3522 /* At this point pNew->nOut is set to the number of rows expected to 3523 ** be visited by the index scan before considering term pTerm, or the 3524 ** values of nIn and nInMul. In other words, assuming that all 3525 ** "x IN(...)" terms are replaced with "x = ?". This block updates 3526 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ 3527 assert( pNew->nOut==saved_nOut ); 3528 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ 3529 /* Adjust nOut using stat4 data. Or, if there is no stat4 3530 ** data, using some other estimate. */ 3531 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); 3532 }else{ 3533 int nEq = ++pNew->u.btree.nEq; 3534 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) ); 3535 3536 assert( pNew->nOut==saved_nOut ); 3537 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){ 3538 assert( (eOp & WO_IN) || nIn==0 ); 3539 testcase( eOp & WO_IN ); 3540 pNew->nOut += pTerm->truthProb; 3541 pNew->nOut -= nIn; 3542 }else{ 3543 #ifdef SQLITE_ENABLE_STAT4 3544 tRowcnt nOut = 0; 3545 if( nInMul==0 3546 && pProbe->nSample 3547 && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol) 3548 && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr)) 3549 && OptimizationEnabled(db, SQLITE_Stat4) 3550 ){ 3551 Expr *pExpr = pTerm->pExpr; 3552 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){ 3553 testcase( eOp & WO_EQ ); 3554 testcase( eOp & WO_IS ); 3555 testcase( eOp & WO_ISNULL ); 3556 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); 3557 }else{ 3558 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); 3559 } 3560 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; 3561 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ 3562 if( nOut ){ 3563 pNew->nOut = sqlite3LogEst(nOut); 3564 if( nEq==1 3565 /* TUNING: Mark terms as "low selectivity" if they seem likely 3566 ** to be true for half or more of the rows in the table. 3567 ** See tag-`202002240`-1 */ 3568 && pNew->nOut+10 > pProbe->aiRowLogEst[0] 3569 ){ 3570 #if WHERETRACE_ENABLED /* 0x01 */ 3571 if( sqlite3WhereTrace & 0x20 ){ 3572 sqlite3DebugPrintf( 3573 "STAT4 determines term has low selectivity:\n"); 3574 sqlite3WhereTermPrint(pTerm, 999); 3575 } 3576 #endif 3577 pTerm->wtFlags |= TERM_HIGHTRUTH; 3578 if( pTerm->wtFlags & TERM_HEURTRUTH ){ 3579 /* If the term has previously been used with an assumption of 3580 ** higher selectivity, then set the flag to rerun the 3581 ** loop computations. */ 3582 pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS; 3583 } 3584 } 3585 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; 3586 pNew->nOut -= nIn; 3587 } 3588 } 3589 if( nOut==0 ) 3590 #endif 3591 { 3592 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]); 3593 if( eOp & WO_ISNULL ){ 3594 /* TUNING: If there is no likelihood() value, assume that a 3595 ** "col IS NULL" expression matches twice as many rows 3596 ** as (col=?). */ 3597 pNew->nOut += 10; 3598 } 3599 } 3600 } 3601 } 3602 3603 /* Set rCostIdx to the estimated cost of visiting selected rows in the 3604 ** index. The estimate is the sum of two values: 3605 ** 1. The cost of doing one search-by-key to find the first matching 3606 ** entry 3607 ** 2. Stepping forward in the index pNew->nOut times to find all 3608 ** additional matching entries. 3609 */ 3610 assert( pSrc->pSTab->szTabRow>0 ); 3611 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){ 3612 /* The pProbe->szIdxRow is low for an IPK table since the interior 3613 ** pages are small. Thus szIdxRow gives a good estimate of seek cost. 3614 ** But the leaf pages are full-size, so pProbe->szIdxRow would badly 3615 ** under-estimate the scanning cost. */ 3616 rCostIdx = pNew->nOut + 16; 3617 }else{ 3618 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pSTab->szTabRow; 3619 } 3620 rCostIdx = sqlite3LogEstAdd(rLogSize, rCostIdx); 3621 3622 /* Estimate the cost of running the loop. If all data is coming 3623 ** from the index, then this is just the cost of doing the index 3624 ** lookup and scan. But if some data is coming out of the main table, 3625 ** we also have to add in the cost of doing pNew->nOut searches to 3626 ** locate the row in the main table that corresponds to the index entry. 3627 */ 3628 pNew->rRun = rCostIdx; 3629 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK|WHERE_EXPRIDX))==0 ){ 3630 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); 3631 } 3632 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); 3633 3634 nOutUnadjusted = pNew->nOut; 3635 pNew->rRun += nInMul + nIn; 3636 pNew->nOut += nInMul + nIn; 3637 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize); 3638 if( pSrc->fg.fromExists ) pNew->nOut = 0; 3639 rc = whereLoopInsert(pBuilder, pNew); 3640 3641 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ 3642 pNew->nOut = saved_nOut; 3643 }else{ 3644 pNew->nOut = nOutUnadjusted; 3645 } 3646 3647 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 3648 && pNew->u.btree.nEqnColumn 3649 && (pNew->u.btree.nEqnKeyCol || 3650 pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY) 3651 ){ 3652 if( pNew->u.btree.nEq>3 ){ 3653 sqlite3ProgressCheck(pParse); 3654 } 3655 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); 3656 } 3657 pNew->nOut = saved_nOut; 3658 #ifdef SQLITE_ENABLE_STAT4 3659 pBuilder->nRecValid = nRecValid; 3660 #endif 3661 } 3662 pNew->prereq = saved_prereq; 3663 pNew->u.btree.nEq = saved_nEq; 3664 pNew->u.btree.nBtm = saved_nBtm; 3665 pNew->u.btree.nTop = saved_nTop; 3666 pNew->nSkip = saved_nSkip; 3667 pNew->wsFlags = saved_wsFlags; 3668 pNew->nOut = saved_nOut; 3669 pNew->nLTerm = saved_nLTerm; 3670 3671 /* Consider using a skip-scan if there are no WHERE clause constraints 3672 ** available for the left-most terms of the index, and if the average 3673 ** number of repeats in the left-most terms is at least 18. 3674 ** 3675 ** The magic number 18 is selected on the basis that scanning 17 rows 3676 ** is almost always quicker than an index seek (even though if the index 3677 ** contains fewer than 2^17 rows we assume otherwise in other parts of 3678 ** the code). And, even if it is not, it should not be too much slower. 3679 ** On the other hand, the extra seeks could end up being significantly 3680 ** more expensive. */ 3681 assert( 42==sqlite3LogEst(18) ); 3682 if( saved_nEq==saved_nSkip 3683 && saved_nEq+1nKeyCol 3684 && saved_nEq==pNew->nLTerm 3685 && pProbe->noSkipScan==0 3686 && pProbe->hasStat1!=0 3687 && OptimizationEnabled(db, SQLITE_SkipScan) 3688 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ 3689 && pSrc->fg.fromExists==0 3690 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK 3691 ){ 3692 LogEst nIter; 3693 pNew->u.btree.nEq++; 3694 pNew->nSkip++; 3695 pNew->aLTerm[pNew->nLTerm++] = 0; 3696 pNew->wsFlags |= WHERE_SKIPSCAN; 3697 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; 3698 pNew->nOut -= nIter; 3699 /* TUNING: Because uncertainties in the estimates for skip-scan queries, 3700 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */ 3701 nIter += 5; 3702 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); 3703 pNew->nOut = saved_nOut; 3704 pNew->u.btree.nEq = saved_nEq; 3705 pNew->nSkip = saved_nSkip; 3706 pNew->wsFlags = saved_wsFlags; 3707 } 3708 3709 WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n", 3710 pProbe->pTable->zName, pProbe->zName, saved_nEq, rc)); 3711 return rc; 3712 } 3713 3714 /* 3715 ** Return True if it is possible that pIndex might be useful in 3716 ** implementing the ORDER BY clause in pBuilder. 3717 ** 3718 ** Return False if pBuilder does not contain an ORDER BY clause or 3719 ** if there is no way for pIndex to be useful in implementing that 3720 ** ORDER BY clause. 3721 */ 3722 static int indexMightHelpWithOrderBy( 3723 WhereLoopBuilder *pBuilder, 3724 Index *pIndex, 3725 int iCursor 3726 ){ 3727 ExprList *pOB; 3728 ExprList *aColExpr; 3729 int ii, jj; 3730 3731 if( pIndex->bUnordered ) return 0; 3732 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; 3733 for(ii=0; iinExpr; ii++){ 3734 Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr); 3735 if( NEVER(pExpr==0) ) continue; 3736 if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) 3737 && pExpr->iTable==iCursor 3738 ){ 3739 if( pExpr->iColumn<0 ) return 1; 3740 for(jj=0; jjnKeyCol; jj++){ 3741 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; 3742 } 3743 }else if( (aColExpr = pIndex->aColExpr)!=0 ){ 3744 for(jj=0; jjnKeyCol; jj++){ 3745 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue; 3746 if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ 3747 return 1; 3748 } 3749 } 3750 } 3751 } 3752 return 0; 3753 } 3754 3755 /* Check to see if a partial index with pPartIndexWhere can be used 3756 ** in the current query. Return true if it can be and false if not. 3757 */ 3758 static int whereUsablePartialIndex( 3759 int iTab, /* The table for which we want an index */ 3760 u8 jointype, /* The JT_* flags on the join */ 3761 WhereClause *pWC, /* The WHERE clause of the query */ 3762 Expr *pWhere /* The WHERE clause from the partial index */ 3763 ){ 3764 int i; 3765 WhereTerm *pTerm; 3766 Parse *pParse; 3767 3768 if( jointype & JT_LTORJ ) return 0; 3769 pParse = pWC->pWInfo->pParse; 3770 while( pWhere->op==TK_AND ){ 3771 if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0; 3772 pWhere = pWhere->pRight; 3773 } 3774 for(i=0, pTerm=pWC->a; inTerm; i++, pTerm++){ 3775 Expr *pExpr; 3776 pExpr = pTerm->pExpr; 3777 if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab) 3778 && ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON)) 3779 && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) 3780 && !sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, -1) 3781 && (pTerm->wtFlags & TERM_VNULL)==0 3782 ){ 3783 return 1; 3784 } 3785 } 3786 return 0; 3787 } 3788 3789 /* 3790 ** pIdx is an index containing expressions. Check it see if any of the 3791 ** expressions in the index match the pExpr expression. 3792 */ 3793 static int exprIsCoveredByIndex( 3794 const Expr *pExpr, 3795 const Index *pIdx, 3796 int iTabCur 3797 ){ 3798 int i; 3799 for(i=0; inColumn; i++){ 3800 if( pIdx->aiColumn[i]==XN_EXPR 3801 && sqlite3ExprCompare(0, pExpr, pIdx->aColExpr->a[i].pExpr, iTabCur)==0 3802 ){ 3803 return 1; 3804 } 3805 } 3806 return 0; 3807 } 3808 3809 /* 3810 ** Structure passed to the whereIsCoveringIndex Walker callback. 3811 */ 3812 typedef struct CoveringIndexCheck CoveringIndexCheck; 3813 struct CoveringIndexCheck { 3814 Index *pIdx; /* The index */ 3815 int iTabCur; /* Cursor number for the corresponding table */ 3816 WhereClause *pWC; /* Ignore terms of this WHERE implied by pIdx, or NULL */ 3817 u8 bExpr; /* Uses an indexed expression */ 3818 u8 bUnidx; /* Uses an unindexed column not within an indexed expr */ 3819 }; 3820 3821 /* 3822 ** Return true if pExpr is a term of the WHERE clause pCk->pWC (not merely 3823 ** a copy of such a term) and is identical to one of the AND-connected 3824 ** terms of the WHERE clause of partial index pCk->pIdx. Such a term is 3825 ** never evaluated when pCk->pIdx drives the loop, because the 3826 ** whereApplyPartialIndexConstraints() routine marks it as already coded. 3827 ** Hence any columns used by the term do not need to be in the index. 3828 */ 3829 static int whereTermImpliedByPartialIndex( 3830 CoveringIndexCheck *pCk, 3831 const Expr *pExpr 3832 ){ 3833 WhereClause *pWC = pCk->pWC; 3834 Expr *pPart; 3835 int i; 3836 for(i=0; inTerm; i++){ 3837 if( pWC->a[i].pExpr==pExpr ) break; 3838 } 3839 if( i>=pWC->nTerm ) return 0; 3840 pPart = pCk->pIdx->pPartIdxWhere; 3841 while( pPart->op==TK_AND ){ 3842 if( sqlite3ExprCompare(0, pExpr, pPart->pRight, pCk->iTabCur)==0 ){ 3843 return 1; 3844 } 3845 pPart = pPart->pLeft; 3846 } 3847 return sqlite3ExprCompare(0, pExpr, pPart, pCk->iTabCur)==0; 3848 } 3849 3850 /* 3851 ** Information passed in is pWalk->u.pCovIdxCk. Call it pCk. 3852 ** 3853 ** If the Expr node references the table with cursor pCk->iTabCur, then 3854 ** make sure that column is covered by the index pCk->pIdx. We know that 3855 ** all columns less than 63 (really BMS-1) are covered, so we don't need 3856 ** to check them. But we do need to check any column at 63 or greater. 3857 ** 3858 ** If the index does not cover the column, then set pWalk->eCode to 3859 ** non-zero and return WRC_Abort to stop the search. 3860 ** 3861 ** If this node does not disprove that the index can be a covering index, 3862 ** then just return WRC_Continue, to continue the search. 3863 ** 3864 ** If pCk->pIdx contains indexed expressions and one of those expressions 3865 ** matches pExpr, then prune the search. 3866 */ 3867 static int whereIsCoveringIndexWalkCallback(Walker *pWalk, Expr *pExpr){ 3868 int i; /* Loop counter */ 3869 const Index *pIdx; /* The index of interest */ 3870 const i16 *aiColumn; /* Columns contained in the index */ 3871 u16 nColumn; /* Number of columns in the index */ 3872 CoveringIndexCheck *pCk; /* Info about this search */ 3873 3874 pCk = pWalk->u.pCovIdxCk; 3875 pIdx = pCk->pIdx; 3876 if( pCk->pWC && whereTermImpliedByPartialIndex(pCk, pExpr) ){ 3877 return WRC_Prune; 3878 } 3879 if( (pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN) ){ 3880 /* if( pExpr->iColumn<(BMS-1) && pIdx->bHasExpr==0 ) return WRC_Continue;*/ 3881 if( pExpr->iTable!=pCk->iTabCur ) return WRC_Continue; 3882 pIdx = pWalk->u.pCovIdxCk->pIdx; 3883 aiColumn = pIdx->aiColumn; 3884 nColumn = pIdx->nColumn; 3885 for(i=0; iiColumn ) return WRC_Continue; 3887 } 3888 pCk->bUnidx = 1; 3889 return WRC_Abort; 3890 }else if( pIdx->bHasExpr 3891 && exprIsCoveredByIndex(pExpr, pIdx, pWalk->u.pCovIdxCk->iTabCur) ){ 3892 pCk->bExpr = 1; 3893 return WRC_Prune; 3894 } 3895 return WRC_Continue; 3896 } 3897 3898 3899 /* 3900 ** pIdx is an index that covers all of the low-number columns used by 3901 ** pWInfo->pSelect (columns from 0 through 62) or an index that has 3902 ** expressions terms. Hence, we cannot determine whether or not it is 3903 ** a covering index by using the colUsed bitmasks. We have to do a search 3904 ** to see if the index is covering. This routine does that search. 3905 ** 3906 ** If pWC is not NULL, then pIdx is a partial index and terms of the 3907 ** WHERE clause pWC that are implied by the WHERE clause of pIdx are 3908 ** ignored, as they will never be evaluated when pIdx drives the loop. 3909 ** In this case pIdx might not cover all low-numbered columns used by 3910 ** pWInfo->pSelect. 3911 ** 3912 ** The return value is one of these: 3913 ** 3914 ** 0 The index is definitely not a covering index 3915 ** 3916 ** WHERE_IDX_ONLY The index is definitely a covering index 3917 ** 3918 ** WHERE_EXPRIDX The index is likely a covering index, but it is 3919 ** difficult to determine precisely because of the 3920 ** expressions that are indexed. Score it as a 3921 ** covering index, but still keep the main table open 3922 ** just in case we need it. 3923 ** 3924 ** This routine is an optimization. It is always safe to return zero. 3925 ** But returning one of the other two values when zero should have been 3926 ** returned can lead to incorrect bytecode and assertion faults. 3927 */ 3928 static SQLITE_NOINLINE u32 whereIsCoveringIndex( 3929 WhereInfo *pWInfo, /* The WHERE clause context */ 3930 Index *pIdx, /* Index that is being tested */ 3931 int iTabCur, /* Cursor for the table being indexed */ 3932 WhereClause *pWC /* Ignore terms implied by pIdx, or NULL */ 3933 ){ 3934 int i, rc; 3935 struct CoveringIndexCheck ck; 3936 Walker w; 3937 if( pWInfo->pSelect==0 ){ 3938 /* We don't have access to the full query, so we cannot check to see 3939 ** if pIdx is covering. Assume it is not. */ 3940 return 0; 3941 } 3942 if( pIdx->bHasExpr==0 && pWC==0 ){ 3943 for(i=0; inColumn; i++){ 3944 if( pIdx->aiColumn[i]>=BMS-1 ) break; 3945 } 3946 if( i>=pIdx->nColumn ){ 3947 /* pIdx does not index any columns greater than 62, but we know from 3948 ** colMask that columns greater than 62 are used, so this is not a 3949 ** covering index */ 3950 return 0; 3951 } 3952 } 3953 ck.pIdx = pIdx; 3954 ck.iTabCur = iTabCur; 3955 ck.pWC = pWC; 3956 ck.bExpr = 0; 3957 ck.bUnidx = 0; 3958 memset(&w, 0, sizeof(w)); 3959 w.xExprCallback = whereIsCoveringIndexWalkCallback; 3960 w.xSelectCallback = sqlite3SelectWalkNoop; 3961 w.u.pCovIdxCk = &ck; 3962 sqlite3WalkSelect(&w, pWInfo->pSelect); 3963 if( ck.bUnidx ){ 3964 rc = 0; 3965 }else if( ck.bExpr ){ 3966 rc = WHERE_EXPRIDX; 3967 }else{ 3968 rc = WHERE_IDX_ONLY; 3969 } 3970 return rc; 3971 } 3972 3973 /* 3974 ** This is an sqlite3ParserAddCleanup() callback that is invoked to 3975 ** free the Parse->pIdxEpr list when the Parse object is destroyed. 3976 */ 3977 static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){ 3978 IndexedExpr **pp = (IndexedExpr**)pObject; 3979 while( *pp!=0 ){ 3980 IndexedExpr *p = *pp; 3981 *pp = p->pIENext; 3982 sqlite3ExprDelete(db, p->pExpr); 3983 sqlite3DbFreeNN(db, p); 3984 } 3985 } 3986 3987 /* 3988 ** This function is called for a partial index - one with a WHERE clause - in 3989 ** two scenarios. In both cases, it determines whether or not the WHERE 3990 ** clause on the index implies that a column of the table may be safely 3991 ** replaced by a constant expression. For example, in the following 3992 ** SELECT: 3993 ** 3994 ** CREATE INDEX i1 ON t1(b, c) WHERE a=; 3995 ** SELECT a, b, c FROM t1 WHERE a= AND b=?; 3996 ** 3997 ** The "a" in the select-list may be replaced by , iff: 3998 ** 3999 ** (a) is a constant expression, and 4000 ** (b) The (a=) comparison uses the BINARY collation sequence, and 4001 ** (c) Column "a" has an affinity other than NONE or BLOB. 4002 ** 4003 ** If argument pItem is NULL, then pMask must not be NULL. In this case this 4004 ** function is being called as part of determining whether or not pIdx 4005 ** is a covering index. This function clears any bits in (*pMask) 4006 ** corresponding to columns that may be replaced by constants as described 4007 ** above. 4008 ** 4009 ** Otherwise, if pItem is not NULL, then this function is being called 4010 ** as part of coding a loop that uses index pIdx. In this case, add entries 4011 ** to the Parse.pIdxPartExpr list for each column that can be replaced 4012 ** by a constant. 4013 */ 4014 static void wherePartIdxExpr( 4015 Parse *pParse, /* Parse context */ 4016 Index *pIdx, /* Partial index being processed */ 4017 Expr *pPart, /* WHERE clause being processed */ 4018 Bitmask *pMask, /* Mask to clear bits in */ 4019 int iIdxCur, /* Cursor number for index */ 4020 SrcItem *pItem /* The FROM clause entry for the table */ 4021 ){ 4022 assert( pItem==0 || (pItem->fg.jointype & JT_RIGHT)==0 ); 4023 assert( (pItem==0 || pMask==0) && (pMask!=0 || pItem!=0) ); 4024 4025 if( pPart->op==TK_AND ){ 4026 wherePartIdxExpr(pParse, pIdx, pPart->pRight, pMask, iIdxCur, pItem); 4027 pPart = pPart->pLeft; 4028 } 4029 4030 if( (pPart->op==TK_EQ || pPart->op==TK_IS) ){ 4031 Expr *pLeft = pPart->pLeft; 4032 Expr *pRight = pPart->pRight; 4033 Table *pLeftTab; /* Table of the left operand */ 4034 Column *pLeftCol; /* Column of the left operand */ 4035 u8 affRight, affLeft; 4036 4037 if( pLeft->op!=TK_COLUMN ) return; 4038 if( !sqlite3ExprIsConstant(0, pRight) ) return; 4039 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pParse, pPart)) ) return; 4040 if( pLeft->iColumn<0 ) return; 4041 pLeftTab = pIdx->pTable; 4042 pLeftCol = &pLeftTab->aCol[pLeft->iColumn]; 4043 affLeft = pLeftCol->affinity; 4044 assert( SQLITE_AFF_BLOBdb; 4050 IndexedExpr *p = (IndexedExpr*)sqlite3DbMallocRaw(db, sizeof(*p)); 4051 if( p ){ 4052 int bNullRow = (pItem->fg.jointype&(JT_LEFT|JT_LTORJ))!=0; 4053 pRight = sqlite3ExprDup(db, pRight, 0); 4054 if( (pLeftTab->tabFlags & TF_Strict)!=0 ){ 4055 Token t; 4056 t.z = sqlite3ColumnType(pLeftCol, 0); 4057 assert( t.z!=0 ); /* Because affLeft>=SQLITE_AFF_TEXT */ 4058 t.n = (int)strlen(t.z); 4059 p->pExpr = sqlite3ExprAlloc(db, TK_CAST, &t, 1); 4060 sqlite3ExprAttachSubtrees(db, p->pExpr, pRight, 0); 4061 }else{ 4062 p->pExpr = pRight; 4063 } 4064 p->iDataCur = pItem->iCursor; 4065 p->iIdxCur = iIdxCur; 4066 p->iIdxCol = pLeft->iColumn; 4067 p->bMaybeNullRow = bNullRow; 4068 p->pIENext = pParse->pIdxPartExpr; 4069 p->aff = affLeft; 4070 pParse->pIdxPartExpr = p; 4071 if( p->pIENext==0 ){ 4072 void *pArg = (void*)&pParse->pIdxPartExpr; 4073 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg); 4074 } 4075 } 4076 }else if( pLeft->iColumn<(BMS-1) ){ 4077 *pMask &= ~((Bitmask)1 << pLeft->iColumn); 4078 } 4079 } 4080 } 4081 4082 4083 /* 4084 ** Add all WhereLoop objects for a single table of the join where the table 4085 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be 4086 ** a b-tree table, not a virtual table. 4087 ** 4088 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function 4089 ** are calculated as follows: 4090 ** 4091 ** For a full scan, assuming the table (or index) contains nRow rows: 4092 ** 4093 ** cost = nRow * 3.0 // full-table scan 4094 ** cost = nRow * K // scan of covering index 4095 ** cost = nRow * (K+3.0) // scan of non-covering index 4096 ** 4097 ** where K is a value between 1.1 and 3.0 set based on the relative 4098 ** estimated average size of the index and table records. 4099 ** 4100 ** For an index scan, where nVisit is the number of index rows visited 4101 ** by the scan, and nSeek is the number of seek operations required on 4102 ** the index b-tree: 4103 ** 4104 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index 4105 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index 4106 ** 4107 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the 4108 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 4109 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans. 4110 ** 4111 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount 4112 ** of uncertainty. For this reason, scoring is designed to pick plans that 4113 ** "do the least harm" if the estimates are inaccurate. For example, a 4114 ** log(nRow) factor is omitted from a non-covering index scan in order to 4115 ** bias the scoring in favor of using an index, since the worst-case 4116 ** performance of using an index is far better than the worst-case performance 4117 ** of a full table scan. 4118 */ 4119 static int whereLoopAddBtree( 4120 WhereLoopBuilder *pBuilder, /* WHERE clause information */ 4121 Bitmask mPrereq /* Extra prerequisites for using this table */ 4122 ){ 4123 WhereInfo *pWInfo; /* WHERE analysis context */ 4124 Index *pProbe; /* An index we are evaluating */ 4125 Index sPk; /* A fake index object for the primary key */ 4126 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */ 4127 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */ 4128 SrcList *pTabList; /* The FROM clause */ 4129 SrcItem *pSrc; /* The FROM clause btree term to add */ 4130 WhereLoop *pNew; /* Template WhereLoop object */ 4131 int rc = SQLITE_OK; /* Return code */ 4132 int iSortIdx; /* Index number */ 4133 int b; /* A boolean value */ 4134 LogEst rSize; /* number of rows in the table */ 4135 WhereClause *pWC; /* The parsed WHERE clause */ 4136 Table *pTab; /* Table being queried */ 4137 4138 pNew = pBuilder->pNew; 4139 pWInfo = pBuilder->pWInfo; 4140 pTabList = pWInfo->pTabList; 4141 pSrc = pTabList->a + pNew->iTab; 4142 pTab = pSrc->pSTab; 4143 pWC = pBuilder->pWC; 4144 assert( !IsVirtual(pSrc->pSTab) ); 4145 4146 if( pSrc->fg.isIndexedBy ){ 4147 assert( pSrc->fg.isCte==0 ); 4148 /* An INDEXED BY clause specifies a particular index to use */ 4149 pProbe = pSrc->u2.pIBIndex; 4150 }else if( !HasRowid(pTab) ){ 4151 if( pSrc->fg.notIndexed ){ 4152 pProbe = sqlite3PrimaryKeyIndex(pTab); 4153 }else{ 4154 pProbe = pTab->pIndex; 4155 } 4156 }else{ 4157 /* There is no INDEXED BY clause. Create a fake Index object in local 4158 ** variable sPk to represent the rowid primary key index. Make this 4159 ** fake index the first in a chain of Index objects with all of the real 4160 ** indices to follow */ 4161 Index *pFirst; /* First of real indices on the table */ 4162 memset(&sPk, 0, sizeof(Index)); 4163 sPk.nKeyCol = 1; 4164 sPk.nColumn = 1; 4165 sPk.aiColumn = &aiColumnPk; 4166 sPk.aiRowLogEst = aiRowEstPk; 4167 sPk.onError = OE_Replace; 4168 sPk.pTable = pTab; 4169 sPk.szIdxRow = 3; /* TUNING: Interior rows of IPK table are very small */ 4170 sPk.idxType = SQLITE_IDXTYPE_IPK; 4171 aiRowEstPk[0] = pTab->nRowLogEst; 4172 aiRowEstPk[1] = 0; 4173 pFirst = pSrc->pSTab->pIndex; 4174 sPk.pNext = pFirst; 4175 pProbe = &sPk; 4176 } 4177 rSize = pTab->nRowLogEst; 4178 4179 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 4180 /* Automatic indexes */ 4181 if( !pBuilder->pOrSet /* Not part of an OR optimization */ 4182 && (pWInfo->wctrlFlags & (WHERE_RIGHT_JOIN|WHERE_OR_SUBCLAUSE))==0 4183 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 4184 && !pSrc->fg.isIndexedBy /* Has no INDEXED BY clause */ 4185 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */ 4186 && !pSrc->fg.isCorrelated /* Not a correlated subquery */ 4187 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */ 4188 && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */ 4189 ){ 4190 /* Generate auto-index WhereLoops */ 4191 LogEst rLogSize; /* Logarithm of the number of rows in the table */ 4192 WhereTerm *pTerm; 4193 WhereTerm *pWCEnd = pWC->a + pWC->nTerm; 4194 rLogSize = estLog(rSize); 4195 for(pTerm=pWC->a; rc==SQLITE_OK && pTermprereqRight & pNew->maskSelf ) continue; 4197 if( termCanDriveIndex(pTerm, pSrc, 0) ){ 4198 pNew->u.btree.nEq = 1; 4199 pNew->nSkip = 0; 4200 pNew->u.btree.pIndex = 0; 4201 pNew->nLTerm = 1; 4202 pNew->aLTerm[0] = pTerm; 4203 /* TUNING: One-time cost for computing the automatic index is 4204 ** estimated to be X*N*log2(N) where N is the number of rows in 4205 ** the table being indexed and where X is 7 (LogEst=28) for normal 4206 ** tables or 0.5 (LogEst=-10) for views and subqueries. The value 4207 ** of X is smaller for views and subqueries so that the query planner 4208 ** will be more aggressive about generating automatic indexes for 4209 ** those objects, since there is no opportunity to add schema 4210 ** indexes on subqueries and views. */ 4211 pNew->rSetup = rLogSize + rSize; 4212 if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){ 4213 pNew->rSetup += 28; 4214 }else{ 4215 pNew->rSetup -= 25; /* Greatly reduced setup cost for auto indexes 4216 ** on ephemeral materializations of views */ 4217 } 4218 ApplyCostMultiplier(pNew->rSetup, pTab->costMult); 4219 if( pNew->rSetup<0 ) pNew->rSetup = 0; 4220 /* TUNING: Each index lookup yields 20 rows in the table. This 4221 ** is more than the usual guess of 10 rows, since we have no way 4222 ** of knowing how selective the index will ultimately be. It would 4223 ** not be unreasonable to make this value much larger. */ 4224 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); 4225 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); 4226 pNew->wsFlags = WHERE_AUTO_INDEX; 4227 pNew->prereq = mPrereq | pTerm->prereqRight; 4228 rc = whereLoopInsert(pBuilder, pNew); 4229 } 4230 } 4231 } 4232 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 4233 4234 /* Loop over all indices. If there was an INDEXED BY clause, then only 4235 ** consider index pProbe. */ 4236 for(iSortIdx=1; 4237 rc==SQLITE_OK && pProbe; 4238 pProbe=(pSrc->fg.isIndexedBy||pSrc->fg.notIndexed)?0:pProbe->pNext, 4239 iSortIdx++ 4240 ){ 4241 if( pProbe->pPartIdxWhere!=0 4242 && !whereUsablePartialIndex(pSrc->iCursor, pSrc->fg.jointype, pWC, 4243 pProbe->pPartIdxWhere) 4244 ){ 4245 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [`98d973b8f5`] */ 4246 continue; /* Partial index inappropriate for this query */ 4247 } 4248 if( pProbe->bNoQuery ) continue; 4249 rSize = pProbe->aiRowLogEst[0]; 4250 pNew->u.btree.nEq = 0; 4251 pNew->u.btree.nBtm = 0; 4252 pNew->u.btree.nTop = 0; 4253 pNew->u.btree.nDistinctCol = 0; 4254 pNew->nSkip = 0; 4255 pNew->nLTerm = 0; 4256 pNew->iSortIdx = 0; 4257 pNew->rSetup = 0; 4258 pNew->prereq = mPrereq; 4259 pNew->nOut = rSize; 4260 pNew->u.btree.pIndex = pProbe; 4261 pNew->u.btree.pOrderBy = 0; 4262 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); 4263 4264 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ 4265 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); 4266 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){ 4267 /* Integer primary key index */ 4268 pNew->wsFlags = WHERE_IPK; 4269 4270 /* Full table scan */ 4271 pNew->iSortIdx = b ? iSortIdx : 0; 4272 /* TUNING: Cost of full table scan is 3.0*N. The 3.0 factor is an 4273 ** extra cost designed to discourage the use of full table scans, 4274 ** since index lookups have better worst-case performance if our 4275 ** stat guesses are wrong. Reduce the 3.0 penalty slightly 4276 ** (to 2.75) if we have valid STAT4 information for the table. 4277 ** At 2.75, a full table scan is preferred over using an index on 4278 ** a column with just two distinct values where each value has about 4279 ** an equal number of appearances. Without STAT4 data, we still want 4280 ** to use an index in that case, since the constraint might be for 4281 ** the scarcer of the two values, and in that case an index lookup is 4282 ** better. 4283 */ 4284 #ifdef SQLITE_ENABLE_STAT4 4285 pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0); 4286 #else 4287 pNew->rRun = rSize + 16; 4288 #endif 4289 ApplyCostMultiplier(pNew->rRun, pTab->costMult); 4290 whereLoopOutputAdjust(pWC, pNew, rSize); 4291 if( pSrc->fg.isSubquery ){ 4292 if( pSrc->fg.viaCoroutine ) pNew->wsFlags |= WHERE_COROUTINE; 4293 /* Do not set btree.pOrderBy for a recursive CTE. In this case 4294 ** the ORDER BY clause does not determine the overall order that 4295 ** rows are emitted from the CTE in. */ 4296 if( (pSrc->u4.pSubq->pSelect->selFlags & SF_Recursive)==0 ){ 4297 pNew->u.btree.pOrderBy = pSrc->u4.pSubq->pSelect->pOrderBy; 4298 } 4299 }else if( pSrc->fg.fromExists ){ 4300 pNew->nOut = 0; 4301 } 4302 rc = whereLoopInsert(pBuilder, pNew); 4303 pNew->nOut = rSize; 4304 if( rc ) break; 4305 }else{ 4306 Bitmask m; 4307 WhereClause *pPartWC = 0; /* WHERE terms that pProbe might imply */ 4308 if( pProbe->isCovering ){ 4309 m = 0; 4310 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; 4311 }else{ 4312 m = pSrc->colUsed & pProbe->colNotIdxed; 4313 if( pProbe->pPartIdxWhere 4314 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 4315 ){ 4316 wherePartIdxExpr( 4317 pWInfo->pParse, pProbe, pProbe->pPartIdxWhere, &m, 0, 0 4318 ); 4319 /* WHERE clause terms implied by the partial index WHERE clause 4320 ** are not evaluated, so the columns they use need not be in the 4321 ** index. But this does not apply to outer joins. See the 4322 ** call to whereApplyPartialIndexConstraints() in wherecode.c. */ 4323 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==0 4324 && pWC==&pWInfo->sWC 4325 ){ 4326 pPartWC = pWC; 4327 } 4328 } 4329 pNew->wsFlags = WHERE_INDEXED; 4330 if( m==0 ){ 4331 if( HasRowid(pTab) || pWInfo->pSelect!=0 || sqlite3FaultSim(700) ){ 4332 WHERETRACE(0x200, 4333 ("-> %s is a covering index according to bitmasks\n", 4334 pProbe->zName, m==0 ? "is" : "is not")); 4335 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; 4336 } 4337 }else if( m==TOPBIT 4338 || (pProbe->bHasExpr && !pProbe->bHasVCol) 4339 || pPartWC 4340 ){ 4341 u32 isCov = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor, 4342 pPartWC); 4343 if( isCov==0 ){ 4344 WHERETRACE(0x200, 4345 ("-> %s is not a covering index" 4346 " according to whereIsCoveringIndex()\n", pProbe->zName)); 4347 assert( m!=0 ); 4348 }else{ 4349 m = 0; 4350 pNew->wsFlags |= isCov; 4351 if( isCov & WHERE_IDX_ONLY ){ 4352 WHERETRACE(0x200, 4353 ("-> %s is a covering expression index" 4354 " according to whereIsCoveringIndex()\n", pProbe->zName)); 4355 }else{ 4356 assert( isCov==WHERE_EXPRIDX ); 4357 WHERETRACE(0x200, 4358 ("-> %s might be a covering expression index" 4359 " according to whereIsCoveringIndex()\n", pProbe->zName)); 4360 } 4361 } 4362 } 4363 } 4364 4365 /* Full scan via index */ 4366 if( b 4367 || !HasRowid(pTab) 4368 || pProbe->pPartIdxWhere!=0 4369 || pSrc->fg.isIndexedBy 4370 || ( m==0 4371 && pProbe->bUnordered==0 4372 && (pProbe->szIdxRowszTabRow) 4373 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 4374 && sqlite3GlobalConfig.bUseCis 4375 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) 4376 ) 4377 ){ 4378 pNew->iSortIdx = b ? iSortIdx : 0; 4379 4380 /* The cost of visiting the index rows is N*K, where K is 4381 ** between 1.1 and 3.0, depending on the relative sizes of the 4382 ** index and table rows. */ 4383 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; 4384 if( m!=0 ){ 4385 /* If this is a non-covering index scan, add in the cost of 4386 ** doing table lookups. The cost will be 3x the number of 4387 ** lookups. Take into account WHERE clause terms that can be 4388 ** satisfied using just the index, and that do not require a 4389 ** table lookup. */ 4390 LogEst nLookup = rSize + 16; /* Base cost: N*3 */ 4391 int ii; 4392 int iCur = pSrc->iCursor; 4393 WhereClause *pWC2 = &pWInfo->sWC; 4394 for(ii=0; iinTerm; ii++){ 4395 WhereTerm *pTerm = &pWC2->a[ii]; 4396 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){ 4397 break; 4398 } 4399 /* pTerm can be evaluated using just the index. So reduce 4400 ** the expected number of table lookups accordingly */ 4401 if( pTerm->truthProb<=0 ){ 4402 nLookup += pTerm->truthProb; 4403 }else{ 4404 nLookup--; 4405 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19; 4406 } 4407 } 4408 4409 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup); 4410 } 4411 ApplyCostMultiplier(pNew->rRun, pTab->costMult); 4412 whereLoopOutputAdjust(pWC, pNew, rSize); 4413 if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){ 4414 /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN 4415 ** because the cursor used to access the index might not be 4416 ** positioned to the correct row during the right-join no-match 4417 ** loop. */ 4418 }else{ 4419 if( pSrc->fg.fromExists ) pNew->nOut = 0; 4420 rc = whereLoopInsert(pBuilder, pNew); 4421 } 4422 pNew->nOut = rSize; 4423 if( rc ) break; 4424 } 4425 } 4426 4427 pBuilder->bldFlags1 = 0; 4428 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); 4429 if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){ 4430 /* If a non-unique index is used, or if a prefix of the key for 4431 ** unique index is used (making the index functionally non-unique) 4432 ** then the sqlite_stat1 data becomes important for scoring the 4433 ** plan */ 4434 pTab->tabFlags |= TF_MaybeReanalyze; 4435 } 4436 #ifdef SQLITE_ENABLE_STAT4 4437 sqlite3Stat4ProbeFree(pBuilder->pRec); 4438 pBuilder->nRecValid = 0; 4439 pBuilder->pRec = 0; 4440 #endif 4441 } 4442 return rc; 4443 } 4444 4445 #ifndef SQLITE_OMIT_VIRTUALTABLE 4446 4447 /* 4448 ** Return true if pTerm is a virtual table LIMIT or OFFSET term. 4449 */ 4450 static int isLimitTerm(WhereTerm *pTerm){ 4451 assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 ); 4452 return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT 4453 && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET; 4454 } 4455 4456 /* 4457 ** Return true if the first nCons constraints in the pUsage array are 4458 ** marked as in-use (have argvIndex>0). False otherwise. 4459 */ 4460 static int allConstraintsUsed( 4461 struct sqlite3_index_constraint_usage *aUsage, 4462 int nCons 4463 ){ 4464 int ii; 4465 for(ii=0; iipNew->iTab. This 4474 ** function marks a subset of those constraints usable, invokes the 4475 ** xBestIndex method and adds the returned plan to pBuilder. 4476 ** 4477 ** A constraint is marked usable if: 4478 ** 4479 ** * Argument mUsable indicates that its prerequisites are available, and 4480 ** 4481 ** * It is not one of the operators specified in the mExclude mask passed 4482 ** as the fourth argument (which in practice is either WO_IN or 0). 4483 ** 4484 ** Argument mPrereq is a mask of tables that must be scanned before the 4485 ** virtual table in question. These are added to the plans prerequisites 4486 ** before it is added to pBuilder. 4487 ** 4488 ** Output parameter *pbIn is set to true if the plan added to pBuilder 4489 ** uses one or more WO_IN terms, or false otherwise. 4490 */ 4491 static int whereLoopAddVirtualOne( 4492 WhereLoopBuilder *pBuilder, 4493 Bitmask mPrereq, /* Mask of tables that must be used. */ 4494 Bitmask mUsable, /* Mask of usable tables */ 4495 u16 mExclude, /* Exclude terms using these operators */ 4496 sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */ 4497 u16 mNoOmit, /* Do not omit these constraints */ 4498 int *pbIn, /* OUT: True if plan uses an IN(...) op */ 4499 int *pbRetryLimit /* OUT: Retry without LIMIT/OFFSET */ 4500 ){ 4501 WhereClause *pWC = pBuilder->pWC; 4502 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; 4503 struct sqlite3_index_constraint *pIdxCons; 4504 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage; 4505 int i; 4506 int mxTerm; 4507 int rc = SQLITE_OK; 4508 WhereLoop *pNew = pBuilder->pNew; 4509 Parse *pParse = pBuilder->pWInfo->pParse; 4510 SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab]; 4511 int nConstraint = pIdxInfo->nConstraint; 4512 4513 assert( (mUsable & mPrereq)==mPrereq ); 4514 *pbIn = 0; 4515 pNew->prereq = mPrereq; 4516 4517 /* Set the usable flag on the subset of constraints identified by 4518 ** arguments mUsable and mExclude. */ 4519 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 4520 for(i=0; iiTermOffset); 4522 pIdxCons->usable = 0; 4523 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight 4524 && (pTerm->eOperator & mExclude)==0 4525 && (pbRetryLimit || !isLimitTerm(pTerm)) 4526 ){ 4527 pIdxCons->usable = 1; 4528 } 4529 } 4530 4531 /* Initialize the output fields of the sqlite3_index_info structure */ 4532 memset(pUsage, 0, sizeof(pUsage[0])*nConstraint); 4533 assert( pIdxInfo->needToFreeIdxStr==0 ); 4534 pIdxInfo->idxStr = 0; 4535 pIdxInfo->idxNum = 0; 4536 pIdxInfo->orderByConsumed = 0; 4537 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; 4538 pIdxInfo->estimatedRows = 25; 4539 pIdxInfo->idxFlags = 0; 4540 pHidden->mHandleIn = 0; 4541 4542 /* Invoke the virtual table xBestIndex() method */ 4543 rc = vtabBestIndex(pParse, pSrc->pSTab, pIdxInfo); 4544 if( rc ){ 4545 if( rc==SQLITE_CONSTRAINT ){ 4546 /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means 4547 ** that the particular combination of parameters provided is unusable. 4548 ** Make no entries in the loop table. 4549 */ 4550 WHERETRACE(0xffffffff, (" ^^^^--- non-viable plan rejected!\n")); 4551 freeIdxStr(pIdxInfo); 4552 return SQLITE_OK; 4553 } 4554 return rc; 4555 } 4556 4557 mxTerm = -1; 4558 assert( pNew->nLSlot>=nConstraint ); 4559 memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint ); 4560 memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab)); 4561 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 4562 for(i=0; i=0 ){ 4565 WhereTerm *pTerm; 4566 int j = pIdxCons->iTermOffset; 4567 if( iTerm>=nConstraint 4568 || j<0 4569 || (pTerm = termFromWhereClause(pWC, j))==0 4570 || pNew->aLTerm[iTerm]!=0 4571 || pIdxCons->usable==0 4572 ){ 4573 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pSTab->zName); 4574 freeIdxStr(pIdxInfo); 4575 return SQLITE_ERROR; 4576 } 4577 testcase( iTerm==nConstraint-1 ); 4578 testcase( j==0 ); 4579 testcase( j==pWC->nTerm-1 ); 4580 pNew->prereq |= pTerm->prereqRight; 4581 assert( iTermnLSlot ); 4582 pNew->aLTerm[iTerm] = pTerm; 4583 if( iTerm>mxTerm ) mxTerm = iTerm; 4584 testcase( iTerm==15 ); 4585 testcase( iTerm==16 ); 4586 if( pUsage[i].omit ){ 4587 if( i<16 && ((1<u.vtab.omitMask |= 1<eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){ 4594 pNew->u.vtab.bOmitOffset = 1; 4595 } 4596 } 4597 if( SMASKBIT32(i) & pHidden->mHandleIn ){ 4598 pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm); 4599 }else if( (pTerm->eOperator & WO_IN)!=0 ){ 4600 /* A virtual table that is constrained by an IN clause may not 4601 ** consume the ORDER BY clause because (1) the order of IN terms 4602 ** is not necessarily related to the order of output terms and 4603 ** (2) Multiple outputs from a single IN value will not merge 4604 ** together. */ 4605 pIdxInfo->orderByConsumed = 0; 4606 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE; 4607 *pbIn = 1; assert( (mExclude & WO_IN)==0 ); 4608 } 4609 4610 /* Unless pbRetryLimit is non-NULL, there should be no LIMIT/OFFSET 4611 ** terms. And if there are any, they should follow all other terms. */ 4612 assert( pbRetryLimit || !isLimitTerm(pTerm) ); 4613 assert( !isLimitTerm(pTerm) || i>=nConstraint-2 ); 4614 assert( !isLimitTerm(pTerm) || i==nConstraint-1 || isLimitTerm(pTerm+1) ); 4615 4616 if( isLimitTerm(pTerm) && (*pbIn || !allConstraintsUsed(pUsage, i)) ){ 4617 /* If there is an IN(...) term handled as an == (separate call to 4618 ** xFilter for each value on the RHS of the IN) and a LIMIT or 4619 ** OFFSET term handled as well, the plan is unusable. Similarly, 4620 ** if there is a LIMIT/OFFSET and there are other unused terms, 4621 ** the plan cannot be used. In these cases set variable *pbRetryLimit 4622 ** to true to tell the caller to retry with LIMIT and OFFSET 4623 ** disabled. */ 4624 freeIdxStr(pIdxInfo); 4625 *pbRetryLimit = 1; 4626 return SQLITE_OK; 4627 } 4628 } 4629 } 4630 4631 pNew->nLTerm = mxTerm+1; 4632 for(i=0; i<=mxTerm; i++){ 4633 if( pNew->aLTerm[i]==0 ){ 4634 /* The non-zero argvIdx values must be contiguous. Raise an 4635 ** error if they are not */ 4636 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pSTab->zName); 4637 freeIdxStr(pIdxInfo); 4638 return SQLITE_ERROR; 4639 } 4640 } 4641 assert( pNew->nLTerm<=pNew->nLSlot ); 4642 pNew->u.vtab.idxNum = pIdxInfo->idxNum; 4643 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; 4644 pIdxInfo->needToFreeIdxStr = 0; 4645 pNew->u.vtab.idxStr = pIdxInfo->idxStr; 4646 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? 4647 pIdxInfo->nOrderBy : 0); 4648 pNew->u.vtab.bIdxNumHex = (pIdxInfo->idxFlags&SQLITE_INDEX_SCAN_HEX)!=0; 4649 pNew->rSetup = 0; 4650 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); 4651 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); 4652 4653 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated 4654 ** that the scan will visit at most one row. Clear it otherwise. */ 4655 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){ 4656 pNew->wsFlags |= WHERE_ONEROW; 4657 }else{ 4658 pNew->wsFlags &= ~WHERE_ONEROW; 4659 } 4660 rc = whereLoopInsert(pBuilder, pNew); 4661 if( pNew->u.vtab.needFree ){ 4662 sqlite3_free(pNew->u.vtab.idxStr); 4663 pNew->u.vtab.needFree = 0; 4664 } 4665 WHERETRACE(0xffffffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n", 4666 *pbIn, (sqlite3_uint64)mPrereq, 4667 (sqlite3_uint64)(pNew->prereq & ~mPrereq))); 4668 4669 return rc; 4670 } 4671 4672 /* 4673 ** Return the collating sequence for a constraint passed into xBestIndex. 4674 ** 4675 ** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex. 4676 ** This routine depends on there being a HiddenIndexInfo structure immediately 4677 ** following the sqlite3_index_info structure. 4678 ** 4679 ** Return a pointer to the collation name: 4680 ** 4681 ** 1. If there is an explicit COLLATE operator on the constraint, return it. 4682 ** 4683 ** 2. Else, if the column has an alternative collation, return that. 4684 ** 4685 ** 3. Otherwise, return "BINARY". 4686 */ 4687 const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){ 4688 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; 4689 const char *zRet = 0; 4690 if( iCons>=0 && iConsnConstraint ){ 4691 CollSeq *pC = 0; 4692 int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset; 4693 Expr *pX = termFromWhereClause(pHidden->pWC, iTerm)->pExpr; 4694 if( pX->pLeft ){ 4695 pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX); 4696 } 4697 zRet = (pC ? pC->zName : sqlite3StrBINARY); 4698 } 4699 return zRet; 4700 } 4701 4702 /* 4703 ** Return true if constraint iCons is really an IN(...) constraint, or 4704 ** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0) 4705 ** or clear (if bHandle==0) the flag to handle it using an iterator. 4706 */ 4707 int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){ 4708 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; 4709 u32 m = SMASKBIT32(iCons); 4710 if( m & pHidden->mIn ){ 4711 if( bHandle==0 ){ 4712 pHidden->mHandleIn &= ~m; 4713 }else if( bHandle>0 ){ 4714 pHidden->mHandleIn |= m; 4715 } 4716 return 1; 4717 } 4718 return 0; 4719 } 4720 4721 /* 4722 ** This interface is callable from within the xBestIndex callback only. 4723 ** 4724 ** If possible, set (*ppVal) to point to an object containing the value 4725 ** on the right-hand-side of constraint iCons. 4726 */ 4727 int sqlite3_vtab_rhs_value( 4728 sqlite3_index_info *pIdxInfo, /* Copy of first argument to xBestIndex */ 4729 int iCons, /* Constraint for which RHS is wanted */ 4730 sqlite3_value **ppVal /* Write value extracted here */ 4731 ){ 4732 HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1]; 4733 sqlite3_value *pVal = 0; 4734 int rc = SQLITE_OK; 4735 if( iCons<0 || iCons>=pIdxInfo->nConstraint ){ 4736 rc = SQLITE_MISUSE_BKPT; /* EV: R-30545-25046 */ 4737 }else{ 4738 if( pH->aRhs[iCons]==0 ){ 4739 WhereTerm *pTerm = termFromWhereClause( 4740 pH->pWC, pIdxInfo->aConstraint[iCons].iTermOffset 4741 ); 4742 rc = sqlite3ValueFromExpr( 4743 pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db), 4744 SQLITE_AFF_BLOB, &pH->aRhs[iCons] 4745 ); 4746 testcase( rc!=SQLITE_OK ); 4747 } 4748 pVal = pH->aRhs[iCons]; 4749 } 4750 *ppVal = pVal; 4751 4752 if( rc==SQLITE_OK && pVal==0 ){ /* IMP: R-19933-32160 */ 4753 rc = SQLITE_NOTFOUND; /* IMP: R-36424-56542 */ 4754 } 4755 4756 return rc; 4757 } 4758 4759 /* 4760 ** Return true if ORDER BY clause may be handled as DISTINCT. 4761 */ 4762 int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){ 4763 HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1]; 4764 assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 ); 4765 return pHidden->eDistinct; 4766 } 4767 4768 /* 4769 ** Cause the prepared statement that is associated with a call to 4770 ** xBestIndex to potentially use all schemas. If the statement being 4771 ** prepared is read-only, then just start read transactions on all 4772 ** schemas. But if this is a write operation, start writes on all 4773 ** schemas. 4774 ** 4775 ** This is used by the (built-in) sqlite_dbpage virtual table. 4776 */ 4777 void sqlite3VtabUsesAllSchemas(Parse *pParse){ 4778 int nDb = pParse->db->nDb; 4779 int i; 4780 for(i=0; iwriteMask) ){ 4784 for(i=0; ipNew->iTab. That table is guaranteed to be a virtual table. 4793 ** 4794 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and 4795 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause 4796 ** entries that occur before the virtual table in the FROM clause and are 4797 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the 4798 ** mUnusable mask contains all FROM clause entries that occur after the 4799 ** virtual table and are separated from it by at least one LEFT or 4800 ** CROSS JOIN. 4801 ** 4802 ** For example, if the query were: 4803 ** 4804 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6; 4805 ** 4806 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6). 4807 ** 4808 ** All the tables in mPrereq must be scanned before the current virtual 4809 ** table. So any terms for which all prerequisites are satisfied by 4810 ** mPrereq may be specified as "usable" in all calls to xBestIndex. 4811 ** Conversely, all tables in mUnusable must be scanned after the current 4812 ** virtual table, so any terms for which the prerequisites overlap with 4813 ** mUnusable should always be configured as "not-usable" for xBestIndex. 4814 */ 4815 static int whereLoopAddVirtual( 4816 WhereLoopBuilder *pBuilder, /* WHERE clause information */ 4817 Bitmask mPrereq, /* Tables that must be scanned before this one */ 4818 Bitmask mUnusable /* Tables that must be scanned after this one */ 4819 ){ 4820 int rc = SQLITE_OK; /* Return code */ 4821 WhereInfo *pWInfo; /* WHERE analysis context */ 4822 Parse *pParse; /* The parsing context */ 4823 WhereClause *pWC; /* The WHERE clause */ 4824 SrcItem *pSrc; /* The FROM clause term to search */ 4825 sqlite3_index_info *p; /* Object to pass to xBestIndex() */ 4826 int nConstraint; /* Number of constraints in p */ 4827 int bIn; /* True if plan uses IN(...) operator */ 4828 WhereLoop *pNew; 4829 Bitmask mBest; /* Tables used by best possible plan */ 4830 u16 mNoOmit; 4831 int bRetry = 0; /* True to retry with LIMIT/OFFSET disabled */ 4832 4833 assert( (mPrereq & mUnusable)==0 ); 4834 pWInfo = pBuilder->pWInfo; 4835 pParse = pWInfo->pParse; 4836 pWC = pBuilder->pWC; 4837 pNew = pBuilder->pNew; 4838 pSrc = &pWInfo->pTabList->a[pNew->iTab]; 4839 assert( IsVirtual(pSrc->pSTab) ); 4840 p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit); 4841 if( p==0 ) return SQLITE_NOMEM_BKPT; 4842 pNew->rSetup = 0; 4843 pNew->wsFlags = WHERE_VIRTUALTABLE; 4844 pNew->nLTerm = 0; 4845 pNew->u.vtab.needFree = 0; 4846 nConstraint = p->nConstraint; 4847 if( whereLoopResize(pParse->db, pNew, nConstraint) ){ 4848 freeIndexInfo(pParse->db, p); 4849 return SQLITE_NOMEM_BKPT; 4850 } 4851 4852 /* First call xBestIndex() with all constraints usable. */ 4853 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pSTab->zName)); 4854 WHERETRACE(0x800, (" VirtualOne: all usable\n")); 4855 rc = whereLoopAddVirtualOne( 4856 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry 4857 ); 4858 if( bRetry ){ 4859 assert( rc==SQLITE_OK ); 4860 rc = whereLoopAddVirtualOne( 4861 pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0 4862 ); 4863 } 4864 4865 /* If the call to xBestIndex() with all terms enabled produced a plan 4866 ** that does not require any source tables (IOW: a plan with mBest==0) 4867 ** and does not use an IN(...) operator, then there is no point in making 4868 ** any further calls to xBestIndex() since they will all return the same 4869 ** result (if the xBestIndex() implementation is sane). */ 4870 if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){ 4871 int seenZero = 0; /* True if a plan with no prereqs seen */ 4872 int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */ 4873 Bitmask mPrev = 0; 4874 Bitmask mBestNoIn = 0; 4875 4876 /* If the plan produced by the earlier call uses an IN(...) term, call 4877 ** xBestIndex again, this time with IN(...) terms disabled. */ 4878 if( bIn ){ 4879 WHERETRACE(0x800, (" VirtualOne: all usable w/o IN\n")); 4880 rc = whereLoopAddVirtualOne( 4881 pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0); 4882 assert( bIn==0 ); 4883 mBestNoIn = pNew->prereq & ~mPrereq; 4884 if( mBestNoIn==0 ){ 4885 seenZero = 1; 4886 seenZeroNoIN = 1; 4887 } 4888 } 4889 4890 /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) 4891 ** in the set of terms that apply to the current virtual table. */ 4892 while( rc==SQLITE_OK ){ 4893 int i; 4894 Bitmask mNext = ALLBITS; 4895 assert( mNext>0 ); 4896 for(i=0; iaConstraint[i].iTermOffset; 4898 Bitmask mThis = termFromWhereClause(pWC, iTerm)->prereqRight & ~mPrereq; 4899 if( mThis>mPrev && mThisprereq==mPrereq ){ 4909 seenZero = 1; 4910 if( bIn==0 ) seenZeroNoIN = 1; 4911 } 4912 } 4913 4914 /* If the calls to xBestIndex() in the above loop did not find a plan 4915 ** that requires no source tables at all (i.e. one guaranteed to be 4916 ** usable), make a call here with all source tables disabled */ 4917 if( rc==SQLITE_OK && seenZero==0 ){ 4918 WHERETRACE(0x800, (" VirtualOne: all disabled\n")); 4919 rc = whereLoopAddVirtualOne( 4920 pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0); 4921 if( bIn==0 ) seenZeroNoIN = 1; 4922 } 4923 4924 /* If the calls to xBestIndex() have so far failed to find a plan 4925 ** that requires no source tables at all and does not use an IN(...) 4926 ** operator, make a final call to obtain one here. */ 4927 if( rc==SQLITE_OK && seenZeroNoIN==0 ){ 4928 WHERETRACE(0x800, (" VirtualOne: all disabled and w/o IN\n")); 4929 rc = whereLoopAddVirtualOne( 4930 pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0); 4931 } 4932 } 4933 4934 freeIndexInfo(pParse->db, p); 4935 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pSTab->zName, rc)); 4936 return rc; 4937 } 4938 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 4939 4940 /* 4941 ** Add WhereLoop entries to handle OR terms. This works for either 4942 ** btrees or virtual tables. 4943 */ 4944 static int whereLoopAddOr( 4945 WhereLoopBuilder *pBuilder, 4946 Bitmask mPrereq, 4947 Bitmask mUnusable 4948 ){ 4949 WhereInfo *pWInfo = pBuilder->pWInfo; 4950 WhereClause *pWC; 4951 WhereLoop *pNew; 4952 WhereTerm *pTerm, *pWCEnd; 4953 int rc = SQLITE_OK; 4954 int iCur; 4955 WhereClause tempWC; 4956 WhereLoopBuilder sSubBuild; 4957 WhereOrSet sSum, sCur; 4958 SrcItem *pItem; 4959 4960 pWC = pBuilder->pWC; 4961 pWCEnd = pWC->a + pWC->nTerm; 4962 pNew = pBuilder->pNew; 4963 memset(&sSum, 0, sizeof(sSum)); 4964 pItem = pWInfo->pTabList->a + pNew->iTab; 4965 iCur = pItem->iCursor; 4966 4967 /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */ 4968 if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK; 4969 4970 for(pTerm=pWC->a; pTermeOperator & WO_OR)!=0 4972 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 4973 && (!ExprHasProperty(pTerm->pExpr, EP_OuterON) 4974 || pTerm->pExpr->w.iJoin==iCur) 4975 ){ 4976 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; 4977 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; 4978 WhereTerm *pOrTerm; 4979 int once = 1; 4980 int i, j; 4981 4982 sSubBuild = *pBuilder; 4983 sSubBuild.pOrSet = &sCur; 4984 4985 WHERETRACE(0x400, ("Begin processing OR-clause %p\n", pTerm)); 4986 for(pOrTerm=pOrWC->a; pOrTermeOperator & WO_AND)!=0 ){ 4988 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; 4989 }else if( pOrTerm->leftCursor==iCur ){ 4990 tempWC.pWInfo = pWC->pWInfo; 4991 tempWC.pOuter = pWC; 4992 tempWC.op = TK_AND; 4993 tempWC.nTerm = 1; 4994 tempWC.nBase = 1; 4995 tempWC.a = pOrTerm; 4996 sSubBuild.pWC = &tempWC; 4997 }else{ 4998 continue; 4999 } 5000 sCur.n = 0; 5001 #ifdef WHERETRACE_ENABLED 5002 WHERETRACE(0x400, ("OR-term %d of %p has %d subterms:\n", 5003 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); 5004 if( sqlite3WhereTrace & 0x20000 ){ 5005 sqlite3WhereClausePrint(sSubBuild.pWC); 5006 } 5007 #endif 5008 #ifndef SQLITE_OMIT_VIRTUALTABLE 5009 if( IsVirtual(pItem->pSTab) ){ 5010 rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable); 5011 }else 5012 #endif 5013 { 5014 rc = whereLoopAddBtree(&sSubBuild, mPrereq); 5015 } 5016 if( rc==SQLITE_OK ){ 5017 rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable); 5018 } 5019 testcase( rc==SQLITE_NOMEM && sCur.n>0 ); 5020 testcase( rc==SQLITE_DONE ); 5021 if( sCur.n==0 ){ 5022 sSum.n = 0; 5023 break; 5024 }else if( once ){ 5025 whereOrMove(&sSum, &sCur); 5026 once = 0; 5027 }else{ 5028 WhereOrSet sPrev; 5029 whereOrMove(&sPrev, &sSum); 5030 sSum.n = 0; 5031 for(i=0; inLTerm = 1; 5041 pNew->aLTerm[0] = pTerm; 5042 pNew->wsFlags = WHERE_MULTI_OR; 5043 pNew->rSetup = 0; 5044 pNew->iSortIdx = 0; 5045 memset(&pNew->u, 0, sizeof(pNew->u)); 5046 for(i=0; rc==SQLITE_OK && irRun = sSum.a[i].rRun + 1; 5060 pNew->nOut = sSum.a[i].nOut; 5061 pNew->prereq = sSum.a[i].prereq; 5062 rc = whereLoopInsert(pBuilder, pNew); 5063 } 5064 WHERETRACE(0x400, ("End processing OR-clause %p\n", pTerm)); 5065 } 5066 } 5067 return rc; 5068 } 5069 5070 /* 5071 ** Add all WhereLoop objects for all tables 5072 */ 5073 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ 5074 WhereInfo *pWInfo = pBuilder->pWInfo; 5075 Bitmask mPrereq = 0; 5076 Bitmask mPrior = 0; 5077 int iTab; 5078 SrcList *pTabList = pWInfo->pTabList; 5079 SrcItem *pItem; 5080 SrcItem *pEnd = &pTabList->a[pWInfo->nLevel]; 5081 sqlite3 *db = pWInfo->pParse->db; 5082 int rc = SQLITE_OK; 5083 int bFirstPastRJ = 0; 5084 int hasRightCrossJoin = 0; 5085 WhereLoop *pNew; 5086 5087 5088 /* Loop over the tables in the join, from left to right */ 5089 pNew = pBuilder->pNew; 5090 5091 /* Verify that pNew has already been initialized */ 5092 assert( pNew->nLTerm==0 ); 5093 assert( pNew->wsFlags==0 ); 5094 assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) ); 5095 assert( pNew->aLTerm!=0 ); 5096 5097 pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT; 5098 for(iTab=0, pItem=pTabList->a; pItemiTab = iTab; 5101 pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR; 5102 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); 5103 if( bFirstPastRJ 5104 || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0 5105 ){ 5106 /* Add prerequisites to prevent reordering of FROM clause terms 5107 ** across CROSS joins and outer joins. The bFirstPastRJ boolean 5108 ** prevents the right operand of a RIGHT JOIN from being swapped with 5109 ** other elements even further to the right. 5110 ** 5111 ** The hasRightCrossJoin flag prevent FROM-clause terms from moving 5112 ** from the right side of a LEFT JOIN or CROSS JOIN over to the 5113 ** left side of that same join. This is a required restriction in 5114 ** the case of LEFT JOIN - an incorrect answer may results if it is 5115 ** not enforced. This restriction is not required for CROSS JOIN. 5116 ** It is provided merely as a means of controlling join order, under 5117 ** the theory that no real-world queries that care about performance 5118 ** actually use the CROSS JOIN syntax. 5119 */ 5120 if( pItem->fg.jointype & (JT_LTORJ|JT_CROSS) ){ 5121 testcase( pItem->fg.jointype & JT_LTORJ ); 5122 testcase( pItem->fg.jointype & JT_CROSS ); 5123 hasRightCrossJoin = 1; 5124 } 5125 mPrereq |= mPrior; 5126 bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0; 5127 }else if( pItem->fg.fromExists ){ 5128 /* joins that result from the EXISTS-to-JOIN optimization should not 5129 ** be moved to the left of any of their dependencies */ 5130 WhereClause *pWC = &pWInfo->sWC; 5131 WhereTerm *pTerm; 5132 int i; 5133 for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){ 5134 if( (pNew->maskSelf & pTerm->prereqAll)!=0 ){ 5135 mPrereq |= (pTerm->prereqAll & (pNew->maskSelf-1)); 5136 } 5137 } 5138 }else if( !hasRightCrossJoin ){ 5139 mPrereq = 0; 5140 } 5141 #ifndef SQLITE_OMIT_VIRTUALTABLE 5142 if( IsVirtual(pItem->pSTab) ){ 5143 SrcItem *p; 5144 for(p=&pItem[1]; pfg.jointype & (JT_OUTER|JT_CROSS)) ){ 5146 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); 5147 } 5148 } 5149 rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable); 5150 }else 5151 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 5152 { 5153 rc = whereLoopAddBtree(pBuilder, mPrereq); 5154 } 5155 if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){ 5156 rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); 5157 } 5158 mPrior |= pNew->maskSelf; 5159 if( rc || db->mallocFailed ){ 5160 if( rc==SQLITE_DONE ){ 5161 /* We hit the query planner search limit set by iPlanLimit */ 5162 sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search"); 5163 rc = SQLITE_OK; 5164 }else{ 5165 break; 5166 } 5167 } 5168 } 5169 5170 whereLoopClear(db, pNew); 5171 return rc; 5172 } 5173 5174 /* Implementation of the order-by-subquery optimization: 5175 ** 5176 ** WhereLoop pLoop, which the iLoop-th term of the nested loop, is really 5177 ** a subquery or CTE that has an ORDER BY clause. See if any of the terms 5178 ** in the subquery ORDER BY clause will satisfy pOrderBy from the outer 5179 ** query. Mark off all satisfied terms (by setting bits in *pOBSat) and 5180 ** return TRUE if they do. If not, return false. 5181 ** 5182 ** Example: 5183 ** 5184 ** CREATE TABLE t1(a,b,c, PRIMARY KEY(a,b)); 5185 ** CREATE TABLE t2(x,y); 5186 ** WITH t3(p,q) AS MATERIALIZED (SELECT x+y, x-y FROM t2 ORDER BY x+y) 5187 ** SELECT * FROM t3 JOIN t1 ON a=q ORDER BY p, b; 5188 ** 5189 ** The CTE named "t3" comes out in the natural order of "p", so the first 5190 ** first them of "ORDER BY p,b" is satisfied by a sequential scan of "t3" 5191 ** and sorting only needs to occur on the second term "b". 5192 ** 5193 ** Limitations: 5194 ** 5195 ** (1) The optimization is not applied if the outer ORDER BY contains 5196 ** a COLLATE clause. The optimization might be applied if the 5197 ** outer ORDER BY uses NULLS FIRST, NULLS LAST, ASC, and/or DESC as 5198 ** long as the subquery ORDER BY does the same. But if the 5199 ** outer ORDER BY uses COLLATE, even a redundant COLLATE, the 5200 ** optimization is bypassed. 5201 ** 5202 ** (2) The subquery ORDER BY terms must exactly match subquery result 5203 ** columns, and the collations used must match as well. 5204 ** 5205 ** (3) The subquery and outer ORDER BY can be in opposite directions as 5206 ** long as the subquery is materialized. If the subquery is 5207 ** implemented as a co-routine, the sort orders must be in the same 5208 ** direction because there is no way to run a co-routine backwards. 5209 */ 5210 static SQLITE_NOINLINE int wherePathMatchSubqueryOB( 5211 Parse *pParse, /* The parsing context */ 5212 WhereLoop *pLoop, /* The nested loop term that is a subquery */ 5213 int iLoop, /* Which level of the nested loop. 0==outermost */ 5214 int iCur, /* Cursor used by the this loop */ 5215 ExprList *pOrderBy, /* The ORDER BY clause on the whole query */ 5216 Bitmask *pRevMask, /* When loops need to go in reverse order */ 5217 Bitmask *pOBSat, /* Which terms of pOrderBy are satisfied so far */ 5218 u16 wctrlFlags /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ 5219 ){ 5220 int iOB; /* Index into pOrderBy->a[] */ 5221 int jSub; /* Index into pSubOB->a[] */ 5222 u8 rev = 0; /* True if iOB and jSub sort in opposite directions */ 5223 u8 revIdx = 0; /* Sort direction for jSub */ 5224 Expr *pOBExpr; /* Current term of outer ORDER BY */ 5225 ExprList *pSubOB; /* Complete ORDER BY on the subquery */ 5226 5227 pSubOB = pLoop->u.btree.pOrderBy; 5228 assert( pSubOB!=0 ); 5229 for(iOB=0; (MASKBIT(iOB) & *pOBSat)!=0; iOB++){} 5230 for(jSub=0; jSubnExpr && iOBnExpr; jSub++, iOB++){ 5231 struct ExprList_item *pItem = &pSubOB->a[jSub]; 5232 if( pItem->u.x.iOrderByCol==0 ) break; 5233 pOBExpr = pOrderBy->a[iOB].pExpr; 5234 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) break; 5235 if( pOBExpr->iTable!=iCur ) break; 5236 if( pOBExpr->iColumn!=pItem->u.x.iOrderByCol-1 ) break; 5237 if( 0==sqlite3ExprCollSeqMatch(pParse, pOBExpr, pItem->pExpr) ) break; 5238 if( (wctrlFlags & WHERE_GROUPBY)==0 ){ 5239 u8 sfOB = pOrderBy->a[iOB].fg.sortFlags; /* sortFlags for iOB */ 5240 u8 sfSub = pItem->fg.sortFlags; /* sortFlags for jSub */ 5241 if( (sfSub & KEYINFO_ORDER_BIGNULL) != (sfOB & KEYINFO_ORDER_BIGNULL) ){ 5242 break; 5243 } 5244 revIdx = sfSub & KEYINFO_ORDER_DESC; 5245 if( jSub>0 ){ 5246 if( (rev^revIdx)!=(sfOB & KEYINFO_ORDER_DESC) ){ 5247 break; 5248 } 5249 }else{ 5250 rev = revIdx ^ (sfOB & KEYINFO_ORDER_DESC); 5251 if( rev ){ 5252 if( (pLoop->wsFlags & WHERE_COROUTINE)!=0 ){ 5253 /* Cannot run a co-routine in reverse order */ 5254 break; 5255 } 5256 *pRevMask |= MASKBIT(iLoop); 5257 } 5258 } 5259 } 5260 *pOBSat |= MASKBIT(iOB); 5261 } 5262 return jSub>0; 5263 } 5264 5265 /* 5266 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th 5267 ** parameters) to see if it outputs rows in the requested ORDER BY 5268 ** (or GROUP BY) without requiring a separate sort operation. Return N: 5269 ** 5270 ** N>0: N terms of the ORDER BY clause are satisfied 5271 ** N==0: No terms of the ORDER BY clause are satisfied 5272 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied. 5273 ** 5274 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as 5275 ** strict. With GROUP BY and DISTINCT the only requirement is that 5276 ** equivalent rows appear immediately adjacent to one another. GROUP BY 5277 ** and DISTINCT do not require rows to appear in any particular order as long 5278 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT 5279 ** the pOrderBy terms can be matched in any order. With ORDER BY, the 5280 ** pOrderBy terms must be matched in strict left-to-right order. 5281 */ 5282 static i8 wherePathSatisfiesOrderBy( 5283 WhereInfo *pWInfo, /* The WHERE clause */ 5284 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ 5285 WherePath *pPath, /* The WherePath to check */ 5286 u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */ 5287 u16 nLoop, /* Number of entries in pPath->aLoop[] */ 5288 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ 5289 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ 5290 ){ 5291 u8 revSet; /* True if rev is known */ 5292 u8 rev; /* Composite sort order */ 5293 u8 revIdx; /* Index sort order */ 5294 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ 5295 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ 5296 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ 5297 u16 eqOpMask; /* Allowed equality operators */ 5298 u16 nKeyCol; /* Number of key columns in pIndex */ 5299 u16 nColumn; /* Total number of ordered columns in the index */ 5300 u16 nOrderBy; /* Number terms in the ORDER BY clause */ 5301 int iLoop; /* Index of WhereLoop in pPath being processed */ 5302 int i, j; /* Loop counters */ 5303 int iCur; /* Cursor number for current WhereLoop */ 5304 int iColumn; /* A column number within table iCur */ 5305 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ 5306 WhereTerm *pTerm; /* A single term of the WHERE clause */ 5307 Expr *pOBExpr; /* An expression from the ORDER BY clause */ 5308 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ 5309 Index *pIndex; /* The index associated with pLoop */ 5310 sqlite3 *db = pWInfo->pParse->db; /* Database connection */ 5311 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ 5312 Bitmask obDone; /* Mask of all ORDER BY terms */ 5313 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ 5314 Bitmask ready; /* Mask of inner loops */ 5315 5316 /* 5317 ** We say the WhereLoop is "one-row" if it generates no more than one 5318 ** row of output. A WhereLoop is one-row if all of the following are true: 5319 ** (a) All index columns match with WHERE_COLUMN_EQ. 5320 ** (b) The index is unique 5321 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. 5322 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. 5323 ** 5324 ** We say the WhereLoop is "order-distinct" if the set of columns from 5325 ** that WhereLoop that are in the ORDER BY clause are different for every 5326 ** row of the WhereLoop. Every one-row WhereLoop is automatically 5327 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause 5328 ** is not order-distinct. To be order-distinct is not quite the same as being 5329 ** UNIQUE since a UNIQUE column or index can have multiple rows that 5330 ** are NULL and NULL values are equivalent for the purpose of order-distinct. 5331 ** To be order-distinct, the columns must be UNIQUE and NOT NULL. 5332 ** 5333 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the 5334 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is 5335 ** automatically order-distinct. 5336 */ 5337 5338 assert( pOrderBy!=0 ); 5339 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; 5340 5341 nOrderBy = pOrderBy->nExpr; 5342 testcase( nOrderBy==BMS-1 ); 5343 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ 5344 isOrderDistinct = 1; 5345 obDone = MASKBIT(nOrderBy)-1; 5346 orderDistinctMask = 0; 5347 ready = 0; 5348 eqOpMask = WO_EQ | WO_IS | WO_ISNULL; 5349 if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){ 5350 eqOpMask |= WO_IN; 5351 } 5352 for(iLoop=0; isOrderDistinct && obSat0 ) ready |= pLoop->maskSelf; 5354 if( iLoopaLoop[iLoop]; 5356 if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue; 5357 }else{ 5358 pLoop = pLast; 5359 } 5360 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ 5361 if( pLoop->u.vtab.isOrdered && pWInfo->pOrderBy==pOrderBy ){ 5362 obSat = obDone; 5363 }else{ 5364 /* No further ORDER BY terms may be matched. So this call should 5365 ** return >=0, not -1. Clear isOrderDistinct to ensure it does so. */ 5366 isOrderDistinct = 0; 5367 } 5368 break; 5369 } 5370 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; 5371 5372 /* Mark off any ORDER BY term X that is a column in the table of 5373 ** the current loop for which there is term in the WHERE 5374 ** clause of the form X IS NULL or X=? that reference only outer 5375 ** loops. 5376 */ 5377 for(i=0; ia[i].pExpr); 5380 if( NEVER(pOBExpr==0) ) continue; 5381 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue; 5382 if( pOBExpr->iTable!=iCur ) continue; 5383 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, 5384 ~ready, eqOpMask, 0); 5385 if( pTerm==0 ) continue; 5386 if( pTerm->eOperator==WO_IN ){ 5387 /* IN terms are only valid for sorting in the ORDER BY LIMIT 5388 ** optimization, and then only if they are actually used 5389 ** by the query plan */ 5390 assert( wctrlFlags & 5391 (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ); 5392 for(j=0; jnLTerm && pTerm!=pLoop->aLTerm[j]; j++){} 5393 if( j>=pLoop->nLTerm ) continue; 5394 } 5395 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ 5396 Parse *pParse = pWInfo->pParse; 5397 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr); 5398 const Expr *pCExpr = pTerm->pExpr; 5399 CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pCExpr); 5400 char affRight; 5401 assert( pColl1 ); 5402 if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){ 5403 continue; 5404 } 5405 affRight = sqlite3ExprAffinity(pCExpr->pRight); 5406 /* Left operand must be a column, hence always has affinity */ 5407 assert( sqlite3ExprAffinity(pCExpr->pLeft)!=0 ); 5408 if( affRight!=0 && affRight!=sqlite3ExprAffinity(pCExpr->pLeft) ){ 5409 continue; /* An affinity conversion would be required */ 5410 } 5411 testcase( pCExpr->op==TK_IS ); 5412 } 5413 obSat |= MASKBIT(i); 5414 } 5415 5416 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ 5417 if( pLoop->wsFlags & WHERE_IPK ){ 5418 if( pLoop->u.btree.pOrderBy 5419 && OptimizationEnabled(db, SQLITE_OrderBySubq) 5420 && wherePathMatchSubqueryOB(pWInfo->pParse, pLoop,iLoop,iCur, 5421 pOrderBy,pRevMask, &obSat, wctrlFlags) 5422 ){ 5423 nColumn = 0; 5424 isOrderDistinct = 0; 5425 }else{ 5426 nColumn = 1; 5427 } 5428 pIndex = 0; 5429 nKeyCol = 1; 5430 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ 5431 return 0; 5432 }else{ 5433 nKeyCol = pIndex->nKeyCol; 5434 nColumn = pIndex->nColumn; 5435 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); 5436 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID 5437 || !HasRowid(pIndex->pTable)); 5438 /* All relevant terms of the index must also be non-NULL in order 5439 ** for isOrderDistinct to be true. So the isOrderDistinct value 5440 ** computed here might be a false positive. Corrections will be 5441 ** made at tag-`20210426`-1 below */ 5442 isOrderDistinct = IsUniqueIndex(pIndex) 5443 && (pLoop->wsFlags & WHERE_SKIPSCAN)==0; 5444 } 5445 5446 /* Loop through all columns of the index and deal with the ones 5447 ** that are not constrained by == or IN. 5448 */ 5449 rev = revSet = 0; 5450 distinctColumns = 0; 5451 for(j=0; j=pLoop->u.btree.nEq 5455 || (pLoop->aLTerm[j]==0)==(jnSkip) 5456 ); 5457 if( ju.btree.nEq && j>=pLoop->nSkip ){ 5458 u16 eOp = pLoop->aLTerm[j]->eOperator; 5459 5460 /* Skip over == and IS and ISNULL terms. (Also skip IN terms when 5461 ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL 5462 ** terms imply that the index is not UNIQUE NOT NULL in which case 5463 ** the loop need to be marked as not order-distinct because it can 5464 ** have repeated NULL rows. 5465 ** 5466 ** If the current term is a column of an ((?,?) IN (SELECT...)) 5467 ** expression for which the SELECT returns more than one column, 5468 ** check that it is the only column used by this loop. Otherwise, 5469 ** if it is one of two or more, none of the columns can be 5470 ** considered to match an ORDER BY term. 5471 */ 5472 if( (eOp & eqOpMask)!=0 ){ 5473 if( eOp & (WO_ISNULL|WO_IS) ){ 5474 testcase( eOp & WO_ISNULL ); 5475 testcase( eOp & WO_IS ); 5476 testcase( isOrderDistinct ); 5477 isOrderDistinct = 0; 5478 } 5479 continue; 5480 }else if( ALWAYS(eOp & WO_IN) ){ 5481 /* ALWAYS() justification: eOp is an equality operator due to the 5482 ** ju.btree.nEq constraint above. Any equality other 5483 ** than WO_IN is captured by the previous "if". So this one 5484 ** always has to be WO_IN. */ 5485 Expr *pX = pLoop->aLTerm[j]->pExpr; 5486 for(i=j+1; iu.btree.nEq; i++){ 5487 if( pLoop->aLTerm[i]->pExpr==pX ){ 5488 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) ); 5489 bOnce = 0; 5490 break; 5491 } 5492 } 5493 } 5494 } 5495 5496 /* Get the column number in the table (iColumn) and sort order 5497 ** (revIdx) for the j-th column of the index. 5498 */ 5499 if( pIndex ){ 5500 iColumn = pIndex->aiColumn[j]; 5501 revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC; 5502 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID; 5503 }else{ 5504 iColumn = XN_ROWID; 5505 revIdx = 0; 5506 } 5507 5508 /* An unconstrained column that might be NULL means that this 5509 ** WhereLoop is not well-ordered. tag-`20210426`-1 5510 */ 5511 if( isOrderDistinct ){ 5512 if( iColumn>=0 5513 && j>=pLoop->u.btree.nEq 5514 && pIndex->pTable->aCol[iColumn].notNull==0 5515 ){ 5516 isOrderDistinct = 0; 5517 } 5518 if( iColumn==XN_EXPR ){ 5519 isOrderDistinct = 0; 5520 } 5521 } 5522 5523 /* Find the ORDER BY term that corresponds to the j-th column 5524 ** of the index and mark that ORDER BY term having been satisfied. 5525 */ 5526 isMatch = 0; 5527 for(i=0; bOnce && ia[i].pExpr); 5530 testcase( wctrlFlags & WHERE_GROUPBY ); 5531 testcase( wctrlFlags & WHERE_DISTINCTBY ); 5532 if( NEVER(pOBExpr==0) ) continue; 5533 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; 5534 if( iColumn>=XN_ROWID ){ 5535 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue; 5536 if( pOBExpr->iTable!=iCur ) continue; 5537 if( pOBExpr->iColumn!=iColumn ) continue; 5538 }else{ 5539 Expr *pIxExpr = pIndex->aColExpr->a[j].pExpr; 5540 if( sqlite3ExprCompareSkip(pOBExpr, pIxExpr, iCur) ){ 5541 continue; 5542 } 5543 } 5544 if( iColumn!=XN_ROWID ){ 5545 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); 5546 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; 5547 } 5548 if( wctrlFlags & WHERE_DISTINCTBY ){ 5549 pLoop->u.btree.nDistinctCol = j+1; 5550 } 5551 isMatch = 1; 5552 break; 5553 } 5554 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ 5555 /* Make sure the sort order is compatible in an ORDER BY clause. 5556 ** Sort order is irrelevant for a GROUP BY clause. */ 5557 if( revSet ){ 5558 if( (rev ^ revIdx) 5559 != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC) 5560 ){ 5561 isMatch = 0; 5562 } 5563 }else{ 5564 rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC); 5565 if( rev ) *pRevMask |= MASKBIT(iLoop); 5566 revSet = 1; 5567 } 5568 } 5569 if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){ 5570 if( j==pLoop->u.btree.nEq 5571 && (jpTable)||!IsPrimaryKeyIndex(pIndex)) 5572 ){ 5573 /* If this is the PK of a WITHOUT ROWID table, do not use any 5574 ** field past nKeyCol for a NULLS LAST sort. If ALTER TABLE has 5575 ** been used to add columns to the table, this field may not 5576 ** be present in all records, which causes problems for the seeks 5577 ** used by NULLS LAST sorts. */ 5578 pLoop->wsFlags |= WHERE_BIGNULL_SORT; 5579 }else{ 5580 isMatch = 0; 5581 } 5582 } 5583 if( isMatch ){ 5584 if( iColumn==XN_ROWID ){ 5585 testcase( distinctColumns==0 ); 5586 distinctColumns = 1; 5587 } 5588 obSat |= MASKBIT(i); 5589 }else{ 5590 /* No match found */ 5591 assert( nKeyCol>0 ); 5592 if( jmaskSelf; 5608 for(i=0; ia[i].pExpr; 5613 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); 5614 if( mTerm==0 && !sqlite3ExprIsConstant(0,p) ) continue; 5615 if( (mTerm&~orderDistinctMask)==0 ){ 5616 obSat |= MASKBIT(i); 5617 } 5618 } 5619 } 5620 } /* End the loop over all WhereLoops from outer-most down to inner-most */ 5621 if( obSat==obDone ) return (i8)nOrderBy; 5622 if( !isOrderDistinct ){ 5623 for(i=nOrderBy-1; i>0; i--){ 5624 Bitmask m = ALWAYS(iwctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) ); 5658 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); 5659 return pWInfo->sorted; 5660 } 5661 5662 #ifdef WHERETRACE_ENABLED 5663 /* For debugging use only: */ 5664 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ 5665 static char zName[65]; 5666 int i; 5667 for(i=0; iaLoop[i]->cId; } 5668 if( pLast ) zName[i++] = pLast->cId; 5669 zName[i] = 0; 5670 return zName; 5671 } 5672 #endif 5673 5674 /* 5675 ** Return the cost of sorting nRow rows, assuming that the keys have 5676 ** nOrderby columns and that the first nSorted columns are already in 5677 ** order. 5678 */ 5679 static LogEst whereSortingCost( 5680 WhereInfo *pWInfo, /* Query planning context */ 5681 LogEst nRow, /* Estimated number of rows to sort */ 5682 int nOrderBy, /* Number of ORDER BY clause terms */ 5683 int nSorted /* Number of initial ORDER BY terms naturally in order */ 5684 ){ 5685 /* Estimated cost of a full external sort, where N is 5686 ** the number of rows to sort is: 5687 ** 5688 ** cost = (K * N * log(N)). 5689 ** 5690 ** Or, if the order-by clause has X terms but only the last Y 5691 ** terms are out of order, then block-sorting will reduce the 5692 ** sorting cost to: 5693 ** 5694 ** cost = (K * N * log(N)) * (Y/X) 5695 ** 5696 ** The constant K is at least 2.0 but will be larger if there are a 5697 ** large number of columns to be sorted, as the sorting time is 5698 ** proportional to the amount of content to be sorted. The algorithm 5699 ** does not currently distinguish between fat columns (BLOBs and TEXTs) 5700 ** and skinny columns (INTs). It just uses the number of columns as 5701 ** an approximation for the row width. 5702 ** 5703 ** And extra factor of 2.0 or 3.0 is added to the sorting cost if the sort 5704 ** is built using OP_IdxInsert and OP_Sort rather than with OP_SorterInsert. 5705 */ 5706 LogEst rSortCost, nCol; 5707 assert( pWInfo->pSelect!=0 ); 5708 assert( pWInfo->pSelect->pEList!=0 ); 5709 /* TUNING: sorting cost proportional to the number of output columns: */ 5710 nCol = sqlite3LogEst((pWInfo->pSelect->pEList->nExpr+59)/30); 5711 rSortCost = nRow + nCol; 5712 if( nSorted>0 ){ 5713 /* Scale the result by (Y/X) */ 5714 rSortCost += sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66; 5715 } 5716 5717 /* Multiple by log(M) where M is the number of output rows. 5718 ** Use the LIMIT for M if it is smaller. Or if this sort is for 5719 ** a DISTINCT operator, M will be the number of distinct output 5720 ** rows, so fudge it downwards a bit. 5721 */ 5722 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 ){ 5723 rSortCost += 10; /* TUNING: Extra 2.0x if using LIMIT */ 5724 if( nSorted!=0 ){ 5725 rSortCost += 6; /* TUNING: Extra 1.5x if also using partial sort */ 5726 } 5727 if( pWInfo->iLimitiLimit; 5729 } 5730 }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){ 5731 /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT 5732 ** reduces the number of output rows by a factor of 2 */ 5733 if( nRow>10 ){ nRow -= 10; assert( 10==sqlite3LogEst(2) ); } 5734 } 5735 rSortCost += estLog(nRow); 5736 return rSortCost; 5737 } 5738 5739 /* 5740 ** Compute the maximum number of paths in the solver algorithm, for 5741 ** queries that have three or more terms in the FROM clause. Queries with 5742 ** two or fewer FROM clause terms are handled by the caller. 5743 ** 5744 ** Query planning is NP-hard. We must limit the number of paths at 5745 ** each step of the solver search algorithm to avoid exponential behavior. 5746 ** 5747 ** The value returned is a tuning parameter. Currently the value is: 5748 ** 5749 ** 18 for star queries 5750 ** 12 otherwise 5751 ** 5752 ** For the purposes of this heuristic, a star-query is defined as a query 5753 ** with a central "fact" table that is joined against multiple 5754 ** "dimension" tables, subject to the following constraints: 5755 ** 5756 ** (aa) Only a five-way or larger join is considered for this 5757 ** optimization. If there are fewer than four terms in the FROM 5758 ** clause, this heuristic does not apply. 5759 ** 5760 ** (bb) The join between the fact table and the dimension tables must 5761 ** be an INNER join. CROSS and OUTER JOINs do not qualify. 5762 ** 5763 ** (cc) A table must have 3 or more dimension tables in order to be 5764 ** considered a fact table. (Was 4 prior to 2026-02-10.) 5765 ** 5766 ** (dd) A table that is a self-join cannot be a dimension table. 5767 ** Dimension tables are joined against fact tables. 5768 ** 5769 ** SIDE EFFECT: (and really the whole point of this subroutine) 5770 ** 5771 ** If pWInfo describes a star-query, then the cost for SCANs of dimension 5772 ** WhereLoops is increased to be slightly larger than the cost of a SCAN 5773 ** in the fact table. Only SCAN costs are increased. SEARCH costs are 5774 ** unchanged. This heuristic helps keep fact tables in outer loops. Without 5775 ** this heuristic, paths with fact tables in outer loops tend to get pruned 5776 ** by the mxChoice limit on the number of paths, resulting in poor query 5777 ** plans. See the starschema1.test test module for examples of queries 5778 ** that need this heuristic to find good query plans. 5779 ** 5780 ** This heuristic can be completely disabled, so that no query is 5781 ** considered a star-query, using SQLITE_TESTCTRL_OPTIMIZATION to 5782 ** disable the SQLITE_StarQuery optimization. In the CLI, the command 5783 ** to do that is: ".testctrl opt -starquery". 5784 ** 5785 ** HISTORICAL NOTES: 5786 ** 5787 ** This optimization was first added on 2024-05-09 by check-in `38db9b5c83d`. 5788 ** The original optimization reduced the cost and output size estimate for 5789 ** fact tables to help them move to outer loops. But months later (as people 5790 ** started upgrading) performance regression reports started caming in, 5791 ** including: 5792 ** 5793 ** forum post `b18ef983e68d06d1` (2024-12-21) 5794 ** forum post `0025389d0860af82` (2025-01-14) 5795 ** forum post `d87570a145599033` (2025-01-17) 5796 ** 5797 ** To address these, the criteria for a star-query was tightened to exclude 5798 ** cases where the fact and dimensions are separated by an outer join, and 5799 ** the affect of star-schema detection was changed to increase the rRun cost 5800 ** on just full table scans of dimension tables, rather than reducing costs 5801 ** in the all access methods of the fact table. 5802 */ 5803 static int computeMxChoice(WhereInfo *pWInfo){ 5804 int nLoop = pWInfo->nLevel; /* Number of terms in the join */ 5805 WhereLoop *pWLoop; /* For looping over WhereLoops */ 5806 5807 #ifdef SQLITE_DEBUG 5808 /* The star-query detection code below makes use of the following 5809 ** properties of the WhereLoop list, so verify them before 5810 ** continuing: 5811 ** (1) .maskSelf is the bitmask corresponding to .iTab 5812 ** (2) The WhereLoop list is in ascending .iTab order 5813 */ 5814 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ 5815 assert( pWLoop->maskSelf==MASKBIT(pWLoop->iTab) ); 5816 assert( pWLoop->pNextLoop==0 || pWLoop->iTab<=pWLoop->pNextLoop->iTab ); 5817 } 5818 #endif /* SQLITE_DEBUG */ 5819 5820 if( nLoop>=4 /* Constraint (aa) */ 5821 && !pWInfo->bStarDone 5822 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_StarQuery) 5823 ){ 5824 SrcItem *aFromTabs; /* All terms of the FROM clause */ 5825 int iFromIdx; /* Term of FROM clause is the candidate fact-table */ 5826 Bitmask m; /* Bitmask for candidate fact-table */ 5827 Bitmask mSelfJoin = 0; /* Tables that cannot be dimension tables */ 5828 WhereLoop *pStart; /* Where to start searching for dimension-tables */ 5829 5830 pWInfo->bStarDone = 1; /* Only do this computation once */ 5831 5832 /* Look for fact tables with three or more dimensions where the 5833 ** dimension tables are not separately from the fact tables by an outer 5834 ** or cross join. Adjust cost weights if found. 5835 */ 5836 assert( !pWInfo->bStarUsed ); 5837 aFromTabs = pWInfo->pTabList->a; 5838 pStart = pWInfo->pLoops; 5839 for(iFromIdx=0, m=1; iFromIdxfg.jointype & (JT_OUTER|JT_CROSS))!=0 ){ 5847 /* If the candidate fact-table is the right table of an outer join 5848 ** restrict the search for dimension-tables to be tables to the right 5849 ** of the fact-table. Constraint (bb) */ 5850 if( iFromIdx+3 > nLoop ){ 5851 break; /* ^-- Impossible to reach nDep>=2 - Constraint (cc) */ 5852 } 5853 while( pStart && pStart->iTab<=iFromIdx ){ 5854 pStart = pStart->pNextLoop; 5855 } 5856 } 5857 for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){ 5858 if( (aFromTabs[pWLoop->iTab].fg.jointype & (JT_OUTER|JT_CROSS))!=0 ){ 5859 break; /* Constraint (bb) */ 5860 } 5861 if( (pWLoop->prereq & m)!=0 /* pWInfo depends on iFromIdx */ 5862 && (pWLoop->maskSelf & mSeen)==0 /* pWInfo not already a dependency */ 5863 && (pWLoop->maskSelf & mSelfJoin)==0 /* Not a self-join */ 5864 ){ 5865 if( aFromTabs[pWLoop->iTab].pSTab==pFactTab->pSTab ){ 5866 mSelfJoin |= m; 5867 }else{ 5868 nDep++; 5869 mSeen |= pWLoop->maskSelf; 5870 } 5871 } 5872 } 5873 if( nDep<=2 ){ 5874 continue; /* Constraint (cc) */ 5875 } 5876 5877 /* If we reach this point, it means that pFactTab is a fact table 5878 ** with four or more dimensions connected by inner joins. Proceed 5879 ** to make cost adjustments. */ 5880 5881 #ifdef WHERETRACE_ENABLED 5882 /* Make sure rStarDelta values are initialized */ 5883 if( !pWInfo->bStarUsed ){ 5884 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ 5885 pWLoop->rStarDelta = 0; 5886 } 5887 } 5888 #endif 5889 #ifdef WHERETRACE_ENABLED /* 0x80000 */ 5890 if( sqlite3WhereTrace & 0x80000 ){ 5891 Bitmask mShow = mSeen; 5892 sqlite3DebugPrintf("Fact table %s(%d), dimensions:", 5893 pFactTab->zAlias ? pFactTab->zAlias : pFactTab->pSTab->zName, 5894 iFromIdx); 5895 for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){ 5896 if( mShow & pWLoop->maskSelf ){ 5897 SrcItem *pDim = aFromTabs + pWLoop->iTab; 5898 mShow &= ~pWLoop->maskSelf; 5899 sqlite3DebugPrintf(" %s(%d)", 5900 pDim->zAlias ? pDim->zAlias: pDim->pSTab->zName, pWLoop->iTab); 5901 } 5902 } 5903 sqlite3DebugPrintf("\n"); 5904 } 5905 #endif 5906 pWInfo->bStarUsed = 1; 5907 5908 /* Compute the maximum cost of any WhereLoop for the 5909 ** fact table plus one epsilon */ 5910 mxRun = LOGEST_MIN; 5911 for(pWLoop=pStart; pWLoop; pWLoop=pWLoop->pNextLoop){ 5912 if( pWLoop->iTabiTab>iFromIdx ) break; 5914 if( pWLoop->rRun>mxRun ) mxRun = pWLoop->rRun; 5915 } 5916 if( mxRunpNextLoop){ 5921 if( (pWLoop->maskSelf & mSeen)==0 ) continue; 5922 if( pWLoop->nLTerm ) continue; 5923 if( pWLoop->rRuniTab; 5927 sqlite3DebugPrintf( 5928 "Increase SCAN cost of %s to %d\n", 5929 pDim->zAlias ? pDim->zAlias: pDim->pSTab->zName, mxRun 5930 ); 5931 } 5932 pWLoop->rStarDelta = mxRun - pWLoop->rRun; 5933 #endif /* WHERETRACE_ENABLED */ 5934 pWLoop->rRun = mxRun; 5935 } 5936 } 5937 } 5938 #ifdef WHERETRACE_ENABLED /* 0x80000 */ 5939 if( (sqlite3WhereTrace & 0x80000)!=0 && pWInfo->bStarUsed ){ 5940 sqlite3DebugPrintf("WhereLoops changed by star-query heuristic:\n"); 5941 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ 5942 if( pWLoop->rStarDelta ){ 5943 sqlite3WhereLoopPrint(pWLoop, &pWInfo->sWC); 5944 } 5945 } 5946 } 5947 #endif 5948 } 5949 return pWInfo->bStarUsed ? 18 : 12; 5950 } 5951 5952 /* 5953 ** Two WhereLoop objects, pCandidate and pBaseline, are known to have the 5954 ** same cost. Look deep into each to see if pCandidate is even slightly 5955 ** better than pBaseline. Return false if it is, if pCandidate is is preferred. 5956 ** Return true if pBaseline is preferred or if we cannot tell the difference. 5957 ** 5958 ** Result Meaning 5959 ** -------- ---------------------------------------------------------- 5960 ** true We cannot tell the difference in pCandidate and pBaseline 5961 ** false pCandidate seems like a better choice than pBaseline 5962 */ 5963 static SQLITE_NOINLINE int whereLoopIsNoBetter( 5964 const WhereLoop *pCandidate, 5965 const WhereLoop *pBaseline 5966 ){ 5967 if( (pCandidate->wsFlags & WHERE_INDEXED)==0 ) return 1; 5968 if( (pBaseline->wsFlags & WHERE_INDEXED)==0 ) return 1; 5969 if( pCandidate->u.btree.pIndex->szIdxRow < 5970 pBaseline->u.btree.pIndex->szIdxRow ) return 0; 5971 return 1; 5972 } 5973 5974 /* 5975 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine 5976 ** attempts to find the lowest cost path that visits each WhereLoop 5977 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields. 5978 ** 5979 ** Assume that the total number of output rows that will need to be sorted 5980 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting 5981 ** costs if nRowEst==0. 5982 ** 5983 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation 5984 ** error occurs. 5985 */ 5986 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ 5987 int mxChoice; /* Maximum number of simultaneous paths tracked */ 5988 int nLoop; /* Number of terms in the join */ 5989 Parse *pParse; /* Parsing context */ 5990 int iLoop; /* Loop counter over the terms of the join */ 5991 int ii, jj; /* Loop counters */ 5992 int mxI = 0; /* Index of next entry to replace */ 5993 int nOrderBy; /* Number of ORDER BY clause terms */ 5994 LogEst mxCost = 0; /* Maximum cost of a set of paths */ 5995 LogEst mxUnsort = 0; /* Maximum unsorted cost of a set of path */ 5996 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ 5997 WherePath *aFrom; /* All nFrom paths at the previous level */ 5998 WherePath *aTo; /* The nTo best paths at the current level */ 5999 WherePath *pFrom; /* An element of aFrom[] that we are working on */ 6000 WherePath *pTo; /* An element of aTo[] that we are working on */ 6001 WhereLoop *pWLoop; /* One of the WhereLoop objects */ 6002 WhereLoop **pX; /* Used to divy up the pSpace memory */ 6003 LogEst *aSortCost = 0; /* Sorting and partial sorting costs */ 6004 char *pSpace; /* Temporary memory used by this routine */ 6005 int nSpace; /* Bytes of space allocated at pSpace */ 6006 6007 pParse = pWInfo->pParse; 6008 nLoop = pWInfo->nLevel; 6009 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d, nQueryLoop=%d)\n", 6010 nRowEst, pParse->nQueryLoop)); 6011 /* TUNING: mxChoice is the maximum number of possible paths to preserve 6012 ** at each step. Based on the number of loops in the FROM clause: 6013 ** 6014 ** nLoop mxChoice 6015 ** ----- -------- 6016 ** 1 1 // the most common case 6017 ** 2 5 6018 ** 3+ 12 or 18 // see computeMxChoice() 6019 */ 6020 if( nLoop<=1 ){ 6021 mxChoice = 1; 6022 }else if( nLoop==2 ){ 6023 mxChoice = 5; 6024 }else if( pParse->nErr ){ 6025 mxChoice = 1; 6026 }else{ 6027 mxChoice = computeMxChoice(pWInfo); 6028 } 6029 assert( nLoop<=pWInfo->pTabList->nSrc ); 6030 6031 /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this 6032 ** case the purpose of this call is to estimate the number of rows returned 6033 ** by the overall query. Once this estimate has been obtained, the caller 6034 ** will invoke this function a second time, passing the estimate as the 6035 ** nRowEst parameter. */ 6036 if( pWInfo->pOrderBy==0 || nRowEst==0 ){ 6037 nOrderBy = 0; 6038 }else{ 6039 nOrderBy = pWInfo->pOrderBy->nExpr; 6040 } 6041 6042 /* Allocate and initialize space for aTo, aFrom and aSortCost[] */ 6043 nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; 6044 nSpace += sizeof(LogEst) * nOrderBy; 6045 pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace); 6046 if( pSpace==0 ) return SQLITE_NOMEM_BKPT; 6047 aTo = (WherePath*)pSpace; 6048 aFrom = aTo+mxChoice; 6049 memset(aFrom, 0, sizeof(aFrom[0])); 6050 pX = (WhereLoop**)(aFrom+mxChoice); 6051 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ 6052 pFrom->aLoop = pX; 6053 } 6054 if( nOrderBy ){ 6055 /* If there is an ORDER BY clause and it is not being ignored, set up 6056 ** space for the aSortCost[] array. Each element of the aSortCost array 6057 ** is either zero - meaning it has not yet been initialized - or the 6058 ** cost of sorting nRowEst rows of data where the first X terms of 6059 ** the ORDER BY clause are already in order, where X is the array 6060 ** index. */ 6061 aSortCost = (LogEst*)pX; 6062 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); 6063 } 6064 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); 6065 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); 6066 6067 /* Seed the search with a single WherePath containing zero WhereLoops. 6068 ** 6069 ** TUNING: Do not let the number of iterations go above 28. If the cost 6070 ** of computing an automatic index is not paid back within the first 28 6071 ** rows, then do not use the automatic index. */ 6072 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) ); 6073 nFrom = 1; 6074 assert( aFrom[0].isOrdered==0 ); 6075 if( nOrderBy ){ 6076 /* If nLoop is zero, then there are no FROM terms in the query. Since 6077 ** in this case the query may return a maximum of one row, the results 6078 ** are already in the requested order. Set isOrdered to nOrderBy to 6079 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to 6080 ** -1, indicating that the result set may or may not be ordered, 6081 ** depending on the loops added to the current plan. */ 6082 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; 6083 } 6084 6085 /* Compute successively longer WherePaths using the previous generation 6086 ** of WherePaths as the basis for the next. Keep track of the mxChoice 6087 ** best paths at each generation */ 6088 for(iLoop=0; iLooppLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ 6092 LogEst nOut; /* Rows visited by (pFrom+pWLoop) */ 6093 LogEst rCost; /* Cost of path (pFrom+pWLoop) */ 6094 LogEst rUnsort; /* Unsorted cost of (pFrom+pWLoop) */ 6095 i8 isOrdered; /* isOrdered for (pFrom+pWLoop) */ 6096 Bitmask maskNew; /* Mask of src visited by (..) */ 6097 Bitmask revMask; /* Mask of rev-order loops for (..) */ 6098 6099 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; 6100 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; 6101 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){ 6102 /* Do not use an automatic index if the this loop is expected 6103 ** to run less than 1.25 times. It is tempting to also exclude 6104 ** automatic index usage on an outer loop, but sometimes an automatic 6105 ** index is useful in the outer loop of a correlated subquery. */ 6106 assert( 10==sqlite3LogEst(2) ); 6107 continue; 6108 } 6109 6110 /* At this point, pWLoop is a candidate to be the next loop. 6111 ** Compute its cost */ 6112 rUnsort = pWLoop->rRun + pFrom->nRow; 6113 if( pWLoop->rSetup ){ 6114 rUnsort = sqlite3LogEstAdd(pWLoop->rSetup, rUnsort); 6115 } 6116 rUnsort = sqlite3LogEstAdd(rUnsort, pFrom->rUnsort); 6117 nOut = pFrom->nRow + pWLoop->nOut; 6118 maskNew = pFrom->maskLoop | pWLoop->maskSelf; 6119 isOrdered = pFrom->isOrdered; 6120 if( isOrdered<0 ){ 6121 revMask = 0; 6122 isOrdered = wherePathSatisfiesOrderBy(pWInfo, 6123 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, 6124 iLoop, pWLoop, &revMask); 6125 }else{ 6126 revMask = pFrom->revLoop; 6127 } 6128 if( isOrdered>=0 && isOrdered=0, or 6160 ** (C) ordering does not matter because this is the last round 6161 ** of the solver. 6162 ** 6163 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent 6164 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range 6165 ** of legal values for isOrdered, -1..64. 6166 */ 6167 testcase( nTo==0 ); 6168 for(jj=0, pTo=aTo; jjmaskLoop==maskNew 6170 && ( ((pTo->isOrdered^isOrdered)&0x80)==0 || iLoop==nLoop-1 ) 6171 ){ 6172 testcase( jj==nTo-1 ); 6173 break; 6174 } 6175 } 6176 if( jj>=nTo ){ 6177 /* None of the existing best-so-far paths match the candidate. */ 6178 if( nTo>=mxChoice 6179 && (rCost>mxCost || (rCost==mxCost && rUnsort>=mxUnsort)) 6180 ){ 6181 /* The current candidate is no better than any of the mxChoice 6182 ** paths currently in the best-so-far buffer. So discard 6183 ** this candidate as not viable. */ 6184 #ifdef WHERETRACE_ENABLED /* 0x4 */ 6185 if( sqlite3WhereTrace&0x4 ){ 6186 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n", 6187 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsort, 6188 isOrdered>=0 ? isOrdered+'0' : '?'); 6189 } 6190 #endif 6191 continue; 6192 } 6193 /* If we reach this points it means that the new candidate path 6194 ** needs to be added to the set of best-so-far paths. */ 6195 if( nTo=0 ? isOrdered+'0' : '?'); 6208 } 6209 #endif 6210 }else{ 6211 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the 6212 ** same set of loops and has the same isOrdered setting as the 6213 ** candidate path. Check to see if the candidate should replace 6214 ** pTo or if the candidate should be skipped. 6215 ** 6216 ** The conditional is an expanded vector comparison equivalent to: 6217 ** (pTo->rCost,pTo->nRow,pTo->rUnsort) <= (rCost,nOut,rUnsort) 6218 */ 6219 if( (pTo->rCostrCost==rCost && pTo->nRowrCost==rCost && pTo->nRow==nOut && pTo->rUnsortrCost==rCost && pTo->nRow==nOut && pTo->rUnsort==rUnsort 6223 && whereLoopIsNoBetter(pWLoop, pTo->aLoop[iLoop]) ) 6224 ){ 6225 #ifdef WHERETRACE_ENABLED /* 0x4 */ 6226 if( sqlite3WhereTrace&0x4 ){ 6227 sqlite3DebugPrintf( 6228 "Skip %s cost=%-3d,%3d,%3d order=%c", 6229 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsort, 6230 isOrdered>=0 ? isOrdered+'0' : '?'); 6231 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n", 6232 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 6233 pTo->rUnsort, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); 6234 } 6235 #endif 6236 /* Discard the candidate path from further consideration */ 6237 testcase( pTo->rCost==rCost ); 6238 continue; 6239 } 6240 testcase( pTo->rCost==rCost+1 ); 6241 /* Control reaches here if the candidate path is better than the 6242 ** pTo path. Replace pTo with the candidate. */ 6243 #ifdef WHERETRACE_ENABLED /* 0x4 */ 6244 if( sqlite3WhereTrace&0x4 ){ 6245 sqlite3DebugPrintf( 6246 "Update %s cost=%-3d,%3d,%3d order=%c", 6247 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsort, 6248 isOrdered>=0 ? isOrdered+'0' : '?'); 6249 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n", 6250 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 6251 pTo->rUnsort, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); 6252 } 6253 #endif 6254 } 6255 /* pWLoop is a winner. Add it to the set of best so far */ 6256 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; 6257 pTo->revLoop = revMask; 6258 pTo->nRow = nOut; 6259 pTo->rCost = rCost; 6260 pTo->rUnsort = rUnsort; 6261 pTo->isOrdered = isOrdered; 6262 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); 6263 pTo->aLoop[iLoop] = pWLoop; 6264 if( nTo>=mxChoice ){ 6265 mxI = 0; 6266 mxCost = aTo[0].rCost; 6267 mxUnsort = aTo[0].nRow; 6268 for(jj=1, pTo=&aTo[1]; jjrCost>mxCost 6270 || (pTo->rCost==mxCost && pTo->rUnsort>mxUnsort) 6271 ){ 6272 mxCost = pTo->rCost; 6273 mxUnsort = pTo->rUnsort; 6274 mxI = jj; 6275 } 6276 } 6277 } 6278 } 6279 } 6280 6281 #ifdef WHERETRACE_ENABLED /* >=2 */ 6282 if( sqlite3WhereTrace & 0x02 ){ 6283 LogEst rMin, rFloor = 0; 6284 int nDone = 0; 6285 int nProgress; 6286 sqlite3DebugPrintf("---- after round %d ----\n", iLoop); 6287 do{ 6288 nProgress = 0; 6289 rMin = 0x7fff; 6290 for(ii=0, pTo=aTo; iirCost>rFloor && pTo->rCostrCost; 6292 } 6293 for(ii=0, pTo=aTo; iirCost==rMin ){ 6295 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", 6296 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 6297 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); 6298 if( pTo->isOrdered>0 ){ 6299 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); 6300 }else{ 6301 sqlite3DebugPrintf("\n"); 6302 } 6303 nDone++; 6304 nProgress++; 6305 } 6306 } 6307 rFloor = rMin; 6308 }while( nDone0 ); 6309 } 6310 #endif 6311 6312 /* Swap the roles of aFrom and aTo for the next generation */ 6313 pFrom = aTo; 6314 aTo = aFrom; 6315 aFrom = pFrom; 6316 nFrom = nTo; 6317 } 6318 6319 if( nFrom==0 ){ 6320 sqlite3ErrorMsg(pParse, "no query solution"); 6321 sqlite3StackFreeNN(pParse->db, pSpace); 6322 return SQLITE_ERROR; 6323 } 6324 6325 /* Only one path is available, which is the best path */ 6326 assert( nFrom==1 ); 6327 pFrom = aFrom; 6328 6329 assert( pWInfo->nLevel==nLoop ); 6330 /* Load the lowest cost path into pWInfo */ 6331 for(iLoop=0; iLoopa + iLoop; 6333 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; 6334 pLevel->iFrom = pWLoop->iTab; 6335 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; 6336 } 6337 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 6338 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 6339 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP 6340 && nRowEst 6341 ){ 6342 Bitmask notUsed; 6343 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom, 6344 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); 6345 if( rc==pWInfo->pResultSet->nExpr ){ 6346 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; 6347 } 6348 } 6349 pWInfo->bOrderedInnerLoop = 0; 6350 if( pWInfo->pOrderBy ){ 6351 pWInfo->nOBSat = pFrom->isOrdered; 6352 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ 6353 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ 6354 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; 6355 } 6356 /* vvv--- See check-in [`12ad822d9b827777`] on 2023-03-16 ---vvv */ 6357 assert( pWInfo->pSelect->pOrderBy==0 6358 || pWInfo->nOBSat <= pWInfo->pSelect->pOrderBy->nExpr ); 6359 }else{ 6360 pWInfo->revMask = pFrom->revLoop; 6361 if( pWInfo->nOBSat<=0 ){ 6362 pWInfo->nOBSat = 0; 6363 if( nLoop>0 ){ 6364 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags; 6365 if( (wsFlags & WHERE_ONEROW)==0 6366 && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN) 6367 ){ 6368 Bitmask m = 0; 6369 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom, 6370 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m); 6371 testcase( wsFlags & WHERE_IPK ); 6372 testcase( wsFlags & WHERE_COLUMN_IN ); 6373 if( rc==pWInfo->pOrderBy->nExpr ){ 6374 pWInfo->bOrderedInnerLoop = 1; 6375 pWInfo->revMask = m; 6376 } 6377 } 6378 } 6379 }else if( nLoop 6380 && pWInfo->nOBSat==1 6381 && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0 6382 ){ 6383 pWInfo->bOrderedInnerLoop = 1; 6384 } 6385 } 6386 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) 6387 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0 6388 ){ 6389 Bitmask revMask = 0; 6390 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 6391 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask 6392 ); 6393 assert( pWInfo->sorted==0 ); 6394 if( nOrder==pWInfo->pOrderBy->nExpr ){ 6395 pWInfo->sorted = 1; 6396 pWInfo->revMask = revMask; 6397 } 6398 } 6399 } 6400 6401 pWInfo->nRowOut = pFrom->nRow; 6402 #ifdef WHERETRACE_ENABLED 6403 pWInfo->rTotalCost = pFrom->rCost; 6404 #endif 6405 6406 /* Free temporary memory and return success */ 6407 sqlite3StackFreeNN(pParse->db, pSpace); 6408 return SQLITE_OK; 6409 } 6410 6411 /* 6412 ** This routine implements a heuristic designed to improve query planning. 6413 ** This routine is called in between the first and second call to 6414 ** wherePathSolver(). Hence the name "Interstage" "Heuristic". 6415 ** 6416 ** The first call to wherePathSolver() (hereafter just "solver()") computes 6417 ** the best path without regard to the order of the outputs. The second call 6418 ** to the solver() builds upon the first call to try to find an alternative 6419 ** path that satisfies the ORDER BY clause. 6420 ** 6421 ** This routine looks at the results of the first solver() run, and for 6422 ** every FROM clause term in the resulting query plan that uses an equality 6423 ** constraint against an index, disable other WhereLoops for that same 6424 ** FROM clause term that would try to do a full-table scan. This prevents 6425 ** an index search from being converted into a full-table scan in order to 6426 ** satisfy an ORDER BY clause, since even though we might get slightly better 6427 ** performance using the full-scan without sorting if the output size 6428 ** estimates are very precise, we might also get severe performance 6429 ** degradation using the full-scan if the output size estimate is too large. 6430 ** It is better to err on the side of caution. 6431 ** 6432 ** Except, if the first solver() call generated a full-table scan in an outer 6433 ** loop then stop this analysis at the first full-scan, since the second 6434 ** solver() run might try to swap that full-scan for another in order to 6435 ** get the output into the correct order. In other words, we allow a 6436 ** rewrite like this: 6437 ** 6438 ** First Solver() Second Solver() 6439 ** |-- SCAN t1 |-- SCAN t2 6440 ** |-- SEARCH t2 `-- SEARCH t1 6441 ** `-- SORT USING B-TREE 6442 ** 6443 ** The purpose of this routine is to disallow rewrites such as: 6444 ** 6445 ** First Solver() Second Solver() 6446 ** |-- SEARCH t1 |-- SCAN t2 <--- bad! 6447 ** |-- SEARCH t2 `-- SEARCH t1 6448 ** `-- SORT USING B-TREE 6449 ** 6450 ** See test cases in test/whereN.test for the real-world query that 6451 ** originally provoked this heuristic. 6452 */ 6453 static SQLITE_NOINLINE void whereInterstageHeuristic(WhereInfo *pWInfo){ 6454 int i; 6455 #ifdef WHERETRACE_ENABLED 6456 int once = 0; 6457 #endif 6458 for(i=0; inLevel; i++){ 6459 WhereLoop *p = pWInfo->a[i].pWLoop; 6460 if( p==0 ) break; 6461 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 6462 /* Treat a vtab scan as similar to a full-table scan */ 6463 break; 6464 } 6465 if( (p->wsFlags & (WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0 ){ 6466 u8 iTab = p->iTab; 6467 WhereLoop *pLoop; 6468 for(pLoop=pWInfo->pLoops; pLoop; pLoop=pLoop->pNextLoop){ 6469 if( pLoop->iTab!=iTab ) continue; 6470 if( (pLoop->wsFlags & (WHERE_CONSTRAINT|WHERE_AUTO_INDEX))!=0 ){ 6471 /* Auto-index and index-constrained loops allowed to remain */ 6472 continue; 6473 } 6474 #ifdef WHERETRACE_ENABLED 6475 if( sqlite3WhereTrace & 0x80 ){ 6476 if( once==0 ){ 6477 sqlite3DebugPrintf("Loops disabled by interstage heuristic:\n"); 6478 once = 1; 6479 } 6480 sqlite3WhereLoopPrint(pLoop, &pWInfo->sWC); 6481 } 6482 #endif /* WHERETRACE_ENABLED */ 6483 pLoop->prereq = ALLBITS; /* Prevent 2nd solver() from using this one */ 6484 } 6485 }else{ 6486 break; 6487 } 6488 } 6489 } 6490 6491 /* 6492 ** Most queries use only a single table (they are not joins) and have 6493 ** simple == constraints against indexed fields. This routine attempts 6494 ** to plan those simple cases using much less ceremony than the 6495 ** general-purpose query planner, and thereby yield faster sqlite3_prepare() 6496 ** times for the common case. 6497 ** 6498 ** Return non-zero on success, if this query can be handled by this 6499 ** no-frills query planner. Return zero if this query needs the 6500 ** general-purpose query planner. 6501 */ 6502 static int whereShortCut(WhereLoopBuilder *pBuilder){ 6503 WhereInfo *pWInfo; 6504 SrcItem *pItem; 6505 WhereClause *pWC; 6506 WhereTerm *pTerm; 6507 WhereLoop *pLoop; 6508 int iCur; 6509 int j; 6510 Table *pTab; 6511 Index *pIdx; 6512 WhereScan scan; 6513 6514 pWInfo = pBuilder->pWInfo; 6515 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0; 6516 assert( pWInfo->pTabList->nSrc>=1 ); 6517 pItem = pWInfo->pTabList->a; 6518 pTab = pItem->pSTab; 6519 if( IsVirtual(pTab) ) return 0; 6520 if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){ 6521 testcase( pItem->fg.isIndexedBy ); 6522 testcase( pItem->fg.notIndexed ); 6523 return 0; 6524 } 6525 iCur = pItem->iCursor; 6526 pWC = &pWInfo->sWC; 6527 pLoop = pBuilder->pNew; 6528 pLoop->wsFlags = 0; 6529 pLoop->nSkip = 0; 6530 pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0); 6531 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan); 6532 if( pTerm ){ 6533 testcase( pTerm->eOperator & WO_IS ); 6534 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; 6535 pLoop->aLTerm[0] = pTerm; 6536 pLoop->nLTerm = 1; 6537 pLoop->u.btree.nEq = 1; 6538 /* TUNING: Cost of a rowid lookup is 10 */ 6539 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ 6540 }else{ 6541 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 6542 int opMask; 6543 assert( pLoop->aLTermSpace==pLoop->aLTerm ); 6544 if( !IsUniqueIndex(pIdx) 6545 || pIdx->pPartIdxWhere!=0 6546 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 6547 ) continue; 6548 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ; 6549 for(j=0; jnKeyCol; j++){ 6550 pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx); 6551 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan); 6552 if( pTerm==0 ) break; 6553 testcase( pTerm->eOperator & WO_IS ); 6554 pLoop->aLTerm[j] = pTerm; 6555 } 6556 if( j!=pIdx->nKeyCol ) continue; 6557 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; 6558 if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){ 6559 pLoop->wsFlags |= WHERE_IDX_ONLY; 6560 } 6561 pLoop->nLTerm = j; 6562 pLoop->u.btree.nEq = j; 6563 pLoop->u.btree.pIndex = pIdx; 6564 /* TUNING: Cost of a unique index lookup is 15 */ 6565 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ 6566 break; 6567 } 6568 } 6569 if( pLoop->wsFlags ){ 6570 pLoop->nOut = (LogEst)1; 6571 pWInfo->a[0].pWLoop = pLoop; 6572 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] ); 6573 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */ 6574 pWInfo->a[0].iTabCur = iCur; 6575 pWInfo->nRowOut = 1; 6576 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; 6577 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ 6578 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 6579 } 6580 if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS; 6581 #ifdef SQLITE_DEBUG 6582 pLoop->cId = '0'; 6583 #endif 6584 #ifdef WHERETRACE_ENABLED 6585 if( sqlite3WhereTrace & 0x02 ){ 6586 sqlite3DebugPrintf("whereShortCut() used to compute solution\n"); 6587 } 6588 #endif 6589 return 1; 6590 } 6591 return 0; 6592 } 6593 6594 /* 6595 ** Helper function for exprIsDeterministic(). 6596 */ 6597 static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){ 6598 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){ 6599 pWalker->eCode = 0; 6600 return WRC_Abort; 6601 } 6602 return WRC_Continue; 6603 } 6604 6605 /* 6606 ** Return true if the expression contains no non-deterministic SQL 6607 ** functions. Do not consider non-deterministic SQL functions that are 6608 ** part of sub-select statements. 6609 */ 6610 static int exprIsDeterministic(Expr *p){ 6611 Walker w; 6612 memset(&w, 0, sizeof(w)); 6613 w.eCode = 1; 6614 w.xExprCallback = exprNodeIsDeterministic; 6615 w.xSelectCallback = sqlite3SelectWalkFail; 6616 sqlite3WalkExpr(&w, p); 6617 return w.eCode; 6618 } 6619 6620 6621 #ifdef WHERETRACE_ENABLED 6622 /* 6623 ** Display all WhereLoops in pWInfo 6624 */ 6625 static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){ 6626 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ 6627 WhereLoop *p; 6628 int i; 6629 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" 6630 "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; 6631 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ 6632 p->cId = zLabel[i%(sizeof(zLabel)-1)]; 6633 sqlite3WhereLoopPrint(p, pWC); 6634 } 6635 } 6636 } 6637 # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C) 6638 #else 6639 # define WHERETRACE_ALL_LOOPS(W,C) 6640 #endif 6641 6642 /* Attempt to omit tables from a join that do not affect the result. 6643 ** For a table to not affect the result, the following must be true: 6644 ** 6645 ** 1) The query must not be an aggregate. 6646 ** 2) The table must be the RHS of a LEFT JOIN. 6647 ** 3) Either the query must be DISTINCT, or else the ON or USING clause 6648 ** must contain a constraint that limits the scan of the table to 6649 ** at most a single row. 6650 ** 4) The table must not be referenced by any part of the query apart 6651 ** from its own USING or ON clause. 6652 ** 5) The table must not have an inner-join ON or USING clause if there is 6653 ** a RIGHT JOIN anywhere in the query. Otherwise the ON/USING clause 6654 ** might move from the right side to the left side of the RIGHT JOIN. 6655 ** Note: Due to (2), this condition can only arise if the table is 6656 ** the right-most table of a subquery that was flattened into the 6657 ** main query and that subquery was the right-hand operand of an 6658 ** inner join that held an ON or USING clause. 6659 ** 6) The ORDER BY clause has 63 or fewer terms 6660 ** 7) The omit-noop-join optimization is enabled. 6661 ** 6662 ** Items (1), (6), and (7) are checked by the caller. 6663 ** 6664 ** For example, given: 6665 ** 6666 ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1); 6667 ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2); 6668 ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3); 6669 ** 6670 ** then table t2 can be omitted from the following: 6671 ** 6672 ** SELECT v1, v3 FROM t1 6673 ** LEFT JOIN t2 ON (t1.ipk=t2.ipk) 6674 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) 6675 ** 6676 ** or from: 6677 ** 6678 ** SELECT DISTINCT v1, v3 FROM t1 6679 ** LEFT JOIN t2 6680 ** LEFT JOIN t3 ON (t1.ipk=t3.ipk) 6681 */ 6682 static SQLITE_NOINLINE Bitmask whereOmitNoopJoin( 6683 WhereInfo *pWInfo, 6684 Bitmask notReady 6685 ){ 6686 int i; 6687 Bitmask tabUsed; 6688 int hasRightJoin; 6689 6690 /* Preconditions checked by the caller */ 6691 assert( pWInfo->nLevel>=2 ); 6692 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) ); 6693 6694 /* These two preconditions checked by the caller combine to guarantee 6695 ** condition (1) of the header comment */ 6696 assert( pWInfo->pResultSet!=0 ); 6697 assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) ); 6698 6699 tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet); 6700 if( pWInfo->pOrderBy ){ 6701 tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy); 6702 } 6703 hasRightJoin = (pWInfo->pTabList->a[0].fg.jointype & JT_LTORJ)!=0; 6704 for(i=pWInfo->nLevel-1; i>=1; i--){ 6705 WhereTerm *pTerm, *pEnd; 6706 SrcItem *pItem; 6707 WhereLoop *pLoop; 6708 Bitmask m1; 6709 pLoop = pWInfo->a[i].pWLoop; 6710 pItem = &pWInfo->pTabList->a[pLoop->iTab]; 6711 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue; 6712 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0 6713 && (pLoop->wsFlags & WHERE_ONEROW)==0 6714 ){ 6715 continue; 6716 } 6717 if( (tabUsed & pLoop->maskSelf)!=0 ) continue; 6718 pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm; 6719 for(pTerm=pWInfo->sWC.a; pTermprereqAll & pLoop->maskSelf)!=0 ){ 6721 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON) 6722 || pTerm->pExpr->w.iJoin!=pItem->iCursor 6723 ){ 6724 break; 6725 } 6726 } 6727 if( hasRightJoin 6728 && ExprHasProperty(pTerm->pExpr, EP_InnerON) 6729 && NEVER(pTerm->pExpr->w.iJoin==pItem->iCursor) 6730 ){ 6731 break; /* restriction (5) */ 6732 } 6733 } 6734 if( pTerm omit unused FROM-clause term %c\n",pLoop->cId)); 6736 m1 = MASKBIT(i)-1; 6737 testcase( ((pWInfo->revMask>>1) & ~m1)!=0 ); 6738 pWInfo->revMask = (m1 & pWInfo->revMask) | ((pWInfo->revMask>>1) & ~m1); 6739 notReady &= ~pLoop->maskSelf; 6740 for(pTerm=pWInfo->sWC.a; pTermprereqAll & pLoop->maskSelf)!=0 ){ 6742 pTerm->wtFlags |= TERM_CODED; 6743 pTerm->prereqAll = 0; 6744 } 6745 } 6746 if( i!=pWInfo->nLevel-1 ){ 6747 int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel); 6748 memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte); 6749 } 6750 pWInfo->nLevel--; 6751 assert( pWInfo->nLevel>0 ); 6752 } 6753 return notReady; 6754 } 6755 6756 /* 6757 ** Check to see if there are any SEARCH loops that might benefit from 6758 ** using a Bloom filter. Consider a Bloom filter if: 6759 ** 6760 ** (1) The SEARCH happens more than N times where N is the number 6761 ** of rows in the table that is being considered for the Bloom 6762 ** filter. 6763 ** (2) Some searches are expected to find zero rows. (This is determined 6764 ** by the WHERE_SELFCULL flag on the term.) 6765 ** (3) Bloom-filter processing is not disabled. (Checked by the 6766 ** caller.) 6767 ** (4) The size of the table being searched is known by ANALYZE. 6768 ** 6769 ** This block of code merely checks to see if a Bloom filter would be 6770 ** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the 6771 ** WhereLoop. The implementation of the Bloom filter comes further 6772 ** down where the code for each WhereLoop is generated. 6773 */ 6774 static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful( 6775 const WhereInfo *pWInfo 6776 ){ 6777 int i; 6778 LogEst nSearch = 0; 6779 6780 assert( pWInfo->nLevel>=2 ); 6781 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) ); 6782 for(i=0; inLevel; i++){ 6783 WhereLoop *pLoop = pWInfo->a[i].pWLoop; 6784 const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ); 6785 SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab]; 6786 Table *pTab = pItem->pSTab; 6787 if( (pTab->tabFlags & TF_HasStat1)==0 ) break; 6788 pTab->tabFlags |= TF_MaybeReanalyze; 6789 if( i>=1 6790 && (pLoop->wsFlags & reqFlags)==reqFlags 6791 && sqlite3WhereLoopBloomable(pLoop) 6792 && nSearch > pTab->nRowLogEst 6793 ){ 6794 testcase( pItem->fg.jointype & JT_LEFT ); 6795 pLoop->wsFlags |= WHERE_BLOOMFILTER; 6796 pLoop->wsFlags &= ~WHERE_IDX_ONLY; 6797 WHERETRACE(0xffffffff, ( 6798 "-> use Bloom-filter on loop %c because there are ~%.1e " 6799 "lookups into %s which has only ~%.1e rows\n", 6800 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName, 6801 (double)sqlite3LogEstToInt(pTab->nRowLogEst))); 6802 } 6803 nSearch += pLoop->nOut; 6804 } 6805 } 6806 6807 /* 6808 ** The index pIdx is used by a query and contains one or more expressions. 6809 ** In other words pIdx is an index on an expression. iIdxCur is the cursor 6810 ** number for the index and iDataCur is the cursor number for the corresponding 6811 ** table. 6812 ** 6813 ** This routine adds IndexedExpr entries to the Parse->pIdxEpr field for 6814 ** each of the expressions in the index so that the expression code generator 6815 ** will know to replace occurrences of the indexed expression with 6816 ** references to the corresponding column of the index. 6817 */ 6818 static SQLITE_NOINLINE void whereAddIndexedExpr( 6819 Parse *pParse, /* Add IndexedExpr entries to pParse->pIdxEpr */ 6820 Index *pIdx, /* The index-on-expression that contains the expressions */ 6821 int iIdxCur, /* Cursor number for pIdx */ 6822 SrcItem *pTabItem /* The FROM clause entry for the table */ 6823 ){ 6824 int i; 6825 IndexedExpr *p; 6826 Table *pTab; 6827 assert( pIdx->bHasExpr ); 6828 pTab = pIdx->pTable; 6829 for(i=0; inColumn; i++){ 6830 Expr *pExpr; 6831 int j = pIdx->aiColumn[i]; 6832 if( j==XN_EXPR ){ 6833 pExpr = pIdx->aColExpr->a[i].pExpr; 6834 }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){ 6835 pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]); 6836 }else{ 6837 continue; 6838 } 6839 if( sqlite3ExprIsConstant(0,pExpr) ) continue; 6840 p = sqlite3DbMallocRaw(pParse->db, sizeof(IndexedExpr)); 6841 if( p==0 ) break; 6842 p->pIENext = pParse->pIdxEpr; 6843 #ifdef WHERETRACE_ENABLED 6844 if( sqlite3WhereTrace & 0x200 ){ 6845 sqlite3DebugPrintf("New pParse->pIdxEpr term {%d,%d}\n", iIdxCur, i); 6846 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(pExpr); 6847 } 6848 #endif 6849 p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); 6850 p->iDataCur = pTabItem->iCursor; 6851 p->iIdxCur = iIdxCur; 6852 p->iIdxCol = i; 6853 p->bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0; 6854 if( sqlite3IndexAffinityStr(pParse->db, pIdx) ){ 6855 p->aff = pIdx->zColAff[i]; 6856 } 6857 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 6858 p->zIdxName = pIdx->zName; 6859 #endif 6860 pParse->pIdxEpr = p; 6861 if( p->pIENext==0 ){ 6862 void *pArg = (void*)&pParse->pIdxEpr; 6863 sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pArg); 6864 } 6865 } 6866 } 6867 6868 /* 6869 ** Set the reverse-scan order mask to one for all tables in the query 6870 ** with the exception of MATERIALIZED common table expressions that have 6871 ** their own internal ORDER BY clauses. 6872 ** 6873 ** This implements the PRAGMA reverse_unordered_selects=ON setting. 6874 ** (Also SQLITE_DBCONFIG_REVERSE_SCANORDER). 6875 */ 6876 static SQLITE_NOINLINE void whereReverseScanOrder(WhereInfo *pWInfo){ 6877 int ii; 6878 for(ii=0; iipTabList->nSrc; ii++){ 6879 SrcItem *pItem = &pWInfo->pTabList->a[ii]; 6880 if( !pItem->fg.isCte 6881 || pItem->u2.pCteUse->eM10d!=M10d_Yes 6882 || NEVER(pItem->fg.isSubquery==0) 6883 || pItem->u4.pSubq->pSelect->pOrderBy==0 6884 ){ 6885 pWInfo->revMask |= MASKBIT(ii); 6886 } 6887 } 6888 } 6889 6890 /* 6891 ** Generate the beginning of the loop used for WHERE clause processing. 6892 ** The return value is a pointer to an opaque structure that contains 6893 ** information needed to terminate the loop. Later, the calling routine 6894 ** should invoke sqlite3WhereEnd() with the return value of this function 6895 ** in order to complete the WHERE clause processing. 6896 ** 6897 ** If an error occurs, this routine returns NULL. 6898 ** 6899 ** The basic idea is to do a nested loop, one loop for each table in 6900 ** the FROM clause of a select. (INSERT and UPDATE statements are the 6901 ** same as a SELECT with only a single table in the FROM clause.) For 6902 ** example, if the SQL is this: 6903 ** 6904 ** SELECT * FROM t1, t2, t3 WHERE ...; 6905 ** 6906 ** Then the code generated is conceptually like the following: 6907 ** 6908 ** foreach row1 in t1 do \ Code generated 6909 ** foreach row2 in t2 do |-- by sqlite3WhereBegin() 6910 ** foreach row3 in t3 do / 6911 ** ... 6912 ** end \ Code generated 6913 ** end |-- by sqlite3WhereEnd() 6914 ** end / 6915 ** 6916 ** Note that the loops might not be nested in the order in which they 6917 ** appear in the FROM clause if a different order is better able to make 6918 ** use of indices. Note also that when the IN operator appears in 6919 ** the WHERE clause, it might result in additional nested loops for 6920 ** scanning through all values on the right-hand side of the IN. 6921 ** 6922 ** There are Btree cursors associated with each table. t1 uses cursor 6923 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. 6924 ** And so forth. This routine generates code to open those VDBE cursors 6925 ** and sqlite3WhereEnd() generates the code to close them. 6926 ** 6927 ** The code that sqlite3WhereBegin() generates leaves the cursors named 6928 ** in pTabList pointing at their appropriate entries. The [...] code 6929 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract 6930 ** data from the various tables of the loop. 6931 ** 6932 ** If the WHERE clause is empty, the foreach loops must each scan their 6933 ** entire tables. Thus a three-way join is an O(N^3) operation. But if 6934 ** the tables have indices and there are terms in the WHERE clause that 6935 ** refer to those indices, a complete table scan can be avoided and the 6936 ** code will run much faster. Most of the work of this routine is checking 6937 ** to see if there are indices that can be used to speed up the loop. 6938 ** 6939 ** Terms of the WHERE clause are also used to limit which rows actually 6940 ** make it to the "..." in the middle of the loop. After each "foreach", 6941 ** terms of the WHERE clause that use only terms in that loop and outer 6942 ** loops are evaluated and if false a jump is made around all subsequent 6943 ** inner loops (or around the "..." if the test occurs within the inner- 6944 ** most loop) 6945 ** 6946 ** OUTER JOINS 6947 ** 6948 ** An outer join of tables t1 and t2 is conceptually coded as follows: 6949 ** 6950 ** foreach row1 in t1 do 6951 ** flag = 0 6952 ** foreach row2 in t2 do 6953 ** start: 6954 ** ... 6955 ** flag = 1 6956 ** end 6957 ** if flag==0 then 6958 ** move the row2 cursor to a null row 6959 ** goto start 6960 ** fi 6961 ** end 6962 ** 6963 ** ORDER BY CLAUSE PROCESSING 6964 ** 6965 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause 6966 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement 6967 ** if there is one. If there is no ORDER BY clause or if this routine 6968 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. 6969 ** 6970 ** The iIdxCur parameter is the cursor number of an index. If 6971 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index 6972 ** to use for OR clause processing. The WHERE clause should use this 6973 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is 6974 ** the first cursor in an array of cursors for all indices. iIdxCur should 6975 ** be used to compute the appropriate cursor depending on which index is 6976 ** used. 6977 */ 6978 WhereInfo *sqlite3WhereBegin( 6979 Parse *pParse, /* The parser context */ 6980 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ 6981 Expr *pWhere, /* The WHERE clause */ 6982 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ 6983 ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */ 6984 Select *pSelect, /* The entire SELECT statement */ 6985 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */ 6986 int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number 6987 ** If WHERE_USE_LIMIT, then the limit amount */ 6988 ){ 6989 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ 6990 int nTabList; /* Number of elements in pTabList */ 6991 WhereInfo *pWInfo; /* Will become the return value of this function */ 6992 Vdbe *v = pParse->pVdbe; /* The virtual database engine */ 6993 Bitmask notReady; /* Cursors that are not yet positioned */ 6994 WhereLoopBuilder sWLB; /* The WhereLoop builder */ 6995 WhereMaskSet *pMaskSet; /* The expression mask set */ 6996 WhereLevel *pLevel; /* A single level in pWInfo->a[] */ 6997 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ 6998 int ii; /* Loop counter */ 6999 sqlite3 *db; /* Database connection */ 7000 int rc; /* Return code */ 7001 u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */ 7002 7003 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || ( 7004 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 7005 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 7006 )); 7007 7008 /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */ 7009 assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 7010 || (wctrlFlags & WHERE_USE_LIMIT)==0 ); 7011 7012 /* Variable initialization */ 7013 db = pParse->db; 7014 memset(&sWLB, 0, sizeof(sWLB)); 7015 7016 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ 7017 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); 7018 if( pOrderBy && pOrderBy->nExpr>=BMS ){ 7019 pOrderBy = 0; 7020 wctrlFlags &= ~WHERE_WANT_DISTINCT; 7021 wctrlFlags |= WHERE_KEEP_ALL_JOINS; /* Disable omit-noop-join opt */ 7022 } 7023 7024 /* The number of tables in the FROM clause is limited by the number of 7025 ** bits in a Bitmask 7026 */ 7027 testcase( pTabList->nSrc==BMS ); 7028 if( pTabList->nSrc>BMS ){ 7029 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); 7030 return 0; 7031 } 7032 7033 /* This function normally generates a nested loop for all tables in 7034 ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should 7035 ** only generate code for the first table in pTabList and assume that 7036 ** any cursors associated with subsequent tables are uninitialized. 7037 */ 7038 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc; 7039 7040 /* Allocate and initialize the WhereInfo structure that will become the 7041 ** return value. A single allocation is used to store the WhereInfo 7042 ** struct, the contents of WhereInfo.a[], the WhereClause structure 7043 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte 7044 ** field (type Bitmask) it must be aligned on an 8-byte boundary on 7045 ** some architectures. Hence the ROUND8() below. 7046 */ 7047 nByteWInfo = SZ_WHEREINFO(nTabList); 7048 pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop)); 7049 if( db->mallocFailed ){ 7050 sqlite3DbFree(db, pWInfo); 7051 pWInfo = 0; 7052 goto whereBeginError; 7053 } 7054 pWInfo->pParse = pParse; 7055 pWInfo->pTabList = pTabList; 7056 pWInfo->pOrderBy = pOrderBy; 7057 #if WHERETRACE_ENABLED 7058 pWInfo->pWhere = pWhere; 7059 #endif 7060 pWInfo->pResultSet = pResultSet; 7061 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; 7062 pWInfo->nLevel = nTabList; 7063 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse); 7064 pWInfo->wctrlFlags = wctrlFlags; 7065 pWInfo->iLimit = iAuxArg; 7066 pWInfo->savedNQueryLoop = pParse->nQueryLoop; 7067 pWInfo->pSelect = pSelect; 7068 memset(&pWInfo->nOBSat, 0, 7069 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat)); 7070 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel)); 7071 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */ 7072 pMaskSet = &pWInfo->sMaskSet; 7073 pMaskSet->n = 0; 7074 pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be 7075 ** a valid cursor number, to avoid an initial 7076 ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */ 7077 sWLB.pWInfo = pWInfo; 7078 sWLB.pWC = &pWInfo->sWC; 7079 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); 7080 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); 7081 whereLoopInit(sWLB.pNew); 7082 #ifdef SQLITE_DEBUG 7083 sWLB.pNew->cId = '*'; 7084 #endif 7085 7086 /* Split the WHERE clause into separate subexpressions where each 7087 ** subexpression is separated by an AND operator. 7088 */ 7089 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); 7090 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); 7091 7092 /* Special case: No FROM clause 7093 */ 7094 if( nTabList==0 ){ 7095 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; 7096 if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0 7097 && OptimizationEnabled(db, SQLITE_DistinctOpt) 7098 ){ 7099 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 7100 } 7101 if( ALWAYS(pWInfo->pSelect) 7102 && (pWInfo->pSelect->selFlags & SF_MultiValue)==0 7103 ){ 7104 ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW")); 7105 } 7106 }else{ 7107 /* Assign a bit from the bitmask to every term in the FROM clause. 7108 ** 7109 ** The N-th term of the FROM clause is assigned a bitmask of 1<nSrc tables in 7117 ** pTabList, not just the first nTabList tables. nTabList is normally 7118 ** equal to pTabList->nSrc but might be shortened to 1 if the 7119 ** WHERE_OR_SUBCLAUSE flag is set. 7120 */ 7121 ii = 0; 7122 do{ 7123 createMask(pMaskSet, pTabList->a[ii].iCursor); 7124 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); 7125 }while( (++ii)nSrc ); 7126 #ifdef SQLITE_DEBUG 7127 { 7128 Bitmask mx = 0; 7129 for(ii=0; iinSrc; ii++){ 7130 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); 7131 assert( m>=mx ); 7132 mx = m; 7133 } 7134 } 7135 #endif 7136 } 7137 7138 /* Analyze all of the subexpressions. */ 7139 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); 7140 if( pSelect && pSelect->pLimit ){ 7141 sqlite3WhereAddLimit(&pWInfo->sWC, pSelect); 7142 } 7143 if( pParse->nErr ) goto whereBeginError; 7144 7145 /* The False-WHERE-Term-Bypass optimization: 7146 ** 7147 ** If there are WHERE terms that are false, then no rows will be output, 7148 ** so skip over all of the code generated here. 7149 ** 7150 ** Conditions: 7151 ** 7152 ** (1) The WHERE term must not refer to any tables in the join. 7153 ** (2) The term must not come from an ON clause on the 7154 ** right-hand side of a LEFT or FULL JOIN. 7155 ** (3) The term must not come from an ON clause, or there must be 7156 ** no RIGHT or FULL OUTER joins in pTabList. 7157 ** (4) If the expression contains non-deterministic functions 7158 ** that are not within a sub-select. This is not required 7159 ** for correctness but rather to preserves SQLite's legacy 7160 ** behaviour in the following two cases: 7161 ** 7162 ** WHERE random()>0; -- eval random() once per row 7163 ** WHERE (SELECT random())>0; -- eval random() just once overall 7164 ** 7165 ** Note that the Where term need not be a constant in order for this 7166 ** optimization to apply, though it does need to be constant relative to 7167 ** the current subquery (condition 1). The term might include variables 7168 ** from outer queries so that the value of the term changes from one 7169 ** invocation of the current subquery to the next. 7170 */ 7171 for(ii=0; iinBase; ii++){ 7172 WhereTerm *pT = &sWLB.pWC->a[ii]; /* A term of the WHERE clause */ 7173 Expr *pX; /* The expression of pT */ 7174 if( pT->wtFlags & TERM_VIRTUAL ) continue; 7175 pX = pT->pExpr; 7176 assert( pX!=0 ); 7177 assert( pT->prereqAll!=0 || !ExprHasProperty(pX, EP_OuterON) ); 7178 if( pT->prereqAll==0 /* Conditions (1) and (2) */ 7179 && (nTabList==0 || exprIsDeterministic(pX)) /* Condition (4) */ 7180 && !(ExprHasProperty(pX, EP_InnerON) /* Condition (3) */ 7181 && (pTabList->a[0].fg.jointype & JT_LTORJ)!=0 ) 7182 ){ 7183 sqlite3ExprIfFalse(pParse, pX, pWInfo->iBreak, SQLITE_JUMPIFNULL); 7184 pT->wtFlags |= TERM_CODED; 7185 } 7186 } 7187 7188 if( wctrlFlags & WHERE_WANT_DISTINCT ){ 7189 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ 7190 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via 7191 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ 7192 wctrlFlags &= ~WHERE_WANT_DISTINCT; 7193 pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT; 7194 }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ 7195 /* The DISTINCT marking is pointless. Ignore it. */ 7196 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 7197 }else if( pOrderBy==0 ){ 7198 /* Try to ORDER BY the result set to make distinct processing easier */ 7199 pWInfo->wctrlFlags |= WHERE_DISTINCTBY; 7200 pWInfo->pOrderBy = pResultSet; 7201 } 7202 } 7203 7204 /* Construct the WhereLoop objects */ 7205 #if defined(WHERETRACE_ENABLED) 7206 if( sqlite3WhereTrace & 0xffffffff ){ 7207 sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags); 7208 if( wctrlFlags & WHERE_USE_LIMIT ){ 7209 sqlite3DebugPrintf(", limit: %d", iAuxArg); 7210 } 7211 sqlite3DebugPrintf(")\n"); 7212 if( sqlite3WhereTrace & 0x8000 ){ 7213 Select sSelect; 7214 memset(&sSelect, 0, sizeof(sSelect)); 7215 sSelect.selFlags = SF_WhereBegin; 7216 sSelect.pSrc = pTabList; 7217 sSelect.pWhere = pWhere; 7218 sSelect.pOrderBy = pOrderBy; 7219 sSelect.pEList = pResultSet; 7220 sqlite3TreeViewSelect(0, &sSelect, 0); 7221 } 7222 if( sqlite3WhereTrace & 0x4000 ){ /* Display all WHERE clause terms */ 7223 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n"); 7224 sqlite3WhereClausePrint(sWLB.pWC); 7225 } 7226 } 7227 #endif 7228 7229 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ 7230 rc = whereLoopAddAll(&sWLB); 7231 if( rc ) goto whereBeginError; 7232 7233 #ifdef SQLITE_ENABLE_STAT4 7234 /* If one or more WhereTerm.truthProb values were used in estimating 7235 ** loop parameters, but then those truthProb values were subsequently 7236 ** changed based on STAT4 information while computing subsequent loops, 7237 ** then we need to rerun the whole loop building process so that all 7238 ** loops will be built using the revised truthProb values. */ 7239 if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){ 7240 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC); 7241 WHERETRACE(0xffffffff, 7242 ("**** Redo all loop computations due to" 7243 " TERM_HIGHTRUTH changes ****\n")); 7244 while( pWInfo->pLoops ){ 7245 WhereLoop *p = pWInfo->pLoops; 7246 pWInfo->pLoops = p->pNextLoop; 7247 whereLoopDelete(db, p); 7248 } 7249 rc = whereLoopAddAll(&sWLB); 7250 if( rc ) goto whereBeginError; 7251 } 7252 #endif 7253 WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC); 7254 7255 wherePathSolver(pWInfo, 0); 7256 if( db->mallocFailed ) goto whereBeginError; 7257 if( pWInfo->pOrderBy ){ 7258 whereInterstageHeuristic(pWInfo); 7259 wherePathSolver(pWInfo, pWInfo->nRowOut<0 ? 1 : pWInfo->nRowOut+1); 7260 if( db->mallocFailed ) goto whereBeginError; 7261 } 7262 7263 /* TUNING: Assume that a DISTINCT clause on a subquery reduces 7264 ** the output size by a factor of 8 (LogEst -30). Search for 7265 ** tag-`20250414a` to see other cases. 7266 */ 7267 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){ 7268 WHERETRACE(0x0080,("nRowOut reduced from %d to %d due to DISTINCT\n", 7269 pWInfo->nRowOut, pWInfo->nRowOut-30)); 7270 pWInfo->nRowOut -= 30; 7271 } 7272 7273 } 7274 assert( pWInfo->pTabList!=0 ); 7275 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ 7276 whereReverseScanOrder(pWInfo); 7277 } 7278 if( pParse->nErr ){ 7279 goto whereBeginError; 7280 } 7281 assert( db->mallocFailed==0 ); 7282 #ifdef WHERETRACE_ENABLED 7283 if( sqlite3WhereTrace ){ 7284 sqlite3DebugPrintf("---- Solution cost=%d, nRow=%d", 7285 pWInfo->rTotalCost, pWInfo->nRowOut); 7286 if( pWInfo->nOBSat>0 ){ 7287 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); 7288 } 7289 switch( pWInfo->eDistinct ){ 7290 case WHERE_DISTINCT_UNIQUE: { 7291 sqlite3DebugPrintf(" DISTINCT=unique"); 7292 break; 7293 } 7294 case WHERE_DISTINCT_ORDERED: { 7295 sqlite3DebugPrintf(" DISTINCT=ordered"); 7296 break; 7297 } 7298 case WHERE_DISTINCT_UNORDERED: { 7299 sqlite3DebugPrintf(" DISTINCT=unordered"); 7300 break; 7301 } 7302 } 7303 sqlite3DebugPrintf("\n"); 7304 for(ii=0; iinLevel; ii++){ 7305 sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); 7306 } 7307 } 7308 #endif 7309 7310 /* Attempt to omit tables from a join that do not affect the result. 7311 ** See the comment on whereOmitNoopJoin() for further information. 7312 ** 7313 ** This query optimization is factored out into a separate "no-inline" 7314 ** procedure to keep the sqlite3WhereBegin() procedure from becoming 7315 ** too large. If sqlite3WhereBegin() becomes too large, that prevents 7316 ** some C-compiler optimizers from in-lining the 7317 ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to 7318 ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons. 7319 */ 7320 notReady = ~(Bitmask)0; 7321 if( pWInfo->nLevel>=2 /* Must be a join, or this opt8n is pointless */ 7322 && pResultSet!=0 /* Condition (1) */ 7323 && 0==(wctrlFlags & (WHERE_AGG_DISTINCT|WHERE_KEEP_ALL_JOINS)) /* (1),(6) */ 7324 && OptimizationEnabled(db, SQLITE_OmitNoopJoin) /* (7) */ 7325 ){ 7326 notReady = whereOmitNoopJoin(pWInfo, notReady); 7327 nTabList = pWInfo->nLevel; 7328 assert( nTabList>0 ); 7329 } 7330 7331 /* Check to see if there are any SEARCH loops that might benefit from 7332 ** using a Bloom filter. 7333 */ 7334 if( pWInfo->nLevel>=2 7335 && OptimizationEnabled(db, SQLITE_BloomFilter) 7336 ){ 7337 whereCheckIfBloomFilterIsUseful(pWInfo); 7338 } 7339 7340 #if defined(WHERETRACE_ENABLED) 7341 if( sqlite3WhereTrace & 0x4000 ){ /* Display all terms of the WHERE clause */ 7342 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n"); 7343 sqlite3WhereClausePrint(sWLB.pWC); 7344 } 7345 WHERETRACE(0xffffffff,("*** Optimizer Finished ***\n")); 7346 #endif 7347 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; 7348 7349 /* If the caller is an UPDATE or DELETE statement that is requesting 7350 ** to use a one-pass algorithm, determine if this is appropriate. 7351 ** 7352 ** A one-pass approach can be used if the caller has requested one 7353 ** and either (a) the scan visits at most one row or (b) each 7354 ** of the following are true: 7355 ** 7356 ** * the caller has indicated that a one-pass approach can be used 7357 ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and 7358 ** * the table is not a virtual table, and 7359 ** * either the scan does not use the OR optimization or the caller 7360 ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified 7361 ** for DELETE). 7362 ** 7363 ** The last qualification is because an UPDATE statement uses 7364 ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can 7365 ** use a one-pass approach, and this is not set accurately for scans 7366 ** that use the OR optimization. 7367 */ 7368 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); 7369 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){ 7370 int wsFlags = pWInfo->a[0].pWLoop->wsFlags; 7371 int bOnerow = (wsFlags & WHERE_ONEROW)!=0; 7372 assert( !(wsFlags&WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pSTab) ); 7373 if( bOnerow || ( 7374 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW) 7375 && !IsVirtual(pTabList->a[0].pSTab) 7376 && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK)) 7377 && OptimizationEnabled(db, SQLITE_OnePass) 7378 )){ 7379 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI; 7380 if( HasRowid(pTabList->a[0].pSTab) && (wsFlags & WHERE_IDX_ONLY) ){ 7381 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){ 7382 bFordelete = OPFLAG_FORDELETE; 7383 } 7384 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY); 7385 } 7386 } 7387 } 7388 7389 /* Open all tables in the pTabList and any indices selected for 7390 ** searching those tables. 7391 */ 7392 for(ii=0, pLevel=pWInfo->a; iia[pLevel->iFrom]; 7398 pTab = pTabItem->pSTab; 7399 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 7400 pLoop = pLevel->pWLoop; 7401 pLevel->addrBrk = sqlite3VdbeMakeLabel(pParse); 7402 if( ii==0 || (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ 7403 pLevel->addrHalt = pLevel->addrBrk; 7404 }else if( pWInfo->a[ii-1].pRJ ){ 7405 pLevel->addrHalt = pWInfo->a[ii-1].addrBrk; 7406 }else{ 7407 pLevel->addrHalt = pWInfo->a[ii-1].addrHalt; 7408 } 7409 if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){ 7410 /* Do nothing */ 7411 }else 7412 #ifndef SQLITE_OMIT_VIRTUALTABLE 7413 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 7414 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 7415 int iCur = pTabItem->iCursor; 7416 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); 7417 }else if( IsVirtual(pTab) ){ 7418 /* noop */ 7419 }else 7420 #endif 7421 if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0 7422 && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0) 7423 || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0 7424 ){ 7425 int op = OP_OpenRead; 7426 if( pWInfo->eOnePass!=ONEPASS_OFF ){ 7427 op = OP_OpenWrite; 7428 pWInfo->aiCurOnePass[0] = pTabItem->iCursor; 7429 }; 7430 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); 7431 assert( pTabItem->iCursor==pLevel->iTabCur ); 7432 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 ); 7433 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS ); 7434 if( pWInfo->eOnePass==ONEPASS_OFF 7435 && pTab->nColtabFlags & (TF_HasGenerated|TF_WithoutRowid))==0 7437 && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0 7438 ){ 7439 /* If we know that only a prefix of the record will be used, 7440 ** it is advantageous to reduce the "column count" field in 7441 ** the P4 operand of the OP_OpenRead/Write opcode. */ 7442 Bitmask b = pTabItem->colUsed; 7443 int n = 0; 7444 for(; b; b=b>>1, n++){} 7445 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32); 7446 assert( n<=pTab->nCol ); 7447 } 7448 #ifdef SQLITE_ENABLE_CURSOR_HINTS 7449 if( pLoop->u.btree.pIndex!=0 && (pTab->tabFlags & TF_WithoutRowid)==0 ){ 7450 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); 7451 }else 7452 #endif 7453 { 7454 sqlite3VdbeChangeP5(v, bFordelete); 7455 } 7456 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 7457 sqlite3VdbeAddOp3(v, OP_ColumnsUsed, pTabItem->iCursor, 7458 LOWER32(pTabItem->colUsed), UPPER32(pTabItem->colUsed)); 7459 #endif 7460 if( ii>=2 7461 && (pTabItem[0].fg.jointype & (JT_LTORJ|JT_LEFT))==0 7462 && pLevel->addrHalt==pWInfo->a[0].addrHalt 7463 ){ 7464 sqlite3VdbeAddOp2(v, OP_IfEmpty, pTabItem->iCursor, pWInfo->iBreak); 7465 VdbeCoverage(v); 7466 } 7467 }else{ 7468 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 7469 } 7470 if( pLoop->wsFlags & WHERE_INDEXED ){ 7471 Index *pIx = pLoop->u.btree.pIndex; 7472 int iIndexCur; 7473 int op = OP_OpenRead; 7474 /* iAuxArg is always set to a positive value if ONEPASS is possible */ 7475 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); 7476 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) 7477 && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 7478 ){ 7479 /* This is one term of an OR-optimization using the PRIMARY KEY of a 7480 ** WITHOUT ROWID table. No need for a separate index */ 7481 iIndexCur = pLevel->iTabCur; 7482 op = 0; 7483 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){ 7484 Index *pJ = pTabItem->pSTab->pIndex; 7485 iIndexCur = iAuxArg; 7486 assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); 7487 while( ALWAYS(pJ) && pJ!=pIx ){ 7488 iIndexCur++; 7489 pJ = pJ->pNext; 7490 } 7491 op = OP_OpenWrite; 7492 pWInfo->aiCurOnePass[1] = iIndexCur; 7493 }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){ 7494 iIndexCur = iAuxArg; 7495 op = OP_ReopenIdx; 7496 }else{ 7497 iIndexCur = pParse->nTab++; 7498 if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){ 7499 whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem); 7500 } 7501 if( pIx->pPartIdxWhere && (pTabItem->fg.jointype & JT_RIGHT)==0 ){ 7502 wherePartIdxExpr( 7503 pParse, pIx, pIx->pPartIdxWhere, 0, iIndexCur, pTabItem 7504 ); 7505 } 7506 } 7507 pLevel->iIdxCur = iIndexCur; 7508 assert( pIx!=0 ); 7509 assert( pIx->pSchema==pTab->pSchema ); 7510 assert( iIndexCur>=0 ); 7511 if( op ){ 7512 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); 7513 sqlite3VdbeSetP4KeyInfo(pParse, pIx); 7514 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0 7515 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0 7516 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0 7517 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 7518 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 7519 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED 7520 ){ 7521 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); 7522 } 7523 VdbeComment((v, "%s", pIx->zName)); 7524 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 7525 { 7526 u64 colUsed = 0; 7527 int ii, jj; 7528 for(ii=0; iinColumn; ii++){ 7529 jj = pIx->aiColumn[ii]; 7530 if( jj<0 ) continue; 7531 if( jj>63 ) jj = 63; 7532 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; 7533 colUsed |= ((u64)1)<<(ii<63 ? ii : 63); 7534 } 7535 sqlite3VdbeAddOp3(v, OP_ColumnsUsed, iIndexCur, 7536 LOWER32(colUsed),UPPER32(colUsed)); 7537 } 7538 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ 7539 #ifdef SQLITE_ENABLE_CURSOR_HINTS 7540 if( HasRowid(pTab) ){ 7541 sqlite3VdbeAddOp3(v, OP_CursorHint, iIndexCur, 0, pTabItem->iCursor); 7542 } 7543 #endif 7544 } 7545 } 7546 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); 7547 if( (pTabItem->fg.jointype & JT_RIGHT)!=0 7548 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0 7549 ){ 7550 WhereRightJoin *pRJ = pLevel->pRJ; 7551 int bBloomable = 0; 7552 pRJ->iMatch = pParse->nTab++; 7553 pRJ->regReturn = ++pParse->nMem; 7554 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn); 7555 assert( pTab==pTabItem->pSTab ); 7556 if( HasRowid(pTab) ){ 7557 KeyInfo *pInfo; 7558 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1); 7559 bBloomable = 1; 7560 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0); 7561 if( pInfo ){ 7562 pInfo->aColl[0] = 0; 7563 pInfo->aSortFlags[0] = 0; 7564 sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO); 7565 } 7566 }else{ 7567 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 7568 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol); 7569 sqlite3VdbeSetP4KeyInfo(pParse, pPk); 7570 bBloomable = sqlite3IndexBloomable(pPk,pPk->nKeyCol); 7571 } 7572 if( bBloomable ){ 7573 pRJ->regBloom = ++pParse->nMem; 7574 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom); 7575 }else{ 7576 pRJ->regBloom = 0; 7577 } 7578 pLoop->wsFlags &= ~WHERE_IDX_ONLY; 7579 /* The nature of RIGHT JOIN processing is such that it messes up 7580 ** the output order. So omit any ORDER BY/GROUP BY elimination 7581 ** optimizations. We need to do an actual sort for RIGHT JOIN. */ 7582 pWInfo->nOBSat = 0; 7583 pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED; 7584 } 7585 } 7586 pWInfo->iTop = sqlite3VdbeCurrentAddr(v); 7587 if( db->mallocFailed ) goto whereBeginError; 7588 7589 /* Generate the code to do the search. Each iteration of the for 7590 ** loop below generates code for a single nested loop of the VM 7591 ** program. 7592 */ 7593 for(ii=0; iinErr ) goto whereBeginError; 7598 pLevel = &pWInfo->a[ii]; 7599 wsFlags = pLevel->pWLoop->wsFlags; 7600 pSrc = &pTabList->a[pLevel->iFrom]; 7601 if( pSrc->fg.isMaterialized ){ 7602 Subquery *pSubq; 7603 int iOnce = 0; 7604 assert( pSrc->fg.isSubquery ); 7605 pSubq = pSrc->u4.pSubq; 7606 if( pSrc->fg.isCorrelated==0 ){ 7607 iOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 7608 }else{ 7609 iOnce = 0; 7610 } 7611 sqlite3VdbeAddOp2(v, OP_Gosub, pSubq->regReturn, pSubq->addrFillSub); 7612 VdbeComment((v, "materialize %!S", pSrc)); 7613 if( iOnce ) sqlite3VdbeJumpHere(v, iOnce); 7614 } 7615 assert( pTabList == pWInfo->pTabList ); 7616 if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){ 7617 if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){ 7618 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 7619 constructAutomaticIndex(pParse, &pWInfo->sWC, notReady, pLevel); 7620 #endif 7621 }else{ 7622 sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady); 7623 } 7624 if( db->mallocFailed ) goto whereBeginError; 7625 } 7626 addrExplain = sqlite3WhereExplainOneScan( 7627 pParse, pTabList, pLevel, wctrlFlags 7628 ); 7629 pLevel->addrBody = sqlite3VdbeCurrentAddr(v); 7630 notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady); 7631 pWInfo->iContinue = pLevel->addrCont; 7632 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){ 7633 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); 7634 } 7635 } 7636 7637 /* Done. */ 7638 VdbeModuleComment((v, "Begin WHERE-core")); 7639 pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v); 7640 return pWInfo; 7641 7642 /* Jump here if malloc fails */ 7643 whereBeginError: 7644 if( pWInfo ){ 7645 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 7646 whereInfoFree(db, pWInfo); 7647 } 7648 #ifdef WHERETRACE_ENABLED 7649 /* Prevent harmless compiler warnings about debugging routines 7650 ** being declared but never used */ 7651 sqlite3ShowWhereLoopList(0); 7652 #endif /* WHERETRACE_ENABLED */ 7653 return 0; 7654 } 7655 7656 /* 7657 ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the 7658 ** index rather than the main table. In SQLITE_DEBUG mode, we want 7659 ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine 7660 ** does that. 7661 */ 7662 #ifndef SQLITE_DEBUG 7663 # define OpcodeRewriteTrace(D,K,P) /* no-op */ 7664 #else 7665 # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P) 7666 static void sqlite3WhereOpcodeRewriteTrace( 7667 sqlite3 *db, 7668 int pc, 7669 VdbeOp *pOp 7670 ){ 7671 if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return; 7672 sqlite3VdbePrintOp(0, pc, pOp); 7673 sqlite3ShowWhereTerm(0); /* So compiler won't complain about unused func */ 7674 } 7675 #endif 7676 7677 /* 7678 ** Generate the end of the WHERE loop. See comments on 7679 ** sqlite3WhereBegin() for additional information. 7680 */ 7681 void sqlite3WhereEnd(WhereInfo *pWInfo){ 7682 Parse *pParse = pWInfo->pParse; 7683 Vdbe *v = pParse->pVdbe; 7684 int i; 7685 WhereLevel *pLevel; 7686 WhereLoop *pLoop; 7687 SrcList *pTabList = pWInfo->pTabList; 7688 sqlite3 *db = pParse->db; 7689 int iEnd = sqlite3VdbeCurrentAddr(v); 7690 int nRJ = 0; 7691 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT 7692 int addrSeek = 0; 7693 #endif 7694 7695 /* Generate loop termination code. 7696 */ 7697 VdbeModuleComment((v, "End WHERE-core")); 7698 for(i=pWInfo->nLevel-1; i>=0; i--){ 7699 int addr; 7700 pLevel = &pWInfo->a[i]; 7701 if( pLevel->pRJ ){ 7702 /* Terminate the subroutine that forms the interior of the loop of 7703 ** the RIGHT JOIN table */ 7704 WhereRightJoin *pRJ = pLevel->pRJ; 7705 sqlite3VdbeResolveLabel(v, pLevel->addrCont); 7706 /* Replace addrCont with a new label that will never be used, just so 7707 ** the subsequent call to resolve pLevel->addrCont will have something 7708 ** to resolve. */ 7709 pLevel->addrCont = sqlite3VdbeMakeLabel(pParse); 7710 pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v); 7711 sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1); 7712 VdbeCoverage(v); 7713 nRJ++; 7714 } 7715 pLoop = pLevel->pWLoop; 7716 if( pLevel->op!=OP_Noop ){ 7717 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT 7718 Index *pIdx; 7719 int n; 7720 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED 7721 && i==pWInfo->nLevel-1 /* Ticket [`ef9318757b152e3`] 2017-10-21 */ 7722 && (pLoop->wsFlags & WHERE_INDEXED)!=0 7723 && (pIdx = pLoop->u.btree.pIndex)->hasStat1 7724 && (n = pLoop->u.btree.nDistinctCol)>0 7725 && pIdx->aiRowLogEst[n]>=36 7726 ){ 7727 int r1 = pParse->nMem+1; 7728 int j, op; 7729 int addrIfNull = 0; /* Init to avoid false-positive compiler warning */ 7730 if( pLevel->iLeftJoin ){ 7731 addrIfNull = sqlite3VdbeAddOp2(v, OP_IfNullRow, pLevel->iIdxCur, r1); 7732 } 7733 for(j=0; jiIdxCur, j, r1+j); 7735 } 7736 pParse->nMem += n+1; 7737 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT; 7738 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n); 7739 VdbeCoverageIf(v, op==OP_SeekLT); 7740 VdbeCoverageIf(v, op==OP_SeekGT); 7741 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2); 7742 if( pLevel->iLeftJoin ){ 7743 sqlite3VdbeJumpHere(v, addrIfNull); 7744 } 7745 } 7746 #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */ 7747 } 7748 if( pTabList->a[pLevel->iFrom].fg.fromExists ){ 7749 /* This is an EXISTS-to-JOIN optimization loop. If this loop sees a 7750 ** successful row, it should break out of itself. */ 7751 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); 7752 VdbeComment((v, "EXISTS break %d", i)); 7753 }else if( pLevel->addrDeleteCont ){ 7754 /* An inner loop matched no rows on this auto-index driven loop and 7755 ** there are outer loops. So delete the auto-index entry to avoid 7756 ** future unnecessary work. */ 7757 int iBypass = sqlite3VdbeAddOp0(v, OP_Goto); 7758 assert( pLoop->wsFlags & WHERE_AUTO_INDEX ); 7759 sqlite3VdbeResolveLabel(v, pLevel->addrDeleteCont); 7760 sqlite3VdbeAddOp1(v, OP_Delete, pLevel->iIdxCur); 7761 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); 7762 VdbeComment((v, "delete useless auto-index entry")); 7763 sqlite3VdbeJumpHere(v, iBypass); 7764 } 7765 sqlite3VdbeResolveLabel(v, pLevel->addrCont); 7766 if( pLevel->op!=OP_Noop ){ 7767 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); 7768 sqlite3VdbeChangeP5(v, pLevel->p5); 7769 VdbeCoverage(v); 7770 VdbeCoverageIf(v, pLevel->op==OP_Next); 7771 VdbeCoverageIf(v, pLevel->op==OP_Prev); 7772 VdbeCoverageIf(v, pLevel->op==OP_VNext); 7773 #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT 7774 if( addrSeek ){ 7775 sqlite3VdbeJumpHere(v, addrSeek); 7776 addrSeek = 0; 7777 } 7778 #endif 7779 if( pLevel->regBignull ){ 7780 sqlite3VdbeResolveLabel(v, pLevel->addrBignull); 7781 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1); 7782 VdbeCoverage(v); 7783 } 7784 } 7785 if( pLevel->addrNxt!=pLevel->addrBrk ){ 7786 /* This occurs in three cases - (a) for a LIKE/GLOB scan that must visit 7787 ** ranges of text and blob values separately, and (b) when there is 7788 ** an IN(...) constraint driving the index, and (c) when a prior error 7789 ** such as an OOM has left us in an unusual state. This is asserted() 7790 ** in the next block, inside the #ifndef. */ 7791 sqlite3VdbeResolveLabel(v, pLevel->addrNxt); 7792 } 7793 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 7794 assert( (pLevel->addrNxt==pLevel->addrBrk) 7795 || (pLevel->addrLikeRep) /* (a) */ 7796 || ((pLoop->wsFlags & WHERE_IN_ABLE) && pLevel->u.in.nIn>0) /* (b) */ 7797 || pWInfo->pParse->nErr>0 /* (c) */ 7798 ); 7799 if( pLevel->addrLikeRep ){ 7800 /* The LIKE optimization loop is nested inside any IN(...) and 7801 ** skip-scan loops, so it is closed here, before either of those. */ 7802 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1), 7803 pLevel->addrLikeRep); 7804 VdbeCoverage(v); 7805 } 7806 #endif 7807 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){ 7808 struct InLoop *pIn; 7809 int j; 7810 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ 7811 assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull 7812 || pParse->db->mallocFailed ); 7813 sqlite3VdbeJumpHere(v, pIn->addrInTop+1); 7814 if( pIn->eEndLoopOp!=OP_Noop ){ 7815 if( pIn->nPrefix ){ 7816 int bEarlyOut = 7817 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 7818 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0; 7819 if( pLevel->iLeftJoin ){ 7820 /* For LEFT JOIN queries, cursor pIn->iCur might have been 7821 ** disabled by OP_NullRow. This occurs for WHERE clauses such 7822 ** as "a = ? AND b IN (...)", where the index is on (a, b). 7823 ** When the OP_IfNullRow jump is taken, the pIn->iBase register 7824 ** is NULLed out as a side effect. But as that register is not 7825 ** used when the jump is taken, the side-effect is harmless. */ 7826 sqlite3VdbeAddOp3(v, OP_IfNullRow, pIn->iCur, 7827 sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut, pIn->iBase); 7828 VdbeCoverage(v); 7829 } 7830 if( bEarlyOut ){ 7831 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur, 7832 sqlite3VdbeCurrentAddr(v)+2, 7833 pIn->iBase, pIn->nPrefix); 7834 VdbeCoverage(v); 7835 /* Retarget the OP_IsNull against the left operand of IN so 7836 ** it jumps past the OP_IfNoHope. This is because the 7837 ** OP_IsNull also bypasses the OP_Affinity opcode that is 7838 ** required by OP_IfNoHope. */ 7839 sqlite3VdbeJumpHere(v, pIn->addrInTop+1); 7840 } 7841 } 7842 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); 7843 VdbeCoverage(v); 7844 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev); 7845 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next); 7846 } 7847 sqlite3VdbeJumpHere(v, pIn->addrInTop-1); 7848 } 7849 } 7850 sqlite3VdbeResolveLabel(v, pLevel->addrBrk); 7851 if( pLevel->pRJ ){ 7852 sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1); 7853 VdbeCoverage(v); 7854 } 7855 if( pLevel->addrSkip ){ 7856 sqlite3VdbeGoto(v, pLevel->addrSkip); 7857 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); 7858 sqlite3VdbeJumpHere(v, pLevel->addrSkip); 7859 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); 7860 } 7861 if( pLevel->iLeftJoin ){ 7862 int ws = pLoop->wsFlags; 7863 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); 7864 assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 ); 7865 if( (ws & WHERE_IDX_ONLY)==0 ){ 7866 SrcItem *pSrc = &pTabList->a[pLevel->iFrom]; 7867 assert( pLevel->iTabCur==pSrc->iCursor ); 7868 if( pSrc->fg.viaCoroutine ){ 7869 int m, n; 7870 assert( pSrc->fg.isSubquery ); 7871 n = pSrc->u4.pSubq->regResult; 7872 assert( pSrc->pSTab!=0 ); 7873 m = pSrc->pSTab->nCol; 7874 sqlite3VdbeAddOp3(v, OP_Null, 0, n, n+m-1); 7875 } 7876 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur); 7877 } 7878 if( (ws & WHERE_INDEXED) 7879 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx) 7880 ){ 7881 if( ws & WHERE_MULTI_OR ){ 7882 Index *pIx = pLevel->u.pCoveringIdx; 7883 int iDb = sqlite3SchemaToIndex(db, pIx->pSchema); 7884 sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb); 7885 sqlite3VdbeSetP4KeyInfo(pParse, pIx); 7886 } 7887 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); 7888 } 7889 if( ws & WHERE_IN_ABLE ){ 7890 int m; 7891 for(m=0; mu.in.nIn; m++){ 7892 struct InLoop *pIn = &pLevel->u.in.aInLoop[m]; 7893 if( pIn->eEndLoopOp!=OP_Noop ){ 7894 sqlite3VdbeAddOp1(v, OP_NullRow, pIn->iCur); 7895 } 7896 } 7897 } 7898 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 7899 if( pLevel->addrLikeRep ){ 7900 /* The LIKE loop counter is initialized after the == and IN terms 7901 ** are coded, so a NULL == term or an empty IN list can reach this 7902 ** point without ever setting it. Set it to 0 so that the 7903 ** OP_DecrJumpZero at the bottom of the loop falls through after 7904 ** the NULL row instead of reading an undefined register. */ 7905 sqlite3VdbeAddOp2(v, OP_Integer, 0, (int)(pLevel->iLikeRepCntr>>1)); 7906 } 7907 #endif 7908 if( pLevel->op==OP_Return ){ 7909 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); 7910 }else{ 7911 sqlite3VdbeGoto(v, pLevel->addrFirst); 7912 } 7913 sqlite3VdbeJumpHere(v, addr); 7914 } 7915 VdbeModuleComment((v, "End WHERE-loop%d: %s", i, 7916 pWInfo->pTabList->a[pLevel->iFrom].pSTab->zName)); 7917 } 7918 7919 assert( pWInfo->nLevel<=pTabList->nSrc ); 7920 for(i=0, pLevel=pWInfo->a; inLevel; i++, pLevel++){ 7921 int k, last; 7922 VdbeOp *pOp, *pLastOp; 7923 Index *pIdx = 0; 7924 SrcItem *pTabItem = &pTabList->a[pLevel->iFrom]; 7925 Table *pTab = pTabItem->pSTab; 7926 assert( pTab!=0 ); 7927 pLoop = pLevel->pWLoop; 7928 7929 /* Do RIGHT JOIN processing. Generate code that will output the 7930 ** unmatched rows of the right operand of the RIGHT JOIN with 7931 ** all of the columns of the left operand set to NULL. 7932 */ 7933 if( pLevel->pRJ ){ 7934 sqlite3WhereRightJoinLoop(pWInfo, i, pLevel); 7935 continue; 7936 } 7937 7938 /* For a co-routine, change all OP_Column references to the table of 7939 ** the co-routine into OP_Copy of result contained in a register. 7940 ** OP_Rowid becomes OP_Null. 7941 */ 7942 if( pTabItem->fg.viaCoroutine ){ 7943 testcase( pParse->db->mallocFailed ); 7944 assert( pTabItem->fg.isSubquery ); 7945 assert( pTabItem->u4.pSubq->regResult>=0 ); 7946 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur, 7947 pTabItem->u4.pSubq->regResult, 0); 7948 continue; 7949 } 7950 7951 /* If this scan uses an index, make VDBE code substitutions to read data 7952 ** from the index instead of from the table where possible. In some cases 7953 ** this optimization prevents the table from ever being read, which can 7954 ** yield a significant performance boost. 7955 ** 7956 ** Calls to the code generator in between sqlite3WhereBegin and 7957 ** sqlite3WhereEnd will have created code that references the table 7958 ** directly. This loop scans all that code looking for opcodes 7959 ** that reference the table and converts them into opcodes that 7960 ** reference the index. 7961 */ 7962 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ 7963 pIdx = pLoop->u.btree.pIndex; 7964 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ 7965 pIdx = pLevel->u.pCoveringIdx; 7966 } 7967 if( pIdx 7968 && !db->mallocFailed 7969 ){ 7970 if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){ 7971 last = iEnd; 7972 }else{ 7973 last = pWInfo->iEndWhere; 7974 } 7975 if( pIdx->bHasExpr ){ 7976 IndexedExpr *p = pParse->pIdxEpr; 7977 while( p ){ 7978 if( p->iIdxCur==pLevel->iIdxCur ){ 7979 #ifdef WHERETRACE_ENABLED 7980 if( sqlite3WhereTrace & 0x200 ){ 7981 sqlite3DebugPrintf("Disable pParse->pIdxEpr term {%d,%d}\n", 7982 p->iIdxCur, p->iIdxCol); 7983 if( sqlite3WhereTrace & 0x5000 ) sqlite3ShowExpr(p->pExpr); 7984 } 7985 #endif 7986 p->iDataCur = -1; 7987 p->iIdxCur = -1; 7988 } 7989 p = p->pIENext; 7990 } 7991 } 7992 k = pLevel->addrBody + 1; 7993 #ifdef SQLITE_DEBUG 7994 if( db->flags & SQLITE_VdbeAddopTrace ){ 7995 printf("TRANSLATE cursor %d->%d in opcode range %d..%d\n", 7996 pLevel->iTabCur, pLevel->iIdxCur, k, last-1); 7997 } 7998 /* Proof that the "+1" on the k value above is safe */ 7999 pOp = sqlite3VdbeGetOp(v, k - 1); 8000 assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur ); 8001 assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur ); 8002 assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur ); 8003 #endif 8004 pOp = sqlite3VdbeGetOp(v, k); 8005 pLastOp = pOp + (last - k); 8006 assert( pOp<=pLastOp ); 8007 do{ 8008 if( pOp->p1!=pLevel->iTabCur ){ 8009 /* no-op */ 8010 }else if( pOp->opcode==OP_Column 8011 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 8012 || pOp->opcode==OP_Offset 8013 #endif 8014 ){ 8015 int x = pOp->p2; 8016 assert( pIdx->pTable==pTab ); 8017 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 8018 if( pOp->opcode==OP_Offset ){ 8019 /* Do not need to translate the column number */ 8020 }else 8021 #endif 8022 if( !HasRowid(pTab) ){ 8023 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 8024 x = pPk->aiColumn[x]; 8025 assert( x>=0 ); 8026 }else{ 8027 testcase( x!=sqlite3StorageColumnToTable(pTab,x) ); 8028 x = sqlite3StorageColumnToTable(pTab,x); 8029 } 8030 x = sqlite3TableColumnToIndex(pIdx, x); 8031 if( x>=0 ){ 8032 pOp->p2 = x; 8033 pOp->p1 = pLevel->iIdxCur; 8034 OpcodeRewriteTrace(db, k, pOp); 8035 }else if( pLoop->wsFlags & (WHERE_IDX_ONLY|WHERE_EXPRIDX) ){ 8036 if( pLoop->wsFlags & WHERE_IDX_ONLY ){ 8037 /* An error. pLoop is supposed to be a covering index loop, 8038 ** and yet the VM code refers to a column of the table that 8039 ** is not part of the index. */ 8040 sqlite3ErrorMsg(pParse, "internal query planner error"); 8041 pParse->rc = SQLITE_INTERNAL; 8042 }else{ 8043 /* The WHERE_EXPRIDX flag is set by the planner when it is likely 8044 ** that pLoop is a covering index loop, but it is not possible 8045 ** to be 100% sure. In this case, any OP_Explain opcode 8046 ** corresponding to this loop describes the index as a "COVERING 8047 ** INDEX". But, pOp proves that pLoop is not actually a covering 8048 ** index loop. So clear the WHERE_EXPRIDX flag and rewrite the 8049 ** text that accompanies the OP_Explain opcode, if any. */ 8050 pLoop->wsFlags &= ~WHERE_EXPRIDX; 8051 sqlite3WhereAddExplainText(pParse, 8052 pLevel->addrBody-1, 8053 pTabList, 8054 pLevel, 8055 pWInfo->wctrlFlags 8056 ); 8057 } 8058 } 8059 }else if( pOp->opcode==OP_Rowid ){ 8060 pOp->p1 = pLevel->iIdxCur; 8061 pOp->opcode = OP_IdxRowid; 8062 OpcodeRewriteTrace(db, k, pOp); 8063 }else if( pOp->opcode==OP_IfNullRow ){ 8064 pOp->p1 = pLevel->iIdxCur; 8065 OpcodeRewriteTrace(db, k, pOp); 8066 } 8067 #ifdef SQLITE_DEBUG 8068 k++; 8069 #endif 8070 }while( (++pOp)flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n"); 8073 #endif 8074 } 8075 } 8076 8077 /* The "break" point is here, just past the end of the outer loop. 8078 ** Set it. 8079 */ 8080 sqlite3VdbeResolveLabel(v, pWInfo->iBreak); 8081 8082 /* Final cleanup 8083 */ 8084 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 8085 whereInfoFree(db, pWInfo); 8086 pParse->withinRJSubrtn -= nRJ; 8087 return; 8088 }