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