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