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( !IsUniqueIndex(pIdx) ) 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 int iCol = p->aiColumn[nEq]; 2051 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER; 2052 CollSeq *pColl; 2053 2054 sqlite3_value *p1 = 0; /* Value extracted from pLower */ 2055 sqlite3_value *p2 = 0; /* Value extracted from pUpper */ 2056 sqlite3_value *pVal = 0; /* Value extracted from record */ 2057 2058 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); 2059 if( pLower ){ 2060 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); 2061 nLower = 0; 2062 } 2063 if( pUpper && rc==SQLITE_OK ){ 2064 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2); 2065 nUpper = p2 ? 0 : p->nSample; 2066 } 2067 2068 if( p1 || p2 ){ 2069 int i; 2070 int nDiff; 2071 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){ 2072 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal); 2073 if( rc==SQLITE_OK && p1 ){ 2074 int res = sqlite3MemCompare(p1, pVal, pColl); 2075 if( res>=0 ) nLower++; 2076 } 2077 if( rc==SQLITE_OK && p2 ){ 2078 int res = sqlite3MemCompare(p2, pVal, pColl); 2079 if( res>=0 ) nUpper++; 2080 } 2081 } 2082 nDiff = (nUpper - nLower); 2083 if( nDiff<=0 ) nDiff = 1; 2084 2085 /* If there is both an upper and lower bound specified, and the 2086 ** comparisons indicate that they are close together, use the fallback 2087 ** method (assume that the scan visits 1/64 of the rows) for estimating 2088 ** the number of rows visited. Otherwise, estimate the number of rows 2089 ** using the method described in the header comment for this function. */ 2090 if( nDiff!=1 || pUpper==0 || pLower==0 ){ 2091 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff)); 2092 pLoop->nOut -= nAdjust; 2093 *pbDone = 1; 2094 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n", 2095 nLower, nUpper, nAdjust*-1, pLoop->nOut)); 2096 } 2097 2098 }else{ 2099 assert( *pbDone==0 ); 2100 } 2101 2102 sqlite3ValueFree(p1); 2103 sqlite3ValueFree(p2); 2104 sqlite3ValueFree(pVal); 2105 2106 return rc; 2107 } 2108 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ 2109 2110 /* 2111 ** This function is used to estimate the number of rows that will be visited 2112 ** by scanning an index for a range of values. The range may have an upper 2113 ** bound, a lower bound, or both. The WHERE clause terms that set the upper 2114 ** and lower bounds are represented by pLower and pUpper respectively. For 2115 ** example, assuming that index p is on t1(a): 2116 ** 2117 ** ... FROM t1 WHERE a > ? AND a < ? ... 2118 ** |_____| |_____| 2119 ** | | 2120 ** pLower pUpper 2121 ** 2122 ** If either of the upper or lower bound is not present, then NULL is passed in 2123 ** place of the corresponding WhereTerm. 2124 ** 2125 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index 2126 ** column subject to the range constraint. Or, equivalently, the number of 2127 ** equality constraints optimized by the proposed index scan. For example, 2128 ** assuming index p is on t1(a, b), and the SQL query is: 2129 ** 2130 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... 2131 ** 2132 ** then nEq is set to 1 (as the range restricted column, b, is the second 2133 ** left-most column of the index). Or, if the query is: 2134 ** 2135 ** ... FROM t1 WHERE a > ? AND a < ? ... 2136 ** 2137 ** then nEq is set to 0. 2138 ** 2139 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the 2140 ** number of rows that the index scan is expected to visit without 2141 ** considering the range constraints. If nEq is 0, this is the number of 2142 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) 2143 ** to account for the range contraints pLower and pUpper. 2144 ** 2145 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be 2146 ** used, a single range inequality reduces the search space by a factor of 4. 2147 ** and a pair of constraints (x>? AND x<?) reduces the expected number of 2148 ** rows visited by a factor of 64. 2149 */ 2150 static int whereRangeScanEst( 2151 Parse *pParse, /* Parsing & code generating context */ 2152 WhereLoopBuilder *pBuilder, 2153 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ 2154 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ 2155 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ 2156 ){ 2157 int rc = SQLITE_OK; 2158 int nOut = pLoop->nOut; 2159 LogEst nNew; 2160 2161 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 2162 Index *p = pLoop->u.btree.pIndex; 2163 int nEq = pLoop->u.btree.nEq; 2164 2165 if( p->nSample>0 2166 && nEq<p->nSampleCol 2167 && OptimizationEnabled(pParse->db, SQLITE_Stat3) 2168 ){ 2169 if( nEq==pBuilder->nRecValid ){ 2170 UnpackedRecord *pRec = pBuilder->pRec; 2171 tRowcnt a[2]; 2172 u8 aff; 2173 2174 /* Variable iLower will be set to the estimate of the number of rows in 2175 ** the index that are less than the lower bound of the range query. The 2176 ** lower bound being the concatenation of $P and $L, where $P is the 2177 ** key-prefix formed by the nEq values matched against the nEq left-most 2178 ** columns of the index, and $L is the value in pLower. 2179 ** 2180 ** Or, if pLower is NULL or $L cannot be extracted from it (because it 2181 ** is not a simple variable or literal value), the lower bound of the 2182 ** range is $P. Due to a quirk in the way whereKeyStats() works, even 2183 ** if $L is available, whereKeyStats() is called for both ($P) and 2184 ** ($P:$L) and the larger of the two returned values used. 2185 ** 2186 ** Similarly, iUpper is to be set to the estimate of the number of rows 2187 ** less than the upper bound of the range query. Where the upper bound 2188 ** is either ($P) or ($P:$U). Again, even if $U is available, both values 2189 ** of iUpper are requested of whereKeyStats() and the smaller used. 2190 */ 2191 tRowcnt iLower; 2192 tRowcnt iUpper; 2193 2194 if( nEq==p->nKeyCol ){ 2195 aff = SQLITE_AFF_INTEGER; 2196 }else{ 2197 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity; 2198 } 2199 /* Determine iLower and iUpper using ($P) only. */ 2200 if( nEq==0 ){ 2201 iLower = 0; 2202 iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]); 2203 }else{ 2204 /* Note: this call could be optimized away - since the same values must 2205 ** have been requested when testing key $P in whereEqualScanEst(). */ 2206 whereKeyStats(pParse, p, pRec, 0, a); 2207 iLower = a[0]; 2208 iUpper = a[0] + a[1]; 2209 } 2210 2211 /* If possible, improve on the iLower estimate using ($P:$L). */ 2212 if( pLower ){ 2213 int bOk; /* True if value is extracted from pExpr */ 2214 Expr *pExpr = pLower->pExpr->pRight; 2215 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 ); 2216 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); 2217 if( rc==SQLITE_OK && bOk ){ 2218 tRowcnt iNew; 2219 whereKeyStats(pParse, p, pRec, 0, a); 2220 iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0); 2221 if( iNew>iLower ) iLower = iNew; 2222 nOut--; 2223 } 2224 } 2225 2226 /* If possible, improve on the iUpper estimate using ($P:$U). */ 2227 if( pUpper ){ 2228 int bOk; /* True if value is extracted from pExpr */ 2229 Expr *pExpr = pUpper->pExpr->pRight; 2230 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); 2231 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); 2232 if( rc==SQLITE_OK && bOk ){ 2233 tRowcnt iNew; 2234 whereKeyStats(pParse, p, pRec, 1, a); 2235 iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0); 2236 if( iNew<iUpper ) iUpper = iNew; 2237 nOut--; 2238 } 2239 } 2240 2241 pBuilder->pRec = pRec; 2242 if( rc==SQLITE_OK ){ 2243 if( iUpper>iLower ){ 2244 nNew = sqlite3LogEst(iUpper - iLower); 2245 }else{ 2246 nNew = 10; assert( 10==sqlite3LogEst(2) ); 2247 } 2248 if( nNew<nOut ){ 2249 nOut = nNew; 2250 } 2251 pLoop->nOut = (LogEst)nOut; 2252 WHERETRACE(0x10, ("range scan regions: %u..%u est=%d\n", 2253 (u32)iLower, (u32)iUpper, nOut)); 2254 return SQLITE_OK; 2255 } 2256 }else{ 2257 int bDone = 0; 2258 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone); 2259 if( bDone ) return rc; 2260 } 2261 } 2262 #else 2263 UNUSED_PARAMETER(pParse); 2264 UNUSED_PARAMETER(pBuilder); 2265 #endif 2266 assert( pLower || pUpper ); 2267 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 ); 2268 nNew = whereRangeAdjust(pLower, nOut); 2269 nNew = whereRangeAdjust(pUpper, nNew); 2270 2271 /* TUNING: If there is both an upper and lower limit, assume the range is 2272 ** reduced by an additional 75%. This means that, by default, an open-ended 2273 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the 2274 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to 2275 ** match 1/64 of the index. */ 2276 if( pLower && pUpper ) nNew -= 20; 2277 2278 nOut -= (pLower!=0) + (pUpper!=0); 2279 if( nNew<10 ) nNew = 10; 2280 if( nNew<nOut ) nOut = nNew; 2281 pLoop->nOut = (LogEst)nOut; 2282 return rc; 2283 } 2284 2285 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 2286 /* 2287 ** Estimate the number of rows that will be returned based on 2288 ** an equality constraint x=VALUE and where that VALUE occurs in 2289 ** the histogram data. This only works when x is the left-most 2290 ** column of an index and sqlite_stat3 histogram data is available 2291 ** for that index. When pExpr==NULL that means the constraint is 2292 ** "x IS NULL" instead of "x=VALUE". 2293 ** 2294 ** Write the estimated row count into *pnRow and return SQLITE_OK. 2295 ** If unable to make an estimate, leave *pnRow unchanged and return 2296 ** non-zero. 2297 ** 2298 ** This routine can fail if it is unable to load a collating sequence 2299 ** required for string comparison, or if unable to allocate memory 2300 ** for a UTF conversion required for comparison. The error is stored 2301 ** in the pParse structure. 2302 */ 2303 static int whereEqualScanEst( 2304 Parse *pParse, /* Parsing & code generating context */ 2305 WhereLoopBuilder *pBuilder, 2306 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */ 2307 tRowcnt *pnRow /* Write the revised row estimate here */ 2308 ){ 2309 Index *p = pBuilder->pNew->u.btree.pIndex; 2310 int nEq = pBuilder->pNew->u.btree.nEq; 2311 UnpackedRecord *pRec = pBuilder->pRec; 2312 u8 aff; /* Column affinity */ 2313 int rc; /* Subfunction return code */ 2314 tRowcnt a[2]; /* Statistics */ 2315 int bOk; 2316 2317 assert( nEq>=1 ); 2318 assert( nEq<=p->nColumn ); 2319 assert( p->aSample!=0 ); 2320 assert( p->nSample>0 ); 2321 assert( pBuilder->nRecValid<nEq ); 2322 2323 /* If values are not available for all fields of the index to the left 2324 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */ 2325 if( pBuilder->nRecValid<(nEq-1) ){ 2326 return SQLITE_NOTFOUND; 2327 } 2328 2329 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() 2330 ** below would return the same value. */ 2331 if( nEq>=p->nColumn ){ 2332 *pnRow = 1; 2333 return SQLITE_OK; 2334 } 2335 2336 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity; 2337 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk); 2338 pBuilder->pRec = pRec; 2339 if( rc!=SQLITE_OK ) return rc; 2340 if( bOk==0 ) return SQLITE_NOTFOUND; 2341 pBuilder->nRecValid = nEq; 2342 2343 whereKeyStats(pParse, p, pRec, 0, a); 2344 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1])); 2345 *pnRow = a[1]; 2346 2347 return rc; 2348 } 2349 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ 2350 2351 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 2352 /* 2353 ** Estimate the number of rows that will be returned based on 2354 ** an IN constraint where the right-hand side of the IN operator 2355 ** is a list of values. Example: 2356 ** 2357 ** WHERE x IN (1,2,3,4) 2358 ** 2359 ** Write the estimated row count into *pnRow and return SQLITE_OK. 2360 ** If unable to make an estimate, leave *pnRow unchanged and return 2361 ** non-zero. 2362 ** 2363 ** This routine can fail if it is unable to load a collating sequence 2364 ** required for string comparison, or if unable to allocate memory 2365 ** for a UTF conversion required for comparison. The error is stored 2366 ** in the pParse structure. 2367 */ 2368 static int whereInScanEst( 2369 Parse *pParse, /* Parsing & code generating context */ 2370 WhereLoopBuilder *pBuilder, 2371 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */ 2372 tRowcnt *pnRow /* Write the revised row estimate here */ 2373 ){ 2374 Index *p = pBuilder->pNew->u.btree.pIndex; 2375 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]); 2376 int nRecValid = pBuilder->nRecValid; 2377 int rc = SQLITE_OK; /* Subfunction return code */ 2378 tRowcnt nEst; /* Number of rows for a single term */ 2379 tRowcnt nRowEst = 0; /* New estimate of the number of rows */ 2380 int i; /* Loop counter */ 2381 2382 assert( p->aSample!=0 ); 2383 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){ 2384 nEst = nRow0; 2385 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst); 2386 nRowEst += nEst; 2387 pBuilder->nRecValid = nRecValid; 2388 } 2389 2390 if( rc==SQLITE_OK ){ 2391 if( nRowEst > nRow0 ) nRowEst = nRow0; 2392 *pnRow = nRowEst; 2393 WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst)); 2394 } 2395 assert( pBuilder->nRecValid==nRecValid ); 2396 return rc; 2397 } 2398 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ 2399 2400 /* 2401 ** Disable a term in the WHERE clause. Except, do not disable the term 2402 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON 2403 ** or USING clause of that join. 2404 ** 2405 ** Consider the term t2.z='ok' in the following queries: 2406 ** 2407 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' 2408 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' 2409 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' 2410 ** 2411 ** The t2.z='ok' is disabled in the in (2) because it originates 2412 ** in the ON clause. The term is disabled in (3) because it is not part 2413 ** of a LEFT OUTER JOIN. In (1), the term is not disabled. 2414 ** 2415 ** Disabling a term causes that term to not be tested in the inner loop 2416 ** of the join. Disabling is an optimization. When terms are satisfied 2417 ** by indices, we disable them to prevent redundant tests in the inner 2418 ** loop. We would get the correct results if nothing were ever disabled, 2419 ** but joins might run a little slower. The trick is to disable as much 2420 ** as we can without disabling too much. If we disabled in (1), we'd get 2421 ** the wrong answer. See ticket #813. 2422 */ 2423 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ 2424 if( pTerm 2425 && (pTerm->wtFlags & TERM_CODED)==0 2426 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 2427 && (pLevel->notReady & pTerm->prereqAll)==0 2428 ){ 2429 pTerm->wtFlags |= TERM_CODED; 2430 if( pTerm->iParent>=0 ){ 2431 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent]; 2432 if( (--pOther->nChild)==0 ){ 2433 disableTerm(pLevel, pOther); 2434 } 2435 } 2436 } 2437 } 2438 2439 /* 2440 ** Code an OP_Affinity opcode to apply the column affinity string zAff 2441 ** to the n registers starting at base. 2442 ** 2443 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the 2444 ** beginning and end of zAff are ignored. If all entries in zAff are 2445 ** SQLITE_AFF_NONE, then no code gets generated. 2446 ** 2447 ** This routine makes its own copy of zAff so that the caller is free 2448 ** to modify zAff after this routine returns. 2449 */ 2450 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ 2451 Vdbe *v = pParse->pVdbe; 2452 if( zAff==0 ){ 2453 assert( pParse->db->mallocFailed ); 2454 return; 2455 } 2456 assert( v!=0 ); 2457 2458 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning 2459 ** and end of the affinity string. 2460 */ 2461 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){ 2462 n--; 2463 base++; 2464 zAff++; 2465 } 2466 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){ 2467 n--; 2468 } 2469 2470 /* Code the OP_Affinity opcode if there is anything left to do. */ 2471 if( n>0 ){ 2472 sqlite3VdbeAddOp2(v, OP_Affinity, base, n); 2473 sqlite3VdbeChangeP4(v, -1, zAff, n); 2474 sqlite3ExprCacheAffinityChange(pParse, base, n); 2475 } 2476 } 2477 2478 2479 /* 2480 ** Generate code for a single equality term of the WHERE clause. An equality 2481 ** term can be either X=expr or X IN (...). pTerm is the term to be 2482 ** coded. 2483 ** 2484 ** The current value for the constraint is left in register iReg. 2485 ** 2486 ** For a constraint of the form X=expr, the expression is evaluated and its 2487 ** result is left on the stack. For constraints of the form X IN (...) 2488 ** this routine sets up a loop that will iterate over all values of X. 2489 */ 2490 static int codeEqualityTerm( 2491 Parse *pParse, /* The parsing context */ 2492 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ 2493 WhereLevel *pLevel, /* The level of the FROM clause we are working on */ 2494 int iEq, /* Index of the equality term within this level */ 2495 int bRev, /* True for reverse-order IN operations */ 2496 int iTarget /* Attempt to leave results in this register */ 2497 ){ 2498 Expr *pX = pTerm->pExpr; 2499 Vdbe *v = pParse->pVdbe; 2500 int iReg; /* Register holding results */ 2501 2502 assert( iTarget>0 ); 2503 if( pX->op==TK_EQ ){ 2504 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); 2505 }else if( pX->op==TK_ISNULL ){ 2506 iReg = iTarget; 2507 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); 2508 #ifndef SQLITE_OMIT_SUBQUERY 2509 }else{ 2510 int eType; 2511 int iTab; 2512 struct InLoop *pIn; 2513 WhereLoop *pLoop = pLevel->pWLoop; 2514 2515 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 2516 && pLoop->u.btree.pIndex!=0 2517 && pLoop->u.btree.pIndex->aSortOrder[iEq] 2518 ){ 2519 testcase( iEq==0 ); 2520 testcase( bRev ); 2521 bRev = !bRev; 2522 } 2523 assert( pX->op==TK_IN ); 2524 iReg = iTarget; 2525 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0); 2526 if( eType==IN_INDEX_INDEX_DESC ){ 2527 testcase( bRev ); 2528 bRev = !bRev; 2529 } 2530 iTab = pX->iTable; 2531 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); 2532 VdbeCoverageIf(v, bRev); 2533 VdbeCoverageIf(v, !bRev); 2534 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); 2535 pLoop->wsFlags |= WHERE_IN_ABLE; 2536 if( pLevel->u.in.nIn==0 ){ 2537 pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 2538 } 2539 pLevel->u.in.nIn++; 2540 pLevel->u.in.aInLoop = 2541 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, 2542 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); 2543 pIn = pLevel->u.in.aInLoop; 2544 if( pIn ){ 2545 pIn += pLevel->u.in.nIn - 1; 2546 pIn->iCur = iTab; 2547 if( eType==IN_INDEX_ROWID ){ 2548 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); 2549 }else{ 2550 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg); 2551 } 2552 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; 2553 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v); 2554 }else{ 2555 pLevel->u.in.nIn = 0; 2556 } 2557 #endif 2558 } 2559 disableTerm(pLevel, pTerm); 2560 return iReg; 2561 } 2562 2563 /* 2564 ** Generate code that will evaluate all == and IN constraints for an 2565 ** index scan. 2566 ** 2567 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). 2568 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 2569 ** The index has as many as three equality constraints, but in this 2570 ** example, the third "c" value is an inequality. So only two 2571 ** constraints are coded. This routine will generate code to evaluate 2572 ** a==5 and b IN (1,2,3). The current values for a and b will be stored 2573 ** in consecutive registers and the index of the first register is returned. 2574 ** 2575 ** In the example above nEq==2. But this subroutine works for any value 2576 ** of nEq including 0. If nEq==0, this routine is nearly a no-op. 2577 ** The only thing it does is allocate the pLevel->iMem memory cell and 2578 ** compute the affinity string. 2579 ** 2580 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints 2581 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is 2582 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that 2583 ** occurs after the nEq quality constraints. 2584 ** 2585 ** This routine allocates a range of nEq+nExtraReg memory cells and returns 2586 ** the index of the first memory cell in that range. The code that 2587 ** calls this routine will use that memory range to store keys for 2588 ** start and termination conditions of the loop. 2589 ** key value of the loop. If one or more IN operators appear, then 2590 ** this routine allocates an additional nEq memory cells for internal 2591 ** use. 2592 ** 2593 ** Before returning, *pzAff is set to point to a buffer containing a 2594 ** copy of the column affinity string of the index allocated using 2595 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated 2596 ** with equality constraints that use NONE affinity are set to 2597 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following: 2598 ** 2599 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); 2600 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; 2601 ** 2602 ** In the example above, the index on t1(a) has TEXT affinity. But since 2603 ** the right hand side of the equality constraint (t2.b) has NONE affinity, 2604 ** no conversion should be attempted before using a t2.b value as part of 2605 ** a key to search the index. Hence the first byte in the returned affinity 2606 ** string in this example would be set to SQLITE_AFF_NONE. 2607 */ 2608 static int codeAllEqualityTerms( 2609 Parse *pParse, /* Parsing context */ 2610 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ 2611 int bRev, /* Reverse the order of IN operators */ 2612 int nExtraReg, /* Number of extra registers to allocate */ 2613 char **pzAff /* OUT: Set to point to affinity string */ 2614 ){ 2615 u16 nEq; /* The number of == or IN constraints to code */ 2616 u16 nSkip; /* Number of left-most columns to skip */ 2617 Vdbe *v = pParse->pVdbe; /* The vm under construction */ 2618 Index *pIdx; /* The index being used for this loop */ 2619 WhereTerm *pTerm; /* A single constraint term */ 2620 WhereLoop *pLoop; /* The WhereLoop object */ 2621 int j; /* Loop counter */ 2622 int regBase; /* Base register */ 2623 int nReg; /* Number of registers to allocate */ 2624 char *zAff; /* Affinity string to return */ 2625 2626 /* This module is only called on query plans that use an index. */ 2627 pLoop = pLevel->pWLoop; 2628 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); 2629 nEq = pLoop->u.btree.nEq; 2630 nSkip = pLoop->u.btree.nSkip; 2631 pIdx = pLoop->u.btree.pIndex; 2632 assert( pIdx!=0 ); 2633 2634 /* Figure out how many memory cells we will need then allocate them. 2635 */ 2636 regBase = pParse->nMem + 1; 2637 nReg = pLoop->u.btree.nEq + nExtraReg; 2638 pParse->nMem += nReg; 2639 2640 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx)); 2641 if( !zAff ){ 2642 pParse->db->mallocFailed = 1; 2643 } 2644 2645 if( nSkip ){ 2646 int iIdxCur = pLevel->iIdxCur; 2647 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); 2648 VdbeCoverageIf(v, bRev==0); 2649 VdbeCoverageIf(v, bRev!=0); 2650 VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); 2651 j = sqlite3VdbeAddOp0(v, OP_Goto); 2652 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), 2653 iIdxCur, 0, regBase, nSkip); 2654 VdbeCoverageIf(v, bRev==0); 2655 VdbeCoverageIf(v, bRev!=0); 2656 sqlite3VdbeJumpHere(v, j); 2657 for(j=0; j<nSkip; j++){ 2658 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); 2659 assert( pIdx->aiColumn[j]>=0 ); 2660 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName)); 2661 } 2662 } 2663 2664 /* Evaluate the equality constraints 2665 */ 2666 assert( zAff==0 || (int)strlen(zAff)>=nEq ); 2667 for(j=nSkip; j<nEq; j++){ 2668 int r1; 2669 pTerm = pLoop->aLTerm[j]; 2670 assert( pTerm!=0 ); 2671 /* The following testcase is true for indices with redundant columns. 2672 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ 2673 testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); 2674 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 2675 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); 2676 if( r1!=regBase+j ){ 2677 if( nReg==1 ){ 2678 sqlite3ReleaseTempReg(pParse, regBase); 2679 regBase = r1; 2680 }else{ 2681 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); 2682 } 2683 } 2684 testcase( pTerm->eOperator & WO_ISNULL ); 2685 testcase( pTerm->eOperator & WO_IN ); 2686 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ 2687 Expr *pRight = pTerm->pExpr->pRight; 2688 if( sqlite3ExprCanBeNull(pRight) ){ 2689 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); 2690 VdbeCoverage(v); 2691 } 2692 if( zAff ){ 2693 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){ 2694 zAff[j] = SQLITE_AFF_NONE; 2695 } 2696 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ 2697 zAff[j] = SQLITE_AFF_NONE; 2698 } 2699 } 2700 } 2701 } 2702 *pzAff = zAff; 2703 return regBase; 2704 } 2705 2706 #ifndef SQLITE_OMIT_EXPLAIN 2707 /* 2708 ** This routine is a helper for explainIndexRange() below 2709 ** 2710 ** pStr holds the text of an expression that we are building up one term 2711 ** at a time. This routine adds a new term to the end of the expression. 2712 ** Terms are separated by AND so add the "AND" text for second and subsequent 2713 ** terms only. 2714 */ 2715 static void explainAppendTerm( 2716 StrAccum *pStr, /* The text expression being built */ 2717 int iTerm, /* Index of this term. First is zero */ 2718 const char *zColumn, /* Name of the column */ 2719 const char *zOp /* Name of the operator */ 2720 ){ 2721 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5); 2722 sqlite3StrAccumAppendAll(pStr, zColumn); 2723 sqlite3StrAccumAppend(pStr, zOp, 1); 2724 sqlite3StrAccumAppend(pStr, "?", 1); 2725 } 2726 2727 /* 2728 ** Argument pLevel describes a strategy for scanning table pTab. This 2729 ** function returns a pointer to a string buffer containing a description 2730 ** of the subset of table rows scanned by the strategy in the form of an 2731 ** SQL expression. Or, if all rows are scanned, NULL is returned. 2732 ** 2733 ** For example, if the query: 2734 ** 2735 ** SELECT * FROM t1 WHERE a=1 AND b>2; 2736 ** 2737 ** is run and there is an index on (a, b), then this function returns a 2738 ** string similar to: 2739 ** 2740 ** "a=? AND b>?" 2741 ** 2742 ** The returned pointer points to memory obtained from sqlite3DbMalloc(). 2743 ** It is the responsibility of the caller to free the buffer when it is 2744 ** no longer required. 2745 */ 2746 static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){ 2747 Index *pIndex = pLoop->u.btree.pIndex; 2748 u16 nEq = pLoop->u.btree.nEq; 2749 u16 nSkip = pLoop->u.btree.nSkip; 2750 int i, j; 2751 Column *aCol = pTab->aCol; 2752 i16 *aiColumn = pIndex->aiColumn; 2753 StrAccum txt; 2754 2755 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){ 2756 return 0; 2757 } 2758 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH); 2759 txt.db = db; 2760 sqlite3StrAccumAppend(&txt, " (", 2); 2761 for(i=0; i<nEq; i++){ 2762 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName; 2763 if( i>=nSkip ){ 2764 explainAppendTerm(&txt, i, z, "="); 2765 }else{ 2766 if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5); 2767 sqlite3StrAccumAppend(&txt, "ANY(", 4); 2768 sqlite3StrAccumAppendAll(&txt, z); 2769 sqlite3StrAccumAppend(&txt, ")", 1); 2770 } 2771 } 2772 2773 j = i; 2774 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ 2775 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName; 2776 explainAppendTerm(&txt, i++, z, ">"); 2777 } 2778 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ 2779 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName; 2780 explainAppendTerm(&txt, i, z, "<"); 2781 } 2782 sqlite3StrAccumAppend(&txt, ")", 1); 2783 return sqlite3StrAccumFinish(&txt); 2784 } 2785 2786 /* 2787 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN 2788 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single 2789 ** record is added to the output to describe the table scan strategy in 2790 ** pLevel. 2791 */ 2792 static void explainOneScan( 2793 Parse *pParse, /* Parse context */ 2794 SrcList *pTabList, /* Table list this loop refers to */ 2795 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ 2796 int iLevel, /* Value for "level" column of output */ 2797 int iFrom, /* Value for "from" column of output */ 2798 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ 2799 ){ 2800 #ifndef SQLITE_DEBUG 2801 if( pParse->explain==2 ) 2802 #endif 2803 { 2804 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; 2805 Vdbe *v = pParse->pVdbe; /* VM being constructed */ 2806 sqlite3 *db = pParse->db; /* Database handle */ 2807 char *zMsg; /* Text to add to EQP output */ 2808 int iId = pParse->iSelectId; /* Select id (left-most output column) */ 2809 int isSearch; /* True for a SEARCH. False for SCAN. */ 2810 WhereLoop *pLoop; /* The controlling WhereLoop object */ 2811 u32 flags; /* Flags that describe this loop */ 2812 2813 pLoop = pLevel->pWLoop; 2814 flags = pLoop->wsFlags; 2815 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return; 2816 2817 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 2818 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) 2819 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); 2820 2821 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN"); 2822 if( pItem->pSelect ){ 2823 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId); 2824 }else{ 2825 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName); 2826 } 2827 2828 if( pItem->zAlias ){ 2829 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias); 2830 } 2831 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 2832 && ALWAYS(pLoop->u.btree.pIndex!=0) 2833 ){ 2834 const char *zFmt; 2835 Index *pIdx = pLoop->u.btree.pIndex; 2836 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab); 2837 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); 2838 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ 2839 zFmt = zWhere ? "%s USING PRIMARY KEY%.0s%s" : "%s%.0s%s"; 2840 }else if( flags & WHERE_AUTO_INDEX ){ 2841 zFmt = "%s USING AUTOMATIC COVERING INDEX%.0s%s"; 2842 }else if( flags & WHERE_IDX_ONLY ){ 2843 zFmt = "%s USING COVERING INDEX %s%s"; 2844 }else{ 2845 zFmt = "%s USING INDEX %s%s"; 2846 } 2847 zMsg = sqlite3MAppendf(db, zMsg, zFmt, zMsg, pIdx->zName, zWhere); 2848 sqlite3DbFree(db, zWhere); 2849 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ 2850 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg); 2851 2852 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ 2853 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg); 2854 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ 2855 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg); 2856 }else if( flags&WHERE_BTM_LIMIT ){ 2857 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg); 2858 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){ 2859 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg); 2860 } 2861 } 2862 #ifndef SQLITE_OMIT_VIRTUALTABLE 2863 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ 2864 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg, 2865 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); 2866 } 2867 #endif 2868 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg); 2869 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC); 2870 } 2871 } 2872 #else 2873 # define explainOneScan(u,v,w,x,y,z) 2874 #endif /* SQLITE_OMIT_EXPLAIN */ 2875 2876 2877 /* 2878 ** Generate code for the start of the iLevel-th loop in the WHERE clause 2879 ** implementation described by pWInfo. 2880 */ 2881 static Bitmask codeOneLoopStart( 2882 WhereInfo *pWInfo, /* Complete information about the WHERE clause */ 2883 int iLevel, /* Which level of pWInfo->a[] should be coded */ 2884 Bitmask notReady /* Which tables are currently available */ 2885 ){ 2886 int j, k; /* Loop counters */ 2887 int iCur; /* The VDBE cursor for the table */ 2888 int addrNxt; /* Where to jump to continue with the next IN case */ 2889 int omitTable; /* True if we use the index only */ 2890 int bRev; /* True if we need to scan in reverse order */ 2891 WhereLevel *pLevel; /* The where level to be coded */ 2892 WhereLoop *pLoop; /* The WhereLoop object being coded */ 2893 WhereClause *pWC; /* Decomposition of the entire WHERE clause */ 2894 WhereTerm *pTerm; /* A WHERE clause term */ 2895 Parse *pParse; /* Parsing context */ 2896 sqlite3 *db; /* Database connection */ 2897 Vdbe *v; /* The prepared stmt under constructions */ 2898 struct SrcList_item *pTabItem; /* FROM clause term being coded */ 2899 int addrBrk; /* Jump here to break out of the loop */ 2900 int addrCont; /* Jump here to continue with next cycle */ 2901 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ 2902 int iReleaseReg = 0; /* Temp register to free before returning */ 2903 2904 pParse = pWInfo->pParse; 2905 v = pParse->pVdbe; 2906 pWC = &pWInfo->sWC; 2907 db = pParse->db; 2908 pLevel = &pWInfo->a[iLevel]; 2909 pLoop = pLevel->pWLoop; 2910 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 2911 iCur = pTabItem->iCursor; 2912 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur); 2913 bRev = (pWInfo->revMask>>iLevel)&1; 2914 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 2915 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0; 2916 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); 2917 2918 /* Create labels for the "break" and "continue" instructions 2919 ** for the current loop. Jump to addrBrk to break out of a loop. 2920 ** Jump to cont to go immediately to the next iteration of the 2921 ** loop. 2922 ** 2923 ** When there is an IN operator, we also have a "addrNxt" label that 2924 ** means to continue with the next IN value combination. When 2925 ** there are no IN operators in the constraints, the "addrNxt" label 2926 ** is the same as "addrBrk". 2927 */ 2928 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 2929 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); 2930 2931 /* If this is the right table of a LEFT OUTER JOIN, allocate and 2932 ** initialize a memory cell that records if this table matches any 2933 ** row of the left table of the join. 2934 */ 2935 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ 2936 pLevel->iLeftJoin = ++pParse->nMem; 2937 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); 2938 VdbeComment((v, "init LEFT JOIN no-match flag")); 2939 } 2940 2941 /* Special case of a FROM clause subquery implemented as a co-routine */ 2942 if( pTabItem->viaCoroutine ){ 2943 int regYield = pTabItem->regReturn; 2944 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); 2945 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); 2946 VdbeCoverage(v); 2947 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); 2948 pLevel->op = OP_Goto; 2949 }else 2950 2951 #ifndef SQLITE_OMIT_VIRTUALTABLE 2952 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 2953 /* Case 1: The table is a virtual-table. Use the VFilter and VNext 2954 ** to access the data. 2955 */ 2956 int iReg; /* P3 Value for OP_VFilter */ 2957 int addrNotFound; 2958 int nConstraint = pLoop->nLTerm; 2959 2960 sqlite3ExprCachePush(pParse); 2961 iReg = sqlite3GetTempRange(pParse, nConstraint+2); 2962 addrNotFound = pLevel->addrBrk; 2963 for(j=0; j<nConstraint; j++){ 2964 int iTarget = iReg+j+2; 2965 pTerm = pLoop->aLTerm[j]; 2966 if( pTerm==0 ) continue; 2967 if( pTerm->eOperator & WO_IN ){ 2968 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); 2969 addrNotFound = pLevel->addrNxt; 2970 }else{ 2971 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget); 2972 } 2973 } 2974 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); 2975 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); 2976 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, 2977 pLoop->u.vtab.idxStr, 2978 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); 2979 VdbeCoverage(v); 2980 pLoop->u.vtab.needFree = 0; 2981 for(j=0; j<nConstraint && j<16; j++){ 2982 if( (pLoop->u.vtab.omitMask>>j)&1 ){ 2983 disableTerm(pLevel, pLoop->aLTerm[j]); 2984 } 2985 } 2986 pLevel->op = OP_VNext; 2987 pLevel->p1 = iCur; 2988 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 2989 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); 2990 sqlite3ExprCachePop(pParse); 2991 }else 2992 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 2993 2994 if( (pLoop->wsFlags & WHERE_IPK)!=0 2995 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 2996 ){ 2997 /* Case 2: We can directly reference a single row using an 2998 ** equality comparison against the ROWID field. Or 2999 ** we reference multiple rows using a "rowid IN (...)" 3000 ** construct. 3001 */ 3002 assert( pLoop->u.btree.nEq==1 ); 3003 pTerm = pLoop->aLTerm[0]; 3004 assert( pTerm!=0 ); 3005 assert( pTerm->pExpr!=0 ); 3006 assert( omitTable==0 ); 3007 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 3008 iReleaseReg = ++pParse->nMem; 3009 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); 3010 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); 3011 addrNxt = pLevel->addrNxt; 3012 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v); 3013 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg); 3014 VdbeCoverage(v); 3015 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); 3016 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 3017 VdbeComment((v, "pk")); 3018 pLevel->op = OP_Noop; 3019 }else if( (pLoop->wsFlags & WHERE_IPK)!=0 3020 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 3021 ){ 3022 /* Case 3: We have an inequality comparison against the ROWID field. 3023 */ 3024 int testOp = OP_Noop; 3025 int start; 3026 int memEndValue = 0; 3027 WhereTerm *pStart, *pEnd; 3028 3029 assert( omitTable==0 ); 3030 j = 0; 3031 pStart = pEnd = 0; 3032 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; 3033 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; 3034 assert( pStart!=0 || pEnd!=0 ); 3035 if( bRev ){ 3036 pTerm = pStart; 3037 pStart = pEnd; 3038 pEnd = pTerm; 3039 } 3040 if( pStart ){ 3041 Expr *pX; /* The expression that defines the start bound */ 3042 int r1, rTemp; /* Registers for holding the start boundary */ 3043 3044 /* The following constant maps TK_xx codes into corresponding 3045 ** seek opcodes. It depends on a particular ordering of TK_xx 3046 */ 3047 const u8 aMoveOp[] = { 3048 /* TK_GT */ OP_SeekGT, 3049 /* TK_LE */ OP_SeekLE, 3050 /* TK_LT */ OP_SeekLT, 3051 /* TK_GE */ OP_SeekGE 3052 }; 3053 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ 3054 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ 3055 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ 3056 3057 assert( (pStart->wtFlags & TERM_VNULL)==0 ); 3058 testcase( pStart->wtFlags & TERM_VIRTUAL ); 3059 pX = pStart->pExpr; 3060 assert( pX!=0 ); 3061 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ 3062 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); 3063 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1); 3064 VdbeComment((v, "pk")); 3065 VdbeCoverageIf(v, pX->op==TK_GT); 3066 VdbeCoverageIf(v, pX->op==TK_LE); 3067 VdbeCoverageIf(v, pX->op==TK_LT); 3068 VdbeCoverageIf(v, pX->op==TK_GE); 3069 sqlite3ExprCacheAffinityChange(pParse, r1, 1); 3070 sqlite3ReleaseTempReg(pParse, rTemp); 3071 disableTerm(pLevel, pStart); 3072 }else{ 3073 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); 3074 VdbeCoverageIf(v, bRev==0); 3075 VdbeCoverageIf(v, bRev!=0); 3076 } 3077 if( pEnd ){ 3078 Expr *pX; 3079 pX = pEnd->pExpr; 3080 assert( pX!=0 ); 3081 assert( (pEnd->wtFlags & TERM_VNULL)==0 ); 3082 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ 3083 testcase( pEnd->wtFlags & TERM_VIRTUAL ); 3084 memEndValue = ++pParse->nMem; 3085 sqlite3ExprCode(pParse, pX->pRight, memEndValue); 3086 if( pX->op==TK_LT || pX->op==TK_GT ){ 3087 testOp = bRev ? OP_Le : OP_Ge; 3088 }else{ 3089 testOp = bRev ? OP_Lt : OP_Gt; 3090 } 3091 disableTerm(pLevel, pEnd); 3092 } 3093 start = sqlite3VdbeCurrentAddr(v); 3094 pLevel->op = bRev ? OP_Prev : OP_Next; 3095 pLevel->p1 = iCur; 3096 pLevel->p2 = start; 3097 assert( pLevel->p5==0 ); 3098 if( testOp!=OP_Noop ){ 3099 iRowidReg = ++pParse->nMem; 3100 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); 3101 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 3102 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); 3103 VdbeCoverageIf(v, testOp==OP_Le); 3104 VdbeCoverageIf(v, testOp==OP_Lt); 3105 VdbeCoverageIf(v, testOp==OP_Ge); 3106 VdbeCoverageIf(v, testOp==OP_Gt); 3107 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); 3108 } 3109 }else if( pLoop->wsFlags & WHERE_INDEXED ){ 3110 /* Case 4: A scan using an index. 3111 ** 3112 ** The WHERE clause may contain zero or more equality 3113 ** terms ("==" or "IN" operators) that refer to the N 3114 ** left-most columns of the index. It may also contain 3115 ** inequality constraints (>, <, >= or <=) on the indexed 3116 ** column that immediately follows the N equalities. Only 3117 ** the right-most column can be an inequality - the rest must 3118 ** use the "==" and "IN" operators. For example, if the 3119 ** index is on (x,y,z), then the following clauses are all 3120 ** optimized: 3121 ** 3122 ** x=5 3123 ** x=5 AND y=10 3124 ** x=5 AND y<10 3125 ** x=5 AND y>5 AND y<10 3126 ** x=5 AND y=5 AND z<=10 3127 ** 3128 ** The z<10 term of the following cannot be used, only 3129 ** the x=5 term: 3130 ** 3131 ** x=5 AND z<10 3132 ** 3133 ** N may be zero if there are inequality constraints. 3134 ** If there are no inequality constraints, then N is at 3135 ** least one. 3136 ** 3137 ** This case is also used when there are no WHERE clause 3138 ** constraints but an index is selected anyway, in order 3139 ** to force the output order to conform to an ORDER BY. 3140 */ 3141 static const u8 aStartOp[] = { 3142 0, 3143 0, 3144 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ 3145 OP_Last, /* 3: (!start_constraints && startEq && bRev) */ 3146 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ 3147 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ 3148 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ 3149 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ 3150 }; 3151 static const u8 aEndOp[] = { 3152 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ 3153 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ 3154 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ 3155 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ 3156 }; 3157 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ 3158 int regBase; /* Base register holding constraint values */ 3159 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ 3160 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ 3161 int startEq; /* True if range start uses ==, >= or <= */ 3162 int endEq; /* True if range end uses ==, >= or <= */ 3163 int start_constraints; /* Start of range is constrained */ 3164 int nConstraint; /* Number of constraint terms */ 3165 Index *pIdx; /* The index we will be using */ 3166 int iIdxCur; /* The VDBE cursor for the index */ 3167 int nExtraReg = 0; /* Number of extra registers needed */ 3168 int op; /* Instruction opcode */ 3169 char *zStartAff; /* Affinity for start of range constraint */ 3170 char cEndAff = 0; /* Affinity for end of range constraint */ 3171 u8 bSeekPastNull = 0; /* True to seek past initial nulls */ 3172 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ 3173 3174 pIdx = pLoop->u.btree.pIndex; 3175 iIdxCur = pLevel->iIdxCur; 3176 assert( nEq>=pLoop->u.btree.nSkip ); 3177 3178 /* If this loop satisfies a sort order (pOrderBy) request that 3179 ** was passed to this function to implement a "SELECT min(x) ..." 3180 ** query, then the caller will only allow the loop to run for 3181 ** a single iteration. This means that the first row returned 3182 ** should not have a NULL value stored in 'x'. If column 'x' is 3183 ** the first one after the nEq equality constraints in the index, 3184 ** this requires some special handling. 3185 */ 3186 assert( pWInfo->pOrderBy==0 3187 || pWInfo->pOrderBy->nExpr==1 3188 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); 3189 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 3190 && pWInfo->nOBSat>0 3191 && (pIdx->nKeyCol>nEq) 3192 ){ 3193 assert( pLoop->u.btree.nSkip==0 ); 3194 bSeekPastNull = 1; 3195 nExtraReg = 1; 3196 } 3197 3198 /* Find any inequality constraint terms for the start and end 3199 ** of the range. 3200 */ 3201 j = nEq; 3202 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ 3203 pRangeStart = pLoop->aLTerm[j++]; 3204 nExtraReg = 1; 3205 } 3206 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ 3207 pRangeEnd = pLoop->aLTerm[j++]; 3208 nExtraReg = 1; 3209 if( pRangeStart==0 3210 && (j = pIdx->aiColumn[nEq])>=0 3211 && pIdx->pTable->aCol[j].notNull==0 3212 ){ 3213 bSeekPastNull = 1; 3214 } 3215 } 3216 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); 3217 3218 /* Generate code to evaluate all constraint terms using == or IN 3219 ** and store the values of those terms in an array of registers 3220 ** starting at regBase. 3221 */ 3222 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); 3223 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); 3224 if( zStartAff ) cEndAff = zStartAff[nEq]; 3225 addrNxt = pLevel->addrNxt; 3226 3227 /* If we are doing a reverse order scan on an ascending index, or 3228 ** a forward order scan on a descending index, interchange the 3229 ** start and end terms (pRangeStart and pRangeEnd). 3230 */ 3231 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) 3232 || (bRev && pIdx->nKeyCol==nEq) 3233 ){ 3234 SWAP(WhereTerm *, pRangeEnd, pRangeStart); 3235 SWAP(u8, bSeekPastNull, bStopAtNull); 3236 } 3237 3238 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); 3239 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); 3240 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); 3241 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); 3242 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); 3243 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); 3244 start_constraints = pRangeStart || nEq>0; 3245 3246 /* Seek the index cursor to the start of the range. */ 3247 nConstraint = nEq; 3248 if( pRangeStart ){ 3249 Expr *pRight = pRangeStart->pExpr->pRight; 3250 sqlite3ExprCode(pParse, pRight, regBase+nEq); 3251 if( (pRangeStart->wtFlags & TERM_VNULL)==0 3252 && sqlite3ExprCanBeNull(pRight) 3253 ){ 3254 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 3255 VdbeCoverage(v); 3256 } 3257 if( zStartAff ){ 3258 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){ 3259 /* Since the comparison is to be performed with no conversions 3260 ** applied to the operands, set the affinity to apply to pRight to 3261 ** SQLITE_AFF_NONE. */ 3262 zStartAff[nEq] = SQLITE_AFF_NONE; 3263 } 3264 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ 3265 zStartAff[nEq] = SQLITE_AFF_NONE; 3266 } 3267 } 3268 nConstraint++; 3269 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); 3270 }else if( bSeekPastNull ){ 3271 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 3272 nConstraint++; 3273 startEq = 0; 3274 start_constraints = 1; 3275 } 3276 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); 3277 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; 3278 assert( op!=0 ); 3279 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 3280 VdbeCoverage(v); 3281 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 3282 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 3283 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); 3284 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 3285 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 3286 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); 3287 3288 /* Load the value for the inequality constraint at the end of the 3289 ** range (if any). 3290 */ 3291 nConstraint = nEq; 3292 if( pRangeEnd ){ 3293 Expr *pRight = pRangeEnd->pExpr->pRight; 3294 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); 3295 sqlite3ExprCode(pParse, pRight, regBase+nEq); 3296 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 3297 && sqlite3ExprCanBeNull(pRight) 3298 ){ 3299 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 3300 VdbeCoverage(v); 3301 } 3302 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE 3303 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff) 3304 ){ 3305 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff); 3306 } 3307 nConstraint++; 3308 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); 3309 }else if( bStopAtNull ){ 3310 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 3311 endEq = 0; 3312 nConstraint++; 3313 } 3314 sqlite3DbFree(db, zStartAff); 3315 3316 /* Top of the loop body */ 3317 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 3318 3319 /* Check if the index cursor is past the end of the range. */ 3320 if( nConstraint ){ 3321 op = aEndOp[bRev*2 + endEq]; 3322 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 3323 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 3324 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 3325 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 3326 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 3327 } 3328 3329 /* Seek the table cursor, if required */ 3330 disableTerm(pLevel, pRangeStart); 3331 disableTerm(pLevel, pRangeEnd); 3332 if( omitTable ){ 3333 /* pIdx is a covering index. No need to access the main table. */ 3334 }else if( HasRowid(pIdx->pTable) ){ 3335 iRowidReg = ++pParse->nMem; 3336 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); 3337 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 3338 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */ 3339 }else if( iCur!=iIdxCur ){ 3340 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); 3341 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); 3342 for(j=0; j<pPk->nKeyCol; j++){ 3343 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); 3344 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); 3345 } 3346 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, 3347 iRowidReg, pPk->nKeyCol); VdbeCoverage(v); 3348 } 3349 3350 /* Record the instruction used to terminate the loop. Disable 3351 ** WHERE clause terms made redundant by the index range scan. 3352 */ 3353 if( pLoop->wsFlags & WHERE_ONEROW ){ 3354 pLevel->op = OP_Noop; 3355 }else if( bRev ){ 3356 pLevel->op = OP_Prev; 3357 }else{ 3358 pLevel->op = OP_Next; 3359 } 3360 pLevel->p1 = iIdxCur; 3361 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; 3362 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ 3363 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 3364 }else{ 3365 assert( pLevel->p5==0 ); 3366 } 3367 }else 3368 3369 #ifndef SQLITE_OMIT_OR_OPTIMIZATION 3370 if( pLoop->wsFlags & WHERE_MULTI_OR ){ 3371 /* Case 5: Two or more separately indexed terms connected by OR 3372 ** 3373 ** Example: 3374 ** 3375 ** CREATE TABLE t1(a,b,c,d); 3376 ** CREATE INDEX i1 ON t1(a); 3377 ** CREATE INDEX i2 ON t1(b); 3378 ** CREATE INDEX i3 ON t1(c); 3379 ** 3380 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) 3381 ** 3382 ** In the example, there are three indexed terms connected by OR. 3383 ** The top of the loop looks like this: 3384 ** 3385 ** Null 1 # Zero the rowset in reg 1 3386 ** 3387 ** Then, for each indexed term, the following. The arguments to 3388 ** RowSetTest are such that the rowid of the current row is inserted 3389 ** into the RowSet. If it is already present, control skips the 3390 ** Gosub opcode and jumps straight to the code generated by WhereEnd(). 3391 ** 3392 ** sqlite3WhereBegin(<term>) 3393 ** RowSetTest # Insert rowid into rowset 3394 ** Gosub 2 A 3395 ** sqlite3WhereEnd() 3396 ** 3397 ** Following the above, code to terminate the loop. Label A, the target 3398 ** of the Gosub above, jumps to the instruction right after the Goto. 3399 ** 3400 ** Null 1 # Zero the rowset in reg 1 3401 ** Goto B # The loop is finished. 3402 ** 3403 ** A: <loop body> # Return data, whatever. 3404 ** 3405 ** Return 2 # Jump back to the Gosub 3406 ** 3407 ** B: <after the loop> 3408 ** 3409 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then 3410 ** use an ephermeral index instead of a RowSet to record the primary 3411 ** keys of the rows we have already seen. 3412 ** 3413 */ 3414 WhereClause *pOrWc; /* The OR-clause broken out into subterms */ 3415 SrcList *pOrTab; /* Shortened table list or OR-clause generation */ 3416 Index *pCov = 0; /* Potential covering index (or NULL) */ 3417 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ 3418 3419 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ 3420 int regRowset = 0; /* Register for RowSet object */ 3421 int regRowid = 0; /* Register holding rowid */ 3422 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ 3423 int iRetInit; /* Address of regReturn init */ 3424 int untestedTerms = 0; /* Some terms not completely tested */ 3425 int ii; /* Loop counter */ 3426 u16 wctrlFlags; /* Flags for sub-WHERE clause */ 3427 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ 3428 Table *pTab = pTabItem->pTab; 3429 3430 pTerm = pLoop->aLTerm[0]; 3431 assert( pTerm!=0 ); 3432 assert( pTerm->eOperator & WO_OR ); 3433 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); 3434 pOrWc = &pTerm->u.pOrInfo->wc; 3435 pLevel->op = OP_Return; 3436 pLevel->p1 = regReturn; 3437 3438 /* Set up a new SrcList in pOrTab containing the table being scanned 3439 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. 3440 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). 3441 */ 3442 if( pWInfo->nLevel>1 ){ 3443 int nNotReady; /* The number of notReady tables */ 3444 struct SrcList_item *origSrc; /* Original list of tables */ 3445 nNotReady = pWInfo->nLevel - iLevel - 1; 3446 pOrTab = sqlite3StackAllocRaw(db, 3447 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); 3448 if( pOrTab==0 ) return notReady; 3449 pOrTab->nAlloc = (u8)(nNotReady + 1); 3450 pOrTab->nSrc = pOrTab->nAlloc; 3451 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); 3452 origSrc = pWInfo->pTabList->a; 3453 for(k=1; k<=nNotReady; k++){ 3454 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); 3455 } 3456 }else{ 3457 pOrTab = pWInfo->pTabList; 3458 } 3459 3460 /* Initialize the rowset register to contain NULL. An SQL NULL is 3461 ** equivalent to an empty rowset. Or, create an ephermeral index 3462 ** capable of holding primary keys in the case of a WITHOUT ROWID. 3463 ** 3464 ** Also initialize regReturn to contain the address of the instruction 3465 ** immediately following the OP_Return at the bottom of the loop. This 3466 ** is required in a few obscure LEFT JOIN cases where control jumps 3467 ** over the top of the loop into the body of it. In this case the 3468 ** correct response for the end-of-loop code (the OP_Return) is to 3469 ** fall through to the next instruction, just as an OP_Next does if 3470 ** called on an uninitialized cursor. 3471 */ 3472 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 3473 if( HasRowid(pTab) ){ 3474 regRowset = ++pParse->nMem; 3475 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); 3476 }else{ 3477 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 3478 regRowset = pParse->nTab++; 3479 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); 3480 sqlite3VdbeSetP4KeyInfo(pParse, pPk); 3481 } 3482 regRowid = ++pParse->nMem; 3483 } 3484 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); 3485 3486 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y 3487 ** Then for every term xN, evaluate as the subexpression: xN AND z 3488 ** That way, terms in y that are factored into the disjunction will 3489 ** be picked up by the recursive calls to sqlite3WhereBegin() below. 3490 ** 3491 ** Actually, each subexpression is converted to "xN AND w" where w is 3492 ** the "interesting" terms of z - terms that did not originate in the 3493 ** ON or USING clause of a LEFT JOIN, and terms that are usable as 3494 ** indices. 3495 ** 3496 ** This optimization also only applies if the (x1 OR x2 OR ...) term 3497 ** is not contained in the ON clause of a LEFT JOIN. 3498 ** See ticket http://www.sqlite.org/src/info/f2369304e4 3499 */ 3500 if( pWC->nTerm>1 ){ 3501 int iTerm; 3502 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ 3503 Expr *pExpr = pWC->a[iTerm].pExpr; 3504 if( &pWC->a[iTerm] == pTerm ) continue; 3505 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; 3506 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); 3507 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); 3508 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue; 3509 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; 3510 pExpr = sqlite3ExprDup(db, pExpr, 0); 3511 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); 3512 } 3513 if( pAndExpr ){ 3514 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0); 3515 } 3516 } 3517 3518 /* Run a separate WHERE clause for each term of the OR clause. After 3519 ** eliminating duplicates from other WHERE clauses, the action for each 3520 ** sub-WHERE clause is to to invoke the main loop body as a subroutine. 3521 */ 3522 wctrlFlags = WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY | 3523 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY; 3524 for(ii=0; ii<pOrWc->nTerm; ii++){ 3525 WhereTerm *pOrTerm = &pOrWc->a[ii]; 3526 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ 3527 WhereInfo *pSubWInfo; /* Info for single OR-term scan */ 3528 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ 3529 int j1 = 0; /* Address of jump operation */ 3530 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ 3531 pAndExpr->pLeft = pOrExpr; 3532 pOrExpr = pAndExpr; 3533 } 3534 /* Loop through table entries that match term pOrTerm. */ 3535 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 3536 wctrlFlags, iCovCur); 3537 assert( pSubWInfo || pParse->nErr || db->mallocFailed ); 3538 if( pSubWInfo ){ 3539 WhereLoop *pSubLoop; 3540 explainOneScan( 3541 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 3542 ); 3543 /* This is the sub-WHERE clause body. First skip over 3544 ** duplicate rows from prior sub-WHERE clauses, and record the 3545 ** rowid (or PRIMARY KEY) for the current row so that the same 3546 ** row will be skipped in subsequent sub-WHERE clauses. 3547 */ 3548 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 3549 int r; 3550 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); 3551 if( HasRowid(pTab) ){ 3552 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); 3553 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet); 3554 VdbeCoverage(v); 3555 }else{ 3556 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 3557 int nPk = pPk->nKeyCol; 3558 int iPk; 3559 3560 /* Read the PK into an array of temp registers. */ 3561 r = sqlite3GetTempRange(pParse, nPk); 3562 for(iPk=0; iPk<nPk; iPk++){ 3563 int iCol = pPk->aiColumn[iPk]; 3564 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0); 3565 } 3566 3567 /* Check if the temp table already contains this key. If so, 3568 ** the row has already been included in the result set and 3569 ** can be ignored (by jumping past the Gosub below). Otherwise, 3570 ** insert the key into the temp table and proceed with processing 3571 ** the row. 3572 ** 3573 ** Use some of the same optimizations as OP_RowSetTest: If iSet 3574 ** is zero, assume that the key cannot already be present in 3575 ** the temp table. And if iSet is -1, assume that there is no 3576 ** need to insert the key into the temp table, as it will never 3577 ** be tested for. */ 3578 if( iSet ){ 3579 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); 3580 VdbeCoverage(v); 3581 } 3582 if( iSet>=0 ){ 3583 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); 3584 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0); 3585 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 3586 } 3587 3588 /* Release the array of temp registers */ 3589 sqlite3ReleaseTempRange(pParse, r, nPk); 3590 } 3591 } 3592 3593 /* Invoke the main loop body as a subroutine */ 3594 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); 3595 3596 /* Jump here (skipping the main loop body subroutine) if the 3597 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ 3598 if( j1 ) sqlite3VdbeJumpHere(v, j1); 3599 3600 /* The pSubWInfo->untestedTerms flag means that this OR term 3601 ** contained one or more AND term from a notReady table. The 3602 ** terms from the notReady table could not be tested and will 3603 ** need to be tested later. 3604 */ 3605 if( pSubWInfo->untestedTerms ) untestedTerms = 1; 3606 3607 /* If all of the OR-connected terms are optimized using the same 3608 ** index, and the index is opened using the same cursor number 3609 ** by each call to sqlite3WhereBegin() made by this loop, it may 3610 ** be possible to use that index as a covering index. 3611 ** 3612 ** If the call to sqlite3WhereBegin() above resulted in a scan that 3613 ** uses an index, and this is either the first OR-connected term 3614 ** processed or the index is the same as that used by all previous 3615 ** terms, set pCov to the candidate covering index. Otherwise, set 3616 ** pCov to NULL to indicate that no candidate covering index will 3617 ** be available. 3618 */ 3619 pSubLoop = pSubWInfo->a[0].pWLoop; 3620 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 3621 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 3622 && (ii==0 || pSubLoop->u.btree.pIndex==pCov) 3623 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) 3624 ){ 3625 assert( pSubWInfo->a[0].iIdxCur==iCovCur ); 3626 pCov = pSubLoop->u.btree.pIndex; 3627 wctrlFlags |= WHERE_REOPEN_IDX; 3628 }else{ 3629 pCov = 0; 3630 } 3631 3632 /* Finish the loop through table entries that match term pOrTerm. */ 3633 sqlite3WhereEnd(pSubWInfo); 3634 } 3635 } 3636 } 3637 pLevel->u.pCovidx = pCov; 3638 if( pCov ) pLevel->iIdxCur = iCovCur; 3639 if( pAndExpr ){ 3640 pAndExpr->pLeft = 0; 3641 sqlite3ExprDelete(db, pAndExpr); 3642 } 3643 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); 3644 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); 3645 sqlite3VdbeResolveLabel(v, iLoopBody); 3646 3647 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); 3648 if( !untestedTerms ) disableTerm(pLevel, pTerm); 3649 }else 3650 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 3651 3652 { 3653 /* Case 6: There is no usable index. We must do a complete 3654 ** scan of the entire table. 3655 */ 3656 static const u8 aStep[] = { OP_Next, OP_Prev }; 3657 static const u8 aStart[] = { OP_Rewind, OP_Last }; 3658 assert( bRev==0 || bRev==1 ); 3659 if( pTabItem->isRecursive ){ 3660 /* Tables marked isRecursive have only a single row that is stored in 3661 ** a pseudo-cursor. No need to Rewind or Next such cursors. */ 3662 pLevel->op = OP_Noop; 3663 }else{ 3664 pLevel->op = aStep[bRev]; 3665 pLevel->p1 = iCur; 3666 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); 3667 VdbeCoverageIf(v, bRev==0); 3668 VdbeCoverageIf(v, bRev!=0); 3669 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 3670 } 3671 } 3672 3673 /* Insert code to test every subexpression that can be completely 3674 ** computed using the current set of tables. 3675 */ 3676 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 3677 Expr *pE; 3678 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 3679 testcase( pTerm->wtFlags & TERM_CODED ); 3680 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 3681 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 3682 testcase( pWInfo->untestedTerms==0 3683 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ); 3684 pWInfo->untestedTerms = 1; 3685 continue; 3686 } 3687 pE = pTerm->pExpr; 3688 assert( pE!=0 ); 3689 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ 3690 continue; 3691 } 3692 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); 3693 pTerm->wtFlags |= TERM_CODED; 3694 } 3695 3696 /* Insert code to test for implied constraints based on transitivity 3697 ** of the "==" operator. 3698 ** 3699 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" 3700 ** and we are coding the t1 loop and the t2 loop has not yet coded, 3701 ** then we cannot use the "t1.a=t2.b" constraint, but we can code 3702 ** the implied "t1.a=123" constraint. 3703 */ 3704 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 3705 Expr *pE, *pEAlt; 3706 WhereTerm *pAlt; 3707 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 3708 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue; 3709 if( pTerm->leftCursor!=iCur ) continue; 3710 if( pLevel->iLeftJoin ) continue; 3711 pE = pTerm->pExpr; 3712 assert( !ExprHasProperty(pE, EP_FromJoin) ); 3713 assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); 3714 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0); 3715 if( pAlt==0 ) continue; 3716 if( pAlt->wtFlags & (TERM_CODED) ) continue; 3717 testcase( pAlt->eOperator & WO_EQ ); 3718 testcase( pAlt->eOperator & WO_IN ); 3719 VdbeModuleComment((v, "begin transitive constraint")); 3720 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt)); 3721 if( pEAlt ){ 3722 *pEAlt = *pAlt->pExpr; 3723 pEAlt->pLeft = pE->pLeft; 3724 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL); 3725 sqlite3StackFree(db, pEAlt); 3726 } 3727 } 3728 3729 /* For a LEFT OUTER JOIN, generate code that will record the fact that 3730 ** at least one row of the right table has matched the left table. 3731 */ 3732 if( pLevel->iLeftJoin ){ 3733 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); 3734 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); 3735 VdbeComment((v, "record LEFT JOIN hit")); 3736 sqlite3ExprCacheClear(pParse); 3737 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ 3738 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 3739 testcase( pTerm->wtFlags & TERM_CODED ); 3740 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 3741 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 3742 assert( pWInfo->untestedTerms ); 3743 continue; 3744 } 3745 assert( pTerm->pExpr ); 3746 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 3747 pTerm->wtFlags |= TERM_CODED; 3748 } 3749 } 3750 3751 return pLevel->notReady; 3752 } 3753 3754 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN) 3755 /* 3756 ** Generate "Explanation" text for a WhereTerm. 3757 */ 3758 static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){ 3759 char zType[4]; 3760 memcpy(zType, "...", 4); 3761 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; 3762 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; 3763 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; 3764 sqlite3ExplainPrintf(v, "%s ", zType); 3765 sqlite3ExplainExpr(v, pTerm->pExpr); 3766 } 3767 #endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */ 3768 3769 3770 #ifdef WHERETRACE_ENABLED 3771 /* 3772 ** Print a WhereLoop object for debugging purposes 3773 */ 3774 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){ 3775 WhereInfo *pWInfo = pWC->pWInfo; 3776 int nb = 1+(pWInfo->pTabList->nSrc+7)/8; 3777 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab; 3778 Table *pTab = pItem->pTab; 3779 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId, 3780 p->iTab, nb, p->maskSelf, nb, p->prereq); 3781 sqlite3DebugPrintf(" %12s", 3782 pItem->zAlias ? pItem->zAlias : pTab->zName); 3783 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ 3784 const char *zName; 3785 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){ 3786 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){ 3787 int i = sqlite3Strlen30(zName) - 1; 3788 while( zName[i]!='_' ) i--; 3789 zName += i; 3790 } 3791 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq); 3792 }else{ 3793 sqlite3DebugPrintf("%20s",""); 3794 } 3795 }else{ 3796 char *z; 3797 if( p->u.vtab.idxStr ){ 3798 z = sqlite3_mprintf("(%d,\"%s\",%x)", 3799 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); 3800 }else{ 3801 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); 3802 } 3803 sqlite3DebugPrintf(" %-19s", z); 3804 sqlite3_free(z); 3805 } 3806 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); 3807 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); 3808 #ifdef SQLITE_ENABLE_TREE_EXPLAIN 3809 /* If the 0x100 bit of wheretracing is set, then show all of the constraint 3810 ** expressions in the WhereLoop.aLTerm[] array. 3811 */ 3812 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ /* WHERETRACE 0x100 */ 3813 int i; 3814 Vdbe *v = pWInfo->pParse->pVdbe; 3815 sqlite3ExplainBegin(v); 3816 for(i=0; i<p->nLTerm; i++){ 3817 WhereTerm *pTerm = p->aLTerm[i]; 3818 if( pTerm==0 ) continue; 3819 sqlite3ExplainPrintf(v, " (%d) #%-2d ", i+1, (int)(pTerm-pWC->a)); 3820 sqlite3ExplainPush(v); 3821 whereExplainTerm(v, pTerm); 3822 sqlite3ExplainPop(v); 3823 sqlite3ExplainNL(v); 3824 } 3825 sqlite3ExplainFinish(v); 3826 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v)); 3827 } 3828 #endif 3829 } 3830 #endif 3831 3832 /* 3833 ** Convert bulk memory into a valid WhereLoop that can be passed 3834 ** to whereLoopClear harmlessly. 3835 */ 3836 static void whereLoopInit(WhereLoop *p){ 3837 p->aLTerm = p->aLTermSpace; 3838 p->nLTerm = 0; 3839 p->nLSlot = ArraySize(p->aLTermSpace); 3840 p->wsFlags = 0; 3841 } 3842 3843 /* 3844 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. 3845 */ 3846 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ 3847 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ 3848 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ 3849 sqlite3_free(p->u.vtab.idxStr); 3850 p->u.vtab.needFree = 0; 3851 p->u.vtab.idxStr = 0; 3852 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ 3853 sqlite3DbFree(db, p->u.btree.pIndex->zColAff); 3854 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo); 3855 sqlite3DbFree(db, p->u.btree.pIndex); 3856 p->u.btree.pIndex = 0; 3857 } 3858 } 3859 } 3860 3861 /* 3862 ** Deallocate internal memory used by a WhereLoop object 3863 */ 3864 static void whereLoopClear(sqlite3 *db, WhereLoop *p){ 3865 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); 3866 whereLoopClearUnion(db, p); 3867 whereLoopInit(p); 3868 } 3869 3870 /* 3871 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n. 3872 */ 3873 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){ 3874 WhereTerm **paNew; 3875 if( p->nLSlot>=n ) return SQLITE_OK; 3876 n = (n+7)&~7; 3877 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n); 3878 if( paNew==0 ) return SQLITE_NOMEM; 3879 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot); 3880 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm); 3881 p->aLTerm = paNew; 3882 p->nLSlot = n; 3883 return SQLITE_OK; 3884 } 3885 3886 /* 3887 ** Transfer content from the second pLoop into the first. 3888 */ 3889 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){ 3890 whereLoopClearUnion(db, pTo); 3891 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){ 3892 memset(&pTo->u, 0, sizeof(pTo->u)); 3893 return SQLITE_NOMEM; 3894 } 3895 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ); 3896 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0])); 3897 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){ 3898 pFrom->u.vtab.needFree = 0; 3899 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){ 3900 pFrom->u.btree.pIndex = 0; 3901 } 3902 return SQLITE_OK; 3903 } 3904 3905 /* 3906 ** Delete a WhereLoop object 3907 */ 3908 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ 3909 whereLoopClear(db, p); 3910 sqlite3DbFree(db, p); 3911 } 3912 3913 /* 3914 ** Free a WhereInfo structure 3915 */ 3916 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ 3917 if( ALWAYS(pWInfo) ){ 3918 whereClauseClear(&pWInfo->sWC); 3919 while( pWInfo->pLoops ){ 3920 WhereLoop *p = pWInfo->pLoops; 3921 pWInfo->pLoops = p->pNextLoop; 3922 whereLoopDelete(db, p); 3923 } 3924 sqlite3DbFree(db, pWInfo); 3925 } 3926 } 3927 3928 /* 3929 ** Return TRUE if both of the following are true: 3930 ** 3931 ** (1) X has the same or lower cost that Y 3932 ** (2) X is a proper subset of Y 3933 ** 3934 ** By "proper subset" we mean that X uses fewer WHERE clause terms 3935 ** than Y and that every WHERE clause term used by X is also used 3936 ** by Y. 3937 ** 3938 ** If X is a proper subset of Y then Y is a better choice and ought 3939 ** to have a lower cost. This routine returns TRUE when that cost 3940 ** relationship is inverted and needs to be adjusted. 3941 */ 3942 static int whereLoopCheaperProperSubset( 3943 const WhereLoop *pX, /* First WhereLoop to compare */ 3944 const WhereLoop *pY /* Compare against this WhereLoop */ 3945 ){ 3946 int i, j; 3947 if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */ 3948 if( pX->rRun >= pY->rRun ){ 3949 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */ 3950 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */ 3951 } 3952 for(i=pX->nLTerm-1; i>=0; i--){ 3953 for(j=pY->nLTerm-1; j>=0; j--){ 3954 if( pY->aLTerm[j]==pX->aLTerm[i] ) break; 3955 } 3956 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ 3957 } 3958 return 1; /* All conditions meet */ 3959 } 3960 3961 /* 3962 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so 3963 ** that: 3964 ** 3965 ** (1) pTemplate costs less than any other WhereLoops that are a proper 3966 ** subset of pTemplate 3967 ** 3968 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate 3969 ** is a proper subset. 3970 ** 3971 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer 3972 ** WHERE clause terms than Y and that every WHERE clause term used by X is 3973 ** also used by Y. 3974 ** 3975 ** This adjustment is omitted for SKIPSCAN loops. In a SKIPSCAN loop, the 3976 ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE 3977 ** clause terms covered, since some of the first nLTerm entries in aLTerm[] 3978 ** will be NULL (because they are skipped). That makes it more difficult 3979 ** to compare the loops. We could add extra code to do the comparison, and 3980 ** perhaps we will someday. But SKIPSCAN is sufficiently uncommon, and this 3981 ** adjustment is sufficient minor, that it is very difficult to construct 3982 ** a test case where the extra code would improve the query plan. Better 3983 ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN 3984 ** loops. 3985 */ 3986 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ 3987 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; 3988 if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return; 3989 for(; p; p=p->pNextLoop){ 3990 if( p->iTab!=pTemplate->iTab ) continue; 3991 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; 3992 if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue; 3993 if( whereLoopCheaperProperSubset(p, pTemplate) ){ 3994 /* Adjust pTemplate cost downward so that it is cheaper than its 3995 ** subset p */ 3996 pTemplate->rRun = p->rRun; 3997 pTemplate->nOut = p->nOut - 1; 3998 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ 3999 /* Adjust pTemplate cost upward so that it is costlier than p since 4000 ** pTemplate is a proper subset of p */ 4001 pTemplate->rRun = p->rRun; 4002 pTemplate->nOut = p->nOut + 1; 4003 } 4004 } 4005 } 4006 4007 /* 4008 ** Search the list of WhereLoops in *ppPrev looking for one that can be 4009 ** supplanted by pTemplate. 4010 ** 4011 ** Return NULL if the WhereLoop list contains an entry that can supplant 4012 ** pTemplate, in other words if pTemplate does not belong on the list. 4013 ** 4014 ** If pX is a WhereLoop that pTemplate can supplant, then return the 4015 ** link that points to pX. 4016 ** 4017 ** If pTemplate cannot supplant any existing element of the list but needs 4018 ** to be added to the list, then return a pointer to the tail of the list. 4019 */ 4020 static WhereLoop **whereLoopFindLesser( 4021 WhereLoop **ppPrev, 4022 const WhereLoop *pTemplate 4023 ){ 4024 WhereLoop *p; 4025 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){ 4026 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){ 4027 /* If either the iTab or iSortIdx values for two WhereLoop are different 4028 ** then those WhereLoops need to be considered separately. Neither is 4029 ** a candidate to replace the other. */ 4030 continue; 4031 } 4032 /* In the current implementation, the rSetup value is either zero 4033 ** or the cost of building an automatic index (NlogN) and the NlogN 4034 ** is the same for compatible WhereLoops. */ 4035 assert( p->rSetup==0 || pTemplate->rSetup==0 4036 || p->rSetup==pTemplate->rSetup ); 4037 4038 /* whereLoopAddBtree() always generates and inserts the automatic index 4039 ** case first. Hence compatible candidate WhereLoops never have a larger 4040 ** rSetup. Call this SETUP-INVARIANT */ 4041 assert( p->rSetup>=pTemplate->rSetup ); 4042 4043 /* Any loop using an appliation-defined index (or PRIMARY KEY or 4044 ** UNIQUE constraint) with one or more == constraints is better 4045 ** than an automatic index. */ 4046 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 4047 && (pTemplate->wsFlags & WHERE_INDEXED)!=0 4048 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 4049 && (p->prereq & pTemplate->prereq)==pTemplate->prereq 4050 ){ 4051 break; 4052 } 4053 4054 /* If existing WhereLoop p is better than pTemplate, pTemplate can be 4055 ** discarded. WhereLoop p is better if: 4056 ** (1) p has no more dependencies than pTemplate, and 4057 ** (2) p has an equal or lower cost than pTemplate 4058 */ 4059 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */ 4060 && p->rSetup<=pTemplate->rSetup /* (2a) */ 4061 && p->rRun<=pTemplate->rRun /* (2b) */ 4062 && p->nOut<=pTemplate->nOut /* (2c) */ 4063 ){ 4064 return 0; /* Discard pTemplate */ 4065 } 4066 4067 /* If pTemplate is always better than p, then cause p to be overwritten 4068 ** with pTemplate. pTemplate is better than p if: 4069 ** (1) pTemplate has no more dependences than p, and 4070 ** (2) pTemplate has an equal or lower cost than p. 4071 */ 4072 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */ 4073 && p->rRun>=pTemplate->rRun /* (2a) */ 4074 && p->nOut>=pTemplate->nOut /* (2b) */ 4075 ){ 4076 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */ 4077 break; /* Cause p to be overwritten by pTemplate */ 4078 } 4079 } 4080 return ppPrev; 4081 } 4082 4083 /* 4084 ** Insert or replace a WhereLoop entry using the template supplied. 4085 ** 4086 ** An existing WhereLoop entry might be overwritten if the new template 4087 ** is better and has fewer dependencies. Or the template will be ignored 4088 ** and no insert will occur if an existing WhereLoop is faster and has 4089 ** fewer dependencies than the template. Otherwise a new WhereLoop is 4090 ** added based on the template. 4091 ** 4092 ** If pBuilder->pOrSet is not NULL then we care about only the 4093 ** prerequisites and rRun and nOut costs of the N best loops. That 4094 ** information is gathered in the pBuilder->pOrSet object. This special 4095 ** processing mode is used only for OR clause processing. 4096 ** 4097 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we 4098 ** still might overwrite similar loops with the new template if the 4099 ** new template is better. Loops may be overwritten if the following 4100 ** conditions are met: 4101 ** 4102 ** (1) They have the same iTab. 4103 ** (2) They have the same iSortIdx. 4104 ** (3) The template has same or fewer dependencies than the current loop 4105 ** (4) The template has the same or lower cost than the current loop 4106 */ 4107 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ 4108 WhereLoop **ppPrev, *p; 4109 WhereInfo *pWInfo = pBuilder->pWInfo; 4110 sqlite3 *db = pWInfo->pParse->db; 4111 4112 /* If pBuilder->pOrSet is defined, then only keep track of the costs 4113 ** and prereqs. 4114 */ 4115 if( pBuilder->pOrSet!=0 ){ 4116 #if WHERETRACE_ENABLED 4117 u16 n = pBuilder->pOrSet->n; 4118 int x = 4119 #endif 4120 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, 4121 pTemplate->nOut); 4122 #if WHERETRACE_ENABLED /* 0x8 */ 4123 if( sqlite3WhereTrace & 0x8 ){ 4124 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); 4125 whereLoopPrint(pTemplate, pBuilder->pWC); 4126 } 4127 #endif 4128 return SQLITE_OK; 4129 } 4130 4131 /* Look for an existing WhereLoop to replace with pTemplate 4132 */ 4133 whereLoopAdjustCost(pWInfo->pLoops, pTemplate); 4134 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); 4135 4136 if( ppPrev==0 ){ 4137 /* There already exists a WhereLoop on the list that is better 4138 ** than pTemplate, so just ignore pTemplate */ 4139 #if WHERETRACE_ENABLED /* 0x8 */ 4140 if( sqlite3WhereTrace & 0x8 ){ 4141 sqlite3DebugPrintf("ins-noop: "); 4142 whereLoopPrint(pTemplate, pBuilder->pWC); 4143 } 4144 #endif 4145 return SQLITE_OK; 4146 }else{ 4147 p = *ppPrev; 4148 } 4149 4150 /* If we reach this point it means that either p[] should be overwritten 4151 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new 4152 ** WhereLoop and insert it. 4153 */ 4154 #if WHERETRACE_ENABLED /* 0x8 */ 4155 if( sqlite3WhereTrace & 0x8 ){ 4156 if( p!=0 ){ 4157 sqlite3DebugPrintf("ins-del: "); 4158 whereLoopPrint(p, pBuilder->pWC); 4159 } 4160 sqlite3DebugPrintf("ins-new: "); 4161 whereLoopPrint(pTemplate, pBuilder->pWC); 4162 } 4163 #endif 4164 if( p==0 ){ 4165 /* Allocate a new WhereLoop to add to the end of the list */ 4166 *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop)); 4167 if( p==0 ) return SQLITE_NOMEM; 4168 whereLoopInit(p); 4169 p->pNextLoop = 0; 4170 }else{ 4171 /* We will be overwriting WhereLoop p[]. But before we do, first 4172 ** go through the rest of the list and delete any other entries besides 4173 ** p[] that are also supplated by pTemplate */ 4174 WhereLoop **ppTail = &p->pNextLoop; 4175 WhereLoop *pToDel; 4176 while( *ppTail ){ 4177 ppTail = whereLoopFindLesser(ppTail, pTemplate); 4178 if( ppTail==0 ) break; 4179 pToDel = *ppTail; 4180 if( pToDel==0 ) break; 4181 *ppTail = pToDel->pNextLoop; 4182 #if WHERETRACE_ENABLED /* 0x8 */ 4183 if( sqlite3WhereTrace & 0x8 ){ 4184 sqlite3DebugPrintf("ins-del: "); 4185 whereLoopPrint(pToDel, pBuilder->pWC); 4186 } 4187 #endif 4188 whereLoopDelete(db, pToDel); 4189 } 4190 } 4191 whereLoopXfer(db, p, pTemplate); 4192 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){ 4193 Index *pIndex = p->u.btree.pIndex; 4194 if( pIndex && pIndex->tnum==0 ){ 4195 p->u.btree.pIndex = 0; 4196 } 4197 } 4198 return SQLITE_OK; 4199 } 4200 4201 /* 4202 ** Adjust the WhereLoop.nOut value downward to account for terms of the 4203 ** WHERE clause that reference the loop but which are not used by an 4204 ** index. 4205 ** 4206 ** In the current implementation, the first extra WHERE clause term reduces 4207 ** the number of output rows by a factor of 10 and each additional term 4208 ** reduces the number of output rows by sqrt(2). 4209 */ 4210 static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){ 4211 WhereTerm *pTerm, *pX; 4212 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); 4213 int i, j; 4214 4215 if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){ 4216 return; 4217 } 4218 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ 4219 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; 4220 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; 4221 if( (pTerm->prereqAll & notAllowed)!=0 ) continue; 4222 for(j=pLoop->nLTerm-1; j>=0; j--){ 4223 pX = pLoop->aLTerm[j]; 4224 if( pX==0 ) continue; 4225 if( pX==pTerm ) break; 4226 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; 4227 } 4228 if( j<0 ){ 4229 pLoop->nOut += (pTerm->truthProb<=0 ? pTerm->truthProb : -1); 4230 } 4231 } 4232 } 4233 4234 /* 4235 ** Adjust the cost C by the costMult facter T. This only occurs if 4236 ** compiled with -DSQLITE_ENABLE_COSTMULT 4237 */ 4238 #ifdef SQLITE_ENABLE_COSTMULT 4239 # define ApplyCostMultiplier(C,T) C += T 4240 #else 4241 # define ApplyCostMultiplier(C,T) 4242 #endif 4243 4244 /* 4245 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 4246 ** index pIndex. Try to match one more. 4247 ** 4248 ** When this function is called, pBuilder->pNew->nOut contains the 4249 ** number of rows expected to be visited by filtering using the nEq 4250 ** terms only. If it is modified, this value is restored before this 4251 ** function returns. 4252 ** 4253 ** If pProbe->tnum==0, that means pIndex is a fake index used for the 4254 ** INTEGER PRIMARY KEY. 4255 */ 4256 static int whereLoopAddBtreeIndex( 4257 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */ 4258 struct SrcList_item *pSrc, /* FROM clause term being analyzed */ 4259 Index *pProbe, /* An index on pSrc */ 4260 LogEst nInMul /* log(Number of iterations due to IN) */ 4261 ){ 4262 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ 4263 Parse *pParse = pWInfo->pParse; /* Parsing context */ 4264 sqlite3 *db = pParse->db; /* Database connection malloc context */ 4265 WhereLoop *pNew; /* Template WhereLoop under construction */ 4266 WhereTerm *pTerm; /* A WhereTerm under consideration */ 4267 int opMask; /* Valid operators for constraints */ 4268 WhereScan scan; /* Iterator for WHERE terms */ 4269 Bitmask saved_prereq; /* Original value of pNew->prereq */ 4270 u16 saved_nLTerm; /* Original value of pNew->nLTerm */ 4271 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ 4272 u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */ 4273 u32 saved_wsFlags; /* Original value of pNew->wsFlags */ 4274 LogEst saved_nOut; /* Original value of pNew->nOut */ 4275 int iCol; /* Index of the column in the table */ 4276 int rc = SQLITE_OK; /* Return code */ 4277 LogEst rLogSize; /* Logarithm of table size */ 4278 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ 4279 4280 pNew = pBuilder->pNew; 4281 if( db->mallocFailed ) return SQLITE_NOMEM; 4282 4283 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); 4284 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); 4285 if( pNew->wsFlags & WHERE_BTM_LIMIT ){ 4286 opMask = WO_LT|WO_LE; 4287 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){ 4288 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE; 4289 }else{ 4290 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE; 4291 } 4292 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); 4293 4294 assert( pNew->u.btree.nEq<pProbe->nColumn ); 4295 iCol = pProbe->aiColumn[pNew->u.btree.nEq]; 4296 4297 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol, 4298 opMask, pProbe); 4299 saved_nEq = pNew->u.btree.nEq; 4300 saved_nSkip = pNew->u.btree.nSkip; 4301 saved_nLTerm = pNew->nLTerm; 4302 saved_wsFlags = pNew->wsFlags; 4303 saved_prereq = pNew->prereq; 4304 saved_nOut = pNew->nOut; 4305 pNew->rSetup = 0; 4306 rLogSize = estLog(pProbe->aiRowLogEst[0]); 4307 4308 /* Consider using a skip-scan if there are no WHERE clause constraints 4309 ** available for the left-most terms of the index, and if the average 4310 ** number of repeats in the left-most terms is at least 18. 4311 ** 4312 ** The magic number 18 is selected on the basis that scanning 17 rows 4313 ** is almost always quicker than an index seek (even though if the index 4314 ** contains fewer than 2^17 rows we assume otherwise in other parts of 4315 ** the code). And, even if it is not, it should not be too much slower. 4316 ** On the other hand, the extra seeks could end up being significantly 4317 ** more expensive. */ 4318 assert( 42==sqlite3LogEst(18) ); 4319 if( pTerm==0 4320 && saved_nEq==saved_nSkip 4321 && saved_nEq+1<pProbe->nKeyCol 4322 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ 4323 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK 4324 ){ 4325 LogEst nIter; 4326 pNew->u.btree.nEq++; 4327 pNew->u.btree.nSkip++; 4328 pNew->aLTerm[pNew->nLTerm++] = 0; 4329 pNew->wsFlags |= WHERE_SKIPSCAN; 4330 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; 4331 pNew->nOut -= nIter; 4332 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); 4333 pNew->nOut = saved_nOut; 4334 } 4335 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ 4336 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ 4337 LogEst rCostIdx; 4338 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ 4339 int nIn = 0; 4340 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 4341 int nRecValid = pBuilder->nRecValid; 4342 #endif 4343 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) 4344 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull) 4345 ){ 4346 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ 4347 } 4348 if( pTerm->prereqRight & pNew->maskSelf ) continue; 4349 4350 pNew->wsFlags = saved_wsFlags; 4351 pNew->u.btree.nEq = saved_nEq; 4352 pNew->nLTerm = saved_nLTerm; 4353 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ 4354 pNew->aLTerm[pNew->nLTerm++] = pTerm; 4355 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; 4356 4357 assert( nInMul==0 4358 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 4359 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 4360 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 4361 ); 4362 4363 if( eOp & WO_IN ){ 4364 Expr *pExpr = pTerm->pExpr; 4365 pNew->wsFlags |= WHERE_COLUMN_IN; 4366 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 4367 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ 4368 nIn = 46; assert( 46==sqlite3LogEst(25) ); 4369 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ 4370 /* "x IN (value, value, ...)" */ 4371 nIn = sqlite3LogEst(pExpr->x.pList->nExpr); 4372 } 4373 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser 4374 ** changes "x IN (?)" into "x=?". */ 4375 4376 }else if( eOp & (WO_EQ) ){ 4377 pNew->wsFlags |= WHERE_COLUMN_EQ; 4378 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){ 4379 if( iCol>=0 && !IsUniqueIndex(pProbe) ){ 4380 pNew->wsFlags |= WHERE_UNQ_WANTED; 4381 }else{ 4382 pNew->wsFlags |= WHERE_ONEROW; 4383 } 4384 } 4385 }else if( eOp & WO_ISNULL ){ 4386 pNew->wsFlags |= WHERE_COLUMN_NULL; 4387 }else if( eOp & (WO_GT|WO_GE) ){ 4388 testcase( eOp & WO_GT ); 4389 testcase( eOp & WO_GE ); 4390 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; 4391 pBtm = pTerm; 4392 pTop = 0; 4393 }else{ 4394 assert( eOp & (WO_LT|WO_LE) ); 4395 testcase( eOp & WO_LT ); 4396 testcase( eOp & WO_LE ); 4397 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; 4398 pTop = pTerm; 4399 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? 4400 pNew->aLTerm[pNew->nLTerm-2] : 0; 4401 } 4402 4403 /* At this point pNew->nOut is set to the number of rows expected to 4404 ** be visited by the index scan before considering term pTerm, or the 4405 ** values of nIn and nInMul. In other words, assuming that all 4406 ** "x IN(...)" terms are replaced with "x = ?". This block updates 4407 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ 4408 assert( pNew->nOut==saved_nOut ); 4409 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ 4410 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4 4411 ** data, using some other estimate. */ 4412 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); 4413 }else{ 4414 int nEq = ++pNew->u.btree.nEq; 4415 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) ); 4416 4417 assert( pNew->nOut==saved_nOut ); 4418 if( pTerm->truthProb<=0 && iCol>=0 ){ 4419 assert( (eOp & WO_IN) || nIn==0 ); 4420 testcase( eOp & WO_IN ); 4421 pNew->nOut += pTerm->truthProb; 4422 pNew->nOut -= nIn; 4423 }else{ 4424 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 4425 tRowcnt nOut = 0; 4426 if( nInMul==0 4427 && pProbe->nSample 4428 && pNew->u.btree.nEq<=pProbe->nSampleCol 4429 && OptimizationEnabled(db, SQLITE_Stat3) 4430 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) 4431 ){ 4432 Expr *pExpr = pTerm->pExpr; 4433 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){ 4434 testcase( eOp & WO_EQ ); 4435 testcase( eOp & WO_ISNULL ); 4436 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); 4437 }else{ 4438 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); 4439 } 4440 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; 4441 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ 4442 if( nOut ){ 4443 pNew->nOut = sqlite3LogEst(nOut); 4444 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; 4445 pNew->nOut -= nIn; 4446 } 4447 } 4448 if( nOut==0 ) 4449 #endif 4450 { 4451 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]); 4452 if( eOp & WO_ISNULL ){ 4453 /* TUNING: If there is no likelihood() value, assume that a 4454 ** "col IS NULL" expression matches twice as many rows 4455 ** as (col=?). */ 4456 pNew->nOut += 10; 4457 } 4458 } 4459 } 4460 } 4461 4462 /* Set rCostIdx to the cost of visiting selected rows in index. Add 4463 ** it to pNew->rRun, which is currently set to the cost of the index 4464 ** seek only. Then, if this is a non-covering index, add the cost of 4465 ** visiting the rows in the main table. */ 4466 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow; 4467 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx); 4468 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){ 4469 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16); 4470 } 4471 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult); 4472 4473 nOutUnadjusted = pNew->nOut; 4474 pNew->rRun += nInMul + nIn; 4475 pNew->nOut += nInMul + nIn; 4476 whereLoopOutputAdjust(pBuilder->pWC, pNew); 4477 rc = whereLoopInsert(pBuilder, pNew); 4478 4479 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ 4480 pNew->nOut = saved_nOut; 4481 }else{ 4482 pNew->nOut = nOutUnadjusted; 4483 } 4484 4485 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 4486 && pNew->u.btree.nEq<pProbe->nColumn 4487 ){ 4488 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); 4489 } 4490 pNew->nOut = saved_nOut; 4491 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 4492 pBuilder->nRecValid = nRecValid; 4493 #endif 4494 } 4495 pNew->prereq = saved_prereq; 4496 pNew->u.btree.nEq = saved_nEq; 4497 pNew->u.btree.nSkip = saved_nSkip; 4498 pNew->wsFlags = saved_wsFlags; 4499 pNew->nOut = saved_nOut; 4500 pNew->nLTerm = saved_nLTerm; 4501 return rc; 4502 } 4503 4504 /* 4505 ** Return True if it is possible that pIndex might be useful in 4506 ** implementing the ORDER BY clause in pBuilder. 4507 ** 4508 ** Return False if pBuilder does not contain an ORDER BY clause or 4509 ** if there is no way for pIndex to be useful in implementing that 4510 ** ORDER BY clause. 4511 */ 4512 static int indexMightHelpWithOrderBy( 4513 WhereLoopBuilder *pBuilder, 4514 Index *pIndex, 4515 int iCursor 4516 ){ 4517 ExprList *pOB; 4518 int ii, jj; 4519 4520 if( pIndex->bUnordered ) return 0; 4521 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; 4522 for(ii=0; ii<pOB->nExpr; ii++){ 4523 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); 4524 if( pExpr->op!=TK_COLUMN ) return 0; 4525 if( pExpr->iTable==iCursor ){ 4526 for(jj=0; jj<pIndex->nKeyCol; jj++){ 4527 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; 4528 } 4529 } 4530 } 4531 return 0; 4532 } 4533 4534 /* 4535 ** Return a bitmask where 1s indicate that the corresponding column of 4536 ** the table is used by an index. Only the first 63 columns are considered. 4537 */ 4538 static Bitmask columnsInIndex(Index *pIdx){ 4539 Bitmask m = 0; 4540 int j; 4541 for(j=pIdx->nColumn-1; j>=0; j--){ 4542 int x = pIdx->aiColumn[j]; 4543 if( x>=0 ){ 4544 testcase( x==BMS-1 ); 4545 testcase( x==BMS-2 ); 4546 if( x<BMS-1 ) m |= MASKBIT(x); 4547 } 4548 } 4549 return m; 4550 } 4551 4552 /* Check to see if a partial index with pPartIndexWhere can be used 4553 ** in the current query. Return true if it can be and false if not. 4554 */ 4555 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){ 4556 int i; 4557 WhereTerm *pTerm; 4558 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 4559 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1; 4560 } 4561 return 0; 4562 } 4563 4564 /* 4565 ** Add all WhereLoop objects for a single table of the join where the table 4566 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be 4567 ** a b-tree table, not a virtual table. 4568 ** 4569 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function 4570 ** are calculated as follows: 4571 ** 4572 ** For a full scan, assuming the table (or index) contains nRow rows: 4573 ** 4574 ** cost = nRow * 3.0 // full-table scan 4575 ** cost = nRow * K // scan of covering index 4576 ** cost = nRow * (K+3.0) // scan of non-covering index 4577 ** 4578 ** where K is a value between 1.1 and 3.0 set based on the relative 4579 ** estimated average size of the index and table records. 4580 ** 4581 ** For an index scan, where nVisit is the number of index rows visited 4582 ** by the scan, and nSeek is the number of seek operations required on 4583 ** the index b-tree: 4584 ** 4585 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index 4586 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index 4587 ** 4588 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the 4589 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 4590 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans. 4591 ** 4592 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount 4593 ** of uncertainty. For this reason, scoring is designed to pick plans that 4594 ** "do the least harm" if the estimates are inaccurate. For example, a 4595 ** log(nRow) factor is omitted from a non-covering index scan in order to 4596 ** bias the scoring in favor of using an index, since the worst-case 4597 ** performance of using an index is far better than the worst-case performance 4598 ** of a full table scan. 4599 */ 4600 static int whereLoopAddBtree( 4601 WhereLoopBuilder *pBuilder, /* WHERE clause information */ 4602 Bitmask mExtra /* Extra prerequesites for using this table */ 4603 ){ 4604 WhereInfo *pWInfo; /* WHERE analysis context */ 4605 Index *pProbe; /* An index we are evaluating */ 4606 Index sPk; /* A fake index object for the primary key */ 4607 LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */ 4608 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */ 4609 SrcList *pTabList; /* The FROM clause */ 4610 struct SrcList_item *pSrc; /* The FROM clause btree term to add */ 4611 WhereLoop *pNew; /* Template WhereLoop object */ 4612 int rc = SQLITE_OK; /* Return code */ 4613 int iSortIdx = 1; /* Index number */ 4614 int b; /* A boolean value */ 4615 LogEst rSize; /* number of rows in the table */ 4616 LogEst rLogSize; /* Logarithm of the number of rows in the table */ 4617 WhereClause *pWC; /* The parsed WHERE clause */ 4618 Table *pTab; /* Table being queried */ 4619 4620 pNew = pBuilder->pNew; 4621 pWInfo = pBuilder->pWInfo; 4622 pTabList = pWInfo->pTabList; 4623 pSrc = pTabList->a + pNew->iTab; 4624 pTab = pSrc->pTab; 4625 pWC = pBuilder->pWC; 4626 assert( !IsVirtual(pSrc->pTab) ); 4627 4628 if( pSrc->pIndex ){ 4629 /* An INDEXED BY clause specifies a particular index to use */ 4630 pProbe = pSrc->pIndex; 4631 }else if( !HasRowid(pTab) ){ 4632 pProbe = pTab->pIndex; 4633 }else{ 4634 /* There is no INDEXED BY clause. Create a fake Index object in local 4635 ** variable sPk to represent the rowid primary key index. Make this 4636 ** fake index the first in a chain of Index objects with all of the real 4637 ** indices to follow */ 4638 Index *pFirst; /* First of real indices on the table */ 4639 memset(&sPk, 0, sizeof(Index)); 4640 sPk.nKeyCol = 1; 4641 sPk.nColumn = 1; 4642 sPk.aiColumn = &aiColumnPk; 4643 sPk.aiRowLogEst = aiRowEstPk; 4644 sPk.onError = OE_Replace; 4645 sPk.pTable = pTab; 4646 sPk.szIdxRow = pTab->szTabRow; 4647 aiRowEstPk[0] = pTab->nRowLogEst; 4648 aiRowEstPk[1] = 0; 4649 pFirst = pSrc->pTab->pIndex; 4650 if( pSrc->notIndexed==0 ){ 4651 /* The real indices of the table are only considered if the 4652 ** NOT INDEXED qualifier is omitted from the FROM clause */ 4653 sPk.pNext = pFirst; 4654 } 4655 pProbe = &sPk; 4656 } 4657 rSize = pTab->nRowLogEst; 4658 rLogSize = estLog(rSize); 4659 4660 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 4661 /* Automatic indexes */ 4662 if( !pBuilder->pOrSet 4663 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 4664 && pSrc->pIndex==0 4665 && !pSrc->viaCoroutine 4666 && !pSrc->notIndexed 4667 && HasRowid(pTab) 4668 && !pSrc->isCorrelated 4669 && !pSrc->isRecursive 4670 ){ 4671 /* Generate auto-index WhereLoops */ 4672 WhereTerm *pTerm; 4673 WhereTerm *pWCEnd = pWC->a + pWC->nTerm; 4674 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){ 4675 if( pTerm->prereqRight & pNew->maskSelf ) continue; 4676 if( termCanDriveIndex(pTerm, pSrc, 0) ){ 4677 pNew->u.btree.nEq = 1; 4678 pNew->u.btree.nSkip = 0; 4679 pNew->u.btree.pIndex = 0; 4680 pNew->nLTerm = 1; 4681 pNew->aLTerm[0] = pTerm; 4682 /* TUNING: One-time cost for computing the automatic index is 4683 ** approximately 7*N*log2(N) where N is the number of rows in 4684 ** the table being indexed. */ 4685 pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) ); 4686 ApplyCostMultiplier(pNew->rSetup, pTab->costMult); 4687 /* TUNING: Each index lookup yields 20 rows in the table. This 4688 ** is more than the usual guess of 10 rows, since we have no way 4689 ** of knowning how selective the index will ultimately be. It would 4690 ** not be unreasonable to make this value much larger. */ 4691 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) ); 4692 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut); 4693 pNew->wsFlags = WHERE_AUTO_INDEX; 4694 pNew->prereq = mExtra | pTerm->prereqRight; 4695 rc = whereLoopInsert(pBuilder, pNew); 4696 } 4697 } 4698 } 4699 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 4700 4701 /* Loop over all indices 4702 */ 4703 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ 4704 if( pProbe->pPartIdxWhere!=0 4705 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){ 4706 continue; /* Partial index inappropriate for this query */ 4707 } 4708 rSize = pProbe->aiRowLogEst[0]; 4709 pNew->u.btree.nEq = 0; 4710 pNew->u.btree.nSkip = 0; 4711 pNew->nLTerm = 0; 4712 pNew->iSortIdx = 0; 4713 pNew->rSetup = 0; 4714 pNew->prereq = mExtra; 4715 pNew->nOut = rSize; 4716 pNew->u.btree.pIndex = pProbe; 4717 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); 4718 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ 4719 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); 4720 if( pProbe->tnum<=0 ){ 4721 /* Integer primary key index */ 4722 pNew->wsFlags = WHERE_IPK; 4723 4724 /* Full table scan */ 4725 pNew->iSortIdx = b ? iSortIdx : 0; 4726 /* TUNING: Cost of full table scan is (N*3.0). */ 4727 pNew->rRun = rSize + 16; 4728 ApplyCostMultiplier(pNew->rRun, pTab->costMult); 4729 whereLoopOutputAdjust(pWC, pNew); 4730 rc = whereLoopInsert(pBuilder, pNew); 4731 pNew->nOut = rSize; 4732 if( rc ) break; 4733 }else{ 4734 Bitmask m; 4735 if( pProbe->isCovering ){ 4736 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED; 4737 m = 0; 4738 }else{ 4739 m = pSrc->colUsed & ~columnsInIndex(pProbe); 4740 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; 4741 } 4742 4743 /* Full scan via index */ 4744 if( b 4745 || !HasRowid(pTab) 4746 || ( m==0 4747 && pProbe->bUnordered==0 4748 && (pProbe->szIdxRow<pTab->szTabRow) 4749 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 4750 && sqlite3GlobalConfig.bUseCis 4751 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan) 4752 ) 4753 ){ 4754 pNew->iSortIdx = b ? iSortIdx : 0; 4755 4756 /* The cost of visiting the index rows is N*K, where K is 4757 ** between 1.1 and 3.0, depending on the relative sizes of the 4758 ** index and table rows. If this is a non-covering index scan, 4759 ** also add the cost of visiting table rows (N*3.0). */ 4760 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow; 4761 if( m!=0 ){ 4762 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16); 4763 } 4764 ApplyCostMultiplier(pNew->rRun, pTab->costMult); 4765 whereLoopOutputAdjust(pWC, pNew); 4766 rc = whereLoopInsert(pBuilder, pNew); 4767 pNew->nOut = rSize; 4768 if( rc ) break; 4769 } 4770 } 4771 4772 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); 4773 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 4774 sqlite3Stat4ProbeFree(pBuilder->pRec); 4775 pBuilder->nRecValid = 0; 4776 pBuilder->pRec = 0; 4777 #endif 4778 4779 /* If there was an INDEXED BY clause, then only that one index is 4780 ** considered. */ 4781 if( pSrc->pIndex ) break; 4782 } 4783 return rc; 4784 } 4785 4786 #ifndef SQLITE_OMIT_VIRTUALTABLE 4787 /* 4788 ** Add all WhereLoop objects for a table of the join identified by 4789 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. 4790 */ 4791 static int whereLoopAddVirtual( 4792 WhereLoopBuilder *pBuilder, /* WHERE clause information */ 4793 Bitmask mExtra 4794 ){ 4795 WhereInfo *pWInfo; /* WHERE analysis context */ 4796 Parse *pParse; /* The parsing context */ 4797 WhereClause *pWC; /* The WHERE clause */ 4798 struct SrcList_item *pSrc; /* The FROM clause term to search */ 4799 Table *pTab; 4800 sqlite3 *db; 4801 sqlite3_index_info *pIdxInfo; 4802 struct sqlite3_index_constraint *pIdxCons; 4803 struct sqlite3_index_constraint_usage *pUsage; 4804 WhereTerm *pTerm; 4805 int i, j; 4806 int iTerm, mxTerm; 4807 int nConstraint; 4808 int seenIn = 0; /* True if an IN operator is seen */ 4809 int seenVar = 0; /* True if a non-constant constraint is seen */ 4810 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */ 4811 WhereLoop *pNew; 4812 int rc = SQLITE_OK; 4813 4814 pWInfo = pBuilder->pWInfo; 4815 pParse = pWInfo->pParse; 4816 db = pParse->db; 4817 pWC = pBuilder->pWC; 4818 pNew = pBuilder->pNew; 4819 pSrc = &pWInfo->pTabList->a[pNew->iTab]; 4820 pTab = pSrc->pTab; 4821 assert( IsVirtual(pTab) ); 4822 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy); 4823 if( pIdxInfo==0 ) return SQLITE_NOMEM; 4824 pNew->prereq = 0; 4825 pNew->rSetup = 0; 4826 pNew->wsFlags = WHERE_VIRTUALTABLE; 4827 pNew->nLTerm = 0; 4828 pNew->u.vtab.needFree = 0; 4829 pUsage = pIdxInfo->aConstraintUsage; 4830 nConstraint = pIdxInfo->nConstraint; 4831 if( whereLoopResize(db, pNew, nConstraint) ){ 4832 sqlite3DbFree(db, pIdxInfo); 4833 return SQLITE_NOMEM; 4834 } 4835 4836 for(iPhase=0; iPhase<=3; iPhase++){ 4837 if( !seenIn && (iPhase&1)!=0 ){ 4838 iPhase++; 4839 if( iPhase>3 ) break; 4840 } 4841 if( !seenVar && iPhase>1 ) break; 4842 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 4843 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){ 4844 j = pIdxCons->iTermOffset; 4845 pTerm = &pWC->a[j]; 4846 switch( iPhase ){ 4847 case 0: /* Constants without IN operator */ 4848 pIdxCons->usable = 0; 4849 if( (pTerm->eOperator & WO_IN)!=0 ){ 4850 seenIn = 1; 4851 } 4852 if( pTerm->prereqRight!=0 ){ 4853 seenVar = 1; 4854 }else if( (pTerm->eOperator & WO_IN)==0 ){ 4855 pIdxCons->usable = 1; 4856 } 4857 break; 4858 case 1: /* Constants with IN operators */ 4859 assert( seenIn ); 4860 pIdxCons->usable = (pTerm->prereqRight==0); 4861 break; 4862 case 2: /* Variables without IN */ 4863 assert( seenVar ); 4864 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0; 4865 break; 4866 default: /* Variables with IN */ 4867 assert( seenVar && seenIn ); 4868 pIdxCons->usable = 1; 4869 break; 4870 } 4871 } 4872 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint); 4873 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); 4874 pIdxInfo->idxStr = 0; 4875 pIdxInfo->idxNum = 0; 4876 pIdxInfo->needToFreeIdxStr = 0; 4877 pIdxInfo->orderByConsumed = 0; 4878 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; 4879 pIdxInfo->estimatedRows = 25; 4880 rc = vtabBestIndex(pParse, pTab, pIdxInfo); 4881 if( rc ) goto whereLoopAddVtab_exit; 4882 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 4883 pNew->prereq = mExtra; 4884 mxTerm = -1; 4885 assert( pNew->nLSlot>=nConstraint ); 4886 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0; 4887 pNew->u.vtab.omitMask = 0; 4888 for(i=0; i<nConstraint; i++, pIdxCons++){ 4889 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){ 4890 j = pIdxCons->iTermOffset; 4891 if( iTerm>=nConstraint 4892 || j<0 4893 || j>=pWC->nTerm 4894 || pNew->aLTerm[iTerm]!=0 4895 ){ 4896 rc = SQLITE_ERROR; 4897 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName); 4898 goto whereLoopAddVtab_exit; 4899 } 4900 testcase( iTerm==nConstraint-1 ); 4901 testcase( j==0 ); 4902 testcase( j==pWC->nTerm-1 ); 4903 pTerm = &pWC->a[j]; 4904 pNew->prereq |= pTerm->prereqRight; 4905 assert( iTerm<pNew->nLSlot ); 4906 pNew->aLTerm[iTerm] = pTerm; 4907 if( iTerm>mxTerm ) mxTerm = iTerm; 4908 testcase( iTerm==15 ); 4909 testcase( iTerm==16 ); 4910 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm; 4911 if( (pTerm->eOperator & WO_IN)!=0 ){ 4912 if( pUsage[i].omit==0 ){ 4913 /* Do not attempt to use an IN constraint if the virtual table 4914 ** says that the equivalent EQ constraint cannot be safely omitted. 4915 ** If we do attempt to use such a constraint, some rows might be 4916 ** repeated in the output. */ 4917 break; 4918 } 4919 /* A virtual table that is constrained by an IN clause may not 4920 ** consume the ORDER BY clause because (1) the order of IN terms 4921 ** is not necessarily related to the order of output terms and 4922 ** (2) Multiple outputs from a single IN value will not merge 4923 ** together. */ 4924 pIdxInfo->orderByConsumed = 0; 4925 } 4926 } 4927 } 4928 if( i>=nConstraint ){ 4929 pNew->nLTerm = mxTerm+1; 4930 assert( pNew->nLTerm<=pNew->nLSlot ); 4931 pNew->u.vtab.idxNum = pIdxInfo->idxNum; 4932 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; 4933 pIdxInfo->needToFreeIdxStr = 0; 4934 pNew->u.vtab.idxStr = pIdxInfo->idxStr; 4935 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? 4936 pIdxInfo->nOrderBy : 0); 4937 pNew->rSetup = 0; 4938 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); 4939 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); 4940 whereLoopInsert(pBuilder, pNew); 4941 if( pNew->u.vtab.needFree ){ 4942 sqlite3_free(pNew->u.vtab.idxStr); 4943 pNew->u.vtab.needFree = 0; 4944 } 4945 } 4946 } 4947 4948 whereLoopAddVtab_exit: 4949 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); 4950 sqlite3DbFree(db, pIdxInfo); 4951 return rc; 4952 } 4953 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 4954 4955 /* 4956 ** Add WhereLoop entries to handle OR terms. This works for either 4957 ** btrees or virtual tables. 4958 */ 4959 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){ 4960 WhereInfo *pWInfo = pBuilder->pWInfo; 4961 WhereClause *pWC; 4962 WhereLoop *pNew; 4963 WhereTerm *pTerm, *pWCEnd; 4964 int rc = SQLITE_OK; 4965 int iCur; 4966 WhereClause tempWC; 4967 WhereLoopBuilder sSubBuild; 4968 WhereOrSet sSum, sCur; 4969 struct SrcList_item *pItem; 4970 4971 pWC = pBuilder->pWC; 4972 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK; 4973 pWCEnd = pWC->a + pWC->nTerm; 4974 pNew = pBuilder->pNew; 4975 memset(&sSum, 0, sizeof(sSum)); 4976 pItem = pWInfo->pTabList->a + pNew->iTab; 4977 iCur = pItem->iCursor; 4978 4979 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){ 4980 if( (pTerm->eOperator & WO_OR)!=0 4981 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 4982 ){ 4983 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; 4984 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; 4985 WhereTerm *pOrTerm; 4986 int once = 1; 4987 int i, j; 4988 4989 sSubBuild = *pBuilder; 4990 sSubBuild.pOrderBy = 0; 4991 sSubBuild.pOrSet = &sCur; 4992 4993 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){ 4994 if( (pOrTerm->eOperator & WO_AND)!=0 ){ 4995 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc; 4996 }else if( pOrTerm->leftCursor==iCur ){ 4997 tempWC.pWInfo = pWC->pWInfo; 4998 tempWC.pOuter = pWC; 4999 tempWC.op = TK_AND; 5000 tempWC.nTerm = 1; 5001 tempWC.a = pOrTerm; 5002 sSubBuild.pWC = &tempWC; 5003 }else{ 5004 continue; 5005 } 5006 sCur.n = 0; 5007 #ifndef SQLITE_OMIT_VIRTUALTABLE 5008 if( IsVirtual(pItem->pTab) ){ 5009 rc = whereLoopAddVirtual(&sSubBuild, mExtra); 5010 }else 5011 #endif 5012 { 5013 rc = whereLoopAddBtree(&sSubBuild, mExtra); 5014 } 5015 assert( rc==SQLITE_OK || sCur.n==0 ); 5016 if( sCur.n==0 ){ 5017 sSum.n = 0; 5018 break; 5019 }else if( once ){ 5020 whereOrMove(&sSum, &sCur); 5021 once = 0; 5022 }else{ 5023 WhereOrSet sPrev; 5024 whereOrMove(&sPrev, &sSum); 5025 sSum.n = 0; 5026 for(i=0; i<sPrev.n; i++){ 5027 for(j=0; j<sCur.n; j++){ 5028 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq, 5029 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun), 5030 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut)); 5031 } 5032 } 5033 } 5034 } 5035 pNew->nLTerm = 1; 5036 pNew->aLTerm[0] = pTerm; 5037 pNew->wsFlags = WHERE_MULTI_OR; 5038 pNew->rSetup = 0; 5039 pNew->iSortIdx = 0; 5040 memset(&pNew->u, 0, sizeof(pNew->u)); 5041 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){ 5042 /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs 5043 ** of all sub-scans required by the OR-scan. However, due to rounding 5044 ** errors, it may be that the cost of the OR-scan is equal to its 5045 ** most expensive sub-scan. Add the smallest possible penalty 5046 ** (equivalent to multiplying the cost by 1.07) to ensure that 5047 ** this does not happen. Otherwise, for WHERE clauses such as the 5048 ** following where there is an index on "y": 5049 ** 5050 ** WHERE likelihood(x=?, 0.99) OR y=? 5051 ** 5052 ** the planner may elect to "OR" together a full-table scan and an 5053 ** index lookup. And other similarly odd results. */ 5054 pNew->rRun = sSum.a[i].rRun + 1; 5055 pNew->nOut = sSum.a[i].nOut; 5056 pNew->prereq = sSum.a[i].prereq; 5057 rc = whereLoopInsert(pBuilder, pNew); 5058 } 5059 } 5060 } 5061 return rc; 5062 } 5063 5064 /* 5065 ** Add all WhereLoop objects for all tables 5066 */ 5067 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ 5068 WhereInfo *pWInfo = pBuilder->pWInfo; 5069 Bitmask mExtra = 0; 5070 Bitmask mPrior = 0; 5071 int iTab; 5072 SrcList *pTabList = pWInfo->pTabList; 5073 struct SrcList_item *pItem; 5074 sqlite3 *db = pWInfo->pParse->db; 5075 int nTabList = pWInfo->nLevel; 5076 int rc = SQLITE_OK; 5077 u8 priorJoinType = 0; 5078 WhereLoop *pNew; 5079 5080 /* Loop over the tables in the join, from left to right */ 5081 pNew = pBuilder->pNew; 5082 whereLoopInit(pNew); 5083 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){ 5084 pNew->iTab = iTab; 5085 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor); 5086 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){ 5087 mExtra = mPrior; 5088 } 5089 priorJoinType = pItem->jointype; 5090 if( IsVirtual(pItem->pTab) ){ 5091 rc = whereLoopAddVirtual(pBuilder, mExtra); 5092 }else{ 5093 rc = whereLoopAddBtree(pBuilder, mExtra); 5094 } 5095 if( rc==SQLITE_OK ){ 5096 rc = whereLoopAddOr(pBuilder, mExtra); 5097 } 5098 mPrior |= pNew->maskSelf; 5099 if( rc || db->mallocFailed ) break; 5100 } 5101 whereLoopClear(db, pNew); 5102 return rc; 5103 } 5104 5105 /* 5106 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th 5107 ** parameters) to see if it outputs rows in the requested ORDER BY 5108 ** (or GROUP BY) without requiring a separate sort operation. Return N: 5109 ** 5110 ** N>0: N terms of the ORDER BY clause are satisfied 5111 ** N==0: No terms of the ORDER BY clause are satisfied 5112 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied. 5113 ** 5114 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as 5115 ** strict. With GROUP BY and DISTINCT the only requirement is that 5116 ** equivalent rows appear immediately adjacent to one another. GROUP BY 5117 ** and DISTINCT do not require rows to appear in any particular order as long 5118 ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT 5119 ** the pOrderBy terms can be matched in any order. With ORDER BY, the 5120 ** pOrderBy terms must be matched in strict left-to-right order. 5121 */ 5122 static i8 wherePathSatisfiesOrderBy( 5123 WhereInfo *pWInfo, /* The WHERE clause */ 5124 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */ 5125 WherePath *pPath, /* The WherePath to check */ 5126 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */ 5127 u16 nLoop, /* Number of entries in pPath->aLoop[] */ 5128 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */ 5129 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */ 5130 ){ 5131 u8 revSet; /* True if rev is known */ 5132 u8 rev; /* Composite sort order */ 5133 u8 revIdx; /* Index sort order */ 5134 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */ 5135 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */ 5136 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */ 5137 u16 nKeyCol; /* Number of key columns in pIndex */ 5138 u16 nColumn; /* Total number of ordered columns in the index */ 5139 u16 nOrderBy; /* Number terms in the ORDER BY clause */ 5140 int iLoop; /* Index of WhereLoop in pPath being processed */ 5141 int i, j; /* Loop counters */ 5142 int iCur; /* Cursor number for current WhereLoop */ 5143 int iColumn; /* A column number within table iCur */ 5144 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */ 5145 WhereTerm *pTerm; /* A single term of the WHERE clause */ 5146 Expr *pOBExpr; /* An expression from the ORDER BY clause */ 5147 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */ 5148 Index *pIndex; /* The index associated with pLoop */ 5149 sqlite3 *db = pWInfo->pParse->db; /* Database connection */ 5150 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */ 5151 Bitmask obDone; /* Mask of all ORDER BY terms */ 5152 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */ 5153 Bitmask ready; /* Mask of inner loops */ 5154 5155 /* 5156 ** We say the WhereLoop is "one-row" if it generates no more than one 5157 ** row of output. A WhereLoop is one-row if all of the following are true: 5158 ** (a) All index columns match with WHERE_COLUMN_EQ. 5159 ** (b) The index is unique 5160 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row. 5161 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags. 5162 ** 5163 ** We say the WhereLoop is "order-distinct" if the set of columns from 5164 ** that WhereLoop that are in the ORDER BY clause are different for every 5165 ** row of the WhereLoop. Every one-row WhereLoop is automatically 5166 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause 5167 ** is not order-distinct. To be order-distinct is not quite the same as being 5168 ** UNIQUE since a UNIQUE column or index can have multiple rows that 5169 ** are NULL and NULL values are equivalent for the purpose of order-distinct. 5170 ** To be order-distinct, the columns must be UNIQUE and NOT NULL. 5171 ** 5172 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the 5173 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is 5174 ** automatically order-distinct. 5175 */ 5176 5177 assert( pOrderBy!=0 ); 5178 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0; 5179 5180 nOrderBy = pOrderBy->nExpr; 5181 testcase( nOrderBy==BMS-1 ); 5182 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */ 5183 isOrderDistinct = 1; 5184 obDone = MASKBIT(nOrderBy)-1; 5185 orderDistinctMask = 0; 5186 ready = 0; 5187 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){ 5188 if( iLoop>0 ) ready |= pLoop->maskSelf; 5189 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast; 5190 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){ 5191 if( pLoop->u.vtab.isOrdered ) obSat = obDone; 5192 break; 5193 } 5194 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor; 5195 5196 /* Mark off any ORDER BY term X that is a column in the table of 5197 ** the current loop for which there is term in the WHERE 5198 ** clause of the form X IS NULL or X=? that reference only outer 5199 ** loops. 5200 */ 5201 for(i=0; i<nOrderBy; i++){ 5202 if( MASKBIT(i) & obSat ) continue; 5203 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); 5204 if( pOBExpr->op!=TK_COLUMN ) continue; 5205 if( pOBExpr->iTable!=iCur ) continue; 5206 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, 5207 ~ready, WO_EQ|WO_ISNULL, 0); 5208 if( pTerm==0 ) continue; 5209 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){ 5210 const char *z1, *z2; 5211 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); 5212 if( !pColl ) pColl = db->pDfltColl; 5213 z1 = pColl->zName; 5214 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); 5215 if( !pColl ) pColl = db->pDfltColl; 5216 z2 = pColl->zName; 5217 if( sqlite3StrICmp(z1, z2)!=0 ) continue; 5218 } 5219 obSat |= MASKBIT(i); 5220 } 5221 5222 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ 5223 if( pLoop->wsFlags & WHERE_IPK ){ 5224 pIndex = 0; 5225 nKeyCol = 0; 5226 nColumn = 1; 5227 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ 5228 return 0; 5229 }else{ 5230 nKeyCol = pIndex->nKeyCol; 5231 nColumn = pIndex->nColumn; 5232 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); 5233 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable)); 5234 isOrderDistinct = IsUniqueIndex(pIndex); 5235 } 5236 5237 /* Loop through all columns of the index and deal with the ones 5238 ** that are not constrained by == or IN. 5239 */ 5240 rev = revSet = 0; 5241 distinctColumns = 0; 5242 for(j=0; j<nColumn; j++){ 5243 u8 bOnce; /* True to run the ORDER BY search loop */ 5244 5245 /* Skip over == and IS NULL terms */ 5246 if( j<pLoop->u.btree.nEq 5247 && pLoop->u.btree.nSkip==0 5248 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0 5249 ){ 5250 if( i & WO_ISNULL ){ 5251 testcase( isOrderDistinct ); 5252 isOrderDistinct = 0; 5253 } 5254 continue; 5255 } 5256 5257 /* Get the column number in the table (iColumn) and sort order 5258 ** (revIdx) for the j-th column of the index. 5259 */ 5260 if( pIndex ){ 5261 iColumn = pIndex->aiColumn[j]; 5262 revIdx = pIndex->aSortOrder[j]; 5263 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; 5264 }else{ 5265 iColumn = -1; 5266 revIdx = 0; 5267 } 5268 5269 /* An unconstrained column that might be NULL means that this 5270 ** WhereLoop is not well-ordered 5271 */ 5272 if( isOrderDistinct 5273 && iColumn>=0 5274 && j>=pLoop->u.btree.nEq 5275 && pIndex->pTable->aCol[iColumn].notNull==0 5276 ){ 5277 isOrderDistinct = 0; 5278 } 5279 5280 /* Find the ORDER BY term that corresponds to the j-th column 5281 ** of the index and mark that ORDER BY term off 5282 */ 5283 bOnce = 1; 5284 isMatch = 0; 5285 for(i=0; bOnce && i<nOrderBy; i++){ 5286 if( MASKBIT(i) & obSat ) continue; 5287 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); 5288 testcase( wctrlFlags & WHERE_GROUPBY ); 5289 testcase( wctrlFlags & WHERE_DISTINCTBY ); 5290 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; 5291 if( pOBExpr->op!=TK_COLUMN ) continue; 5292 if( pOBExpr->iTable!=iCur ) continue; 5293 if( pOBExpr->iColumn!=iColumn ) continue; 5294 if( iColumn>=0 ){ 5295 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); 5296 if( !pColl ) pColl = db->pDfltColl; 5297 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; 5298 } 5299 isMatch = 1; 5300 break; 5301 } 5302 if( isMatch && (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){ 5303 /* Make sure the sort order is compatible in an ORDER BY clause. 5304 ** Sort order is irrelevant for a GROUP BY clause. */ 5305 if( revSet ){ 5306 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0; 5307 }else{ 5308 rev = revIdx ^ pOrderBy->a[i].sortOrder; 5309 if( rev ) *pRevMask |= MASKBIT(iLoop); 5310 revSet = 1; 5311 } 5312 } 5313 if( isMatch ){ 5314 if( iColumn<0 ){ 5315 testcase( distinctColumns==0 ); 5316 distinctColumns = 1; 5317 } 5318 obSat |= MASKBIT(i); 5319 }else{ 5320 /* No match found */ 5321 if( j==0 || j<nKeyCol ){ 5322 testcase( isOrderDistinct!=0 ); 5323 isOrderDistinct = 0; 5324 } 5325 break; 5326 } 5327 } /* end Loop over all index columns */ 5328 if( distinctColumns ){ 5329 testcase( isOrderDistinct==0 ); 5330 isOrderDistinct = 1; 5331 } 5332 } /* end-if not one-row */ 5333 5334 /* Mark off any other ORDER BY terms that reference pLoop */ 5335 if( isOrderDistinct ){ 5336 orderDistinctMask |= pLoop->maskSelf; 5337 for(i=0; i<nOrderBy; i++){ 5338 Expr *p; 5339 Bitmask mTerm; 5340 if( MASKBIT(i) & obSat ) continue; 5341 p = pOrderBy->a[i].pExpr; 5342 mTerm = exprTableUsage(&pWInfo->sMaskSet,p); 5343 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; 5344 if( (mTerm&~orderDistinctMask)==0 ){ 5345 obSat |= MASKBIT(i); 5346 } 5347 } 5348 } 5349 } /* End the loop over all WhereLoops from outer-most down to inner-most */ 5350 if( obSat==obDone ) return (i8)nOrderBy; 5351 if( !isOrderDistinct ){ 5352 for(i=nOrderBy-1; i>0; i--){ 5353 Bitmask m = MASKBIT(i) - 1; 5354 if( (obSat&m)==m ) return i; 5355 } 5356 return 0; 5357 } 5358 return -1; 5359 } 5360 5361 5362 /* 5363 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(), 5364 ** the planner assumes that the specified pOrderBy list is actually a GROUP 5365 ** BY clause - and so any order that groups rows as required satisfies the 5366 ** request. 5367 ** 5368 ** Normally, in this case it is not possible for the caller to determine 5369 ** whether or not the rows are really being delivered in sorted order, or 5370 ** just in some other order that provides the required grouping. However, 5371 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then 5372 ** this function may be called on the returned WhereInfo object. It returns 5373 ** true if the rows really will be sorted in the specified order, or false 5374 ** otherwise. 5375 ** 5376 ** For example, assuming: 5377 ** 5378 ** CREATE INDEX i1 ON t1(x, Y); 5379 ** 5380 ** then 5381 ** 5382 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1 5383 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0 5384 */ 5385 int sqlite3WhereIsSorted(WhereInfo *pWInfo){ 5386 assert( pWInfo->wctrlFlags & WHERE_GROUPBY ); 5387 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP ); 5388 return pWInfo->sorted; 5389 } 5390 5391 #ifdef WHERETRACE_ENABLED 5392 /* For debugging use only: */ 5393 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){ 5394 static char zName[65]; 5395 int i; 5396 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; } 5397 if( pLast ) zName[i++] = pLast->cId; 5398 zName[i] = 0; 5399 return zName; 5400 } 5401 #endif 5402 5403 /* 5404 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine 5405 ** attempts to find the lowest cost path that visits each WhereLoop 5406 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields. 5407 ** 5408 ** Assume that the total number of output rows that will need to be sorted 5409 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting 5410 ** costs if nRowEst==0. 5411 ** 5412 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation 5413 ** error occurs. 5414 */ 5415 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){ 5416 int mxChoice; /* Maximum number of simultaneous paths tracked */ 5417 int nLoop; /* Number of terms in the join */ 5418 Parse *pParse; /* Parsing context */ 5419 sqlite3 *db; /* The database connection */ 5420 int iLoop; /* Loop counter over the terms of the join */ 5421 int ii, jj; /* Loop counters */ 5422 int mxI = 0; /* Index of next entry to replace */ 5423 int nOrderBy; /* Number of ORDER BY clause terms */ 5424 LogEst rCost; /* Cost of a path */ 5425 LogEst nOut; /* Number of outputs */ 5426 LogEst mxCost = 0; /* Maximum cost of a set of paths */ 5427 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */ 5428 WherePath *aFrom; /* All nFrom paths at the previous level */ 5429 WherePath *aTo; /* The nTo best paths at the current level */ 5430 WherePath *pFrom; /* An element of aFrom[] that we are working on */ 5431 WherePath *pTo; /* An element of aTo[] that we are working on */ 5432 WhereLoop *pWLoop; /* One of the WhereLoop objects */ 5433 WhereLoop **pX; /* Used to divy up the pSpace memory */ 5434 char *pSpace; /* Temporary memory used by this routine */ 5435 5436 pParse = pWInfo->pParse; 5437 db = pParse->db; 5438 nLoop = pWInfo->nLevel; 5439 /* TUNING: For simple queries, only the best path is tracked. 5440 ** For 2-way joins, the 5 best paths are followed. 5441 ** For joins of 3 or more tables, track the 10 best paths */ 5442 mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10); 5443 assert( nLoop<=pWInfo->pTabList->nSrc ); 5444 WHERETRACE(0x002, ("---- begin solver\n")); 5445 5446 /* Allocate and initialize space for aTo and aFrom */ 5447 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2; 5448 pSpace = sqlite3DbMallocRaw(db, ii); 5449 if( pSpace==0 ) return SQLITE_NOMEM; 5450 aTo = (WherePath*)pSpace; 5451 aFrom = aTo+mxChoice; 5452 memset(aFrom, 0, sizeof(aFrom[0])); 5453 pX = (WhereLoop**)(aFrom+mxChoice); 5454 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){ 5455 pFrom->aLoop = pX; 5456 } 5457 5458 /* Seed the search with a single WherePath containing zero WhereLoops. 5459 ** 5460 ** TUNING: Do not let the number of iterations go above 25. If the cost 5461 ** of computing an automatic index is not paid back within the first 25 5462 ** rows, then do not use the automatic index. */ 5463 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) ); 5464 nFrom = 1; 5465 5466 /* Precompute the cost of sorting the final result set, if the caller 5467 ** to sqlite3WhereBegin() was concerned about sorting */ 5468 if( pWInfo->pOrderBy==0 || nRowEst==0 ){ 5469 aFrom[0].isOrdered = 0; 5470 nOrderBy = 0; 5471 }else{ 5472 aFrom[0].isOrdered = nLoop>0 ? -1 : 1; 5473 nOrderBy = pWInfo->pOrderBy->nExpr; 5474 } 5475 5476 /* Compute successively longer WherePaths using the previous generation 5477 ** of WherePaths as the basis for the next. Keep track of the mxChoice 5478 ** best paths at each generation */ 5479 for(iLoop=0; iLoop<nLoop; iLoop++){ 5480 nTo = 0; 5481 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){ 5482 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){ 5483 Bitmask maskNew; 5484 Bitmask revMask = 0; 5485 i8 isOrdered = pFrom->isOrdered; 5486 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue; 5487 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue; 5488 /* At this point, pWLoop is a candidate to be the next loop. 5489 ** Compute its cost */ 5490 rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow); 5491 rCost = sqlite3LogEstAdd(rCost, pFrom->rCost); 5492 nOut = pFrom->nRow + pWLoop->nOut; 5493 maskNew = pFrom->maskLoop | pWLoop->maskSelf; 5494 if( isOrdered<0 ){ 5495 isOrdered = wherePathSatisfiesOrderBy(pWInfo, 5496 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags, 5497 iLoop, pWLoop, &revMask); 5498 if( isOrdered>=0 && isOrdered<nOrderBy ){ 5499 /* TUNING: Estimated cost of a full external sort, where N is 5500 ** the number of rows to sort is: 5501 ** 5502 ** cost = (3.0 * N * log(N)). 5503 ** 5504 ** Or, if the order-by clause has X terms but only the last Y 5505 ** terms are out of order, then block-sorting will reduce the 5506 ** sorting cost to: 5507 ** 5508 ** cost = (3.0 * N * log(N)) * (Y/X) 5509 ** 5510 ** The (Y/X) term is implemented using stack variable rScale 5511 ** below. */ 5512 LogEst rScale, rSortCost; 5513 assert( nOrderBy>0 && 66==sqlite3LogEst(100) ); 5514 rScale = sqlite3LogEst((nOrderBy-isOrdered)*100/nOrderBy) - 66; 5515 rSortCost = nRowEst + estLog(nRowEst) + rScale + 16; 5516 5517 /* TUNING: The cost of implementing DISTINCT using a B-TREE is 5518 ** similar but with a larger constant of proportionality. 5519 ** Multiply by an additional factor of 3.0. */ 5520 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ 5521 rSortCost += 16; 5522 } 5523 WHERETRACE(0x002, 5524 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n", 5525 rSortCost, (nOrderBy-isOrdered), nOrderBy, rCost, 5526 sqlite3LogEstAdd(rCost,rSortCost))); 5527 rCost = sqlite3LogEstAdd(rCost, rSortCost); 5528 } 5529 }else{ 5530 revMask = pFrom->revLoop; 5531 } 5532 /* Check to see if pWLoop should be added to the mxChoice best so far */ 5533 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){ 5534 if( pTo->maskLoop==maskNew 5535 && ((pTo->isOrdered^isOrdered)&80)==0 5536 ){ 5537 testcase( jj==nTo-1 ); 5538 break; 5539 } 5540 } 5541 if( jj>=nTo ){ 5542 if( nTo>=mxChoice && rCost>=mxCost ){ 5543 #ifdef WHERETRACE_ENABLED /* 0x4 */ 5544 if( sqlite3WhereTrace&0x4 ){ 5545 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n", 5546 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, 5547 isOrdered>=0 ? isOrdered+'0' : '?'); 5548 } 5549 #endif 5550 continue; 5551 } 5552 /* Add a new Path to the aTo[] set */ 5553 if( nTo<mxChoice ){ 5554 /* Increase the size of the aTo set by one */ 5555 jj = nTo++; 5556 }else{ 5557 /* New path replaces the prior worst to keep count below mxChoice */ 5558 jj = mxI; 5559 } 5560 pTo = &aTo[jj]; 5561 #ifdef WHERETRACE_ENABLED /* 0x4 */ 5562 if( sqlite3WhereTrace&0x4 ){ 5563 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n", 5564 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, 5565 isOrdered>=0 ? isOrdered+'0' : '?'); 5566 } 5567 #endif 5568 }else{ 5569 if( pTo->rCost<=rCost ){ 5570 #ifdef WHERETRACE_ENABLED /* 0x4 */ 5571 if( sqlite3WhereTrace&0x4 ){ 5572 sqlite3DebugPrintf( 5573 "Skip %s cost=%-3d,%3d order=%c", 5574 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, 5575 isOrdered>=0 ? isOrdered+'0' : '?'); 5576 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n", 5577 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 5578 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); 5579 } 5580 #endif 5581 testcase( pTo->rCost==rCost ); 5582 continue; 5583 } 5584 testcase( pTo->rCost==rCost+1 ); 5585 /* A new and better score for a previously created equivalent path */ 5586 #ifdef WHERETRACE_ENABLED /* 0x4 */ 5587 if( sqlite3WhereTrace&0x4 ){ 5588 sqlite3DebugPrintf( 5589 "Update %s cost=%-3d,%3d order=%c", 5590 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, 5591 isOrdered>=0 ? isOrdered+'0' : '?'); 5592 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n", 5593 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 5594 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?'); 5595 } 5596 #endif 5597 } 5598 /* pWLoop is a winner. Add it to the set of best so far */ 5599 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf; 5600 pTo->revLoop = revMask; 5601 pTo->nRow = nOut; 5602 pTo->rCost = rCost; 5603 pTo->isOrdered = isOrdered; 5604 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop); 5605 pTo->aLoop[iLoop] = pWLoop; 5606 if( nTo>=mxChoice ){ 5607 mxI = 0; 5608 mxCost = aTo[0].rCost; 5609 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){ 5610 if( pTo->rCost>mxCost ){ 5611 mxCost = pTo->rCost; 5612 mxI = jj; 5613 } 5614 } 5615 } 5616 } 5617 } 5618 5619 #ifdef WHERETRACE_ENABLED /* >=2 */ 5620 if( sqlite3WhereTrace>=2 ){ 5621 sqlite3DebugPrintf("---- after round %d ----\n", iLoop); 5622 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){ 5623 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", 5624 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, 5625 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); 5626 if( pTo->isOrdered>0 ){ 5627 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); 5628 }else{ 5629 sqlite3DebugPrintf("\n"); 5630 } 5631 } 5632 } 5633 #endif 5634 5635 /* Swap the roles of aFrom and aTo for the next generation */ 5636 pFrom = aTo; 5637 aTo = aFrom; 5638 aFrom = pFrom; 5639 nFrom = nTo; 5640 } 5641 5642 if( nFrom==0 ){ 5643 sqlite3ErrorMsg(pParse, "no query solution"); 5644 sqlite3DbFree(db, pSpace); 5645 return SQLITE_ERROR; 5646 } 5647 5648 /* Find the lowest cost path. pFrom will be left pointing to that path */ 5649 pFrom = aFrom; 5650 for(ii=1; ii<nFrom; ii++){ 5651 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii]; 5652 } 5653 assert( pWInfo->nLevel==nLoop ); 5654 /* Load the lowest cost path into pWInfo */ 5655 for(iLoop=0; iLoop<nLoop; iLoop++){ 5656 WhereLevel *pLevel = pWInfo->a + iLoop; 5657 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop]; 5658 pLevel->iFrom = pWLoop->iTab; 5659 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor; 5660 } 5661 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0 5662 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0 5663 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP 5664 && nRowEst 5665 ){ 5666 Bitmask notUsed; 5667 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom, 5668 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used); 5669 if( rc==pWInfo->pResultSet->nExpr ){ 5670 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; 5671 } 5672 } 5673 if( pWInfo->pOrderBy ){ 5674 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ 5675 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ 5676 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; 5677 } 5678 }else{ 5679 pWInfo->nOBSat = pFrom->isOrdered; 5680 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0; 5681 pWInfo->revMask = pFrom->revLoop; 5682 } 5683 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) 5684 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr 5685 ){ 5686 Bitmask notUsed = 0; 5687 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 5688 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], ¬Used 5689 ); 5690 assert( pWInfo->sorted==0 ); 5691 pWInfo->sorted = (nOrder==pWInfo->pOrderBy->nExpr); 5692 } 5693 } 5694 5695 5696 pWInfo->nRowOut = pFrom->nRow; 5697 5698 /* Free temporary memory and return success */ 5699 sqlite3DbFree(db, pSpace); 5700 return SQLITE_OK; 5701 } 5702 5703 /* 5704 ** Most queries use only a single table (they are not joins) and have 5705 ** simple == constraints against indexed fields. This routine attempts 5706 ** to plan those simple cases using much less ceremony than the 5707 ** general-purpose query planner, and thereby yield faster sqlite3_prepare() 5708 ** times for the common case. 5709 ** 5710 ** Return non-zero on success, if this query can be handled by this 5711 ** no-frills query planner. Return zero if this query needs the 5712 ** general-purpose query planner. 5713 */ 5714 static int whereShortCut(WhereLoopBuilder *pBuilder){ 5715 WhereInfo *pWInfo; 5716 struct SrcList_item *pItem; 5717 WhereClause *pWC; 5718 WhereTerm *pTerm; 5719 WhereLoop *pLoop; 5720 int iCur; 5721 int j; 5722 Table *pTab; 5723 Index *pIdx; 5724 5725 pWInfo = pBuilder->pWInfo; 5726 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0; 5727 assert( pWInfo->pTabList->nSrc>=1 ); 5728 pItem = pWInfo->pTabList->a; 5729 pTab = pItem->pTab; 5730 if( IsVirtual(pTab) ) return 0; 5731 if( pItem->zIndex ) return 0; 5732 iCur = pItem->iCursor; 5733 pWC = &pWInfo->sWC; 5734 pLoop = pBuilder->pNew; 5735 pLoop->wsFlags = 0; 5736 pLoop->u.btree.nSkip = 0; 5737 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0); 5738 if( pTerm ){ 5739 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; 5740 pLoop->aLTerm[0] = pTerm; 5741 pLoop->nLTerm = 1; 5742 pLoop->u.btree.nEq = 1; 5743 /* TUNING: Cost of a rowid lookup is 10 */ 5744 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ 5745 }else{ 5746 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 5747 assert( pLoop->aLTermSpace==pLoop->aLTerm ); 5748 assert( ArraySize(pLoop->aLTermSpace)==4 ); 5749 if( !IsUniqueIndex(pIdx) 5750 || pIdx->pPartIdxWhere!=0 5751 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 5752 ) continue; 5753 for(j=0; j<pIdx->nKeyCol; j++){ 5754 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx); 5755 if( pTerm==0 ) break; 5756 pLoop->aLTerm[j] = pTerm; 5757 } 5758 if( j!=pIdx->nKeyCol ) continue; 5759 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; 5760 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ 5761 pLoop->wsFlags |= WHERE_IDX_ONLY; 5762 } 5763 pLoop->nLTerm = j; 5764 pLoop->u.btree.nEq = j; 5765 pLoop->u.btree.pIndex = pIdx; 5766 /* TUNING: Cost of a unique index lookup is 15 */ 5767 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ 5768 break; 5769 } 5770 } 5771 if( pLoop->wsFlags ){ 5772 pLoop->nOut = (LogEst)1; 5773 pWInfo->a[0].pWLoop = pLoop; 5774 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur); 5775 pWInfo->a[0].iTabCur = iCur; 5776 pWInfo->nRowOut = 1; 5777 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; 5778 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ 5779 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 5780 } 5781 #ifdef SQLITE_DEBUG 5782 pLoop->cId = '0'; 5783 #endif 5784 return 1; 5785 } 5786 return 0; 5787 } 5788 5789 /* 5790 ** Generate the beginning of the loop used for WHERE clause processing. 5791 ** The return value is a pointer to an opaque structure that contains 5792 ** information needed to terminate the loop. Later, the calling routine 5793 ** should invoke sqlite3WhereEnd() with the return value of this function 5794 ** in order to complete the WHERE clause processing. 5795 ** 5796 ** If an error occurs, this routine returns NULL. 5797 ** 5798 ** The basic idea is to do a nested loop, one loop for each table in 5799 ** the FROM clause of a select. (INSERT and UPDATE statements are the 5800 ** same as a SELECT with only a single table in the FROM clause.) For 5801 ** example, if the SQL is this: 5802 ** 5803 ** SELECT * FROM t1, t2, t3 WHERE ...; 5804 ** 5805 ** Then the code generated is conceptually like the following: 5806 ** 5807 ** foreach row1 in t1 do \ Code generated 5808 ** foreach row2 in t2 do |-- by sqlite3WhereBegin() 5809 ** foreach row3 in t3 do / 5810 ** ... 5811 ** end \ Code generated 5812 ** end |-- by sqlite3WhereEnd() 5813 ** end / 5814 ** 5815 ** Note that the loops might not be nested in the order in which they 5816 ** appear in the FROM clause if a different order is better able to make 5817 ** use of indices. Note also that when the IN operator appears in 5818 ** the WHERE clause, it might result in additional nested loops for 5819 ** scanning through all values on the right-hand side of the IN. 5820 ** 5821 ** There are Btree cursors associated with each table. t1 uses cursor 5822 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. 5823 ** And so forth. This routine generates code to open those VDBE cursors 5824 ** and sqlite3WhereEnd() generates the code to close them. 5825 ** 5826 ** The code that sqlite3WhereBegin() generates leaves the cursors named 5827 ** in pTabList pointing at their appropriate entries. The [...] code 5828 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract 5829 ** data from the various tables of the loop. 5830 ** 5831 ** If the WHERE clause is empty, the foreach loops must each scan their 5832 ** entire tables. Thus a three-way join is an O(N^3) operation. But if 5833 ** the tables have indices and there are terms in the WHERE clause that 5834 ** refer to those indices, a complete table scan can be avoided and the 5835 ** code will run much faster. Most of the work of this routine is checking 5836 ** to see if there are indices that can be used to speed up the loop. 5837 ** 5838 ** Terms of the WHERE clause are also used to limit which rows actually 5839 ** make it to the "..." in the middle of the loop. After each "foreach", 5840 ** terms of the WHERE clause that use only terms in that loop and outer 5841 ** loops are evaluated and if false a jump is made around all subsequent 5842 ** inner loops (or around the "..." if the test occurs within the inner- 5843 ** most loop) 5844 ** 5845 ** OUTER JOINS 5846 ** 5847 ** An outer join of tables t1 and t2 is conceptally coded as follows: 5848 ** 5849 ** foreach row1 in t1 do 5850 ** flag = 0 5851 ** foreach row2 in t2 do 5852 ** start: 5853 ** ... 5854 ** flag = 1 5855 ** end 5856 ** if flag==0 then 5857 ** move the row2 cursor to a null row 5858 ** goto start 5859 ** fi 5860 ** end 5861 ** 5862 ** ORDER BY CLAUSE PROCESSING 5863 ** 5864 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause 5865 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement 5866 ** if there is one. If there is no ORDER BY clause or if this routine 5867 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL. 5868 ** 5869 ** The iIdxCur parameter is the cursor number of an index. If 5870 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index 5871 ** to use for OR clause processing. The WHERE clause should use this 5872 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is 5873 ** the first cursor in an array of cursors for all indices. iIdxCur should 5874 ** be used to compute the appropriate cursor depending on which index is 5875 ** used. 5876 */ 5877 WhereInfo *sqlite3WhereBegin( 5878 Parse *pParse, /* The parser context */ 5879 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */ 5880 Expr *pWhere, /* The WHERE clause */ 5881 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */ 5882 ExprList *pResultSet, /* Result set of the query */ 5883 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */ 5884 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */ 5885 ){ 5886 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ 5887 int nTabList; /* Number of elements in pTabList */ 5888 WhereInfo *pWInfo; /* Will become the return value of this function */ 5889 Vdbe *v = pParse->pVdbe; /* The virtual database engine */ 5890 Bitmask notReady; /* Cursors that are not yet positioned */ 5891 WhereLoopBuilder sWLB; /* The WhereLoop builder */ 5892 WhereMaskSet *pMaskSet; /* The expression mask set */ 5893 WhereLevel *pLevel; /* A single level in pWInfo->a[] */ 5894 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ 5895 int ii; /* Loop counter */ 5896 sqlite3 *db; /* Database connection */ 5897 int rc; /* Return code */ 5898 5899 5900 /* Variable initialization */ 5901 db = pParse->db; 5902 memset(&sWLB, 0, sizeof(sWLB)); 5903 5904 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ 5905 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); 5906 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; 5907 sWLB.pOrderBy = pOrderBy; 5908 5909 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via 5910 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */ 5911 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){ 5912 wctrlFlags &= ~WHERE_WANT_DISTINCT; 5913 } 5914 5915 /* The number of tables in the FROM clause is limited by the number of 5916 ** bits in a Bitmask 5917 */ 5918 testcase( pTabList->nSrc==BMS ); 5919 if( pTabList->nSrc>BMS ){ 5920 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); 5921 return 0; 5922 } 5923 5924 /* This function normally generates a nested loop for all tables in 5925 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should 5926 ** only generate code for the first table in pTabList and assume that 5927 ** any cursors associated with subsequent tables are uninitialized. 5928 */ 5929 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc; 5930 5931 /* Allocate and initialize the WhereInfo structure that will become the 5932 ** return value. A single allocation is used to store the WhereInfo 5933 ** struct, the contents of WhereInfo.a[], the WhereClause structure 5934 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte 5935 ** field (type Bitmask) it must be aligned on an 8-byte boundary on 5936 ** some architectures. Hence the ROUND8() below. 5937 */ 5938 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); 5939 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop)); 5940 if( db->mallocFailed ){ 5941 sqlite3DbFree(db, pWInfo); 5942 pWInfo = 0; 5943 goto whereBeginError; 5944 } 5945 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; 5946 pWInfo->nLevel = nTabList; 5947 pWInfo->pParse = pParse; 5948 pWInfo->pTabList = pTabList; 5949 pWInfo->pOrderBy = pOrderBy; 5950 pWInfo->pResultSet = pResultSet; 5951 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v); 5952 pWInfo->wctrlFlags = wctrlFlags; 5953 pWInfo->savedNQueryLoop = pParse->nQueryLoop; 5954 pMaskSet = &pWInfo->sMaskSet; 5955 sWLB.pWInfo = pWInfo; 5956 sWLB.pWC = &pWInfo->sWC; 5957 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); 5958 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); 5959 whereLoopInit(sWLB.pNew); 5960 #ifdef SQLITE_DEBUG 5961 sWLB.pNew->cId = '*'; 5962 #endif 5963 5964 /* Split the WHERE clause into separate subexpressions where each 5965 ** subexpression is separated by an AND operator. 5966 */ 5967 initMaskSet(pMaskSet); 5968 whereClauseInit(&pWInfo->sWC, pWInfo); 5969 whereSplit(&pWInfo->sWC, pWhere, TK_AND); 5970 5971 /* Special case: a WHERE clause that is constant. Evaluate the 5972 ** expression and either jump over all of the code or fall thru. 5973 */ 5974 for(ii=0; ii<sWLB.pWC->nTerm; ii++){ 5975 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){ 5976 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak, 5977 SQLITE_JUMPIFNULL); 5978 sWLB.pWC->a[ii].wtFlags |= TERM_CODED; 5979 } 5980 } 5981 5982 /* Special case: No FROM clause 5983 */ 5984 if( nTabList==0 ){ 5985 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; 5986 if( wctrlFlags & WHERE_WANT_DISTINCT ){ 5987 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 5988 } 5989 } 5990 5991 /* Assign a bit from the bitmask to every term in the FROM clause. 5992 ** 5993 ** When assigning bitmask values to FROM clause cursors, it must be 5994 ** the case that if X is the bitmask for the N-th FROM clause term then 5995 ** the bitmask for all FROM clause terms to the left of the N-th term 5996 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use 5997 ** its Expr.iRightJoinTable value to find the bitmask of the right table 5998 ** of the join. Subtracting one from the right table bitmask gives a 5999 ** bitmask for all tables to the left of the join. Knowing the bitmask 6000 ** for all tables to the left of a left join is important. Ticket #3015. 6001 ** 6002 ** Note that bitmasks are created for all pTabList->nSrc tables in 6003 ** pTabList, not just the first nTabList tables. nTabList is normally 6004 ** equal to pTabList->nSrc but might be shortened to 1 if the 6005 ** WHERE_ONETABLE_ONLY flag is set. 6006 */ 6007 for(ii=0; ii<pTabList->nSrc; ii++){ 6008 createMask(pMaskSet, pTabList->a[ii].iCursor); 6009 } 6010 #ifndef NDEBUG 6011 { 6012 Bitmask toTheLeft = 0; 6013 for(ii=0; ii<pTabList->nSrc; ii++){ 6014 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor); 6015 assert( (m-1)==toTheLeft ); 6016 toTheLeft |= m; 6017 } 6018 } 6019 #endif 6020 6021 /* Analyze all of the subexpressions. Note that exprAnalyze() might 6022 ** add new virtual terms onto the end of the WHERE clause. We do not 6023 ** want to analyze these virtual terms, so start analyzing at the end 6024 ** and work forward so that the added virtual terms are never processed. 6025 */ 6026 exprAnalyzeAll(pTabList, &pWInfo->sWC); 6027 if( db->mallocFailed ){ 6028 goto whereBeginError; 6029 } 6030 6031 if( wctrlFlags & WHERE_WANT_DISTINCT ){ 6032 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ 6033 /* The DISTINCT marking is pointless. Ignore it. */ 6034 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; 6035 }else if( pOrderBy==0 ){ 6036 /* Try to ORDER BY the result set to make distinct processing easier */ 6037 pWInfo->wctrlFlags |= WHERE_DISTINCTBY; 6038 pWInfo->pOrderBy = pResultSet; 6039 } 6040 } 6041 6042 /* Construct the WhereLoop objects */ 6043 WHERETRACE(0xffff,("*** Optimizer Start ***\n")); 6044 /* Display all terms of the WHERE clause */ 6045 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN) 6046 if( sqlite3WhereTrace & 0x100 ){ 6047 int i; 6048 Vdbe *v = pParse->pVdbe; 6049 sqlite3ExplainBegin(v); 6050 for(i=0; i<sWLB.pWC->nTerm; i++){ 6051 sqlite3ExplainPrintf(v, "#%-2d ", i); 6052 sqlite3ExplainPush(v); 6053 whereExplainTerm(v, &sWLB.pWC->a[i]); 6054 sqlite3ExplainPop(v); 6055 sqlite3ExplainNL(v); 6056 } 6057 sqlite3ExplainFinish(v); 6058 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v)); 6059 } 6060 #endif 6061 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ 6062 rc = whereLoopAddAll(&sWLB); 6063 if( rc ) goto whereBeginError; 6064 6065 /* Display all of the WhereLoop objects if wheretrace is enabled */ 6066 #ifdef WHERETRACE_ENABLED /* !=0 */ 6067 if( sqlite3WhereTrace ){ 6068 WhereLoop *p; 6069 int i; 6070 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" 6071 "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; 6072 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ 6073 p->cId = zLabel[i%sizeof(zLabel)]; 6074 whereLoopPrint(p, sWLB.pWC); 6075 } 6076 } 6077 #endif 6078 6079 wherePathSolver(pWInfo, 0); 6080 if( db->mallocFailed ) goto whereBeginError; 6081 if( pWInfo->pOrderBy ){ 6082 wherePathSolver(pWInfo, pWInfo->nRowOut+1); 6083 if( db->mallocFailed ) goto whereBeginError; 6084 } 6085 } 6086 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ 6087 pWInfo->revMask = (Bitmask)(-1); 6088 } 6089 if( pParse->nErr || NEVER(db->mallocFailed) ){ 6090 goto whereBeginError; 6091 } 6092 #ifdef WHERETRACE_ENABLED /* !=0 */ 6093 if( sqlite3WhereTrace ){ 6094 int ii; 6095 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); 6096 if( pWInfo->nOBSat>0 ){ 6097 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); 6098 } 6099 switch( pWInfo->eDistinct ){ 6100 case WHERE_DISTINCT_UNIQUE: { 6101 sqlite3DebugPrintf(" DISTINCT=unique"); 6102 break; 6103 } 6104 case WHERE_DISTINCT_ORDERED: { 6105 sqlite3DebugPrintf(" DISTINCT=ordered"); 6106 break; 6107 } 6108 case WHERE_DISTINCT_UNORDERED: { 6109 sqlite3DebugPrintf(" DISTINCT=unordered"); 6110 break; 6111 } 6112 } 6113 sqlite3DebugPrintf("\n"); 6114 for(ii=0; ii<pWInfo->nLevel; ii++){ 6115 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); 6116 } 6117 } 6118 #endif 6119 /* Attempt to omit tables from the join that do not effect the result */ 6120 if( pWInfo->nLevel>=2 6121 && pResultSet!=0 6122 && OptimizationEnabled(db, SQLITE_OmitNoopJoin) 6123 ){ 6124 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet); 6125 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy); 6126 while( pWInfo->nLevel>=2 ){ 6127 WhereTerm *pTerm, *pEnd; 6128 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; 6129 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break; 6130 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 6131 && (pLoop->wsFlags & WHERE_ONEROW)==0 6132 ){ 6133 break; 6134 } 6135 if( (tabUsed & pLoop->maskSelf)!=0 ) break; 6136 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; 6137 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ 6138 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 6139 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) 6140 ){ 6141 break; 6142 } 6143 } 6144 if( pTerm<pEnd ) break; 6145 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId)); 6146 pWInfo->nLevel--; 6147 nTabList--; 6148 } 6149 } 6150 WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); 6151 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; 6152 6153 /* If the caller is an UPDATE or DELETE statement that is requesting 6154 ** to use a one-pass algorithm, determine if this is appropriate. 6155 ** The one-pass algorithm only works if the WHERE clause constrains 6156 ** the statement to update a single row. 6157 */ 6158 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); 6159 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 6160 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){ 6161 pWInfo->okOnePass = 1; 6162 if( HasRowid(pTabList->a[0].pTab) ){ 6163 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY; 6164 } 6165 } 6166 6167 /* Open all tables in the pTabList and any indices selected for 6168 ** searching those tables. 6169 */ 6170 notReady = ~(Bitmask)0; 6171 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){ 6172 Table *pTab; /* Table to open */ 6173 int iDb; /* Index of database containing table/index */ 6174 struct SrcList_item *pTabItem; 6175 6176 pTabItem = &pTabList->a[pLevel->iFrom]; 6177 pTab = pTabItem->pTab; 6178 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 6179 pLoop = pLevel->pWLoop; 6180 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ 6181 /* Do nothing */ 6182 }else 6183 #ifndef SQLITE_OMIT_VIRTUALTABLE 6184 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 6185 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 6186 int iCur = pTabItem->iCursor; 6187 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); 6188 }else if( IsVirtual(pTab) ){ 6189 /* noop */ 6190 }else 6191 #endif 6192 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 6193 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){ 6194 int op = OP_OpenRead; 6195 if( pWInfo->okOnePass ){ 6196 op = OP_OpenWrite; 6197 pWInfo->aiCurOnePass[0] = pTabItem->iCursor; 6198 }; 6199 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); 6200 assert( pTabItem->iCursor==pLevel->iTabCur ); 6201 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 ); 6202 testcase( !pWInfo->okOnePass && pTab->nCol==BMS ); 6203 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){ 6204 Bitmask b = pTabItem->colUsed; 6205 int n = 0; 6206 for(; b; b=b>>1, n++){} 6207 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 6208 SQLITE_INT_TO_PTR(n), P4_INT32); 6209 assert( n<=pTab->nCol ); 6210 } 6211 }else{ 6212 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 6213 } 6214 if( pLoop->wsFlags & WHERE_INDEXED ){ 6215 Index *pIx = pLoop->u.btree.pIndex; 6216 int iIndexCur; 6217 int op = OP_OpenRead; 6218 /* iIdxCur is always set if to a positive value if ONEPASS is possible */ 6219 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); 6220 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) 6221 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 6222 ){ 6223 /* This is one term of an OR-optimization using the PRIMARY KEY of a 6224 ** WITHOUT ROWID table. No need for a separate index */ 6225 iIndexCur = pLevel->iTabCur; 6226 op = 0; 6227 }else if( pWInfo->okOnePass ){ 6228 Index *pJ = pTabItem->pTab->pIndex; 6229 iIndexCur = iIdxCur; 6230 assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); 6231 while( ALWAYS(pJ) && pJ!=pIx ){ 6232 iIndexCur++; 6233 pJ = pJ->pNext; 6234 } 6235 op = OP_OpenWrite; 6236 pWInfo->aiCurOnePass[1] = iIndexCur; 6237 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){ 6238 iIndexCur = iIdxCur; 6239 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx; 6240 }else{ 6241 iIndexCur = pParse->nTab++; 6242 } 6243 pLevel->iIdxCur = iIndexCur; 6244 assert( pIx->pSchema==pTab->pSchema ); 6245 assert( iIndexCur>=0 ); 6246 if( op ){ 6247 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); 6248 sqlite3VdbeSetP4KeyInfo(pParse, pIx); 6249 VdbeComment((v, "%s", pIx->zName)); 6250 } 6251 } 6252 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); 6253 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor); 6254 } 6255 pWInfo->iTop = sqlite3VdbeCurrentAddr(v); 6256 if( db->mallocFailed ) goto whereBeginError; 6257 6258 /* Generate the code to do the search. Each iteration of the for 6259 ** loop below generates code for a single nested loop of the VM 6260 ** program. 6261 */ 6262 notReady = ~(Bitmask)0; 6263 for(ii=0; ii<nTabList; ii++){ 6264 pLevel = &pWInfo->a[ii]; 6265 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 6266 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ 6267 constructAutomaticIndex(pParse, &pWInfo->sWC, 6268 &pTabList->a[pLevel->iFrom], notReady, pLevel); 6269 if( db->mallocFailed ) goto whereBeginError; 6270 } 6271 #endif 6272 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags); 6273 pLevel->addrBody = sqlite3VdbeCurrentAddr(v); 6274 notReady = codeOneLoopStart(pWInfo, ii, notReady); 6275 pWInfo->iContinue = pLevel->addrCont; 6276 } 6277 6278 /* Done. */ 6279 VdbeModuleComment((v, "Begin WHERE-core")); 6280 return pWInfo; 6281 6282 /* Jump here if malloc fails */ 6283 whereBeginError: 6284 if( pWInfo ){ 6285 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 6286 whereInfoFree(db, pWInfo); 6287 } 6288 return 0; 6289 } 6290 6291 /* 6292 ** Generate the end of the WHERE loop. See comments on 6293 ** sqlite3WhereBegin() for additional information. 6294 */ 6295 void sqlite3WhereEnd(WhereInfo *pWInfo){ 6296 Parse *pParse = pWInfo->pParse; 6297 Vdbe *v = pParse->pVdbe; 6298 int i; 6299 WhereLevel *pLevel; 6300 WhereLoop *pLoop; 6301 SrcList *pTabList = pWInfo->pTabList; 6302 sqlite3 *db = pParse->db; 6303 6304 /* Generate loop termination code. 6305 */ 6306 VdbeModuleComment((v, "End WHERE-core")); 6307 sqlite3ExprCacheClear(pParse); 6308 for(i=pWInfo->nLevel-1; i>=0; i--){ 6309 int addr; 6310 pLevel = &pWInfo->a[i]; 6311 pLoop = pLevel->pWLoop; 6312 sqlite3VdbeResolveLabel(v, pLevel->addrCont); 6313 if( pLevel->op!=OP_Noop ){ 6314 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3); 6315 sqlite3VdbeChangeP5(v, pLevel->p5); 6316 VdbeCoverage(v); 6317 VdbeCoverageIf(v, pLevel->op==OP_Next); 6318 VdbeCoverageIf(v, pLevel->op==OP_Prev); 6319 VdbeCoverageIf(v, pLevel->op==OP_VNext); 6320 } 6321 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ 6322 struct InLoop *pIn; 6323 int j; 6324 sqlite3VdbeResolveLabel(v, pLevel->addrNxt); 6325 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ 6326 sqlite3VdbeJumpHere(v, pIn->addrInTop+1); 6327 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); 6328 VdbeCoverage(v); 6329 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); 6330 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); 6331 sqlite3VdbeJumpHere(v, pIn->addrInTop-1); 6332 } 6333 sqlite3DbFree(db, pLevel->u.in.aInLoop); 6334 } 6335 sqlite3VdbeResolveLabel(v, pLevel->addrBrk); 6336 if( pLevel->addrSkip ){ 6337 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip); 6338 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); 6339 sqlite3VdbeJumpHere(v, pLevel->addrSkip); 6340 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); 6341 } 6342 if( pLevel->iLeftJoin ){ 6343 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); 6344 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 6345 || (pLoop->wsFlags & WHERE_INDEXED)!=0 ); 6346 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){ 6347 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); 6348 } 6349 if( pLoop->wsFlags & WHERE_INDEXED ){ 6350 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); 6351 } 6352 if( pLevel->op==OP_Return ){ 6353 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); 6354 }else{ 6355 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst); 6356 } 6357 sqlite3VdbeJumpHere(v, addr); 6358 } 6359 VdbeModuleComment((v, "End WHERE-loop%d: %s", i, 6360 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); 6361 } 6362 6363 /* The "break" point is here, just past the end of the outer loop. 6364 ** Set it. 6365 */ 6366 sqlite3VdbeResolveLabel(v, pWInfo->iBreak); 6367 6368 assert( pWInfo->nLevel<=pTabList->nSrc ); 6369 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ 6370 int k, last; 6371 VdbeOp *pOp; 6372 Index *pIdx = 0; 6373 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; 6374 Table *pTab = pTabItem->pTab; 6375 assert( pTab!=0 ); 6376 pLoop = pLevel->pWLoop; 6377 6378 /* For a co-routine, change all OP_Column references to the table of 6379 ** the co-routine into OP_SCopy of result contained in a register. 6380 ** OP_Rowid becomes OP_Null. 6381 */ 6382 if( pTabItem->viaCoroutine && !db->mallocFailed ){ 6383 last = sqlite3VdbeCurrentAddr(v); 6384 k = pLevel->addrBody; 6385 pOp = sqlite3VdbeGetOp(v, k); 6386 for(; k<last; k++, pOp++){ 6387 if( pOp->p1!=pLevel->iTabCur ) continue; 6388 if( pOp->opcode==OP_Column ){ 6389 pOp->opcode = OP_Copy; 6390 pOp->p1 = pOp->p2 + pTabItem->regResult; 6391 pOp->p2 = pOp->p3; 6392 pOp->p3 = 0; 6393 }else if( pOp->opcode==OP_Rowid ){ 6394 pOp->opcode = OP_Null; 6395 pOp->p1 = 0; 6396 pOp->p3 = 0; 6397 } 6398 } 6399 continue; 6400 } 6401 6402 /* Close all of the cursors that were opened by sqlite3WhereBegin. 6403 ** Except, do not close cursors that will be reused by the OR optimization 6404 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors 6405 ** created for the ONEPASS optimization. 6406 */ 6407 if( (pTab->tabFlags & TF_Ephemeral)==0 6408 && pTab->pSelect==0 6409 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 6410 ){ 6411 int ws = pLoop->wsFlags; 6412 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){ 6413 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); 6414 } 6415 if( (ws & WHERE_INDEXED)!=0 6416 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 6417 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] 6418 ){ 6419 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); 6420 } 6421 } 6422 6423 /* If this scan uses an index, make VDBE code substitutions to read data 6424 ** from the index instead of from the table where possible. In some cases 6425 ** this optimization prevents the table from ever being read, which can 6426 ** yield a significant performance boost. 6427 ** 6428 ** Calls to the code generator in between sqlite3WhereBegin and 6429 ** sqlite3WhereEnd will have created code that references the table 6430 ** directly. This loop scans all that code looking for opcodes 6431 ** that reference the table and converts them into opcodes that 6432 ** reference the index. 6433 */ 6434 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ 6435 pIdx = pLoop->u.btree.pIndex; 6436 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ 6437 pIdx = pLevel->u.pCovidx; 6438 } 6439 if( pIdx && !db->mallocFailed ){ 6440 last = sqlite3VdbeCurrentAddr(v); 6441 k = pLevel->addrBody; 6442 pOp = sqlite3VdbeGetOp(v, k); 6443 for(; k<last; k++, pOp++){ 6444 if( pOp->p1!=pLevel->iTabCur ) continue; 6445 if( pOp->opcode==OP_Column ){ 6446 int x = pOp->p2; 6447 assert( pIdx->pTable==pTab ); 6448 if( !HasRowid(pTab) ){ 6449 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 6450 x = pPk->aiColumn[x]; 6451 } 6452 x = sqlite3ColumnOfIndex(pIdx, x); 6453 if( x>=0 ){ 6454 pOp->p2 = x; 6455 pOp->p1 = pLevel->iIdxCur; 6456 } 6457 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 ); 6458 }else if( pOp->opcode==OP_Rowid ){ 6459 pOp->p1 = pLevel->iIdxCur; 6460 pOp->opcode = OP_IdxRowid; 6461 } 6462 } 6463 } 6464 } 6465 6466 /* Final cleanup 6467 */ 6468 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 6469 whereInfoFree(db, pWInfo); 6470 return; 6471 } 6472