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