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