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 21 /* 22 ** Trace output macros 23 */ 24 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) 25 int sqlite3WhereTrace = 0; 26 #endif 27 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG) 28 # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X 29 #else 30 # define WHERETRACE(X) 31 #endif 32 33 /* Forward reference 34 */ 35 typedef struct WhereClause WhereClause; 36 typedef struct WhereMaskSet WhereMaskSet; 37 typedef struct WhereOrInfo WhereOrInfo; 38 typedef struct WhereAndInfo WhereAndInfo; 39 typedef struct WhereCost WhereCost; 40 41 /* 42 ** The query generator uses an array of instances of this structure to 43 ** help it analyze the subexpressions of the WHERE clause. Each WHERE 44 ** clause subexpression is separated from the others by AND operators, 45 ** usually, or sometimes subexpressions separated by OR. 46 ** 47 ** All WhereTerms are collected into a single WhereClause structure. 48 ** The following identity holds: 49 ** 50 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm 51 ** 52 ** When a term is of the form: 53 ** 54 ** X <op> <expr> 55 ** 56 ** where X is a column name and <op> is one of certain operators, 57 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the 58 ** cursor number and column number for X. WhereTerm.eOperator records 59 ** the <op> using a bitmask encoding defined by WO_xxx below. The 60 ** use of a bitmask encoding for the operator allows us to search 61 ** quickly for terms that match any of several different operators. 62 ** 63 ** A WhereTerm might also be two or more subterms connected by OR: 64 ** 65 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR .... 66 ** 67 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR 68 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that 69 ** is collected about the 70 ** 71 ** If a term in the WHERE clause does not match either of the two previous 72 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set 73 ** to the original subexpression content and wtFlags is set up appropriately 74 ** but no other fields in the WhereTerm object are meaningful. 75 ** 76 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers, 77 ** but they do so indirectly. A single WhereMaskSet structure translates 78 ** cursor number into bits and the translated bit is stored in the prereq 79 ** fields. The translation is used in order to maximize the number of 80 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be 81 ** spread out over the non-negative integers. For example, the cursor 82 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet 83 ** translates these sparse cursor numbers into consecutive integers 84 ** beginning with 0 in order to make the best possible use of the available 85 ** bits in the Bitmask. So, in the example above, the cursor numbers 86 ** would be mapped into integers 0 through 7. 87 ** 88 ** The number of terms in a join is limited by the number of bits 89 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite 90 ** is only able to process joins with 64 or fewer tables. 91 */ 92 typedef struct WhereTerm WhereTerm; 93 struct WhereTerm { 94 Expr *pExpr; /* Pointer to the subexpression that is this term */ 95 int iParent; /* Disable pWC->a[iParent] when this term disabled */ 96 int leftCursor; /* Cursor number of X in "X <op> <expr>" */ 97 union { 98 int leftColumn; /* Column number of X in "X <op> <expr>" */ 99 WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */ 100 WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */ 101 } u; 102 u16 eOperator; /* A WO_xx value describing <op> */ 103 u8 wtFlags; /* TERM_xxx bit flags. See below */ 104 u8 nChild; /* Number of children that must disable us */ 105 WhereClause *pWC; /* The clause this term is part of */ 106 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */ 107 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */ 108 }; 109 110 /* 111 ** Allowed values of WhereTerm.wtFlags 112 */ 113 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */ 114 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ 115 #define TERM_CODED 0x04 /* This term is already coded */ 116 #define TERM_COPIED 0x08 /* Has a child */ 117 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */ 118 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */ 119 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */ 120 121 /* 122 ** An instance of the following structure holds all information about a 123 ** WHERE clause. Mostly this is a container for one or more WhereTerms. 124 */ 125 struct WhereClause { 126 Parse *pParse; /* The parser context */ 127 WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */ 128 Bitmask vmask; /* Bitmask identifying virtual table cursors */ 129 u8 op; /* Split operator. TK_AND or TK_OR */ 130 int nTerm; /* Number of terms */ 131 int nSlot; /* Number of entries in a[] */ 132 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */ 133 #if defined(SQLITE_SMALL_STACK) 134 WhereTerm aStatic[1]; /* Initial static space for a[] */ 135 #else 136 WhereTerm aStatic[8]; /* Initial static space for a[] */ 137 #endif 138 }; 139 140 /* 141 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to 142 ** a dynamically allocated instance of the following structure. 143 */ 144 struct WhereOrInfo { 145 WhereClause wc; /* Decomposition into subterms */ 146 Bitmask indexable; /* Bitmask of all indexable tables in the clause */ 147 }; 148 149 /* 150 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to 151 ** a dynamically allocated instance of the following structure. 152 */ 153 struct WhereAndInfo { 154 WhereClause wc; /* The subexpression broken out */ 155 }; 156 157 /* 158 ** An instance of the following structure keeps track of a mapping 159 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm. 160 ** 161 ** The VDBE cursor numbers are small integers contained in 162 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE 163 ** clause, the cursor numbers might not begin with 0 and they might 164 ** contain gaps in the numbering sequence. But we want to make maximum 165 ** use of the bits in our bitmasks. This structure provides a mapping 166 ** from the sparse cursor numbers into consecutive integers beginning 167 ** with 0. 168 ** 169 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask 170 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A. 171 ** 172 ** For example, if the WHERE clause expression used these VDBE 173 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure 174 ** would map those cursor numbers into bits 0 through 5. 175 ** 176 ** Note that the mapping is not necessarily ordered. In the example 177 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0, 178 ** 57->5, 73->4. Or one of 719 other combinations might be used. It 179 ** does not really matter. What is important is that sparse cursor 180 ** numbers all get mapped into bit numbers that begin with 0 and contain 181 ** no gaps. 182 */ 183 struct WhereMaskSet { 184 int n; /* Number of assigned cursor values */ 185 int ix[BMS]; /* Cursor assigned to each bit */ 186 }; 187 188 /* 189 ** A WhereCost object records a lookup strategy and the estimated 190 ** cost of pursuing that strategy. 191 */ 192 struct WhereCost { 193 WherePlan plan; /* The lookup strategy */ 194 double rCost; /* Overall cost of pursuing this search strategy */ 195 double nRow; /* Estimated number of output rows */ 196 Bitmask used; /* Bitmask of cursors used by this plan */ 197 }; 198 199 /* 200 ** Bitmasks for the operators that indices are able to exploit. An 201 ** OR-ed combination of these values can be used when searching for 202 ** terms in the where clause. 203 */ 204 #define WO_IN 0x001 205 #define WO_EQ 0x002 206 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ)) 207 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ)) 208 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ)) 209 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ)) 210 #define WO_MATCH 0x040 211 #define WO_ISNULL 0x080 212 #define WO_OR 0x100 /* Two or more OR-connected terms */ 213 #define WO_AND 0x200 /* Two or more AND-connected terms */ 214 215 #define WO_ALL 0xfff /* Mask of all possible WO_* values */ 216 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */ 217 218 /* 219 ** Value for wsFlags returned by bestIndex() and stored in 220 ** WhereLevel.wsFlags. These flags determine which search 221 ** strategies are appropriate. 222 ** 223 ** The least significant 12 bits is reserved as a mask for WO_ values above. 224 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL. 225 ** But if the table is the right table of a left join, WhereLevel.wsFlags 226 ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as 227 ** the "op" parameter to findTerm when we are resolving equality constraints. 228 ** ISNULL constraints will then not be used on the right table of a left 229 ** join. Tickets #2177 and #2189. 230 */ 231 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */ 232 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */ 233 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */ 234 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */ 235 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */ 236 #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */ 237 #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */ 238 #define WHERE_NOT_FULLSCAN 0x000f3000 /* Does not do a full table scan */ 239 #define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */ 240 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */ 241 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */ 242 #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */ 243 #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */ 244 #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */ 245 #define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */ 246 #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */ 247 #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */ 248 #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */ 249 250 /* 251 ** Initialize a preallocated WhereClause structure. 252 */ 253 static void whereClauseInit( 254 WhereClause *pWC, /* The WhereClause to be initialized */ 255 Parse *pParse, /* The parsing context */ 256 WhereMaskSet *pMaskSet /* Mapping from table cursor numbers to bitmasks */ 257 ){ 258 pWC->pParse = pParse; 259 pWC->pMaskSet = pMaskSet; 260 pWC->nTerm = 0; 261 pWC->nSlot = ArraySize(pWC->aStatic); 262 pWC->a = pWC->aStatic; 263 pWC->vmask = 0; 264 } 265 266 /* Forward reference */ 267 static void whereClauseClear(WhereClause*); 268 269 /* 270 ** Deallocate all memory associated with a WhereOrInfo object. 271 */ 272 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ 273 whereClauseClear(&p->wc); 274 sqlite3DbFree(db, p); 275 } 276 277 /* 278 ** Deallocate all memory associated with a WhereAndInfo object. 279 */ 280 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ 281 whereClauseClear(&p->wc); 282 sqlite3DbFree(db, p); 283 } 284 285 /* 286 ** Deallocate a WhereClause structure. The WhereClause structure 287 ** itself is not freed. This routine is the inverse of whereClauseInit(). 288 */ 289 static void whereClauseClear(WhereClause *pWC){ 290 int i; 291 WhereTerm *a; 292 sqlite3 *db = pWC->pParse->db; 293 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ 294 if( a->wtFlags & TERM_DYNAMIC ){ 295 sqlite3ExprDelete(db, a->pExpr); 296 } 297 if( a->wtFlags & TERM_ORINFO ){ 298 whereOrInfoDelete(db, a->u.pOrInfo); 299 }else if( a->wtFlags & TERM_ANDINFO ){ 300 whereAndInfoDelete(db, a->u.pAndInfo); 301 } 302 } 303 if( pWC->a!=pWC->aStatic ){ 304 sqlite3DbFree(db, pWC->a); 305 } 306 } 307 308 /* 309 ** Add a single new WhereTerm entry to the WhereClause object pWC. 310 ** The new WhereTerm object is constructed from Expr p and with wtFlags. 311 ** The index in pWC->a[] of the new WhereTerm is returned on success. 312 ** 0 is returned if the new WhereTerm could not be added due to a memory 313 ** allocation error. The memory allocation failure will be recorded in 314 ** the db->mallocFailed flag so that higher-level functions can detect it. 315 ** 316 ** This routine will increase the size of the pWC->a[] array as necessary. 317 ** 318 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility 319 ** for freeing the expression p is assumed by the WhereClause object pWC. 320 ** This is true even if this routine fails to allocate a new WhereTerm. 321 ** 322 ** WARNING: This routine might reallocate the space used to store 323 ** WhereTerms. All pointers to WhereTerms should be invalidated after 324 ** calling this routine. Such pointers may be reinitialized by referencing 325 ** the pWC->a[] array. 326 */ 327 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){ 328 WhereTerm *pTerm; 329 int idx; 330 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */ 331 if( pWC->nTerm>=pWC->nSlot ){ 332 WhereTerm *pOld = pWC->a; 333 sqlite3 *db = pWC->pParse->db; 334 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); 335 if( pWC->a==0 ){ 336 if( wtFlags & TERM_DYNAMIC ){ 337 sqlite3ExprDelete(db, p); 338 } 339 pWC->a = pOld; 340 return 0; 341 } 342 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); 343 if( pOld!=pWC->aStatic ){ 344 sqlite3DbFree(db, pOld); 345 } 346 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); 347 } 348 pTerm = &pWC->a[idx = pWC->nTerm++]; 349 pTerm->pExpr = p; 350 pTerm->wtFlags = wtFlags; 351 pTerm->pWC = pWC; 352 pTerm->iParent = -1; 353 return idx; 354 } 355 356 /* 357 ** This routine identifies subexpressions in the WHERE clause where 358 ** each subexpression is separated by the AND operator or some other 359 ** operator specified in the op parameter. The WhereClause structure 360 ** is filled with pointers to subexpressions. For example: 361 ** 362 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) 363 ** \________/ \_______________/ \________________/ 364 ** slot[0] slot[1] slot[2] 365 ** 366 ** The original WHERE clause in pExpr is unaltered. All this routine 367 ** does is make slot[] entries point to substructure within pExpr. 368 ** 369 ** In the previous sentence and in the diagram, "slot[]" refers to 370 ** the WhereClause.a[] array. The slot[] array grows as needed to contain 371 ** all terms of the WHERE clause. 372 */ 373 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){ 374 pWC->op = (u8)op; 375 if( pExpr==0 ) return; 376 if( pExpr->op!=op ){ 377 whereClauseInsert(pWC, pExpr, 0); 378 }else{ 379 whereSplit(pWC, pExpr->pLeft, op); 380 whereSplit(pWC, pExpr->pRight, op); 381 } 382 } 383 384 /* 385 ** Initialize an expression mask set (a WhereMaskSet object) 386 */ 387 #define initMaskSet(P) memset(P, 0, sizeof(*P)) 388 389 /* 390 ** Return the bitmask for the given cursor number. Return 0 if 391 ** iCursor is not in the set. 392 */ 393 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){ 394 int i; 395 assert( pMaskSet->n<=sizeof(Bitmask)*8 ); 396 for(i=0; i<pMaskSet->n; i++){ 397 if( pMaskSet->ix[i]==iCursor ){ 398 return ((Bitmask)1)<<i; 399 } 400 } 401 return 0; 402 } 403 404 /* 405 ** Create a new mask for cursor iCursor. 406 ** 407 ** There is one cursor per table in the FROM clause. The number of 408 ** tables in the FROM clause is limited by a test early in the 409 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] 410 ** array will never overflow. 411 */ 412 static void createMask(WhereMaskSet *pMaskSet, int iCursor){ 413 assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); 414 pMaskSet->ix[pMaskSet->n++] = iCursor; 415 } 416 417 /* 418 ** This routine walks (recursively) an expression tree and generates 419 ** a bitmask indicating which tables are used in that expression 420 ** tree. 421 ** 422 ** In order for this routine to work, the calling function must have 423 ** previously invoked sqlite3ResolveExprNames() on the expression. See 424 ** the header comment on that routine for additional information. 425 ** The sqlite3ResolveExprNames() routines looks for column names and 426 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to 427 ** the VDBE cursor number of the table. This routine just has to 428 ** translate the cursor numbers into bitmask values and OR all 429 ** the bitmasks together. 430 */ 431 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*); 432 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*); 433 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){ 434 Bitmask mask = 0; 435 if( p==0 ) return 0; 436 if( p->op==TK_COLUMN ){ 437 mask = getMask(pMaskSet, p->iTable); 438 return mask; 439 } 440 mask = exprTableUsage(pMaskSet, p->pRight); 441 mask |= exprTableUsage(pMaskSet, p->pLeft); 442 if( ExprHasProperty(p, EP_xIsSelect) ){ 443 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect); 444 }else{ 445 mask |= exprListTableUsage(pMaskSet, p->x.pList); 446 } 447 return mask; 448 } 449 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){ 450 int i; 451 Bitmask mask = 0; 452 if( pList ){ 453 for(i=0; i<pList->nExpr; i++){ 454 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr); 455 } 456 } 457 return mask; 458 } 459 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){ 460 Bitmask mask = 0; 461 while( pS ){ 462 mask |= exprListTableUsage(pMaskSet, pS->pEList); 463 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy); 464 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy); 465 mask |= exprTableUsage(pMaskSet, pS->pWhere); 466 mask |= exprTableUsage(pMaskSet, pS->pHaving); 467 pS = pS->pPrior; 468 } 469 return mask; 470 } 471 472 /* 473 ** Return TRUE if the given operator is one of the operators that is 474 ** allowed for an indexable WHERE clause term. The allowed operators are 475 ** "=", "<", ">", "<=", ">=", and "IN". 476 ** 477 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be 478 ** of one of the following forms: column = expression column > expression 479 ** column >= expression column < expression column <= expression 480 ** expression = column expression > column expression >= column 481 ** expression < column expression <= column column IN 482 ** (expression-list) column IN (subquery) column IS NULL 483 */ 484 static int allowedOp(int op){ 485 assert( TK_GT>TK_EQ && TK_GT<TK_GE ); 486 assert( TK_LT>TK_EQ && TK_LT<TK_GE ); 487 assert( TK_LE>TK_EQ && TK_LE<TK_GE ); 488 assert( TK_GE==TK_EQ+4 ); 489 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL; 490 } 491 492 /* 493 ** Swap two objects of type TYPE. 494 */ 495 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} 496 497 /* 498 ** Commute a comparison operator. Expressions of the form "X op Y" 499 ** are converted into "Y op X". 500 ** 501 ** If a collation sequence is associated with either the left or right 502 ** side of the comparison, it remains associated with the same side after 503 ** the commutation. So "Y collate NOCASE op X" becomes 504 ** "X collate NOCASE op Y". This is because any collation sequence on 505 ** the left hand side of a comparison overrides any collation sequence 506 ** attached to the right. For the same reason the EP_ExpCollate flag 507 ** is not commuted. 508 */ 509 static void exprCommute(Parse *pParse, Expr *pExpr){ 510 u16 expRight = (pExpr->pRight->flags & EP_ExpCollate); 511 u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate); 512 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); 513 pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight); 514 pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 515 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl); 516 pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft; 517 pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight; 518 SWAP(Expr*,pExpr->pRight,pExpr->pLeft); 519 if( pExpr->op>=TK_GT ){ 520 assert( TK_LT==TK_GT+2 ); 521 assert( TK_GE==TK_LE+2 ); 522 assert( TK_GT>TK_EQ ); 523 assert( TK_GT<TK_LE ); 524 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE ); 525 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; 526 } 527 } 528 529 /* 530 ** Translate from TK_xx operator to WO_xx bitmask. 531 */ 532 static u16 operatorMask(int op){ 533 u16 c; 534 assert( allowedOp(op) ); 535 if( op==TK_IN ){ 536 c = WO_IN; 537 }else if( op==TK_ISNULL ){ 538 c = WO_ISNULL; 539 }else{ 540 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); 541 c = (u16)(WO_EQ<<(op-TK_EQ)); 542 } 543 assert( op!=TK_ISNULL || c==WO_ISNULL ); 544 assert( op!=TK_IN || c==WO_IN ); 545 assert( op!=TK_EQ || c==WO_EQ ); 546 assert( op!=TK_LT || c==WO_LT ); 547 assert( op!=TK_LE || c==WO_LE ); 548 assert( op!=TK_GT || c==WO_GT ); 549 assert( op!=TK_GE || c==WO_GE ); 550 return c; 551 } 552 553 /* 554 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>" 555 ** where X is a reference to the iColumn of table iCur and <op> is one of 556 ** the WO_xx operator codes specified by the op parameter. 557 ** Return a pointer to the term. Return 0 if not found. 558 */ 559 static WhereTerm *findTerm( 560 WhereClause *pWC, /* The WHERE clause to be searched */ 561 int iCur, /* Cursor number of LHS */ 562 int iColumn, /* Column number of LHS */ 563 Bitmask notReady, /* RHS must not overlap with this mask */ 564 u32 op, /* Mask of WO_xx values describing operator */ 565 Index *pIdx /* Must be compatible with this index, if not NULL */ 566 ){ 567 WhereTerm *pTerm; 568 int k; 569 assert( iCur>=0 ); 570 op &= WO_ALL; 571 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){ 572 if( pTerm->leftCursor==iCur 573 && (pTerm->prereqRight & notReady)==0 574 && pTerm->u.leftColumn==iColumn 575 && (pTerm->eOperator & op)!=0 576 ){ 577 if( pIdx && pTerm->eOperator!=WO_ISNULL ){ 578 Expr *pX = pTerm->pExpr; 579 CollSeq *pColl; 580 char idxaff; 581 int j; 582 Parse *pParse = pWC->pParse; 583 584 idxaff = pIdx->pTable->aCol[iColumn].affinity; 585 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue; 586 587 /* Figure out the collation sequence required from an index for 588 ** it to be useful for optimising expression pX. Store this 589 ** value in variable pColl. 590 */ 591 assert(pX->pLeft); 592 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); 593 assert(pColl || pParse->nErr); 594 595 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){ 596 if( NEVER(j>=pIdx->nColumn) ) return 0; 597 } 598 if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue; 599 } 600 return pTerm; 601 } 602 } 603 return 0; 604 } 605 606 /* Forward reference */ 607 static void exprAnalyze(SrcList*, WhereClause*, int); 608 609 /* 610 ** Call exprAnalyze on all terms in a WHERE clause. 611 ** 612 ** 613 */ 614 static void exprAnalyzeAll( 615 SrcList *pTabList, /* the FROM clause */ 616 WhereClause *pWC /* the WHERE clause to be analyzed */ 617 ){ 618 int i; 619 for(i=pWC->nTerm-1; i>=0; i--){ 620 exprAnalyze(pTabList, pWC, i); 621 } 622 } 623 624 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION 625 /* 626 ** Check to see if the given expression is a LIKE or GLOB operator that 627 ** can be optimized using inequality constraints. Return TRUE if it is 628 ** so and false if not. 629 ** 630 ** In order for the operator to be optimizible, the RHS must be a string 631 ** literal that does not begin with a wildcard. 632 */ 633 static int isLikeOrGlob( 634 Parse *pParse, /* Parsing and code generating context */ 635 Expr *pExpr, /* Test this expression */ 636 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ 637 int *pisComplete, /* True if the only wildcard is % in the last character */ 638 int *pnoCase /* True if uppercase is equivalent to lowercase */ 639 ){ 640 const char *z = 0; /* String on RHS of LIKE operator */ 641 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ 642 ExprList *pList; /* List of operands to the LIKE operator */ 643 int c; /* One character in z[] */ 644 int cnt; /* Number of non-wildcard prefix characters */ 645 char wc[3]; /* Wildcard characters */ 646 sqlite3 *db = pParse->db; /* Database connection */ 647 sqlite3_value *pVal = 0; 648 int op; /* Opcode of pRight */ 649 650 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ 651 return 0; 652 } 653 #ifdef SQLITE_EBCDIC 654 if( *pnoCase ) return 0; 655 #endif 656 pList = pExpr->x.pList; 657 pLeft = pList->a[1].pExpr; 658 if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){ 659 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must 660 ** be the name of an indexed column with TEXT affinity. */ 661 return 0; 662 } 663 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */ 664 665 pRight = pList->a[0].pExpr; 666 op = pRight->op; 667 if( op==TK_REGISTER ){ 668 op = pRight->op2; 669 } 670 if( op==TK_VARIABLE ){ 671 Vdbe *pReprepare = pParse->pReprepare; 672 int iCol = pRight->iColumn; 673 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE); 674 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ 675 z = (char *)sqlite3_value_text(pVal); 676 } 677 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */ 678 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); 679 }else if( op==TK_STRING ){ 680 z = pRight->u.zToken; 681 } 682 if( z ){ 683 cnt = 0; 684 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ 685 cnt++; 686 } 687 if( cnt!=0 && 255!=(u8)z[cnt-1] ){ 688 Expr *pPrefix; 689 *pisComplete = c==wc[0] && z[cnt+1]==0; 690 pPrefix = sqlite3Expr(db, TK_STRING, z); 691 if( pPrefix ) pPrefix->u.zToken[cnt] = 0; 692 *ppPrefix = pPrefix; 693 if( op==TK_VARIABLE ){ 694 Vdbe *v = pParse->pVdbe; 695 sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */ 696 if( *pisComplete && pRight->u.zToken[1] ){ 697 /* If the rhs of the LIKE expression is a variable, and the current 698 ** value of the variable means there is no need to invoke the LIKE 699 ** function, then no OP_Variable will be added to the program. 700 ** This causes problems for the sqlite3_bind_parameter_name() 701 ** API. To workaround them, add a dummy OP_Variable here. 702 */ 703 int r1 = sqlite3GetTempReg(pParse); 704 sqlite3ExprCodeTarget(pParse, pRight, r1); 705 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); 706 sqlite3ReleaseTempReg(pParse, r1); 707 } 708 } 709 }else{ 710 z = 0; 711 } 712 } 713 714 sqlite3ValueFree(pVal); 715 return (z!=0); 716 } 717 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ 718 719 720 #ifndef SQLITE_OMIT_VIRTUALTABLE 721 /* 722 ** Check to see if the given expression is of the form 723 ** 724 ** column MATCH expr 725 ** 726 ** If it is then return TRUE. If not, return FALSE. 727 */ 728 static int isMatchOfColumn( 729 Expr *pExpr /* Test this expression */ 730 ){ 731 ExprList *pList; 732 733 if( pExpr->op!=TK_FUNCTION ){ 734 return 0; 735 } 736 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){ 737 return 0; 738 } 739 pList = pExpr->x.pList; 740 if( pList->nExpr!=2 ){ 741 return 0; 742 } 743 if( pList->a[1].pExpr->op != TK_COLUMN ){ 744 return 0; 745 } 746 return 1; 747 } 748 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 749 750 /* 751 ** If the pBase expression originated in the ON or USING clause of 752 ** a join, then transfer the appropriate markings over to derived. 753 */ 754 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ 755 pDerived->flags |= pBase->flags & EP_FromJoin; 756 pDerived->iRightJoinTable = pBase->iRightJoinTable; 757 } 758 759 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) 760 /* 761 ** Analyze a term that consists of two or more OR-connected 762 ** subterms. So in: 763 ** 764 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) 765 ** ^^^^^^^^^^^^^^^^^^^^ 766 ** 767 ** This routine analyzes terms such as the middle term in the above example. 768 ** A WhereOrTerm object is computed and attached to the term under 769 ** analysis, regardless of the outcome of the analysis. Hence: 770 ** 771 ** WhereTerm.wtFlags |= TERM_ORINFO 772 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object 773 ** 774 ** The term being analyzed must have two or more of OR-connected subterms. 775 ** A single subterm might be a set of AND-connected sub-subterms. 776 ** Examples of terms under analysis: 777 ** 778 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 779 ** (B) x=expr1 OR expr2=x OR x=expr3 780 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) 781 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') 782 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) 783 ** 784 ** CASE 1: 785 ** 786 ** If all subterms are of the form T.C=expr for some single column of C 787 ** a single table T (as shown in example B above) then create a new virtual 788 ** term that is an equivalent IN expression. In other words, if the term 789 ** being analyzed is: 790 ** 791 ** x = expr1 OR expr2 = x OR x = expr3 792 ** 793 ** then create a new virtual term like this: 794 ** 795 ** x IN (expr1,expr2,expr3) 796 ** 797 ** CASE 2: 798 ** 799 ** If all subterms are indexable by a single table T, then set 800 ** 801 ** WhereTerm.eOperator = WO_OR 802 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T 803 ** 804 ** A subterm is "indexable" if it is of the form 805 ** "T.C <op> <expr>" where C is any column of table T and 806 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". 807 ** A subterm is also indexable if it is an AND of two or more 808 ** subsubterms at least one of which is indexable. Indexable AND 809 ** subterms have their eOperator set to WO_AND and they have 810 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object. 811 ** 812 ** From another point of view, "indexable" means that the subterm could 813 ** potentially be used with an index if an appropriate index exists. 814 ** This analysis does not consider whether or not the index exists; that 815 ** is something the bestIndex() routine will determine. This analysis 816 ** only looks at whether subterms appropriate for indexing exist. 817 ** 818 ** All examples A through E above all satisfy case 2. But if a term 819 ** also statisfies case 1 (such as B) we know that the optimizer will 820 ** always prefer case 1, so in that case we pretend that case 2 is not 821 ** satisfied. 822 ** 823 ** It might be the case that multiple tables are indexable. For example, 824 ** (E) above is indexable on tables P, Q, and R. 825 ** 826 ** Terms that satisfy case 2 are candidates for lookup by using 827 ** separate indices to find rowids for each subterm and composing 828 ** the union of all rowids using a RowSet object. This is similar 829 ** to "bitmap indices" in other database engines. 830 ** 831 ** OTHERWISE: 832 ** 833 ** If neither case 1 nor case 2 apply, then leave the eOperator set to 834 ** zero. This term is not useful for search. 835 */ 836 static void exprAnalyzeOrTerm( 837 SrcList *pSrc, /* the FROM clause */ 838 WhereClause *pWC, /* the complete WHERE clause */ 839 int idxTerm /* Index of the OR-term to be analyzed */ 840 ){ 841 Parse *pParse = pWC->pParse; /* Parser context */ 842 sqlite3 *db = pParse->db; /* Database connection */ 843 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ 844 Expr *pExpr = pTerm->pExpr; /* The expression of the term */ 845 WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */ 846 int i; /* Loop counters */ 847 WhereClause *pOrWc; /* Breakup of pTerm into subterms */ 848 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ 849 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ 850 Bitmask chngToIN; /* Tables that might satisfy case 1 */ 851 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ 852 853 /* 854 ** Break the OR clause into its separate subterms. The subterms are 855 ** stored in a WhereClause structure containing within the WhereOrInfo 856 ** object that is attached to the original OR clause term. 857 */ 858 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); 859 assert( pExpr->op==TK_OR ); 860 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); 861 if( pOrInfo==0 ) return; 862 pTerm->wtFlags |= TERM_ORINFO; 863 pOrWc = &pOrInfo->wc; 864 whereClauseInit(pOrWc, pWC->pParse, pMaskSet); 865 whereSplit(pOrWc, pExpr, TK_OR); 866 exprAnalyzeAll(pSrc, pOrWc); 867 if( db->mallocFailed ) return; 868 assert( pOrWc->nTerm>=2 ); 869 870 /* 871 ** Compute the set of tables that might satisfy cases 1 or 2. 872 */ 873 indexable = ~(Bitmask)0; 874 chngToIN = ~(pWC->vmask); 875 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ 876 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ 877 WhereAndInfo *pAndInfo; 878 assert( pOrTerm->eOperator==0 ); 879 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); 880 chngToIN = 0; 881 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo)); 882 if( pAndInfo ){ 883 WhereClause *pAndWC; 884 WhereTerm *pAndTerm; 885 int j; 886 Bitmask b = 0; 887 pOrTerm->u.pAndInfo = pAndInfo; 888 pOrTerm->wtFlags |= TERM_ANDINFO; 889 pOrTerm->eOperator = WO_AND; 890 pAndWC = &pAndInfo->wc; 891 whereClauseInit(pAndWC, pWC->pParse, pMaskSet); 892 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND); 893 exprAnalyzeAll(pSrc, pAndWC); 894 testcase( db->mallocFailed ); 895 if( !db->mallocFailed ){ 896 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){ 897 assert( pAndTerm->pExpr ); 898 if( allowedOp(pAndTerm->pExpr->op) ){ 899 b |= getMask(pMaskSet, pAndTerm->leftCursor); 900 } 901 } 902 } 903 indexable &= b; 904 } 905 }else if( pOrTerm->wtFlags & TERM_COPIED ){ 906 /* Skip this term for now. We revisit it when we process the 907 ** corresponding TERM_VIRTUAL term */ 908 }else{ 909 Bitmask b; 910 b = getMask(pMaskSet, pOrTerm->leftCursor); 911 if( pOrTerm->wtFlags & TERM_VIRTUAL ){ 912 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; 913 b |= getMask(pMaskSet, pOther->leftCursor); 914 } 915 indexable &= b; 916 if( pOrTerm->eOperator!=WO_EQ ){ 917 chngToIN = 0; 918 }else{ 919 chngToIN &= b; 920 } 921 } 922 } 923 924 /* 925 ** Record the set of tables that satisfy case 2. The set might be 926 ** empty. 927 */ 928 pOrInfo->indexable = indexable; 929 pTerm->eOperator = indexable==0 ? 0 : WO_OR; 930 931 /* 932 ** chngToIN holds a set of tables that *might* satisfy case 1. But 933 ** we have to do some additional checking to see if case 1 really 934 ** is satisfied. 935 ** 936 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means 937 ** that there is no possibility of transforming the OR clause into an 938 ** IN operator because one or more terms in the OR clause contain 939 ** something other than == on a column in the single table. The 1-bit 940 ** case means that every term of the OR clause is of the form 941 ** "table.column=expr" for some single table. The one bit that is set 942 ** will correspond to the common table. We still need to check to make 943 ** sure the same column is used on all terms. The 2-bit case is when 944 ** the all terms are of the form "table1.column=table2.column". It 945 ** might be possible to form an IN operator with either table1.column 946 ** or table2.column as the LHS if either is common to every term of 947 ** the OR clause. 948 ** 949 ** Note that terms of the form "table.column1=table.column2" (the 950 ** same table on both sizes of the ==) cannot be optimized. 951 */ 952 if( chngToIN ){ 953 int okToChngToIN = 0; /* True if the conversion to IN is valid */ 954 int iColumn = -1; /* Column index on lhs of IN operator */ 955 int iCursor = -1; /* Table cursor common to all terms */ 956 int j = 0; /* Loop counter */ 957 958 /* Search for a table and column that appears on one side or the 959 ** other of the == operator in every subterm. That table and column 960 ** will be recorded in iCursor and iColumn. There might not be any 961 ** such table and column. Set okToChngToIN if an appropriate table 962 ** and column is found but leave okToChngToIN false if not found. 963 */ 964 for(j=0; j<2 && !okToChngToIN; j++){ 965 pOrTerm = pOrWc->a; 966 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ 967 assert( pOrTerm->eOperator==WO_EQ ); 968 pOrTerm->wtFlags &= ~TERM_OR_OK; 969 if( pOrTerm->leftCursor==iCursor ){ 970 /* This is the 2-bit case and we are on the second iteration and 971 ** current term is from the first iteration. So skip this term. */ 972 assert( j==1 ); 973 continue; 974 } 975 if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){ 976 /* This term must be of the form t1.a==t2.b where t2 is in the 977 ** chngToIN set but t1 is not. This term will be either preceeded 978 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term 979 ** and use its inversion. */ 980 testcase( pOrTerm->wtFlags & TERM_COPIED ); 981 testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); 982 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); 983 continue; 984 } 985 iColumn = pOrTerm->u.leftColumn; 986 iCursor = pOrTerm->leftCursor; 987 break; 988 } 989 if( i<0 ){ 990 /* No candidate table+column was found. This can only occur 991 ** on the second iteration */ 992 assert( j==1 ); 993 assert( (chngToIN&(chngToIN-1))==0 ); 994 assert( chngToIN==getMask(pMaskSet, iCursor) ); 995 break; 996 } 997 testcase( j==1 ); 998 999 /* We have found a candidate table and column. Check to see if that 1000 ** table and column is common to every term in the OR clause */ 1001 okToChngToIN = 1; 1002 for(; i>=0 && okToChngToIN; i--, pOrTerm++){ 1003 assert( pOrTerm->eOperator==WO_EQ ); 1004 if( pOrTerm->leftCursor!=iCursor ){ 1005 pOrTerm->wtFlags &= ~TERM_OR_OK; 1006 }else if( pOrTerm->u.leftColumn!=iColumn ){ 1007 okToChngToIN = 0; 1008 }else{ 1009 int affLeft, affRight; 1010 /* If the right-hand side is also a column, then the affinities 1011 ** of both right and left sides must be such that no type 1012 ** conversions are required on the right. (Ticket #2249) 1013 */ 1014 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); 1015 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); 1016 if( affRight!=0 && affRight!=affLeft ){ 1017 okToChngToIN = 0; 1018 }else{ 1019 pOrTerm->wtFlags |= TERM_OR_OK; 1020 } 1021 } 1022 } 1023 } 1024 1025 /* At this point, okToChngToIN is true if original pTerm satisfies 1026 ** case 1. In that case, construct a new virtual term that is 1027 ** pTerm converted into an IN operator. 1028 ** 1029 ** EV: R-00211-15100 1030 */ 1031 if( okToChngToIN ){ 1032 Expr *pDup; /* A transient duplicate expression */ 1033 ExprList *pList = 0; /* The RHS of the IN operator */ 1034 Expr *pLeft = 0; /* The LHS of the IN operator */ 1035 Expr *pNew; /* The complete IN operator */ 1036 1037 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ 1038 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; 1039 assert( pOrTerm->eOperator==WO_EQ ); 1040 assert( pOrTerm->leftCursor==iCursor ); 1041 assert( pOrTerm->u.leftColumn==iColumn ); 1042 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); 1043 pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup); 1044 pLeft = pOrTerm->pExpr->pLeft; 1045 } 1046 assert( pLeft!=0 ); 1047 pDup = sqlite3ExprDup(db, pLeft, 0); 1048 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0); 1049 if( pNew ){ 1050 int idxNew; 1051 transferJoinMarkings(pNew, pExpr); 1052 assert( !ExprHasProperty(pNew, EP_xIsSelect) ); 1053 pNew->x.pList = pList; 1054 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); 1055 testcase( idxNew==0 ); 1056 exprAnalyze(pSrc, pWC, idxNew); 1057 pTerm = &pWC->a[idxTerm]; 1058 pWC->a[idxNew].iParent = idxTerm; 1059 pTerm->nChild = 1; 1060 }else{ 1061 sqlite3ExprListDelete(db, pList); 1062 } 1063 pTerm->eOperator = 0; /* case 1 trumps case 2 */ 1064 } 1065 } 1066 } 1067 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ 1068 1069 1070 /* 1071 ** The input to this routine is an WhereTerm structure with only the 1072 ** "pExpr" field filled in. The job of this routine is to analyze the 1073 ** subexpression and populate all the other fields of the WhereTerm 1074 ** structure. 1075 ** 1076 ** If the expression is of the form "<expr> <op> X" it gets commuted 1077 ** to the standard form of "X <op> <expr>". 1078 ** 1079 ** If the expression is of the form "X <op> Y" where both X and Y are 1080 ** columns, then the original expression is unchanged and a new virtual 1081 ** term of the form "Y <op> X" is added to the WHERE clause and 1082 ** analyzed separately. The original term is marked with TERM_COPIED 1083 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr 1084 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it 1085 ** is a commuted copy of a prior term.) The original term has nChild=1 1086 ** and the copy has idxParent set to the index of the original term. 1087 */ 1088 static void exprAnalyze( 1089 SrcList *pSrc, /* the FROM clause */ 1090 WhereClause *pWC, /* the WHERE clause */ 1091 int idxTerm /* Index of the term to be analyzed */ 1092 ){ 1093 WhereTerm *pTerm; /* The term to be analyzed */ 1094 WhereMaskSet *pMaskSet; /* Set of table index masks */ 1095 Expr *pExpr; /* The expression to be analyzed */ 1096 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ 1097 Bitmask prereqAll; /* Prerequesites of pExpr */ 1098 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ 1099 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ 1100 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ 1101 int noCase = 0; /* LIKE/GLOB distinguishes case */ 1102 int op; /* Top-level operator. pExpr->op */ 1103 Parse *pParse = pWC->pParse; /* Parsing context */ 1104 sqlite3 *db = pParse->db; /* Database connection */ 1105 1106 if( db->mallocFailed ){ 1107 return; 1108 } 1109 pTerm = &pWC->a[idxTerm]; 1110 pMaskSet = pWC->pMaskSet; 1111 pExpr = pTerm->pExpr; 1112 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft); 1113 op = pExpr->op; 1114 if( op==TK_IN ){ 1115 assert( pExpr->pRight==0 ); 1116 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 1117 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect); 1118 }else{ 1119 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList); 1120 } 1121 }else if( op==TK_ISNULL ){ 1122 pTerm->prereqRight = 0; 1123 }else{ 1124 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight); 1125 } 1126 prereqAll = exprTableUsage(pMaskSet, pExpr); 1127 if( ExprHasProperty(pExpr, EP_FromJoin) ){ 1128 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable); 1129 prereqAll |= x; 1130 extraRight = x-1; /* ON clause terms may not be used with an index 1131 ** on left table of a LEFT JOIN. Ticket #3015 */ 1132 } 1133 pTerm->prereqAll = prereqAll; 1134 pTerm->leftCursor = -1; 1135 pTerm->iParent = -1; 1136 pTerm->eOperator = 0; 1137 if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){ 1138 Expr *pLeft = pExpr->pLeft; 1139 Expr *pRight = pExpr->pRight; 1140 if( pLeft->op==TK_COLUMN ){ 1141 pTerm->leftCursor = pLeft->iTable; 1142 pTerm->u.leftColumn = pLeft->iColumn; 1143 pTerm->eOperator = operatorMask(op); 1144 } 1145 if( pRight && pRight->op==TK_COLUMN ){ 1146 WhereTerm *pNew; 1147 Expr *pDup; 1148 if( pTerm->leftCursor>=0 ){ 1149 int idxNew; 1150 pDup = sqlite3ExprDup(db, pExpr, 0); 1151 if( db->mallocFailed ){ 1152 sqlite3ExprDelete(db, pDup); 1153 return; 1154 } 1155 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); 1156 if( idxNew==0 ) return; 1157 pNew = &pWC->a[idxNew]; 1158 pNew->iParent = idxTerm; 1159 pTerm = &pWC->a[idxTerm]; 1160 pTerm->nChild = 1; 1161 pTerm->wtFlags |= TERM_COPIED; 1162 }else{ 1163 pDup = pExpr; 1164 pNew = pTerm; 1165 } 1166 exprCommute(pParse, pDup); 1167 pLeft = pDup->pLeft; 1168 pNew->leftCursor = pLeft->iTable; 1169 pNew->u.leftColumn = pLeft->iColumn; 1170 testcase( (prereqLeft | extraRight) != prereqLeft ); 1171 pNew->prereqRight = prereqLeft | extraRight; 1172 pNew->prereqAll = prereqAll; 1173 pNew->eOperator = operatorMask(pDup->op); 1174 } 1175 } 1176 1177 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION 1178 /* If a term is the BETWEEN operator, create two new virtual terms 1179 ** that define the range that the BETWEEN implements. For example: 1180 ** 1181 ** a BETWEEN b AND c 1182 ** 1183 ** is converted into: 1184 ** 1185 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) 1186 ** 1187 ** The two new terms are added onto the end of the WhereClause object. 1188 ** The new terms are "dynamic" and are children of the original BETWEEN 1189 ** term. That means that if the BETWEEN term is coded, the children are 1190 ** skipped. Or, if the children are satisfied by an index, the original 1191 ** BETWEEN term is skipped. 1192 */ 1193 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ 1194 ExprList *pList = pExpr->x.pList; 1195 int i; 1196 static const u8 ops[] = {TK_GE, TK_LE}; 1197 assert( pList!=0 ); 1198 assert( pList->nExpr==2 ); 1199 for(i=0; i<2; i++){ 1200 Expr *pNewExpr; 1201 int idxNew; 1202 pNewExpr = sqlite3PExpr(pParse, ops[i], 1203 sqlite3ExprDup(db, pExpr->pLeft, 0), 1204 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0); 1205 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); 1206 testcase( idxNew==0 ); 1207 exprAnalyze(pSrc, pWC, idxNew); 1208 pTerm = &pWC->a[idxTerm]; 1209 pWC->a[idxNew].iParent = idxTerm; 1210 } 1211 pTerm->nChild = 2; 1212 } 1213 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ 1214 1215 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) 1216 /* Analyze a term that is composed of two or more subterms connected by 1217 ** an OR operator. 1218 */ 1219 else if( pExpr->op==TK_OR ){ 1220 assert( pWC->op==TK_AND ); 1221 exprAnalyzeOrTerm(pSrc, pWC, idxTerm); 1222 pTerm = &pWC->a[idxTerm]; 1223 } 1224 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 1225 1226 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION 1227 /* Add constraints to reduce the search space on a LIKE or GLOB 1228 ** operator. 1229 ** 1230 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints 1231 ** 1232 ** x>='abc' AND x<'abd' AND x LIKE 'abc%' 1233 ** 1234 ** The last character of the prefix "abc" is incremented to form the 1235 ** termination condition "abd". 1236 */ 1237 if( pWC->op==TK_AND 1238 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) 1239 ){ 1240 Expr *pLeft; /* LHS of LIKE/GLOB operator */ 1241 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ 1242 Expr *pNewExpr1; 1243 Expr *pNewExpr2; 1244 int idxNew1; 1245 int idxNew2; 1246 CollSeq *pColl; /* Collating sequence to use */ 1247 1248 pLeft = pExpr->x.pList->a[1].pExpr; 1249 pStr2 = sqlite3ExprDup(db, pStr1, 0); 1250 if( !db->mallocFailed ){ 1251 u8 c, *pC; /* Last character before the first wildcard */ 1252 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; 1253 c = *pC; 1254 if( noCase ){ 1255 /* The point is to increment the last character before the first 1256 ** wildcard. But if we increment '@', that will push it into the 1257 ** alphabetic range where case conversions will mess up the 1258 ** inequality. To avoid this, make sure to also run the full 1259 ** LIKE on all candidate expressions by clearing the isComplete flag 1260 */ 1261 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */ 1262 1263 1264 c = sqlite3UpperToLower[c]; 1265 } 1266 *pC = c + 1; 1267 } 1268 pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0); 1269 pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 1270 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl), 1271 pStr1, 0); 1272 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); 1273 testcase( idxNew1==0 ); 1274 exprAnalyze(pSrc, pWC, idxNew1); 1275 pNewExpr2 = sqlite3PExpr(pParse, TK_LT, 1276 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl), 1277 pStr2, 0); 1278 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC); 1279 testcase( idxNew2==0 ); 1280 exprAnalyze(pSrc, pWC, idxNew2); 1281 pTerm = &pWC->a[idxTerm]; 1282 if( isComplete ){ 1283 pWC->a[idxNew1].iParent = idxTerm; 1284 pWC->a[idxNew2].iParent = idxTerm; 1285 pTerm->nChild = 2; 1286 } 1287 } 1288 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ 1289 1290 #ifndef SQLITE_OMIT_VIRTUALTABLE 1291 /* Add a WO_MATCH auxiliary term to the constraint set if the 1292 ** current expression is of the form: column MATCH expr. 1293 ** This information is used by the xBestIndex methods of 1294 ** virtual tables. The native query optimizer does not attempt 1295 ** to do anything with MATCH functions. 1296 */ 1297 if( isMatchOfColumn(pExpr) ){ 1298 int idxNew; 1299 Expr *pRight, *pLeft; 1300 WhereTerm *pNewTerm; 1301 Bitmask prereqColumn, prereqExpr; 1302 1303 pRight = pExpr->x.pList->a[0].pExpr; 1304 pLeft = pExpr->x.pList->a[1].pExpr; 1305 prereqExpr = exprTableUsage(pMaskSet, pRight); 1306 prereqColumn = exprTableUsage(pMaskSet, pLeft); 1307 if( (prereqExpr & prereqColumn)==0 ){ 1308 Expr *pNewExpr; 1309 pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 1310 0, sqlite3ExprDup(db, pRight, 0), 0); 1311 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); 1312 testcase( idxNew==0 ); 1313 pNewTerm = &pWC->a[idxNew]; 1314 pNewTerm->prereqRight = prereqExpr; 1315 pNewTerm->leftCursor = pLeft->iTable; 1316 pNewTerm->u.leftColumn = pLeft->iColumn; 1317 pNewTerm->eOperator = WO_MATCH; 1318 pNewTerm->iParent = idxTerm; 1319 pTerm = &pWC->a[idxTerm]; 1320 pTerm->nChild = 1; 1321 pTerm->wtFlags |= TERM_COPIED; 1322 pNewTerm->prereqAll = pTerm->prereqAll; 1323 } 1324 } 1325 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 1326 1327 /* Prevent ON clause terms of a LEFT JOIN from being used to drive 1328 ** an index for tables to the left of the join. 1329 */ 1330 pTerm->prereqRight |= extraRight; 1331 } 1332 1333 /* 1334 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain 1335 ** a reference to any table other than the iBase table. 1336 */ 1337 static int referencesOtherTables( 1338 ExprList *pList, /* Search expressions in ths list */ 1339 WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */ 1340 int iFirst, /* Be searching with the iFirst-th expression */ 1341 int iBase /* Ignore references to this table */ 1342 ){ 1343 Bitmask allowed = ~getMask(pMaskSet, iBase); 1344 while( iFirst<pList->nExpr ){ 1345 if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){ 1346 return 1; 1347 } 1348 } 1349 return 0; 1350 } 1351 1352 1353 /* 1354 ** This routine decides if pIdx can be used to satisfy the ORDER BY 1355 ** clause. If it can, it returns 1. If pIdx cannot satisfy the 1356 ** ORDER BY clause, this routine returns 0. 1357 ** 1358 ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the 1359 ** left-most table in the FROM clause of that same SELECT statement and 1360 ** the table has a cursor number of "base". pIdx is an index on pTab. 1361 ** 1362 ** nEqCol is the number of columns of pIdx that are used as equality 1363 ** constraints. Any of these columns may be missing from the ORDER BY 1364 ** clause and the match can still be a success. 1365 ** 1366 ** All terms of the ORDER BY that match against the index must be either 1367 ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE 1368 ** index do not need to satisfy this constraint.) The *pbRev value is 1369 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if 1370 ** the ORDER BY clause is all ASC. 1371 */ 1372 static int isSortingIndex( 1373 Parse *pParse, /* Parsing context */ 1374 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */ 1375 Index *pIdx, /* The index we are testing */ 1376 int base, /* Cursor number for the table to be sorted */ 1377 ExprList *pOrderBy, /* The ORDER BY clause */ 1378 int nEqCol, /* Number of index columns with == constraints */ 1379 int *pbRev /* Set to 1 if ORDER BY is DESC */ 1380 ){ 1381 int i, j; /* Loop counters */ 1382 int sortOrder = 0; /* XOR of index and ORDER BY sort direction */ 1383 int nTerm; /* Number of ORDER BY terms */ 1384 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */ 1385 sqlite3 *db = pParse->db; 1386 1387 assert( pOrderBy!=0 ); 1388 nTerm = pOrderBy->nExpr; 1389 assert( nTerm>0 ); 1390 1391 /* Argument pIdx must either point to a 'real' named index structure, 1392 ** or an index structure allocated on the stack by bestBtreeIndex() to 1393 ** represent the rowid index that is part of every table. */ 1394 assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) ); 1395 1396 /* Match terms of the ORDER BY clause against columns of 1397 ** the index. 1398 ** 1399 ** Note that indices have pIdx->nColumn regular columns plus 1400 ** one additional column containing the rowid. The rowid column 1401 ** of the index is also allowed to match against the ORDER BY 1402 ** clause. 1403 */ 1404 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){ 1405 Expr *pExpr; /* The expression of the ORDER BY pTerm */ 1406 CollSeq *pColl; /* The collating sequence of pExpr */ 1407 int termSortOrder; /* Sort order for this term */ 1408 int iColumn; /* The i-th column of the index. -1 for rowid */ 1409 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */ 1410 const char *zColl; /* Name of the collating sequence for i-th index term */ 1411 1412 pExpr = pTerm->pExpr; 1413 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){ 1414 /* Can not use an index sort on anything that is not a column in the 1415 ** left-most table of the FROM clause */ 1416 break; 1417 } 1418 pColl = sqlite3ExprCollSeq(pParse, pExpr); 1419 if( !pColl ){ 1420 pColl = db->pDfltColl; 1421 } 1422 if( pIdx->zName && i<pIdx->nColumn ){ 1423 iColumn = pIdx->aiColumn[i]; 1424 if( iColumn==pIdx->pTable->iPKey ){ 1425 iColumn = -1; 1426 } 1427 iSortOrder = pIdx->aSortOrder[i]; 1428 zColl = pIdx->azColl[i]; 1429 }else{ 1430 iColumn = -1; 1431 iSortOrder = 0; 1432 zColl = pColl->zName; 1433 } 1434 if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){ 1435 /* Term j of the ORDER BY clause does not match column i of the index */ 1436 if( i<nEqCol ){ 1437 /* If an index column that is constrained by == fails to match an 1438 ** ORDER BY term, that is OK. Just ignore that column of the index 1439 */ 1440 continue; 1441 }else if( i==pIdx->nColumn ){ 1442 /* Index column i is the rowid. All other terms match. */ 1443 break; 1444 }else{ 1445 /* If an index column fails to match and is not constrained by == 1446 ** then the index cannot satisfy the ORDER BY constraint. 1447 */ 1448 return 0; 1449 } 1450 } 1451 assert( pIdx->aSortOrder!=0 || iColumn==-1 ); 1452 assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 ); 1453 assert( iSortOrder==0 || iSortOrder==1 ); 1454 termSortOrder = iSortOrder ^ pTerm->sortOrder; 1455 if( i>nEqCol ){ 1456 if( termSortOrder!=sortOrder ){ 1457 /* Indices can only be used if all ORDER BY terms past the 1458 ** equality constraints are all either DESC or ASC. */ 1459 return 0; 1460 } 1461 }else{ 1462 sortOrder = termSortOrder; 1463 } 1464 j++; 1465 pTerm++; 1466 if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){ 1467 /* If the indexed column is the primary key and everything matches 1468 ** so far and none of the ORDER BY terms to the right reference other 1469 ** tables in the join, then we are assured that the index can be used 1470 ** to sort because the primary key is unique and so none of the other 1471 ** columns will make any difference 1472 */ 1473 j = nTerm; 1474 } 1475 } 1476 1477 *pbRev = sortOrder!=0; 1478 if( j>=nTerm ){ 1479 /* All terms of the ORDER BY clause are covered by this index so 1480 ** this index can be used for sorting. */ 1481 return 1; 1482 } 1483 if( pIdx->onError!=OE_None && i==pIdx->nColumn 1484 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){ 1485 /* All terms of this index match some prefix of the ORDER BY clause 1486 ** and the index is UNIQUE and no terms on the tail of the ORDER BY 1487 ** clause reference other tables in a join. If this is all true then 1488 ** the order by clause is superfluous. */ 1489 return 1; 1490 } 1491 return 0; 1492 } 1493 1494 /* 1495 ** Prepare a crude estimate of the logarithm of the input value. 1496 ** The results need not be exact. This is only used for estimating 1497 ** the total cost of performing operations with O(logN) or O(NlogN) 1498 ** complexity. Because N is just a guess, it is no great tragedy if 1499 ** logN is a little off. 1500 */ 1501 static double estLog(double N){ 1502 double logN = 1; 1503 double x = 10; 1504 while( N>x ){ 1505 logN += 1; 1506 x *= 10; 1507 } 1508 return logN; 1509 } 1510 1511 /* 1512 ** Two routines for printing the content of an sqlite3_index_info 1513 ** structure. Used for testing and debugging only. If neither 1514 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines 1515 ** are no-ops. 1516 */ 1517 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG) 1518 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ 1519 int i; 1520 if( !sqlite3WhereTrace ) return; 1521 for(i=0; i<p->nConstraint; i++){ 1522 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", 1523 i, 1524 p->aConstraint[i].iColumn, 1525 p->aConstraint[i].iTermOffset, 1526 p->aConstraint[i].op, 1527 p->aConstraint[i].usable); 1528 } 1529 for(i=0; i<p->nOrderBy; i++){ 1530 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n", 1531 i, 1532 p->aOrderBy[i].iColumn, 1533 p->aOrderBy[i].desc); 1534 } 1535 } 1536 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ 1537 int i; 1538 if( !sqlite3WhereTrace ) return; 1539 for(i=0; i<p->nConstraint; i++){ 1540 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", 1541 i, 1542 p->aConstraintUsage[i].argvIndex, 1543 p->aConstraintUsage[i].omit); 1544 } 1545 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum); 1546 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr); 1547 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed); 1548 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost); 1549 } 1550 #else 1551 #define TRACE_IDX_INPUTS(A) 1552 #define TRACE_IDX_OUTPUTS(A) 1553 #endif 1554 1555 /* 1556 ** Required because bestIndex() is called by bestOrClauseIndex() 1557 */ 1558 static void bestIndex( 1559 Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*); 1560 1561 /* 1562 ** This routine attempts to find an scanning strategy that can be used 1563 ** to optimize an 'OR' expression that is part of a WHERE clause. 1564 ** 1565 ** The table associated with FROM clause term pSrc may be either a 1566 ** regular B-Tree table or a virtual table. 1567 */ 1568 static void bestOrClauseIndex( 1569 Parse *pParse, /* The parsing context */ 1570 WhereClause *pWC, /* The WHERE clause */ 1571 struct SrcList_item *pSrc, /* The FROM clause term to search */ 1572 Bitmask notReady, /* Mask of cursors that are not available */ 1573 ExprList *pOrderBy, /* The ORDER BY clause */ 1574 WhereCost *pCost /* Lowest cost query plan */ 1575 ){ 1576 #ifndef SQLITE_OMIT_OR_OPTIMIZATION 1577 const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */ 1578 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */ 1579 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */ 1580 WhereTerm *pTerm; /* A single term of the WHERE clause */ 1581 1582 /* No OR-clause optimization allowed if the NOT INDEXED clause is used */ 1583 if( pSrc->notIndexed ){ 1584 return; 1585 } 1586 1587 /* Search the WHERE clause terms for a usable WO_OR term. */ 1588 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ 1589 if( pTerm->eOperator==WO_OR 1590 && ((pTerm->prereqAll & ~maskSrc) & notReady)==0 1591 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 1592 ){ 1593 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc; 1594 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm]; 1595 WhereTerm *pOrTerm; 1596 int flags = WHERE_MULTI_OR; 1597 double rTotal = 0; 1598 double nRow = 0; 1599 Bitmask used = 0; 1600 1601 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){ 1602 WhereCost sTermCost; 1603 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 1604 (pOrTerm - pOrWC->a), (pTerm - pWC->a) 1605 )); 1606 if( pOrTerm->eOperator==WO_AND ){ 1607 WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc; 1608 bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost); 1609 }else if( pOrTerm->leftCursor==iCur ){ 1610 WhereClause tempWC; 1611 tempWC.pParse = pWC->pParse; 1612 tempWC.pMaskSet = pWC->pMaskSet; 1613 tempWC.op = TK_AND; 1614 tempWC.a = pOrTerm; 1615 tempWC.nTerm = 1; 1616 bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost); 1617 }else{ 1618 continue; 1619 } 1620 rTotal += sTermCost.rCost; 1621 nRow += sTermCost.nRow; 1622 used |= sTermCost.used; 1623 if( rTotal>=pCost->rCost ) break; 1624 } 1625 1626 /* If there is an ORDER BY clause, increase the scan cost to account 1627 ** for the cost of the sort. */ 1628 if( pOrderBy!=0 ){ 1629 WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n", 1630 rTotal, rTotal+nRow*estLog(nRow))); 1631 rTotal += nRow*estLog(nRow); 1632 } 1633 1634 /* If the cost of scanning using this OR term for optimization is 1635 ** less than the current cost stored in pCost, replace the contents 1636 ** of pCost. */ 1637 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow)); 1638 if( rTotal<pCost->rCost ){ 1639 pCost->rCost = rTotal; 1640 pCost->nRow = nRow; 1641 pCost->used = used; 1642 pCost->plan.wsFlags = flags; 1643 pCost->plan.u.pTerm = pTerm; 1644 } 1645 } 1646 } 1647 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 1648 } 1649 1650 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 1651 /* 1652 ** Return TRUE if the WHERE clause term pTerm is of a form where it 1653 ** could be used with an index to access pSrc, assuming an appropriate 1654 ** index existed. 1655 */ 1656 static int termCanDriveIndex( 1657 WhereTerm *pTerm, /* WHERE clause term to check */ 1658 struct SrcList_item *pSrc, /* Table we are trying to access */ 1659 Bitmask notReady /* Tables in outer loops of the join */ 1660 ){ 1661 char aff; 1662 if( pTerm->leftCursor!=pSrc->iCursor ) return 0; 1663 if( pTerm->eOperator!=WO_EQ ) return 0; 1664 if( (pTerm->prereqRight & notReady)!=0 ) return 0; 1665 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; 1666 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; 1667 return 1; 1668 } 1669 #endif 1670 1671 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 1672 /* 1673 ** If the query plan for pSrc specified in pCost is a full table scan 1674 ** and indexing is allows (if there is no NOT INDEXED clause) and it 1675 ** possible to construct a transient index that would perform better 1676 ** than a full table scan even when the cost of constructing the index 1677 ** is taken into account, then alter the query plan to use the 1678 ** transient index. 1679 */ 1680 static void bestAutomaticIndex( 1681 Parse *pParse, /* The parsing context */ 1682 WhereClause *pWC, /* The WHERE clause */ 1683 struct SrcList_item *pSrc, /* The FROM clause term to search */ 1684 Bitmask notReady, /* Mask of cursors that are not available */ 1685 WhereCost *pCost /* Lowest cost query plan */ 1686 ){ 1687 double nTableRow; /* Rows in the input table */ 1688 double logN; /* log(nTableRow) */ 1689 double costTempIdx; /* per-query cost of the transient index */ 1690 WhereTerm *pTerm; /* A single term of the WHERE clause */ 1691 WhereTerm *pWCEnd; /* End of pWC->a[] */ 1692 Table *pTable; /* Table tht might be indexed */ 1693 1694 if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){ 1695 /* Automatic indices are disabled at run-time */ 1696 return; 1697 } 1698 if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){ 1699 /* We already have some kind of index in use for this query. */ 1700 return; 1701 } 1702 if( pSrc->notIndexed ){ 1703 /* The NOT INDEXED clause appears in the SQL. */ 1704 return; 1705 } 1706 1707 assert( pParse->nQueryLoop >= (double)1 ); 1708 pTable = pSrc->pTab; 1709 nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000; 1710 logN = estLog(nTableRow); 1711 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1); 1712 if( costTempIdx>=pCost->rCost ){ 1713 /* The cost of creating the transient table would be greater than 1714 ** doing the full table scan */ 1715 return; 1716 } 1717 1718 /* Search for any equality comparison term */ 1719 pWCEnd = &pWC->a[pWC->nTerm]; 1720 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ 1721 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ 1722 WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n", 1723 pCost->rCost, costTempIdx)); 1724 pCost->rCost = costTempIdx; 1725 pCost->nRow = logN + 1; 1726 pCost->plan.wsFlags = WHERE_TEMP_INDEX; 1727 pCost->used = pTerm->prereqRight; 1728 break; 1729 } 1730 } 1731 } 1732 #else 1733 # define bestAutomaticIndex(A,B,C,D,E) /* no-op */ 1734 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 1735 1736 1737 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 1738 /* 1739 ** Generate code to construct the Index object for an automatic index 1740 ** and to set up the WhereLevel object pLevel so that the code generator 1741 ** makes use of the automatic index. 1742 */ 1743 static void constructAutomaticIndex( 1744 Parse *pParse, /* The parsing context */ 1745 WhereClause *pWC, /* The WHERE clause */ 1746 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */ 1747 Bitmask notReady, /* Mask of cursors that are not available */ 1748 WhereLevel *pLevel /* Write new index here */ 1749 ){ 1750 int nColumn; /* Number of columns in the constructed index */ 1751 WhereTerm *pTerm; /* A single term of the WHERE clause */ 1752 WhereTerm *pWCEnd; /* End of pWC->a[] */ 1753 int nByte; /* Byte of memory needed for pIdx */ 1754 Index *pIdx; /* Object describing the transient index */ 1755 Vdbe *v; /* Prepared statement under construction */ 1756 int regIsInit; /* Register set by initialization */ 1757 int addrInit; /* Address of the initialization bypass jump */ 1758 Table *pTable; /* The table being indexed */ 1759 KeyInfo *pKeyinfo; /* Key information for the index */ 1760 int addrTop; /* Top of the index fill loop */ 1761 int regRecord; /* Register holding an index record */ 1762 int n; /* Column counter */ 1763 int i; /* Loop counter */ 1764 int mxBitCol; /* Maximum column in pSrc->colUsed */ 1765 CollSeq *pColl; /* Collating sequence to on a column */ 1766 Bitmask idxCols; /* Bitmap of columns used for indexing */ 1767 Bitmask extraCols; /* Bitmap of additional columns */ 1768 1769 /* Generate code to skip over the creation and initialization of the 1770 ** transient index on 2nd and subsequent iterations of the loop. */ 1771 v = pParse->pVdbe; 1772 assert( v!=0 ); 1773 regIsInit = ++pParse->nMem; 1774 addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit); 1775 sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit); 1776 1777 /* Count the number of columns that will be added to the index 1778 ** and used to match WHERE clause constraints */ 1779 nColumn = 0; 1780 pTable = pSrc->pTab; 1781 pWCEnd = &pWC->a[pWC->nTerm]; 1782 idxCols = 0; 1783 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ 1784 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ 1785 int iCol = pTerm->u.leftColumn; 1786 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol; 1787 testcase( iCol==BMS ); 1788 testcase( iCol==BMS-1 ); 1789 if( (idxCols & cMask)==0 ){ 1790 nColumn++; 1791 idxCols |= cMask; 1792 } 1793 } 1794 } 1795 assert( nColumn>0 ); 1796 pLevel->plan.nEq = nColumn; 1797 1798 /* Count the number of additional columns needed to create a 1799 ** covering index. A "covering index" is an index that contains all 1800 ** columns that are needed by the query. With a covering index, the 1801 ** original table never needs to be accessed. Automatic indices must 1802 ** be a covering index because the index will not be updated if the 1803 ** original table changes and the index and table cannot both be used 1804 ** if they go out of sync. 1805 */ 1806 extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1))); 1807 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol; 1808 testcase( pTable->nCol==BMS-1 ); 1809 testcase( pTable->nCol==BMS-2 ); 1810 for(i=0; i<mxBitCol; i++){ 1811 if( extraCols & (((Bitmask)1)<<i) ) nColumn++; 1812 } 1813 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){ 1814 nColumn += pTable->nCol - BMS + 1; 1815 } 1816 pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ; 1817 1818 /* Construct the Index object to describe this index */ 1819 nByte = sizeof(Index); 1820 nByte += nColumn*sizeof(int); /* Index.aiColumn */ 1821 nByte += nColumn*sizeof(char*); /* Index.azColl */ 1822 nByte += nColumn; /* Index.aSortOrder */ 1823 pIdx = sqlite3DbMallocZero(pParse->db, nByte); 1824 if( pIdx==0 ) return; 1825 pLevel->plan.u.pIdx = pIdx; 1826 pIdx->azColl = (char**)&pIdx[1]; 1827 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn]; 1828 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn]; 1829 pIdx->zName = "auto-index"; 1830 pIdx->nColumn = nColumn; 1831 pIdx->pTable = pTable; 1832 n = 0; 1833 idxCols = 0; 1834 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ 1835 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ 1836 int iCol = pTerm->u.leftColumn; 1837 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol; 1838 if( (idxCols & cMask)==0 ){ 1839 Expr *pX = pTerm->pExpr; 1840 idxCols |= cMask; 1841 pIdx->aiColumn[n] = pTerm->u.leftColumn; 1842 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); 1843 pIdx->azColl[n] = pColl->zName; 1844 n++; 1845 } 1846 } 1847 } 1848 assert( (u32)n==pLevel->plan.nEq ); 1849 1850 /* Add additional columns needed to make the automatic index into 1851 ** a covering index */ 1852 for(i=0; i<mxBitCol; i++){ 1853 if( extraCols & (((Bitmask)1)<<i) ){ 1854 pIdx->aiColumn[n] = i; 1855 pIdx->azColl[n] = "BINARY"; 1856 n++; 1857 } 1858 } 1859 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){ 1860 for(i=BMS-1; i<pTable->nCol; i++){ 1861 pIdx->aiColumn[n] = i; 1862 pIdx->azColl[n] = "BINARY"; 1863 n++; 1864 } 1865 } 1866 assert( n==nColumn ); 1867 1868 /* Create the automatic index */ 1869 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx); 1870 assert( pLevel->iIdxCur>=0 ); 1871 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0, 1872 (char*)pKeyinfo, P4_KEYINFO_HANDOFF); 1873 VdbeComment((v, "for %s", pTable->zName)); 1874 1875 /* Fill the automatic index with content */ 1876 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); 1877 regRecord = sqlite3GetTempReg(pParse); 1878 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1); 1879 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); 1880 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1881 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); 1882 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); 1883 sqlite3VdbeJumpHere(v, addrTop); 1884 sqlite3ReleaseTempReg(pParse, regRecord); 1885 1886 /* Jump here when skipping the initialization */ 1887 sqlite3VdbeJumpHere(v, addrInit); 1888 } 1889 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ 1890 1891 #ifndef SQLITE_OMIT_VIRTUALTABLE 1892 /* 1893 ** Allocate and populate an sqlite3_index_info structure. It is the 1894 ** responsibility of the caller to eventually release the structure 1895 ** by passing the pointer returned by this function to sqlite3_free(). 1896 */ 1897 static sqlite3_index_info *allocateIndexInfo( 1898 Parse *pParse, 1899 WhereClause *pWC, 1900 struct SrcList_item *pSrc, 1901 ExprList *pOrderBy 1902 ){ 1903 int i, j; 1904 int nTerm; 1905 struct sqlite3_index_constraint *pIdxCons; 1906 struct sqlite3_index_orderby *pIdxOrderBy; 1907 struct sqlite3_index_constraint_usage *pUsage; 1908 WhereTerm *pTerm; 1909 int nOrderBy; 1910 sqlite3_index_info *pIdxInfo; 1911 1912 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName)); 1913 1914 /* Count the number of possible WHERE clause constraints referring 1915 ** to this virtual table */ 1916 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 1917 if( pTerm->leftCursor != pSrc->iCursor ) continue; 1918 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 ); 1919 testcase( pTerm->eOperator==WO_IN ); 1920 testcase( pTerm->eOperator==WO_ISNULL ); 1921 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue; 1922 nTerm++; 1923 } 1924 1925 /* If the ORDER BY clause contains only columns in the current 1926 ** virtual table then allocate space for the aOrderBy part of 1927 ** the sqlite3_index_info structure. 1928 */ 1929 nOrderBy = 0; 1930 if( pOrderBy ){ 1931 for(i=0; i<pOrderBy->nExpr; i++){ 1932 Expr *pExpr = pOrderBy->a[i].pExpr; 1933 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break; 1934 } 1935 if( i==pOrderBy->nExpr ){ 1936 nOrderBy = pOrderBy->nExpr; 1937 } 1938 } 1939 1940 /* Allocate the sqlite3_index_info structure 1941 */ 1942 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) 1943 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm 1944 + sizeof(*pIdxOrderBy)*nOrderBy ); 1945 if( pIdxInfo==0 ){ 1946 sqlite3ErrorMsg(pParse, "out of memory"); 1947 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */ 1948 return 0; 1949 } 1950 1951 /* Initialize the structure. The sqlite3_index_info structure contains 1952 ** many fields that are declared "const" to prevent xBestIndex from 1953 ** changing them. We have to do some funky casting in order to 1954 ** initialize those fields. 1955 */ 1956 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; 1957 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; 1958 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; 1959 *(int*)&pIdxInfo->nConstraint = nTerm; 1960 *(int*)&pIdxInfo->nOrderBy = nOrderBy; 1961 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; 1962 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; 1963 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = 1964 pUsage; 1965 1966 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 1967 if( pTerm->leftCursor != pSrc->iCursor ) continue; 1968 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 ); 1969 testcase( pTerm->eOperator==WO_IN ); 1970 testcase( pTerm->eOperator==WO_ISNULL ); 1971 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue; 1972 pIdxCons[j].iColumn = pTerm->u.leftColumn; 1973 pIdxCons[j].iTermOffset = i; 1974 pIdxCons[j].op = (u8)pTerm->eOperator; 1975 /* The direct assignment in the previous line is possible only because 1976 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The 1977 ** following asserts verify this fact. */ 1978 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); 1979 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); 1980 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); 1981 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); 1982 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); 1983 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); 1984 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) ); 1985 j++; 1986 } 1987 for(i=0; i<nOrderBy; i++){ 1988 Expr *pExpr = pOrderBy->a[i].pExpr; 1989 pIdxOrderBy[i].iColumn = pExpr->iColumn; 1990 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; 1991 } 1992 1993 return pIdxInfo; 1994 } 1995 1996 /* 1997 ** The table object reference passed as the second argument to this function 1998 ** must represent a virtual table. This function invokes the xBestIndex() 1999 ** method of the virtual table with the sqlite3_index_info pointer passed 2000 ** as the argument. 2001 ** 2002 ** If an error occurs, pParse is populated with an error message and a 2003 ** non-zero value is returned. Otherwise, 0 is returned and the output 2004 ** part of the sqlite3_index_info structure is left populated. 2005 ** 2006 ** Whether or not an error is returned, it is the responsibility of the 2007 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates 2008 ** that this is required. 2009 */ 2010 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){ 2011 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab; 2012 int i; 2013 int rc; 2014 2015 WHERETRACE(("xBestIndex for %s\n", pTab->zName)); 2016 TRACE_IDX_INPUTS(p); 2017 rc = pVtab->pModule->xBestIndex(pVtab, p); 2018 TRACE_IDX_OUTPUTS(p); 2019 2020 if( rc!=SQLITE_OK ){ 2021 if( rc==SQLITE_NOMEM ){ 2022 pParse->db->mallocFailed = 1; 2023 }else if( !pVtab->zErrMsg ){ 2024 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); 2025 }else{ 2026 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg); 2027 } 2028 } 2029 sqlite3_free(pVtab->zErrMsg); 2030 pVtab->zErrMsg = 0; 2031 2032 for(i=0; i<p->nConstraint; i++){ 2033 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ 2034 sqlite3ErrorMsg(pParse, 2035 "table %s: xBestIndex returned an invalid plan", pTab->zName); 2036 } 2037 } 2038 2039 return pParse->nErr; 2040 } 2041 2042 2043 /* 2044 ** Compute the best index for a virtual table. 2045 ** 2046 ** The best index is computed by the xBestIndex method of the virtual 2047 ** table module. This routine is really just a wrapper that sets up 2048 ** the sqlite3_index_info structure that is used to communicate with 2049 ** xBestIndex. 2050 ** 2051 ** In a join, this routine might be called multiple times for the 2052 ** same virtual table. The sqlite3_index_info structure is created 2053 ** and initialized on the first invocation and reused on all subsequent 2054 ** invocations. The sqlite3_index_info structure is also used when 2055 ** code is generated to access the virtual table. The whereInfoDelete() 2056 ** routine takes care of freeing the sqlite3_index_info structure after 2057 ** everybody has finished with it. 2058 */ 2059 static void bestVirtualIndex( 2060 Parse *pParse, /* The parsing context */ 2061 WhereClause *pWC, /* The WHERE clause */ 2062 struct SrcList_item *pSrc, /* The FROM clause term to search */ 2063 Bitmask notReady, /* Mask of cursors that are not available */ 2064 ExprList *pOrderBy, /* The order by clause */ 2065 WhereCost *pCost, /* Lowest cost query plan */ 2066 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */ 2067 ){ 2068 Table *pTab = pSrc->pTab; 2069 sqlite3_index_info *pIdxInfo; 2070 struct sqlite3_index_constraint *pIdxCons; 2071 struct sqlite3_index_constraint_usage *pUsage; 2072 WhereTerm *pTerm; 2073 int i, j; 2074 int nOrderBy; 2075 double rCost; 2076 2077 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 2078 ** malloc in allocateIndexInfo() fails and this function returns leaving 2079 ** wsFlags in an uninitialized state, the caller may behave unpredictably. 2080 */ 2081 memset(pCost, 0, sizeof(*pCost)); 2082 pCost->plan.wsFlags = WHERE_VIRTUALTABLE; 2083 2084 /* If the sqlite3_index_info structure has not been previously 2085 ** allocated and initialized, then allocate and initialize it now. 2086 */ 2087 pIdxInfo = *ppIdxInfo; 2088 if( pIdxInfo==0 ){ 2089 *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy); 2090 } 2091 if( pIdxInfo==0 ){ 2092 return; 2093 } 2094 2095 /* At this point, the sqlite3_index_info structure that pIdxInfo points 2096 ** to will have been initialized, either during the current invocation or 2097 ** during some prior invocation. Now we just have to customize the 2098 ** details of pIdxInfo for the current invocation and pass it to 2099 ** xBestIndex. 2100 */ 2101 2102 /* The module name must be defined. Also, by this point there must 2103 ** be a pointer to an sqlite3_vtab structure. Otherwise 2104 ** sqlite3ViewGetColumnNames() would have picked up the error. 2105 */ 2106 assert( pTab->azModuleArg && pTab->azModuleArg[0] ); 2107 assert( sqlite3GetVTable(pParse->db, pTab) ); 2108 2109 /* Set the aConstraint[].usable fields and initialize all 2110 ** output variables to zero. 2111 ** 2112 ** aConstraint[].usable is true for constraints where the right-hand 2113 ** side contains only references to tables to the left of the current 2114 ** table. In other words, if the constraint is of the form: 2115 ** 2116 ** column = expr 2117 ** 2118 ** and we are evaluating a join, then the constraint on column is 2119 ** only valid if all tables referenced in expr occur to the left 2120 ** of the table containing column. 2121 ** 2122 ** The aConstraints[] array contains entries for all constraints 2123 ** on the current table. That way we only have to compute it once 2124 ** even though we might try to pick the best index multiple times. 2125 ** For each attempt at picking an index, the order of tables in the 2126 ** join might be different so we have to recompute the usable flag 2127 ** each time. 2128 */ 2129 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 2130 pUsage = pIdxInfo->aConstraintUsage; 2131 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){ 2132 j = pIdxCons->iTermOffset; 2133 pTerm = &pWC->a[j]; 2134 pIdxCons->usable = (pTerm->prereqRight¬Ready) ? 0 : 1; 2135 } 2136 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint); 2137 if( pIdxInfo->needToFreeIdxStr ){ 2138 sqlite3_free(pIdxInfo->idxStr); 2139 } 2140 pIdxInfo->idxStr = 0; 2141 pIdxInfo->idxNum = 0; 2142 pIdxInfo->needToFreeIdxStr = 0; 2143 pIdxInfo->orderByConsumed = 0; 2144 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */ 2145 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2); 2146 nOrderBy = pIdxInfo->nOrderBy; 2147 if( !pOrderBy ){ 2148 pIdxInfo->nOrderBy = 0; 2149 } 2150 2151 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){ 2152 return; 2153 } 2154 2155 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; 2156 for(i=0; i<pIdxInfo->nConstraint; i++){ 2157 if( pUsage[i].argvIndex>0 ){ 2158 pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight; 2159 } 2160 } 2161 2162 /* If there is an ORDER BY clause, and the selected virtual table index 2163 ** does not satisfy it, increase the cost of the scan accordingly. This 2164 ** matches the processing for non-virtual tables in bestBtreeIndex(). 2165 */ 2166 rCost = pIdxInfo->estimatedCost; 2167 if( pOrderBy && pIdxInfo->orderByConsumed==0 ){ 2168 rCost += estLog(rCost)*rCost; 2169 } 2170 2171 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the 2172 ** inital value of lowestCost in this loop. If it is, then the 2173 ** (cost<lowestCost) test below will never be true. 2174 ** 2175 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 2176 ** is defined. 2177 */ 2178 if( (SQLITE_BIG_DBL/((double)2))<rCost ){ 2179 pCost->rCost = (SQLITE_BIG_DBL/((double)2)); 2180 }else{ 2181 pCost->rCost = rCost; 2182 } 2183 pCost->plan.u.pVtabIdx = pIdxInfo; 2184 if( pIdxInfo->orderByConsumed ){ 2185 pCost->plan.wsFlags |= WHERE_ORDERBY; 2186 } 2187 pCost->plan.nEq = 0; 2188 pIdxInfo->nOrderBy = nOrderBy; 2189 2190 /* Try to find a more efficient access pattern by using multiple indexes 2191 ** to optimize an OR expression within the WHERE clause. 2192 */ 2193 bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost); 2194 } 2195 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 2196 2197 /* 2198 ** Argument pIdx is a pointer to an index structure that has an array of 2199 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column 2200 ** stored in Index.aSample. The domain of values stored in said column 2201 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions. 2202 ** Region 0 contains all values smaller than the first sample value. Region 2203 ** 1 contains values larger than or equal to the value of the first sample, 2204 ** but smaller than the value of the second. And so on. 2205 ** 2206 ** If successful, this function determines which of the regions value 2207 ** pVal lies in, sets *piRegion to the region index (a value between 0 2208 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK. 2209 ** Or, if an OOM occurs while converting text values between encodings, 2210 ** SQLITE_NOMEM is returned and *piRegion is undefined. 2211 */ 2212 #ifdef SQLITE_ENABLE_STAT2 2213 static int whereRangeRegion( 2214 Parse *pParse, /* Database connection */ 2215 Index *pIdx, /* Index to consider domain of */ 2216 sqlite3_value *pVal, /* Value to consider */ 2217 int *piRegion /* OUT: Region of domain in which value lies */ 2218 ){ 2219 if( ALWAYS(pVal) ){ 2220 IndexSample *aSample = pIdx->aSample; 2221 int i = 0; 2222 int eType = sqlite3_value_type(pVal); 2223 2224 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){ 2225 double r = sqlite3_value_double(pVal); 2226 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){ 2227 if( aSample[i].eType==SQLITE_NULL ) continue; 2228 if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break; 2229 } 2230 }else{ 2231 sqlite3 *db = pParse->db; 2232 CollSeq *pColl; 2233 const u8 *z; 2234 int n; 2235 2236 /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */ 2237 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); 2238 2239 if( eType==SQLITE_BLOB ){ 2240 z = (const u8 *)sqlite3_value_blob(pVal); 2241 pColl = db->pDfltColl; 2242 assert( pColl->enc==SQLITE_UTF8 ); 2243 }else{ 2244 pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl); 2245 if( pColl==0 ){ 2246 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", 2247 *pIdx->azColl); 2248 return SQLITE_ERROR; 2249 } 2250 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc); 2251 if( !z ){ 2252 return SQLITE_NOMEM; 2253 } 2254 assert( z && pColl && pColl->xCmp ); 2255 } 2256 n = sqlite3ValueBytes(pVal, pColl->enc); 2257 2258 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){ 2259 int r; 2260 int eSampletype = aSample[i].eType; 2261 if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue; 2262 if( (eSampletype!=eType) ) break; 2263 #ifndef SQLITE_OMIT_UTF16 2264 if( pColl->enc!=SQLITE_UTF8 ){ 2265 int nSample; 2266 char *zSample = sqlite3Utf8to16( 2267 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample 2268 ); 2269 if( !zSample ){ 2270 assert( db->mallocFailed ); 2271 return SQLITE_NOMEM; 2272 } 2273 r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z); 2274 sqlite3DbFree(db, zSample); 2275 }else 2276 #endif 2277 { 2278 r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z); 2279 } 2280 if( r>0 ) break; 2281 } 2282 } 2283 2284 assert( i>=0 && i<=SQLITE_INDEX_SAMPLES ); 2285 *piRegion = i; 2286 } 2287 return SQLITE_OK; 2288 } 2289 #endif /* #ifdef SQLITE_ENABLE_STAT2 */ 2290 2291 /* 2292 ** If expression pExpr represents a literal value, set *pp to point to 2293 ** an sqlite3_value structure containing the same value, with affinity 2294 ** aff applied to it, before returning. It is the responsibility of the 2295 ** caller to eventually release this structure by passing it to 2296 ** sqlite3ValueFree(). 2297 ** 2298 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr 2299 ** is an SQL variable that currently has a non-NULL value bound to it, 2300 ** create an sqlite3_value structure containing this value, again with 2301 ** affinity aff applied to it, instead. 2302 ** 2303 ** If neither of the above apply, set *pp to NULL. 2304 ** 2305 ** If an error occurs, return an error code. Otherwise, SQLITE_OK. 2306 */ 2307 #ifdef SQLITE_ENABLE_STAT2 2308 static int valueFromExpr( 2309 Parse *pParse, 2310 Expr *pExpr, 2311 u8 aff, 2312 sqlite3_value **pp 2313 ){ 2314 /* The evalConstExpr() function will have already converted any TK_VARIABLE 2315 ** expression involved in an comparison into a TK_REGISTER. */ 2316 assert( pExpr->op!=TK_VARIABLE ); 2317 if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){ 2318 int iVar = pExpr->iColumn; 2319 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */ 2320 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff); 2321 return SQLITE_OK; 2322 } 2323 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp); 2324 } 2325 #endif 2326 2327 /* 2328 ** This function is used to estimate the number of rows that will be visited 2329 ** by scanning an index for a range of values. The range may have an upper 2330 ** bound, a lower bound, or both. The WHERE clause terms that set the upper 2331 ** and lower bounds are represented by pLower and pUpper respectively. For 2332 ** example, assuming that index p is on t1(a): 2333 ** 2334 ** ... FROM t1 WHERE a > ? AND a < ? ... 2335 ** |_____| |_____| 2336 ** | | 2337 ** pLower pUpper 2338 ** 2339 ** If either of the upper or lower bound is not present, then NULL is passed in 2340 ** place of the corresponding WhereTerm. 2341 ** 2342 ** The nEq parameter is passed the index of the index column subject to the 2343 ** range constraint. Or, equivalently, the number of equality constraints 2344 ** optimized by the proposed index scan. For example, assuming index p is 2345 ** on t1(a, b), and the SQL query is: 2346 ** 2347 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... 2348 ** 2349 ** then nEq should be passed the value 1 (as the range restricted column, 2350 ** b, is the second left-most column of the index). Or, if the query is: 2351 ** 2352 ** ... FROM t1 WHERE a > ? AND a < ? ... 2353 ** 2354 ** then nEq should be passed 0. 2355 ** 2356 ** The returned value is an integer between 1 and 100, inclusive. A return 2357 ** value of 1 indicates that the proposed range scan is expected to visit 2358 ** approximately 1/100th (1%) of the rows selected by the nEq equality 2359 ** constraints (if any). A return value of 100 indicates that it is expected 2360 ** that the range scan will visit every row (100%) selected by the equality 2361 ** constraints. 2362 ** 2363 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality 2364 ** reduces the search space by 2/3rds. Hence a single constraint (x>?) 2365 ** results in a return of 33 and a range constraint (x>? AND x<?) results 2366 ** in a return of 11. 2367 */ 2368 static int whereRangeScanEst( 2369 Parse *pParse, /* Parsing & code generating context */ 2370 Index *p, /* The index containing the range-compared column; "x" */ 2371 int nEq, /* index into p->aCol[] of the range-compared column */ 2372 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ 2373 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ 2374 int *piEst /* OUT: Return value */ 2375 ){ 2376 int rc = SQLITE_OK; 2377 2378 #ifdef SQLITE_ENABLE_STAT2 2379 2380 if( nEq==0 && p->aSample ){ 2381 sqlite3_value *pLowerVal = 0; 2382 sqlite3_value *pUpperVal = 0; 2383 int iEst; 2384 int iLower = 0; 2385 int iUpper = SQLITE_INDEX_SAMPLES; 2386 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity; 2387 2388 if( pLower ){ 2389 Expr *pExpr = pLower->pExpr->pRight; 2390 rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal); 2391 } 2392 if( rc==SQLITE_OK && pUpper ){ 2393 Expr *pExpr = pUpper->pExpr->pRight; 2394 rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal); 2395 } 2396 2397 if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){ 2398 sqlite3ValueFree(pLowerVal); 2399 sqlite3ValueFree(pUpperVal); 2400 goto range_est_fallback; 2401 }else if( pLowerVal==0 ){ 2402 rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper); 2403 if( pLower ) iLower = iUpper/2; 2404 }else if( pUpperVal==0 ){ 2405 rc = whereRangeRegion(pParse, p, pLowerVal, &iLower); 2406 if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2; 2407 }else{ 2408 rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper); 2409 if( rc==SQLITE_OK ){ 2410 rc = whereRangeRegion(pParse, p, pLowerVal, &iLower); 2411 } 2412 } 2413 2414 iEst = iUpper - iLower; 2415 testcase( iEst==SQLITE_INDEX_SAMPLES ); 2416 assert( iEst<=SQLITE_INDEX_SAMPLES ); 2417 if( iEst<1 ){ 2418 iEst = 1; 2419 } 2420 2421 sqlite3ValueFree(pLowerVal); 2422 sqlite3ValueFree(pUpperVal); 2423 *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES; 2424 return rc; 2425 } 2426 range_est_fallback: 2427 #else 2428 UNUSED_PARAMETER(pParse); 2429 UNUSED_PARAMETER(p); 2430 UNUSED_PARAMETER(nEq); 2431 #endif 2432 assert( pLower || pUpper ); 2433 if( pLower && pUpper ){ 2434 *piEst = 11; 2435 }else{ 2436 *piEst = 33; 2437 } 2438 return rc; 2439 } 2440 2441 2442 /* 2443 ** Find the query plan for accessing a particular table. Write the 2444 ** best query plan and its cost into the WhereCost object supplied as the 2445 ** last parameter. 2446 ** 2447 ** The lowest cost plan wins. The cost is an estimate of the amount of 2448 ** CPU and disk I/O need to process the request using the selected plan. 2449 ** Factors that influence cost include: 2450 ** 2451 ** * The estimated number of rows that will be retrieved. (The 2452 ** fewer the better.) 2453 ** 2454 ** * Whether or not sorting must occur. 2455 ** 2456 ** * Whether or not there must be separate lookups in the 2457 ** index and in the main table. 2458 ** 2459 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in 2460 ** the SQL statement, then this function only considers plans using the 2461 ** named index. If no such plan is found, then the returned cost is 2462 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 2463 ** then the cost is calculated in the usual way. 2464 ** 2465 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 2466 ** in the SELECT statement, then no indexes are considered. However, the 2467 ** selected plan may still take advantage of the tables built-in rowid 2468 ** index. 2469 */ 2470 static void bestBtreeIndex( 2471 Parse *pParse, /* The parsing context */ 2472 WhereClause *pWC, /* The WHERE clause */ 2473 struct SrcList_item *pSrc, /* The FROM clause term to search */ 2474 Bitmask notReady, /* Mask of cursors that are not available */ 2475 ExprList *pOrderBy, /* The ORDER BY clause */ 2476 WhereCost *pCost /* Lowest cost query plan */ 2477 ){ 2478 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */ 2479 Index *pProbe; /* An index we are evaluating */ 2480 Index *pIdx; /* Copy of pProbe, or zero for IPK index */ 2481 int eqTermMask; /* Current mask of valid equality operators */ 2482 int idxEqTermMask; /* Index mask of valid equality operators */ 2483 Index sPk; /* A fake index object for the primary key */ 2484 unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */ 2485 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */ 2486 int wsFlagMask; /* Allowed flags in pCost->plan.wsFlag */ 2487 2488 /* Initialize the cost to a worst-case value */ 2489 memset(pCost, 0, sizeof(*pCost)); 2490 pCost->rCost = SQLITE_BIG_DBL; 2491 2492 /* If the pSrc table is the right table of a LEFT JOIN then we may not 2493 ** use an index to satisfy IS NULL constraints on that table. This is 2494 ** because columns might end up being NULL if the table does not match - 2495 ** a circumstance which the index cannot help us discover. Ticket #2177. 2496 */ 2497 if( pSrc->jointype & JT_LEFT ){ 2498 idxEqTermMask = WO_EQ|WO_IN; 2499 }else{ 2500 idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL; 2501 } 2502 2503 if( pSrc->pIndex ){ 2504 /* An INDEXED BY clause specifies a particular index to use */ 2505 pIdx = pProbe = pSrc->pIndex; 2506 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE); 2507 eqTermMask = idxEqTermMask; 2508 }else{ 2509 /* There is no INDEXED BY clause. Create a fake Index object to 2510 ** represent the primary key */ 2511 Index *pFirst; /* Any other index on the table */ 2512 memset(&sPk, 0, sizeof(Index)); 2513 sPk.nColumn = 1; 2514 sPk.aiColumn = &aiColumnPk; 2515 sPk.aiRowEst = aiRowEstPk; 2516 aiRowEstPk[1] = 1; 2517 sPk.onError = OE_Replace; 2518 sPk.pTable = pSrc->pTab; 2519 pFirst = pSrc->pTab->pIndex; 2520 if( pSrc->notIndexed==0 ){ 2521 sPk.pNext = pFirst; 2522 } 2523 /* The aiRowEstPk[0] is an estimate of the total number of rows in the 2524 ** table. Get this information from the ANALYZE information if it is 2525 ** available. If not available, assume the table 1 million rows in size. 2526 */ 2527 if( pFirst ){ 2528 assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */ 2529 aiRowEstPk[0] = pFirst->aiRowEst[0]; 2530 }else{ 2531 aiRowEstPk[0] = 1000000; 2532 } 2533 pProbe = &sPk; 2534 wsFlagMask = ~( 2535 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE 2536 ); 2537 eqTermMask = WO_EQ|WO_IN; 2538 pIdx = 0; 2539 } 2540 2541 /* Loop over all indices looking for the best one to use 2542 */ 2543 for(; pProbe; pIdx=pProbe=pProbe->pNext){ 2544 const unsigned int * const aiRowEst = pProbe->aiRowEst; 2545 double cost; /* Cost of using pProbe */ 2546 double nRow; /* Estimated number of rows in result set */ 2547 int rev; /* True to scan in reverse order */ 2548 int wsFlags = 0; 2549 Bitmask used = 0; 2550 2551 /* The following variables are populated based on the properties of 2552 ** scan being evaluated. They are then used to determine the expected 2553 ** cost and number of rows returned. 2554 ** 2555 ** nEq: 2556 ** Number of equality terms that can be implemented using the index. 2557 ** 2558 ** nInMul: 2559 ** The "in-multiplier". This is an estimate of how many seek operations 2560 ** SQLite must perform on the index in question. For example, if the 2561 ** WHERE clause is: 2562 ** 2563 ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6) 2564 ** 2565 ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is 2566 ** set to 9. Given the same schema and either of the following WHERE 2567 ** clauses: 2568 ** 2569 ** WHERE a = 1 2570 ** WHERE a >= 2 2571 ** 2572 ** nInMul is set to 1. 2573 ** 2574 ** If there exists a WHERE term of the form "x IN (SELECT ...)", then 2575 ** the sub-select is assumed to return 25 rows for the purposes of 2576 ** determining nInMul. 2577 ** 2578 ** bInEst: 2579 ** Set to true if there was at least one "x IN (SELECT ...)" term used 2580 ** in determining the value of nInMul. 2581 ** 2582 ** estBound: 2583 ** An estimate on the amount of the table that must be searched. A 2584 ** value of 100 means the entire table is searched. Range constraints 2585 ** might reduce this to a value less than 100 to indicate that only 2586 ** a fraction of the table needs searching. In the absence of 2587 ** sqlite_stat2 ANALYZE data, a single inequality reduces the search 2588 ** space to 1/3rd its original size. So an x>? constraint reduces 2589 ** estBound to 33. Two constraints (x>? AND x<?) reduce estBound to 11. 2590 ** 2591 ** bSort: 2592 ** Boolean. True if there is an ORDER BY clause that will require an 2593 ** external sort (i.e. scanning the index being evaluated will not 2594 ** correctly order records). 2595 ** 2596 ** bLookup: 2597 ** Boolean. True if for each index entry visited a lookup on the 2598 ** corresponding table b-tree is required. This is always false 2599 ** for the rowid index. For other indexes, it is true unless all the 2600 ** columns of the table used by the SELECT statement are present in 2601 ** the index (such an index is sometimes described as a covering index). 2602 ** For example, given the index on (a, b), the second of the following 2603 ** two queries requires table b-tree lookups, but the first does not. 2604 ** 2605 ** SELECT a, b FROM tbl WHERE a = 1; 2606 ** SELECT a, b, c FROM tbl WHERE a = 1; 2607 */ 2608 int nEq; 2609 int bInEst = 0; 2610 int nInMul = 1; 2611 int estBound = 100; 2612 int nBound = 0; /* Number of range constraints seen */ 2613 int bSort = 0; 2614 int bLookup = 0; 2615 WhereTerm *pTerm; /* A single term of the WHERE clause */ 2616 2617 /* Determine the values of nEq and nInMul */ 2618 for(nEq=0; nEq<pProbe->nColumn; nEq++){ 2619 int j = pProbe->aiColumn[nEq]; 2620 pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx); 2621 if( pTerm==0 ) break; 2622 wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ); 2623 if( pTerm->eOperator & WO_IN ){ 2624 Expr *pExpr = pTerm->pExpr; 2625 wsFlags |= WHERE_COLUMN_IN; 2626 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2627 nInMul *= 25; 2628 bInEst = 1; 2629 }else if( ALWAYS(pExpr->x.pList) ){ 2630 nInMul *= pExpr->x.pList->nExpr + 1; 2631 } 2632 }else if( pTerm->eOperator & WO_ISNULL ){ 2633 wsFlags |= WHERE_COLUMN_NULL; 2634 } 2635 used |= pTerm->prereqRight; 2636 } 2637 2638 /* Determine the value of estBound. */ 2639 if( nEq<pProbe->nColumn ){ 2640 int j = pProbe->aiColumn[nEq]; 2641 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){ 2642 WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx); 2643 WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx); 2644 whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound); 2645 if( pTop ){ 2646 nBound = 1; 2647 wsFlags |= WHERE_TOP_LIMIT; 2648 used |= pTop->prereqRight; 2649 } 2650 if( pBtm ){ 2651 nBound++; 2652 wsFlags |= WHERE_BTM_LIMIT; 2653 used |= pBtm->prereqRight; 2654 } 2655 wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE); 2656 } 2657 }else if( pProbe->onError!=OE_None ){ 2658 testcase( wsFlags & WHERE_COLUMN_IN ); 2659 testcase( wsFlags & WHERE_COLUMN_NULL ); 2660 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){ 2661 wsFlags |= WHERE_UNIQUE; 2662 } 2663 } 2664 2665 /* If there is an ORDER BY clause and the index being considered will 2666 ** naturally scan rows in the required order, set the appropriate flags 2667 ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index 2668 ** will scan rows in a different order, set the bSort variable. */ 2669 if( pOrderBy ){ 2670 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 2671 && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) 2672 ){ 2673 wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY; 2674 wsFlags |= (rev ? WHERE_REVERSE : 0); 2675 }else{ 2676 bSort = 1; 2677 } 2678 } 2679 2680 /* If currently calculating the cost of using an index (not the IPK 2681 ** index), determine if all required column data may be obtained without 2682 ** using the main table (i.e. if the index is a covering 2683 ** index for this query). If it is, set the WHERE_IDX_ONLY flag in 2684 ** wsFlags. Otherwise, set the bLookup variable to true. */ 2685 if( pIdx && wsFlags ){ 2686 Bitmask m = pSrc->colUsed; 2687 int j; 2688 for(j=0; j<pIdx->nColumn; j++){ 2689 int x = pIdx->aiColumn[j]; 2690 if( x<BMS-1 ){ 2691 m &= ~(((Bitmask)1)<<x); 2692 } 2693 } 2694 if( m==0 ){ 2695 wsFlags |= WHERE_IDX_ONLY; 2696 }else{ 2697 bLookup = 1; 2698 } 2699 } 2700 2701 /* 2702 ** Estimate the number of rows of output. For an IN operator, 2703 ** do not let the estimate exceed half the rows in the table. 2704 */ 2705 nRow = (double)(aiRowEst[nEq] * nInMul); 2706 if( bInEst && nRow*2>aiRowEst[0] ){ 2707 nRow = aiRowEst[0]/2; 2708 nInMul = (int)(nRow / aiRowEst[nEq]); 2709 } 2710 2711 /* Assume constant cost to access a row and logarithmic cost to 2712 ** do a binary search. Hence, the initial cost is the number of output 2713 ** rows plus log2(table-size) times the number of binary searches. 2714 */ 2715 cost = nRow + nInMul*estLog(aiRowEst[0]); 2716 2717 /* Adjust the number of rows and the cost downward to reflect rows 2718 ** that are excluded by range constraints. 2719 */ 2720 nRow = (nRow * (double)estBound) / (double)100; 2721 cost = (cost * (double)estBound) / (double)100; 2722 2723 /* Add in the estimated cost of sorting the result 2724 */ 2725 if( bSort ){ 2726 cost += cost*estLog(cost); 2727 } 2728 2729 /* If all information can be taken directly from the index, we avoid 2730 ** doing table lookups. This reduces the cost by half. (Not really - 2731 ** this needs to be fixed.) 2732 */ 2733 if( pIdx && bLookup==0 ){ 2734 cost /= (double)2; 2735 } 2736 /**** Cost of using this index has now been computed ****/ 2737 2738 /* If there are additional constraints on this table that cannot 2739 ** be used with the current index, but which might lower the number 2740 ** of output rows, adjust the nRow value accordingly. This only 2741 ** matters if the current index is the least costly, so do not bother 2742 ** with this step if we already know this index will not be chosen. 2743 ** Also, never reduce the output row count below 2 using this step. 2744 ** 2745 ** Do not reduce the output row count if pSrc is the only table that 2746 ** is notReady; if notReady is a power of two. This will be the case 2747 ** when the main sqlite3WhereBegin() loop is scanning for a table with 2748 ** and "optimal" index, and on such a scan the output row count 2749 ** reduction is not valid because it does not update the "pCost->used" 2750 ** bitmap. The notReady bitmap will also be a power of two when we 2751 ** are scanning for the last table in a 64-way join. We are willing 2752 ** to bypass this optimization in that corner case. 2753 */ 2754 if( nRow>2 && cost<=pCost->rCost && (notReady & (notReady-1))!=0 ){ 2755 int k; /* Loop counter */ 2756 int nSkipEq = nEq; /* Number of == constraints to skip */ 2757 int nSkipRange = nBound; /* Number of < constraints to skip */ 2758 Bitmask thisTab; /* Bitmap for pSrc */ 2759 2760 thisTab = getMask(pWC->pMaskSet, iCur); 2761 for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){ 2762 if( pTerm->wtFlags & TERM_VIRTUAL ) continue; 2763 if( (pTerm->prereqAll & notReady)!=thisTab ) continue; 2764 if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){ 2765 if( nSkipEq ){ 2766 /* Ignore the first nEq equality matches since the index 2767 ** has already accounted for these */ 2768 nSkipEq--; 2769 }else{ 2770 /* Assume each additional equality match reduces the result 2771 ** set size by a factor of 10 */ 2772 nRow /= 10; 2773 } 2774 }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){ 2775 if( nSkipRange ){ 2776 /* Ignore the first nBound range constraints since the index 2777 ** has already accounted for these */ 2778 nSkipRange--; 2779 }else{ 2780 /* Assume each additional range constraint reduces the result 2781 ** set size by a factor of 3 */ 2782 nRow /= 3; 2783 } 2784 }else{ 2785 /* Any other expression lowers the output row count by half */ 2786 nRow /= 2; 2787 } 2788 } 2789 if( nRow<2 ) nRow = 2; 2790 } 2791 2792 2793 WHERETRACE(( 2794 "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n" 2795 " notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n", 2796 pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 2797 nEq, nInMul, estBound, bSort, bLookup, wsFlags, 2798 notReady, nRow, cost, used 2799 )); 2800 2801 /* If this index is the best we have seen so far, then record this 2802 ** index and its cost in the pCost structure. 2803 */ 2804 if( (!pIdx || wsFlags) 2805 && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow)) 2806 ){ 2807 pCost->rCost = cost; 2808 pCost->nRow = nRow; 2809 pCost->used = used; 2810 pCost->plan.wsFlags = (wsFlags&wsFlagMask); 2811 pCost->plan.nEq = nEq; 2812 pCost->plan.u.pIdx = pIdx; 2813 } 2814 2815 /* If there was an INDEXED BY clause, then only that one index is 2816 ** considered. */ 2817 if( pSrc->pIndex ) break; 2818 2819 /* Reset masks for the next index in the loop */ 2820 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE); 2821 eqTermMask = idxEqTermMask; 2822 } 2823 2824 /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag 2825 ** is set, then reverse the order that the index will be scanned 2826 ** in. This is used for application testing, to help find cases 2827 ** where application behaviour depends on the (undefined) order that 2828 ** SQLite outputs rows in in the absence of an ORDER BY clause. */ 2829 if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){ 2830 pCost->plan.wsFlags |= WHERE_REVERSE; 2831 } 2832 2833 assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 ); 2834 assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 ); 2835 assert( pSrc->pIndex==0 2836 || pCost->plan.u.pIdx==0 2837 || pCost->plan.u.pIdx==pSrc->pIndex 2838 ); 2839 2840 WHERETRACE(("best index is: %s\n", 2841 ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 2842 pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk") 2843 )); 2844 2845 bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost); 2846 bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost); 2847 pCost->plan.wsFlags |= eqTermMask; 2848 } 2849 2850 /* 2851 ** Find the query plan for accessing table pSrc->pTab. Write the 2852 ** best query plan and its cost into the WhereCost object supplied 2853 ** as the last parameter. This function may calculate the cost of 2854 ** both real and virtual table scans. 2855 */ 2856 static void bestIndex( 2857 Parse *pParse, /* The parsing context */ 2858 WhereClause *pWC, /* The WHERE clause */ 2859 struct SrcList_item *pSrc, /* The FROM clause term to search */ 2860 Bitmask notReady, /* Mask of cursors that are not available */ 2861 ExprList *pOrderBy, /* The ORDER BY clause */ 2862 WhereCost *pCost /* Lowest cost query plan */ 2863 ){ 2864 #ifndef SQLITE_OMIT_VIRTUALTABLE 2865 if( IsVirtual(pSrc->pTab) ){ 2866 sqlite3_index_info *p = 0; 2867 bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p); 2868 if( p->needToFreeIdxStr ){ 2869 sqlite3_free(p->idxStr); 2870 } 2871 sqlite3DbFree(pParse->db, p); 2872 }else 2873 #endif 2874 { 2875 bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost); 2876 } 2877 } 2878 2879 /* 2880 ** Disable a term in the WHERE clause. Except, do not disable the term 2881 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON 2882 ** or USING clause of that join. 2883 ** 2884 ** Consider the term t2.z='ok' in the following queries: 2885 ** 2886 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' 2887 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' 2888 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' 2889 ** 2890 ** The t2.z='ok' is disabled in the in (2) because it originates 2891 ** in the ON clause. The term is disabled in (3) because it is not part 2892 ** of a LEFT OUTER JOIN. In (1), the term is not disabled. 2893 ** 2894 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are 2895 ** completely satisfied by indices. 2896 ** 2897 ** Disabling a term causes that term to not be tested in the inner loop 2898 ** of the join. Disabling is an optimization. When terms are satisfied 2899 ** by indices, we disable them to prevent redundant tests in the inner 2900 ** loop. We would get the correct results if nothing were ever disabled, 2901 ** but joins might run a little slower. The trick is to disable as much 2902 ** as we can without disabling too much. If we disabled in (1), we'd get 2903 ** the wrong answer. See ticket #813. 2904 */ 2905 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ 2906 if( pTerm 2907 && (pTerm->wtFlags & TERM_CODED)==0 2908 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 2909 ){ 2910 pTerm->wtFlags |= TERM_CODED; 2911 if( pTerm->iParent>=0 ){ 2912 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent]; 2913 if( (--pOther->nChild)==0 ){ 2914 disableTerm(pLevel, pOther); 2915 } 2916 } 2917 } 2918 } 2919 2920 /* 2921 ** Code an OP_Affinity opcode to apply the column affinity string zAff 2922 ** to the n registers starting at base. 2923 ** 2924 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the 2925 ** beginning and end of zAff are ignored. If all entries in zAff are 2926 ** SQLITE_AFF_NONE, then no code gets generated. 2927 ** 2928 ** This routine makes its own copy of zAff so that the caller is free 2929 ** to modify zAff after this routine returns. 2930 */ 2931 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ 2932 Vdbe *v = pParse->pVdbe; 2933 if( zAff==0 ){ 2934 assert( pParse->db->mallocFailed ); 2935 return; 2936 } 2937 assert( v!=0 ); 2938 2939 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning 2940 ** and end of the affinity string. 2941 */ 2942 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){ 2943 n--; 2944 base++; 2945 zAff++; 2946 } 2947 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){ 2948 n--; 2949 } 2950 2951 /* Code the OP_Affinity opcode if there is anything left to do. */ 2952 if( n>0 ){ 2953 sqlite3VdbeAddOp2(v, OP_Affinity, base, n); 2954 sqlite3VdbeChangeP4(v, -1, zAff, n); 2955 sqlite3ExprCacheAffinityChange(pParse, base, n); 2956 } 2957 } 2958 2959 2960 /* 2961 ** Generate code for a single equality term of the WHERE clause. An equality 2962 ** term can be either X=expr or X IN (...). pTerm is the term to be 2963 ** coded. 2964 ** 2965 ** The current value for the constraint is left in register iReg. 2966 ** 2967 ** For a constraint of the form X=expr, the expression is evaluated and its 2968 ** result is left on the stack. For constraints of the form X IN (...) 2969 ** this routine sets up a loop that will iterate over all values of X. 2970 */ 2971 static int codeEqualityTerm( 2972 Parse *pParse, /* The parsing context */ 2973 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ 2974 WhereLevel *pLevel, /* When level of the FROM clause we are working on */ 2975 int iTarget /* Attempt to leave results in this register */ 2976 ){ 2977 Expr *pX = pTerm->pExpr; 2978 Vdbe *v = pParse->pVdbe; 2979 int iReg; /* Register holding results */ 2980 2981 assert( iTarget>0 ); 2982 if( pX->op==TK_EQ ){ 2983 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); 2984 }else if( pX->op==TK_ISNULL ){ 2985 iReg = iTarget; 2986 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); 2987 #ifndef SQLITE_OMIT_SUBQUERY 2988 }else{ 2989 int eType; 2990 int iTab; 2991 struct InLoop *pIn; 2992 2993 assert( pX->op==TK_IN ); 2994 iReg = iTarget; 2995 eType = sqlite3FindInIndex(pParse, pX, 0); 2996 iTab = pX->iTable; 2997 sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); 2998 assert( pLevel->plan.wsFlags & WHERE_IN_ABLE ); 2999 if( pLevel->u.in.nIn==0 ){ 3000 pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 3001 } 3002 pLevel->u.in.nIn++; 3003 pLevel->u.in.aInLoop = 3004 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, 3005 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); 3006 pIn = pLevel->u.in.aInLoop; 3007 if( pIn ){ 3008 pIn += pLevel->u.in.nIn - 1; 3009 pIn->iCur = iTab; 3010 if( eType==IN_INDEX_ROWID ){ 3011 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); 3012 }else{ 3013 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg); 3014 } 3015 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); 3016 }else{ 3017 pLevel->u.in.nIn = 0; 3018 } 3019 #endif 3020 } 3021 disableTerm(pLevel, pTerm); 3022 return iReg; 3023 } 3024 3025 /* 3026 ** Generate code that will evaluate all == and IN constraints for an 3027 ** index. 3028 ** 3029 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). 3030 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 3031 ** The index has as many as three equality constraints, but in this 3032 ** example, the third "c" value is an inequality. So only two 3033 ** constraints are coded. This routine will generate code to evaluate 3034 ** a==5 and b IN (1,2,3). The current values for a and b will be stored 3035 ** in consecutive registers and the index of the first register is returned. 3036 ** 3037 ** In the example above nEq==2. But this subroutine works for any value 3038 ** of nEq including 0. If nEq==0, this routine is nearly a no-op. 3039 ** The only thing it does is allocate the pLevel->iMem memory cell and 3040 ** compute the affinity string. 3041 ** 3042 ** This routine always allocates at least one memory cell and returns 3043 ** the index of that memory cell. The code that 3044 ** calls this routine will use that memory cell to store the termination 3045 ** key value of the loop. If one or more IN operators appear, then 3046 ** this routine allocates an additional nEq memory cells for internal 3047 ** use. 3048 ** 3049 ** Before returning, *pzAff is set to point to a buffer containing a 3050 ** copy of the column affinity string of the index allocated using 3051 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated 3052 ** with equality constraints that use NONE affinity are set to 3053 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following: 3054 ** 3055 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); 3056 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; 3057 ** 3058 ** In the example above, the index on t1(a) has TEXT affinity. But since 3059 ** the right hand side of the equality constraint (t2.b) has NONE affinity, 3060 ** no conversion should be attempted before using a t2.b value as part of 3061 ** a key to search the index. Hence the first byte in the returned affinity 3062 ** string in this example would be set to SQLITE_AFF_NONE. 3063 */ 3064 static int codeAllEqualityTerms( 3065 Parse *pParse, /* Parsing context */ 3066 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ 3067 WhereClause *pWC, /* The WHERE clause */ 3068 Bitmask notReady, /* Which parts of FROM have not yet been coded */ 3069 int nExtraReg, /* Number of extra registers to allocate */ 3070 char **pzAff /* OUT: Set to point to affinity string */ 3071 ){ 3072 int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */ 3073 Vdbe *v = pParse->pVdbe; /* The vm under construction */ 3074 Index *pIdx; /* The index being used for this loop */ 3075 int iCur = pLevel->iTabCur; /* The cursor of the table */ 3076 WhereTerm *pTerm; /* A single constraint term */ 3077 int j; /* Loop counter */ 3078 int regBase; /* Base register */ 3079 int nReg; /* Number of registers to allocate */ 3080 char *zAff; /* Affinity string to return */ 3081 3082 /* This module is only called on query plans that use an index. */ 3083 assert( pLevel->plan.wsFlags & WHERE_INDEXED ); 3084 pIdx = pLevel->plan.u.pIdx; 3085 3086 /* Figure out how many memory cells we will need then allocate them. 3087 */ 3088 regBase = pParse->nMem + 1; 3089 nReg = pLevel->plan.nEq + nExtraReg; 3090 pParse->nMem += nReg; 3091 3092 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx)); 3093 if( !zAff ){ 3094 pParse->db->mallocFailed = 1; 3095 } 3096 3097 /* Evaluate the equality constraints 3098 */ 3099 assert( pIdx->nColumn>=nEq ); 3100 for(j=0; j<nEq; j++){ 3101 int r1; 3102 int k = pIdx->aiColumn[j]; 3103 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx); 3104 if( NEVER(pTerm==0) ) break; 3105 /* The following true for indices with redundant columns. 3106 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ 3107 testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); 3108 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */ 3109 r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j); 3110 if( r1!=regBase+j ){ 3111 if( nReg==1 ){ 3112 sqlite3ReleaseTempReg(pParse, regBase); 3113 regBase = r1; 3114 }else{ 3115 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); 3116 } 3117 } 3118 testcase( pTerm->eOperator & WO_ISNULL ); 3119 testcase( pTerm->eOperator & WO_IN ); 3120 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ 3121 Expr *pRight = pTerm->pExpr->pRight; 3122 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk); 3123 if( zAff ){ 3124 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){ 3125 zAff[j] = SQLITE_AFF_NONE; 3126 } 3127 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ 3128 zAff[j] = SQLITE_AFF_NONE; 3129 } 3130 } 3131 } 3132 } 3133 *pzAff = zAff; 3134 return regBase; 3135 } 3136 3137 /* 3138 ** Generate code for the start of the iLevel-th loop in the WHERE clause 3139 ** implementation described by pWInfo. 3140 */ 3141 static Bitmask codeOneLoopStart( 3142 WhereInfo *pWInfo, /* Complete information about the WHERE clause */ 3143 int iLevel, /* Which level of pWInfo->a[] should be coded */ 3144 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */ 3145 Bitmask notReady /* Which tables are currently available */ 3146 ){ 3147 int j, k; /* Loop counters */ 3148 int iCur; /* The VDBE cursor for the table */ 3149 int addrNxt; /* Where to jump to continue with the next IN case */ 3150 int omitTable; /* True if we use the index only */ 3151 int bRev; /* True if we need to scan in reverse order */ 3152 WhereLevel *pLevel; /* The where level to be coded */ 3153 WhereClause *pWC; /* Decomposition of the entire WHERE clause */ 3154 WhereTerm *pTerm; /* A WHERE clause term */ 3155 Parse *pParse; /* Parsing context */ 3156 Vdbe *v; /* The prepared stmt under constructions */ 3157 struct SrcList_item *pTabItem; /* FROM clause term being coded */ 3158 int addrBrk; /* Jump here to break out of the loop */ 3159 int addrCont; /* Jump here to continue with next cycle */ 3160 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ 3161 int iReleaseReg = 0; /* Temp register to free before returning */ 3162 3163 pParse = pWInfo->pParse; 3164 v = pParse->pVdbe; 3165 pWC = pWInfo->pWC; 3166 pLevel = &pWInfo->a[iLevel]; 3167 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 3168 iCur = pTabItem->iCursor; 3169 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0; 3170 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 3171 && (wctrlFlags & WHERE_FORCE_TABLE)==0; 3172 3173 /* Create labels for the "break" and "continue" instructions 3174 ** for the current loop. Jump to addrBrk to break out of a loop. 3175 ** Jump to cont to go immediately to the next iteration of the 3176 ** loop. 3177 ** 3178 ** When there is an IN operator, we also have a "addrNxt" label that 3179 ** means to continue with the next IN value combination. When 3180 ** there are no IN operators in the constraints, the "addrNxt" label 3181 ** is the same as "addrBrk". 3182 */ 3183 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 3184 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); 3185 3186 /* If this is the right table of a LEFT OUTER JOIN, allocate and 3187 ** initialize a memory cell that records if this table matches any 3188 ** row of the left table of the join. 3189 */ 3190 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ 3191 pLevel->iLeftJoin = ++pParse->nMem; 3192 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); 3193 VdbeComment((v, "init LEFT JOIN no-match flag")); 3194 } 3195 3196 #ifndef SQLITE_OMIT_VIRTUALTABLE 3197 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 3198 /* Case 0: The table is a virtual-table. Use the VFilter and VNext 3199 ** to access the data. 3200 */ 3201 int iReg; /* P3 Value for OP_VFilter */ 3202 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx; 3203 int nConstraint = pVtabIdx->nConstraint; 3204 struct sqlite3_index_constraint_usage *aUsage = 3205 pVtabIdx->aConstraintUsage; 3206 const struct sqlite3_index_constraint *aConstraint = 3207 pVtabIdx->aConstraint; 3208 3209 sqlite3ExprCachePush(pParse); 3210 iReg = sqlite3GetTempRange(pParse, nConstraint+2); 3211 for(j=1; j<=nConstraint; j++){ 3212 for(k=0; k<nConstraint; k++){ 3213 if( aUsage[k].argvIndex==j ){ 3214 int iTerm = aConstraint[k].iTermOffset; 3215 sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1); 3216 break; 3217 } 3218 } 3219 if( k==nConstraint ) break; 3220 } 3221 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg); 3222 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1); 3223 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr, 3224 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC); 3225 pVtabIdx->needToFreeIdxStr = 0; 3226 for(j=0; j<nConstraint; j++){ 3227 if( aUsage[j].omit ){ 3228 int iTerm = aConstraint[j].iTermOffset; 3229 disableTerm(pLevel, &pWC->a[iTerm]); 3230 } 3231 } 3232 pLevel->op = OP_VNext; 3233 pLevel->p1 = iCur; 3234 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 3235 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); 3236 sqlite3ExprCachePop(pParse, 1); 3237 }else 3238 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 3239 3240 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){ 3241 /* Case 1: We can directly reference a single row using an 3242 ** equality comparison against the ROWID field. Or 3243 ** we reference multiple rows using a "rowid IN (...)" 3244 ** construct. 3245 */ 3246 iReleaseReg = sqlite3GetTempReg(pParse); 3247 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0); 3248 assert( pTerm!=0 ); 3249 assert( pTerm->pExpr!=0 ); 3250 assert( pTerm->leftCursor==iCur ); 3251 assert( omitTable==0 ); 3252 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */ 3253 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg); 3254 addrNxt = pLevel->addrNxt; 3255 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); 3256 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg); 3257 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 3258 VdbeComment((v, "pk")); 3259 pLevel->op = OP_Noop; 3260 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){ 3261 /* Case 2: We have an inequality comparison against the ROWID field. 3262 */ 3263 int testOp = OP_Noop; 3264 int start; 3265 int memEndValue = 0; 3266 WhereTerm *pStart, *pEnd; 3267 3268 assert( omitTable==0 ); 3269 pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0); 3270 pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0); 3271 if( bRev ){ 3272 pTerm = pStart; 3273 pStart = pEnd; 3274 pEnd = pTerm; 3275 } 3276 if( pStart ){ 3277 Expr *pX; /* The expression that defines the start bound */ 3278 int r1, rTemp; /* Registers for holding the start boundary */ 3279 3280 /* The following constant maps TK_xx codes into corresponding 3281 ** seek opcodes. It depends on a particular ordering of TK_xx 3282 */ 3283 const u8 aMoveOp[] = { 3284 /* TK_GT */ OP_SeekGt, 3285 /* TK_LE */ OP_SeekLe, 3286 /* TK_LT */ OP_SeekLt, 3287 /* TK_GE */ OP_SeekGe 3288 }; 3289 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ 3290 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ 3291 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ 3292 3293 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */ 3294 pX = pStart->pExpr; 3295 assert( pX!=0 ); 3296 assert( pStart->leftCursor==iCur ); 3297 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); 3298 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1); 3299 VdbeComment((v, "pk")); 3300 sqlite3ExprCacheAffinityChange(pParse, r1, 1); 3301 sqlite3ReleaseTempReg(pParse, rTemp); 3302 disableTerm(pLevel, pStart); 3303 }else{ 3304 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); 3305 } 3306 if( pEnd ){ 3307 Expr *pX; 3308 pX = pEnd->pExpr; 3309 assert( pX!=0 ); 3310 assert( pEnd->leftCursor==iCur ); 3311 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */ 3312 memEndValue = ++pParse->nMem; 3313 sqlite3ExprCode(pParse, pX->pRight, memEndValue); 3314 if( pX->op==TK_LT || pX->op==TK_GT ){ 3315 testOp = bRev ? OP_Le : OP_Ge; 3316 }else{ 3317 testOp = bRev ? OP_Lt : OP_Gt; 3318 } 3319 disableTerm(pLevel, pEnd); 3320 } 3321 start = sqlite3VdbeCurrentAddr(v); 3322 pLevel->op = bRev ? OP_Prev : OP_Next; 3323 pLevel->p1 = iCur; 3324 pLevel->p2 = start; 3325 if( pStart==0 && pEnd==0 ){ 3326 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 3327 }else{ 3328 assert( pLevel->p5==0 ); 3329 } 3330 if( testOp!=OP_Noop ){ 3331 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse); 3332 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); 3333 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 3334 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); 3335 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); 3336 } 3337 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){ 3338 /* Case 3: A scan using an index. 3339 ** 3340 ** The WHERE clause may contain zero or more equality 3341 ** terms ("==" or "IN" operators) that refer to the N 3342 ** left-most columns of the index. It may also contain 3343 ** inequality constraints (>, <, >= or <=) on the indexed 3344 ** column that immediately follows the N equalities. Only 3345 ** the right-most column can be an inequality - the rest must 3346 ** use the "==" and "IN" operators. For example, if the 3347 ** index is on (x,y,z), then the following clauses are all 3348 ** optimized: 3349 ** 3350 ** x=5 3351 ** x=5 AND y=10 3352 ** x=5 AND y<10 3353 ** x=5 AND y>5 AND y<10 3354 ** x=5 AND y=5 AND z<=10 3355 ** 3356 ** The z<10 term of the following cannot be used, only 3357 ** the x=5 term: 3358 ** 3359 ** x=5 AND z<10 3360 ** 3361 ** N may be zero if there are inequality constraints. 3362 ** If there are no inequality constraints, then N is at 3363 ** least one. 3364 ** 3365 ** This case is also used when there are no WHERE clause 3366 ** constraints but an index is selected anyway, in order 3367 ** to force the output order to conform to an ORDER BY. 3368 */ 3369 static const u8 aStartOp[] = { 3370 0, 3371 0, 3372 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ 3373 OP_Last, /* 3: (!start_constraints && startEq && bRev) */ 3374 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */ 3375 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */ 3376 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */ 3377 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */ 3378 }; 3379 static const u8 aEndOp[] = { 3380 OP_Noop, /* 0: (!end_constraints) */ 3381 OP_IdxGE, /* 1: (end_constraints && !bRev) */ 3382 OP_IdxLT /* 2: (end_constraints && bRev) */ 3383 }; 3384 int nEq = pLevel->plan.nEq; /* Number of == or IN terms */ 3385 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */ 3386 int regBase; /* Base register holding constraint values */ 3387 int r1; /* Temp register */ 3388 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ 3389 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ 3390 int startEq; /* True if range start uses ==, >= or <= */ 3391 int endEq; /* True if range end uses ==, >= or <= */ 3392 int start_constraints; /* Start of range is constrained */ 3393 int nConstraint; /* Number of constraint terms */ 3394 Index *pIdx; /* The index we will be using */ 3395 int iIdxCur; /* The VDBE cursor for the index */ 3396 int nExtraReg = 0; /* Number of extra registers needed */ 3397 int op; /* Instruction opcode */ 3398 char *zStartAff; /* Affinity for start of range constraint */ 3399 char *zEndAff; /* Affinity for end of range constraint */ 3400 3401 pIdx = pLevel->plan.u.pIdx; 3402 iIdxCur = pLevel->iIdxCur; 3403 k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */ 3404 3405 /* If this loop satisfies a sort order (pOrderBy) request that 3406 ** was passed to this function to implement a "SELECT min(x) ..." 3407 ** query, then the caller will only allow the loop to run for 3408 ** a single iteration. This means that the first row returned 3409 ** should not have a NULL value stored in 'x'. If column 'x' is 3410 ** the first one after the nEq equality constraints in the index, 3411 ** this requires some special handling. 3412 */ 3413 if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0 3414 && (pLevel->plan.wsFlags&WHERE_ORDERBY) 3415 && (pIdx->nColumn>nEq) 3416 ){ 3417 /* assert( pOrderBy->nExpr==1 ); */ 3418 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */ 3419 isMinQuery = 1; 3420 nExtraReg = 1; 3421 } 3422 3423 /* Find any inequality constraint terms for the start and end 3424 ** of the range. 3425 */ 3426 if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){ 3427 pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx); 3428 nExtraReg = 1; 3429 } 3430 if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){ 3431 pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx); 3432 nExtraReg = 1; 3433 } 3434 3435 /* Generate code to evaluate all constraint terms using == or IN 3436 ** and store the values of those terms in an array of registers 3437 ** starting at regBase. 3438 */ 3439 regBase = codeAllEqualityTerms( 3440 pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff 3441 ); 3442 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff); 3443 addrNxt = pLevel->addrNxt; 3444 3445 /* If we are doing a reverse order scan on an ascending index, or 3446 ** a forward order scan on a descending index, interchange the 3447 ** start and end terms (pRangeStart and pRangeEnd). 3448 */ 3449 if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){ 3450 SWAP(WhereTerm *, pRangeEnd, pRangeStart); 3451 } 3452 3453 testcase( pRangeStart && pRangeStart->eOperator & WO_LE ); 3454 testcase( pRangeStart && pRangeStart->eOperator & WO_GE ); 3455 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE ); 3456 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE ); 3457 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); 3458 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); 3459 start_constraints = pRangeStart || nEq>0; 3460 3461 /* Seek the index cursor to the start of the range. */ 3462 nConstraint = nEq; 3463 if( pRangeStart ){ 3464 Expr *pRight = pRangeStart->pExpr->pRight; 3465 sqlite3ExprCode(pParse, pRight, regBase+nEq); 3466 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt); 3467 if( zStartAff ){ 3468 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){ 3469 /* Since the comparison is to be performed with no conversions 3470 ** applied to the operands, set the affinity to apply to pRight to 3471 ** SQLITE_AFF_NONE. */ 3472 zStartAff[nEq] = SQLITE_AFF_NONE; 3473 } 3474 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ 3475 zStartAff[nEq] = SQLITE_AFF_NONE; 3476 } 3477 } 3478 nConstraint++; 3479 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */ 3480 }else if( isMinQuery ){ 3481 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 3482 nConstraint++; 3483 startEq = 0; 3484 start_constraints = 1; 3485 } 3486 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff); 3487 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; 3488 assert( op!=0 ); 3489 testcase( op==OP_Rewind ); 3490 testcase( op==OP_Last ); 3491 testcase( op==OP_SeekGt ); 3492 testcase( op==OP_SeekGe ); 3493 testcase( op==OP_SeekLe ); 3494 testcase( op==OP_SeekLt ); 3495 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 3496 3497 /* Load the value for the inequality constraint at the end of the 3498 ** range (if any). 3499 */ 3500 nConstraint = nEq; 3501 if( pRangeEnd ){ 3502 Expr *pRight = pRangeEnd->pExpr->pRight; 3503 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); 3504 sqlite3ExprCode(pParse, pRight, regBase+nEq); 3505 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt); 3506 if( zEndAff ){ 3507 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){ 3508 /* Since the comparison is to be performed with no conversions 3509 ** applied to the operands, set the affinity to apply to pRight to 3510 ** SQLITE_AFF_NONE. */ 3511 zEndAff[nEq] = SQLITE_AFF_NONE; 3512 } 3513 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){ 3514 zEndAff[nEq] = SQLITE_AFF_NONE; 3515 } 3516 } 3517 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff); 3518 nConstraint++; 3519 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */ 3520 } 3521 sqlite3DbFree(pParse->db, zStartAff); 3522 sqlite3DbFree(pParse->db, zEndAff); 3523 3524 /* Top of the loop body */ 3525 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 3526 3527 /* Check if the index cursor is past the end of the range. */ 3528 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)]; 3529 testcase( op==OP_Noop ); 3530 testcase( op==OP_IdxGE ); 3531 testcase( op==OP_IdxLT ); 3532 if( op!=OP_Noop ){ 3533 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 3534 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0); 3535 } 3536 3537 /* If there are inequality constraints, check that the value 3538 ** of the table column that the inequality contrains is not NULL. 3539 ** If it is, jump to the next iteration of the loop. 3540 */ 3541 r1 = sqlite3GetTempReg(pParse); 3542 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ); 3543 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ); 3544 if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){ 3545 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1); 3546 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont); 3547 } 3548 sqlite3ReleaseTempReg(pParse, r1); 3549 3550 /* Seek the table cursor, if required */ 3551 disableTerm(pLevel, pRangeStart); 3552 disableTerm(pLevel, pRangeEnd); 3553 if( !omitTable ){ 3554 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse); 3555 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); 3556 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 3557 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */ 3558 } 3559 3560 /* Record the instruction used to terminate the loop. Disable 3561 ** WHERE clause terms made redundant by the index range scan. 3562 */ 3563 pLevel->op = bRev ? OP_Prev : OP_Next; 3564 pLevel->p1 = iIdxCur; 3565 }else 3566 3567 #ifndef SQLITE_OMIT_OR_OPTIMIZATION 3568 if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){ 3569 /* Case 4: Two or more separately indexed terms connected by OR 3570 ** 3571 ** Example: 3572 ** 3573 ** CREATE TABLE t1(a,b,c,d); 3574 ** CREATE INDEX i1 ON t1(a); 3575 ** CREATE INDEX i2 ON t1(b); 3576 ** CREATE INDEX i3 ON t1(c); 3577 ** 3578 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) 3579 ** 3580 ** In the example, there are three indexed terms connected by OR. 3581 ** The top of the loop looks like this: 3582 ** 3583 ** Null 1 # Zero the rowset in reg 1 3584 ** 3585 ** Then, for each indexed term, the following. The arguments to 3586 ** RowSetTest are such that the rowid of the current row is inserted 3587 ** into the RowSet. If it is already present, control skips the 3588 ** Gosub opcode and jumps straight to the code generated by WhereEnd(). 3589 ** 3590 ** sqlite3WhereBegin(<term>) 3591 ** RowSetTest # Insert rowid into rowset 3592 ** Gosub 2 A 3593 ** sqlite3WhereEnd() 3594 ** 3595 ** Following the above, code to terminate the loop. Label A, the target 3596 ** of the Gosub above, jumps to the instruction right after the Goto. 3597 ** 3598 ** Null 1 # Zero the rowset in reg 1 3599 ** Goto B # The loop is finished. 3600 ** 3601 ** A: <loop body> # Return data, whatever. 3602 ** 3603 ** Return 2 # Jump back to the Gosub 3604 ** 3605 ** B: <after the loop> 3606 ** 3607 */ 3608 WhereClause *pOrWc; /* The OR-clause broken out into subterms */ 3609 WhereTerm *pFinal; /* Final subterm within the OR-clause. */ 3610 SrcList *pOrTab; /* Shortened table list or OR-clause generation */ 3611 3612 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ 3613 int regRowset = 0; /* Register for RowSet object */ 3614 int regRowid = 0; /* Register holding rowid */ 3615 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ 3616 int iRetInit; /* Address of regReturn init */ 3617 int untestedTerms = 0; /* Some terms not completely tested */ 3618 int ii; 3619 3620 pTerm = pLevel->plan.u.pTerm; 3621 assert( pTerm!=0 ); 3622 assert( pTerm->eOperator==WO_OR ); 3623 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); 3624 pOrWc = &pTerm->u.pOrInfo->wc; 3625 pFinal = &pOrWc->a[pOrWc->nTerm-1]; 3626 pLevel->op = OP_Return; 3627 pLevel->p1 = regReturn; 3628 3629 /* Set up a new SrcList ni pOrTab containing the table being scanned 3630 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. 3631 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). 3632 */ 3633 if( pWInfo->nLevel>1 ){ 3634 int nNotReady; /* The number of notReady tables */ 3635 struct SrcList_item *origSrc; /* Original list of tables */ 3636 nNotReady = pWInfo->nLevel - iLevel - 1; 3637 pOrTab = sqlite3StackAllocRaw(pParse->db, 3638 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); 3639 if( pOrTab==0 ) return notReady; 3640 pOrTab->nAlloc = (i16)(nNotReady + 1); 3641 pOrTab->nSrc = pOrTab->nAlloc; 3642 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); 3643 origSrc = pWInfo->pTabList->a; 3644 for(k=1; k<=nNotReady; k++){ 3645 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); 3646 } 3647 }else{ 3648 pOrTab = pWInfo->pTabList; 3649 } 3650 3651 /* Initialize the rowset register to contain NULL. An SQL NULL is 3652 ** equivalent to an empty rowset. 3653 ** 3654 ** Also initialize regReturn to contain the address of the instruction 3655 ** immediately following the OP_Return at the bottom of the loop. This 3656 ** is required in a few obscure LEFT JOIN cases where control jumps 3657 ** over the top of the loop into the body of it. In this case the 3658 ** correct response for the end-of-loop code (the OP_Return) is to 3659 ** fall through to the next instruction, just as an OP_Next does if 3660 ** called on an uninitialized cursor. 3661 */ 3662 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 3663 regRowset = ++pParse->nMem; 3664 regRowid = ++pParse->nMem; 3665 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); 3666 } 3667 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); 3668 3669 for(ii=0; ii<pOrWc->nTerm; ii++){ 3670 WhereTerm *pOrTerm = &pOrWc->a[ii]; 3671 if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){ 3672 WhereInfo *pSubWInfo; /* Info for single OR-term scan */ 3673 /* Loop through table entries that match term pOrTerm. */ 3674 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0, 3675 WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE | 3676 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY); 3677 if( pSubWInfo ){ 3678 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 3679 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); 3680 int r; 3681 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 3682 regRowid); 3683 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 3684 sqlite3VdbeCurrentAddr(v)+2, r, iSet); 3685 } 3686 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); 3687 3688 /* The pSubWInfo->untestedTerms flag means that this OR term 3689 ** contained one or more AND term from a notReady table. The 3690 ** terms from the notReady table could not be tested and will 3691 ** need to be tested later. 3692 */ 3693 if( pSubWInfo->untestedTerms ) untestedTerms = 1; 3694 3695 /* Finish the loop through table entries that match term pOrTerm. */ 3696 sqlite3WhereEnd(pSubWInfo); 3697 } 3698 } 3699 } 3700 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); 3701 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); 3702 sqlite3VdbeResolveLabel(v, iLoopBody); 3703 3704 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab); 3705 if( !untestedTerms ) disableTerm(pLevel, pTerm); 3706 }else 3707 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 3708 3709 { 3710 /* Case 5: There is no usable index. We must do a complete 3711 ** scan of the entire table. 3712 */ 3713 static const u8 aStep[] = { OP_Next, OP_Prev }; 3714 static const u8 aStart[] = { OP_Rewind, OP_Last }; 3715 assert( bRev==0 || bRev==1 ); 3716 assert( omitTable==0 ); 3717 pLevel->op = aStep[bRev]; 3718 pLevel->p1 = iCur; 3719 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); 3720 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 3721 } 3722 notReady &= ~getMask(pWC->pMaskSet, iCur); 3723 3724 /* Insert code to test every subexpression that can be completely 3725 ** computed using the current set of tables. 3726 ** 3727 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through 3728 ** the use of indices become tests that are evaluated against each row of 3729 ** the relevant input tables. 3730 */ 3731 k = 0; 3732 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 3733 Expr *pE; 3734 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */ 3735 testcase( pTerm->wtFlags & TERM_CODED ); 3736 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 3737 if( (pTerm->prereqAll & notReady)!=0 ){ 3738 testcase( pWInfo->untestedTerms==0 3739 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ); 3740 pWInfo->untestedTerms = 1; 3741 continue; 3742 } 3743 pE = pTerm->pExpr; 3744 assert( pE!=0 ); 3745 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ 3746 continue; 3747 } 3748 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); 3749 k = 1; 3750 pTerm->wtFlags |= TERM_CODED; 3751 } 3752 3753 /* For a LEFT OUTER JOIN, generate code that will record the fact that 3754 ** at least one row of the right table has matched the left table. 3755 */ 3756 if( pLevel->iLeftJoin ){ 3757 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); 3758 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); 3759 VdbeComment((v, "record LEFT JOIN hit")); 3760 sqlite3ExprCacheClear(pParse); 3761 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ 3762 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */ 3763 testcase( pTerm->wtFlags & TERM_CODED ); 3764 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 3765 if( (pTerm->prereqAll & notReady)!=0 ){ 3766 assert( pWInfo->untestedTerms ); 3767 continue; 3768 } 3769 assert( pTerm->pExpr ); 3770 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 3771 pTerm->wtFlags |= TERM_CODED; 3772 } 3773 } 3774 sqlite3ReleaseTempReg(pParse, iReleaseReg); 3775 3776 return notReady; 3777 } 3778 3779 #if defined(SQLITE_TEST) 3780 /* 3781 ** The following variable holds a text description of query plan generated 3782 ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin 3783 ** overwrites the previous. This information is used for testing and 3784 ** analysis only. 3785 */ 3786 char sqlite3_query_plan[BMS*2*40]; /* Text of the join */ 3787 static int nQPlan = 0; /* Next free slow in _query_plan[] */ 3788 3789 #endif /* SQLITE_TEST */ 3790 3791 3792 /* 3793 ** Free a WhereInfo structure 3794 */ 3795 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ 3796 if( ALWAYS(pWInfo) ){ 3797 int i; 3798 for(i=0; i<pWInfo->nLevel; i++){ 3799 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo; 3800 if( pInfo ){ 3801 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */ 3802 if( pInfo->needToFreeIdxStr ){ 3803 sqlite3_free(pInfo->idxStr); 3804 } 3805 sqlite3DbFree(db, pInfo); 3806 } 3807 if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){ 3808 Index *pIdx = pWInfo->a[i].plan.u.pIdx; 3809 if( pIdx ){ 3810 sqlite3DbFree(db, pIdx->zColAff); 3811 sqlite3DbFree(db, pIdx); 3812 } 3813 } 3814 } 3815 whereClauseClear(pWInfo->pWC); 3816 sqlite3DbFree(db, pWInfo); 3817 } 3818 } 3819 3820 3821 /* 3822 ** Generate the beginning of the loop used for WHERE clause processing. 3823 ** The return value is a pointer to an opaque structure that contains 3824 ** information needed to terminate the loop. Later, the calling routine 3825 ** should invoke sqlite3WhereEnd() with the return value of this function 3826 ** in order to complete the WHERE clause processing. 3827 ** 3828 ** If an error occurs, this routine returns NULL. 3829 ** 3830 ** The basic idea is to do a nested loop, one loop for each table in 3831 ** the FROM clause of a select. (INSERT and UPDATE statements are the 3832 ** same as a SELECT with only a single table in the FROM clause.) For 3833 ** example, if the SQL is this: 3834 ** 3835 ** SELECT * FROM t1, t2, t3 WHERE ...; 3836 ** 3837 ** Then the code generated is conceptually like the following: 3838 ** 3839 ** foreach row1 in t1 do \ Code generated 3840 ** foreach row2 in t2 do |-- by sqlite3WhereBegin() 3841 ** foreach row3 in t3 do / 3842 ** ... 3843 ** end \ Code generated 3844 ** end |-- by sqlite3WhereEnd() 3845 ** end / 3846 ** 3847 ** Note that the loops might not be nested in the order in which they 3848 ** appear in the FROM clause if a different order is better able to make 3849 ** use of indices. Note also that when the IN operator appears in 3850 ** the WHERE clause, it might result in additional nested loops for 3851 ** scanning through all values on the right-hand side of the IN. 3852 ** 3853 ** There are Btree cursors associated with each table. t1 uses cursor 3854 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor. 3855 ** And so forth. This routine generates code to open those VDBE cursors 3856 ** and sqlite3WhereEnd() generates the code to close them. 3857 ** 3858 ** The code that sqlite3WhereBegin() generates leaves the cursors named 3859 ** in pTabList pointing at their appropriate entries. The [...] code 3860 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract 3861 ** data from the various tables of the loop. 3862 ** 3863 ** If the WHERE clause is empty, the foreach loops must each scan their 3864 ** entire tables. Thus a three-way join is an O(N^3) operation. But if 3865 ** the tables have indices and there are terms in the WHERE clause that 3866 ** refer to those indices, a complete table scan can be avoided and the 3867 ** code will run much faster. Most of the work of this routine is checking 3868 ** to see if there are indices that can be used to speed up the loop. 3869 ** 3870 ** Terms of the WHERE clause are also used to limit which rows actually 3871 ** make it to the "..." in the middle of the loop. After each "foreach", 3872 ** terms of the WHERE clause that use only terms in that loop and outer 3873 ** loops are evaluated and if false a jump is made around all subsequent 3874 ** inner loops (or around the "..." if the test occurs within the inner- 3875 ** most loop) 3876 ** 3877 ** OUTER JOINS 3878 ** 3879 ** An outer join of tables t1 and t2 is conceptally coded as follows: 3880 ** 3881 ** foreach row1 in t1 do 3882 ** flag = 0 3883 ** foreach row2 in t2 do 3884 ** start: 3885 ** ... 3886 ** flag = 1 3887 ** end 3888 ** if flag==0 then 3889 ** move the row2 cursor to a null row 3890 ** goto start 3891 ** fi 3892 ** end 3893 ** 3894 ** ORDER BY CLAUSE PROCESSING 3895 ** 3896 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement, 3897 ** if there is one. If there is no ORDER BY clause or if this routine 3898 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL. 3899 ** 3900 ** If an index can be used so that the natural output order of the table 3901 ** scan is correct for the ORDER BY clause, then that index is used and 3902 ** *ppOrderBy is set to NULL. This is an optimization that prevents an 3903 ** unnecessary sort of the result set if an index appropriate for the 3904 ** ORDER BY clause already exists. 3905 ** 3906 ** If the where clause loops cannot be arranged to provide the correct 3907 ** output order, then the *ppOrderBy is unchanged. 3908 */ 3909 WhereInfo *sqlite3WhereBegin( 3910 Parse *pParse, /* The parser context */ 3911 SrcList *pTabList, /* A list of all tables to be scanned */ 3912 Expr *pWhere, /* The WHERE clause */ 3913 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */ 3914 u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */ 3915 ){ 3916 int i; /* Loop counter */ 3917 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */ 3918 int nTabList; /* Number of elements in pTabList */ 3919 WhereInfo *pWInfo; /* Will become the return value of this function */ 3920 Vdbe *v = pParse->pVdbe; /* The virtual database engine */ 3921 Bitmask notReady; /* Cursors that are not yet positioned */ 3922 WhereMaskSet *pMaskSet; /* The expression mask set */ 3923 WhereClause *pWC; /* Decomposition of the WHERE clause */ 3924 struct SrcList_item *pTabItem; /* A single entry from pTabList */ 3925 WhereLevel *pLevel; /* A single level in the pWInfo list */ 3926 int iFrom; /* First unused FROM clause element */ 3927 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */ 3928 sqlite3 *db; /* Database connection */ 3929 3930 /* The number of tables in the FROM clause is limited by the number of 3931 ** bits in a Bitmask 3932 */ 3933 testcase( pTabList->nSrc==BMS ); 3934 if( pTabList->nSrc>BMS ){ 3935 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); 3936 return 0; 3937 } 3938 3939 /* This function normally generates a nested loop for all tables in 3940 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should 3941 ** only generate code for the first table in pTabList and assume that 3942 ** any cursors associated with subsequent tables are uninitialized. 3943 */ 3944 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc; 3945 3946 /* Allocate and initialize the WhereInfo structure that will become the 3947 ** return value. A single allocation is used to store the WhereInfo 3948 ** struct, the contents of WhereInfo.a[], the WhereClause structure 3949 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte 3950 ** field (type Bitmask) it must be aligned on an 8-byte boundary on 3951 ** some architectures. Hence the ROUND8() below. 3952 */ 3953 db = pParse->db; 3954 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel)); 3955 pWInfo = sqlite3DbMallocZero(db, 3956 nByteWInfo + 3957 sizeof(WhereClause) + 3958 sizeof(WhereMaskSet) 3959 ); 3960 if( db->mallocFailed ){ 3961 sqlite3DbFree(db, pWInfo); 3962 pWInfo = 0; 3963 goto whereBeginError; 3964 } 3965 pWInfo->nLevel = nTabList; 3966 pWInfo->pParse = pParse; 3967 pWInfo->pTabList = pTabList; 3968 pWInfo->iBreak = sqlite3VdbeMakeLabel(v); 3969 pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo]; 3970 pWInfo->wctrlFlags = wctrlFlags; 3971 pWInfo->savedNQueryLoop = pParse->nQueryLoop; 3972 pMaskSet = (WhereMaskSet*)&pWC[1]; 3973 3974 /* Split the WHERE clause into separate subexpressions where each 3975 ** subexpression is separated by an AND operator. 3976 */ 3977 initMaskSet(pMaskSet); 3978 whereClauseInit(pWC, pParse, pMaskSet); 3979 sqlite3ExprCodeConstants(pParse, pWhere); 3980 whereSplit(pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */ 3981 3982 /* Special case: a WHERE clause that is constant. Evaluate the 3983 ** expression and either jump over all of the code or fall thru. 3984 */ 3985 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){ 3986 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL); 3987 pWhere = 0; 3988 } 3989 3990 /* Assign a bit from the bitmask to every term in the FROM clause. 3991 ** 3992 ** When assigning bitmask values to FROM clause cursors, it must be 3993 ** the case that if X is the bitmask for the N-th FROM clause term then 3994 ** the bitmask for all FROM clause terms to the left of the N-th term 3995 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use 3996 ** its Expr.iRightJoinTable value to find the bitmask of the right table 3997 ** of the join. Subtracting one from the right table bitmask gives a 3998 ** bitmask for all tables to the left of the join. Knowing the bitmask 3999 ** for all tables to the left of a left join is important. Ticket #3015. 4000 ** 4001 ** Configure the WhereClause.vmask variable so that bits that correspond 4002 ** to virtual table cursors are set. This is used to selectively disable 4003 ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 4004 ** with virtual tables. 4005 ** 4006 ** Note that bitmasks are created for all pTabList->nSrc tables in 4007 ** pTabList, not just the first nTabList tables. nTabList is normally 4008 ** equal to pTabList->nSrc but might be shortened to 1 if the 4009 ** WHERE_ONETABLE_ONLY flag is set. 4010 */ 4011 assert( pWC->vmask==0 && pMaskSet->n==0 ); 4012 for(i=0; i<pTabList->nSrc; i++){ 4013 createMask(pMaskSet, pTabList->a[i].iCursor); 4014 #ifndef SQLITE_OMIT_VIRTUALTABLE 4015 if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){ 4016 pWC->vmask |= ((Bitmask)1 << i); 4017 } 4018 #endif 4019 } 4020 #ifndef NDEBUG 4021 { 4022 Bitmask toTheLeft = 0; 4023 for(i=0; i<pTabList->nSrc; i++){ 4024 Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor); 4025 assert( (m-1)==toTheLeft ); 4026 toTheLeft |= m; 4027 } 4028 } 4029 #endif 4030 4031 /* Analyze all of the subexpressions. Note that exprAnalyze() might 4032 ** add new virtual terms onto the end of the WHERE clause. We do not 4033 ** want to analyze these virtual terms, so start analyzing at the end 4034 ** and work forward so that the added virtual terms are never processed. 4035 */ 4036 exprAnalyzeAll(pTabList, pWC); 4037 if( db->mallocFailed ){ 4038 goto whereBeginError; 4039 } 4040 4041 /* Chose the best index to use for each table in the FROM clause. 4042 ** 4043 ** This loop fills in the following fields: 4044 ** 4045 ** pWInfo->a[].pIdx The index to use for this level of the loop. 4046 ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx 4047 ** pWInfo->a[].nEq The number of == and IN constraints 4048 ** pWInfo->a[].iFrom Which term of the FROM clause is being coded 4049 ** pWInfo->a[].iTabCur The VDBE cursor for the database table 4050 ** pWInfo->a[].iIdxCur The VDBE cursor for the index 4051 ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term 4052 ** 4053 ** This loop also figures out the nesting order of tables in the FROM 4054 ** clause. 4055 */ 4056 notReady = ~(Bitmask)0; 4057 pTabItem = pTabList->a; 4058 pLevel = pWInfo->a; 4059 andFlags = ~0; 4060 WHERETRACE(("*** Optimizer Start ***\n")); 4061 for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){ 4062 WhereCost bestPlan; /* Most efficient plan seen so far */ 4063 Index *pIdx; /* Index for FROM table at pTabItem */ 4064 int j; /* For looping over FROM tables */ 4065 int bestJ = -1; /* The value of j */ 4066 Bitmask m; /* Bitmask value for j or bestJ */ 4067 int isOptimal; /* Iterator for optimal/non-optimal search */ 4068 int nUnconstrained; /* Number tables without INDEXED BY */ 4069 Bitmask notIndexed; /* Mask of tables that cannot use an index */ 4070 4071 memset(&bestPlan, 0, sizeof(bestPlan)); 4072 bestPlan.rCost = SQLITE_BIG_DBL; 4073 4074 /* Loop through the remaining entries in the FROM clause to find the 4075 ** next nested loop. The loop tests all FROM clause entries 4076 ** either once or twice. 4077 ** 4078 ** The first test is always performed if there are two or more entries 4079 ** remaining and never performed if there is only one FROM clause entry 4080 ** to choose from. The first test looks for an "optimal" scan. In 4081 ** this context an optimal scan is one that uses the same strategy 4082 ** for the given FROM clause entry as would be selected if the entry 4083 ** were used as the innermost nested loop. In other words, a table 4084 ** is chosen such that the cost of running that table cannot be reduced 4085 ** by waiting for other tables to run first. This "optimal" test works 4086 ** by first assuming that the FROM clause is on the inner loop and finding 4087 ** its query plan, then checking to see if that query plan uses any 4088 ** other FROM clause terms that are notReady. If no notReady terms are 4089 ** used then the "optimal" query plan works. 4090 ** 4091 ** The second loop iteration is only performed if no optimal scan 4092 ** strategies were found by the first loop. This 2nd iteration is used to 4093 ** search for the lowest cost scan overall. 4094 ** 4095 ** Previous versions of SQLite performed only the second iteration - 4096 ** the next outermost loop was always that with the lowest overall 4097 ** cost. However, this meant that SQLite could select the wrong plan 4098 ** for scripts such as the following: 4099 ** 4100 ** CREATE TABLE t1(a, b); 4101 ** CREATE TABLE t2(c, d); 4102 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a; 4103 ** 4104 ** The best strategy is to iterate through table t1 first. However it 4105 ** is not possible to determine this with a simple greedy algorithm. 4106 ** However, since the cost of a linear scan through table t2 is the same 4107 ** as the cost of a linear scan through table t1, a simple greedy 4108 ** algorithm may choose to use t2 for the outer loop, which is a much 4109 ** costlier approach. 4110 */ 4111 nUnconstrained = 0; 4112 notIndexed = 0; 4113 for(isOptimal=(iFrom<nTabList-1); isOptimal>=0; isOptimal--){ 4114 Bitmask mask; /* Mask of tables not yet ready */ 4115 for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){ 4116 int doNotReorder; /* True if this table should not be reordered */ 4117 WhereCost sCost; /* Cost information from best[Virtual]Index() */ 4118 ExprList *pOrderBy; /* ORDER BY clause for index to optimize */ 4119 4120 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0; 4121 if( j!=iFrom && doNotReorder ) break; 4122 m = getMask(pMaskSet, pTabItem->iCursor); 4123 if( (m & notReady)==0 ){ 4124 if( j==iFrom ) iFrom++; 4125 continue; 4126 } 4127 mask = (isOptimal ? m : notReady); 4128 pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0); 4129 if( pTabItem->pIndex==0 ) nUnconstrained++; 4130 4131 assert( pTabItem->pTab ); 4132 #ifndef SQLITE_OMIT_VIRTUALTABLE 4133 if( IsVirtual(pTabItem->pTab) ){ 4134 sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo; 4135 bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp); 4136 }else 4137 #endif 4138 { 4139 bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost); 4140 } 4141 assert( isOptimal || (sCost.used¬Ready)==0 ); 4142 4143 /* If an INDEXED BY clause is present, then the plan must use that 4144 ** index if it uses any index at all */ 4145 assert( pTabItem->pIndex==0 4146 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 4147 || sCost.plan.u.pIdx==pTabItem->pIndex ); 4148 4149 if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){ 4150 notIndexed |= m; 4151 } 4152 4153 /* Conditions under which this table becomes the best so far: 4154 ** 4155 ** (1) The table must not depend on other tables that have not 4156 ** yet run. 4157 ** 4158 ** (2) A full-table-scan plan cannot supercede another plan unless 4159 ** it is an "optimal" plan as defined above. 4160 ** 4161 ** (3) All tables have an INDEXED BY clause or this table lacks an 4162 ** INDEXED BY clause or this table uses the specific 4163 ** index specified by its INDEXED BY clause. This rule ensures 4164 ** that a best-so-far is always selected even if an impossible 4165 ** combination of INDEXED BY clauses are given. The error 4166 ** will be detected and relayed back to the application later. 4167 ** The NEVER() comes about because rule (2) above prevents 4168 ** An indexable full-table-scan from reaching rule (3). 4169 ** 4170 ** (4) The plan cost must be lower than prior plans or else the 4171 ** cost must be the same and the number of rows must be lower. 4172 */ 4173 if( (sCost.used¬Ready)==0 /* (1) */ 4174 && (bestJ<0 || (notIndexed&m)!=0 /* (2) */ 4175 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0) 4176 && (nUnconstrained==0 || pTabItem->pIndex==0 /* (3) */ 4177 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)) 4178 && (bestJ<0 || sCost.rCost<bestPlan.rCost /* (4) */ 4179 || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow)) 4180 ){ 4181 WHERETRACE(("... best so far with cost=%g and nRow=%g\n", 4182 sCost.rCost, sCost.nRow)); 4183 bestPlan = sCost; 4184 bestJ = j; 4185 } 4186 if( doNotReorder ) break; 4187 } 4188 } 4189 assert( bestJ>=0 ); 4190 assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) ); 4191 WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ, 4192 pLevel-pWInfo->a)); 4193 if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){ 4194 *ppOrderBy = 0; 4195 } 4196 andFlags &= bestPlan.plan.wsFlags; 4197 pLevel->plan = bestPlan.plan; 4198 testcase( bestPlan.plan.wsFlags & WHERE_INDEXED ); 4199 testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX ); 4200 if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){ 4201 pLevel->iIdxCur = pParse->nTab++; 4202 }else{ 4203 pLevel->iIdxCur = -1; 4204 } 4205 notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor); 4206 pLevel->iFrom = (u8)bestJ; 4207 if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow; 4208 4209 /* Check that if the table scanned by this loop iteration had an 4210 ** INDEXED BY clause attached to it, that the named index is being 4211 ** used for the scan. If not, then query compilation has failed. 4212 ** Return an error. 4213 */ 4214 pIdx = pTabList->a[bestJ].pIndex; 4215 if( pIdx ){ 4216 if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){ 4217 sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName); 4218 goto whereBeginError; 4219 }else{ 4220 /* If an INDEXED BY clause is used, the bestIndex() function is 4221 ** guaranteed to find the index specified in the INDEXED BY clause 4222 ** if it find an index at all. */ 4223 assert( bestPlan.plan.u.pIdx==pIdx ); 4224 } 4225 } 4226 } 4227 WHERETRACE(("*** Optimizer Finished ***\n")); 4228 if( pParse->nErr || db->mallocFailed ){ 4229 goto whereBeginError; 4230 } 4231 4232 /* If the total query only selects a single row, then the ORDER BY 4233 ** clause is irrelevant. 4234 */ 4235 if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){ 4236 *ppOrderBy = 0; 4237 } 4238 4239 /* If the caller is an UPDATE or DELETE statement that is requesting 4240 ** to use a one-pass algorithm, determine if this is appropriate. 4241 ** The one-pass algorithm only works if the WHERE clause constraints 4242 ** the statement to update a single row. 4243 */ 4244 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); 4245 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){ 4246 pWInfo->okOnePass = 1; 4247 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY; 4248 } 4249 4250 /* Open all tables in the pTabList and any indices selected for 4251 ** searching those tables. 4252 */ 4253 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */ 4254 notReady = ~(Bitmask)0; 4255 for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){ 4256 Table *pTab; /* Table to open */ 4257 int iDb; /* Index of database containing table/index */ 4258 4259 #ifndef SQLITE_OMIT_EXPLAIN 4260 if( pParse->explain==2 ){ 4261 char *zMsg; 4262 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; 4263 zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName); 4264 if( pItem->zAlias ){ 4265 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias); 4266 } 4267 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){ 4268 zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg); 4269 }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){ 4270 zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s", 4271 zMsg, pLevel->plan.u.pIdx->zName); 4272 }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){ 4273 zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg); 4274 }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){ 4275 zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg); 4276 } 4277 #ifndef SQLITE_OMIT_VIRTUALTABLE 4278 else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 4279 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx; 4280 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg, 4281 pVtabIdx->idxNum, pVtabIdx->idxStr); 4282 } 4283 #endif 4284 if( pLevel->plan.wsFlags & WHERE_ORDERBY ){ 4285 zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg); 4286 } 4287 sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC); 4288 } 4289 #endif /* SQLITE_OMIT_EXPLAIN */ 4290 pTabItem = &pTabList->a[pLevel->iFrom]; 4291 pTab = pTabItem->pTab; 4292 pLevel->iTabCur = pTabItem->iCursor; 4293 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 4294 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ 4295 /* Do nothing */ 4296 }else 4297 #ifndef SQLITE_OMIT_VIRTUALTABLE 4298 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 4299 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); 4300 int iCur = pTabItem->iCursor; 4301 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); 4302 }else 4303 #endif 4304 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 4305 && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){ 4306 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead; 4307 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); 4308 testcase( pTab->nCol==BMS-1 ); 4309 testcase( pTab->nCol==BMS ); 4310 if( !pWInfo->okOnePass && pTab->nCol<BMS ){ 4311 Bitmask b = pTabItem->colUsed; 4312 int n = 0; 4313 for(; b; b=b>>1, n++){} 4314 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 4315 SQLITE_INT_TO_PTR(n), P4_INT32); 4316 assert( n<=pTab->nCol ); 4317 } 4318 }else{ 4319 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 4320 } 4321 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX 4322 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){ 4323 constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel); 4324 }else 4325 #endif 4326 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){ 4327 Index *pIx = pLevel->plan.u.pIdx; 4328 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx); 4329 int iIdxCur = pLevel->iIdxCur; 4330 assert( pIx->pSchema==pTab->pSchema ); 4331 assert( iIdxCur>=0 ); 4332 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb, 4333 (char*)pKey, P4_KEYINFO_HANDOFF); 4334 VdbeComment((v, "%s", pIx->zName)); 4335 } 4336 sqlite3CodeVerifySchema(pParse, iDb); 4337 notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor); 4338 } 4339 pWInfo->iTop = sqlite3VdbeCurrentAddr(v); 4340 if( db->mallocFailed ) goto whereBeginError; 4341 4342 /* Generate the code to do the search. Each iteration of the for 4343 ** loop below generates code for a single nested loop of the VM 4344 ** program. 4345 */ 4346 notReady = ~(Bitmask)0; 4347 for(i=0; i<nTabList; i++){ 4348 notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady); 4349 pWInfo->iContinue = pWInfo->a[i].addrCont; 4350 } 4351 4352 #ifdef SQLITE_TEST /* For testing and debugging use only */ 4353 /* Record in the query plan information about the current table 4354 ** and the index used to access it (if any). If the table itself 4355 ** is not used, its name is just '{}'. If no index is used 4356 ** the index is listed as "{}". If the primary key is used the 4357 ** index name is '*'. 4358 */ 4359 for(i=0; i<nTabList; i++){ 4360 char *z; 4361 int n; 4362 pLevel = &pWInfo->a[i]; 4363 pTabItem = &pTabList->a[pLevel->iFrom]; 4364 z = pTabItem->zAlias; 4365 if( z==0 ) z = pTabItem->pTab->zName; 4366 n = sqlite3Strlen30(z); 4367 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){ 4368 if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){ 4369 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2); 4370 nQPlan += 2; 4371 }else{ 4372 memcpy(&sqlite3_query_plan[nQPlan], z, n); 4373 nQPlan += n; 4374 } 4375 sqlite3_query_plan[nQPlan++] = ' '; 4376 } 4377 testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ ); 4378 testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ); 4379 if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){ 4380 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2); 4381 nQPlan += 2; 4382 }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){ 4383 n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName); 4384 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){ 4385 memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n); 4386 nQPlan += n; 4387 sqlite3_query_plan[nQPlan++] = ' '; 4388 } 4389 }else{ 4390 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3); 4391 nQPlan += 3; 4392 } 4393 } 4394 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){ 4395 sqlite3_query_plan[--nQPlan] = 0; 4396 } 4397 sqlite3_query_plan[nQPlan] = 0; 4398 nQPlan = 0; 4399 #endif /* SQLITE_TEST // Testing and debugging use only */ 4400 4401 /* Record the continuation address in the WhereInfo structure. Then 4402 ** clean up and return. 4403 */ 4404 return pWInfo; 4405 4406 /* Jump here if malloc fails */ 4407 whereBeginError: 4408 if( pWInfo ){ 4409 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 4410 whereInfoFree(db, pWInfo); 4411 } 4412 return 0; 4413 } 4414 4415 /* 4416 ** Generate the end of the WHERE loop. See comments on 4417 ** sqlite3WhereBegin() for additional information. 4418 */ 4419 void sqlite3WhereEnd(WhereInfo *pWInfo){ 4420 Parse *pParse = pWInfo->pParse; 4421 Vdbe *v = pParse->pVdbe; 4422 int i; 4423 WhereLevel *pLevel; 4424 SrcList *pTabList = pWInfo->pTabList; 4425 sqlite3 *db = pParse->db; 4426 4427 /* Generate loop termination code. 4428 */ 4429 sqlite3ExprCacheClear(pParse); 4430 for(i=pWInfo->nLevel-1; i>=0; i--){ 4431 pLevel = &pWInfo->a[i]; 4432 sqlite3VdbeResolveLabel(v, pLevel->addrCont); 4433 if( pLevel->op!=OP_Noop ){ 4434 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2); 4435 sqlite3VdbeChangeP5(v, pLevel->p5); 4436 } 4437 if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){ 4438 struct InLoop *pIn; 4439 int j; 4440 sqlite3VdbeResolveLabel(v, pLevel->addrNxt); 4441 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ 4442 sqlite3VdbeJumpHere(v, pIn->addrInTop+1); 4443 sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop); 4444 sqlite3VdbeJumpHere(v, pIn->addrInTop-1); 4445 } 4446 sqlite3DbFree(db, pLevel->u.in.aInLoop); 4447 } 4448 sqlite3VdbeResolveLabel(v, pLevel->addrBrk); 4449 if( pLevel->iLeftJoin ){ 4450 int addr; 4451 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); 4452 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 4453 || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ); 4454 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){ 4455 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); 4456 } 4457 if( pLevel->iIdxCur>=0 ){ 4458 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); 4459 } 4460 if( pLevel->op==OP_Return ){ 4461 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); 4462 }else{ 4463 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst); 4464 } 4465 sqlite3VdbeJumpHere(v, addr); 4466 } 4467 } 4468 4469 /* The "break" point is here, just past the end of the outer loop. 4470 ** Set it. 4471 */ 4472 sqlite3VdbeResolveLabel(v, pWInfo->iBreak); 4473 4474 /* Close all of the cursors that were opened by sqlite3WhereBegin. 4475 */ 4476 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc ); 4477 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ 4478 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; 4479 Table *pTab = pTabItem->pTab; 4480 assert( pTab!=0 ); 4481 if( (pTab->tabFlags & TF_Ephemeral)==0 4482 && pTab->pSelect==0 4483 && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 4484 ){ 4485 int ws = pLevel->plan.wsFlags; 4486 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){ 4487 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); 4488 } 4489 if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){ 4490 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); 4491 } 4492 } 4493 4494 /* If this scan uses an index, make code substitutions to read data 4495 ** from the index in preference to the table. Sometimes, this means 4496 ** the table need never be read from. This is a performance boost, 4497 ** as the vdbe level waits until the table is read before actually 4498 ** seeking the table cursor to the record corresponding to the current 4499 ** position in the index. 4500 ** 4501 ** Calls to the code generator in between sqlite3WhereBegin and 4502 ** sqlite3WhereEnd will have created code that references the table 4503 ** directly. This loop scans all that code looking for opcodes 4504 ** that reference the table and converts them into opcodes that 4505 ** reference the index. 4506 */ 4507 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){ 4508 int k, j, last; 4509 VdbeOp *pOp; 4510 Index *pIdx = pLevel->plan.u.pIdx; 4511 4512 assert( pIdx!=0 ); 4513 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop); 4514 last = sqlite3VdbeCurrentAddr(v); 4515 for(k=pWInfo->iTop; k<last; k++, pOp++){ 4516 if( pOp->p1!=pLevel->iTabCur ) continue; 4517 if( pOp->opcode==OP_Column ){ 4518 for(j=0; j<pIdx->nColumn; j++){ 4519 if( pOp->p2==pIdx->aiColumn[j] ){ 4520 pOp->p2 = j; 4521 pOp->p1 = pLevel->iIdxCur; 4522 break; 4523 } 4524 } 4525 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 4526 || j<pIdx->nColumn ); 4527 }else if( pOp->opcode==OP_Rowid ){ 4528 pOp->p1 = pLevel->iIdxCur; 4529 pOp->opcode = OP_IdxRowid; 4530 } 4531 } 4532 } 4533 } 4534 4535 /* Final cleanup 4536 */ 4537 pParse->nQueryLoop = pWInfo->savedNQueryLoop; 4538 whereInfoFree(db, pWInfo); 4539 return; 4540 } 4541