Merge branch 'deb' into prerelease-int
[sqlcipher.git] / src / where.c
blobe614f4a6d864e70ec4328d0bdb254e3ac9f0d287
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.
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".
19 #include "sqliteInt.h"
23 ** Trace output macros
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(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
31 #else
32 # define WHERETRACE(X)
33 #endif
35 /* Forward reference
37 typedef struct WhereClause WhereClause;
38 typedef struct WhereMaskSet WhereMaskSet;
39 typedef struct WhereOrInfo WhereOrInfo;
40 typedef struct WhereAndInfo WhereAndInfo;
41 typedef struct WhereCost WhereCost;
44 ** The query generator uses an array of instances of this structure to
45 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
46 ** clause subexpression is separated from the others by AND operators,
47 ** usually, or sometimes subexpressions separated by OR.
49 ** All WhereTerms are collected into a single WhereClause structure.
50 ** The following identity holds:
52 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
54 ** When a term is of the form:
56 ** X <op> <expr>
58 ** where X is a column name and <op> is one of certain operators,
59 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
60 ** cursor number and column number for X. WhereTerm.eOperator records
61 ** the <op> using a bitmask encoding defined by WO_xxx below. The
62 ** use of a bitmask encoding for the operator allows us to search
63 ** quickly for terms that match any of several different operators.
65 ** A WhereTerm might also be two or more subterms connected by OR:
67 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
69 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
70 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
71 ** is collected about the
73 ** If a term in the WHERE clause does not match either of the two previous
74 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
75 ** to the original subexpression content and wtFlags is set up appropriately
76 ** but no other fields in the WhereTerm object are meaningful.
78 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
79 ** but they do so indirectly. A single WhereMaskSet structure translates
80 ** cursor number into bits and the translated bit is stored in the prereq
81 ** fields. The translation is used in order to maximize the number of
82 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
83 ** spread out over the non-negative integers. For example, the cursor
84 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
85 ** translates these sparse cursor numbers into consecutive integers
86 ** beginning with 0 in order to make the best possible use of the available
87 ** bits in the Bitmask. So, in the example above, the cursor numbers
88 ** would be mapped into integers 0 through 7.
90 ** The number of terms in a join is limited by the number of bits
91 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
92 ** is only able to process joins with 64 or fewer tables.
94 typedef struct WhereTerm WhereTerm;
95 struct WhereTerm {
96 Expr *pExpr; /* Pointer to the subexpression that is this term */
97 int iParent; /* Disable pWC->a[iParent] when this term disabled */
98 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
99 union {
100 int leftColumn; /* Column number of X in "X <op> <expr>" */
101 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
102 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
103 } u;
104 u16 eOperator; /* A WO_xx value describing <op> */
105 u8 wtFlags; /* TERM_xxx bit flags. See below */
106 u8 nChild; /* Number of children that must disable us */
107 WhereClause *pWC; /* The clause this term is part of */
108 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
109 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
113 ** Allowed values of WhereTerm.wtFlags
115 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
116 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
117 #define TERM_CODED 0x04 /* This term is already coded */
118 #define TERM_COPIED 0x08 /* Has a child */
119 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
120 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
121 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
122 #ifdef SQLITE_ENABLE_STAT3
123 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
124 #else
125 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
126 #endif
129 ** An instance of the following structure holds all information about a
130 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
132 ** Explanation of pOuter: For a WHERE clause of the form
134 ** a AND ((b AND c) OR (d AND e)) AND f
136 ** There are separate WhereClause objects for the whole clause and for
137 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
138 ** subclauses points to the WhereClause object for the whole clause.
140 struct WhereClause {
141 Parse *pParse; /* The parser context */
142 WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
143 WhereClause *pOuter; /* Outer conjunction */
144 u8 op; /* Split operator. TK_AND or TK_OR */
145 u16 wctrlFlags; /* Might include WHERE_AND_ONLY */
146 int nTerm; /* Number of terms */
147 int nSlot; /* Number of entries in a[] */
148 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
149 #if defined(SQLITE_SMALL_STACK)
150 WhereTerm aStatic[1]; /* Initial static space for a[] */
151 #else
152 WhereTerm aStatic[8]; /* Initial static space for a[] */
153 #endif
157 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
158 ** a dynamically allocated instance of the following structure.
160 struct WhereOrInfo {
161 WhereClause wc; /* Decomposition into subterms */
162 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
166 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
167 ** a dynamically allocated instance of the following structure.
169 struct WhereAndInfo {
170 WhereClause wc; /* The subexpression broken out */
174 ** An instance of the following structure keeps track of a mapping
175 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
177 ** The VDBE cursor numbers are small integers contained in
178 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
179 ** clause, the cursor numbers might not begin with 0 and they might
180 ** contain gaps in the numbering sequence. But we want to make maximum
181 ** use of the bits in our bitmasks. This structure provides a mapping
182 ** from the sparse cursor numbers into consecutive integers beginning
183 ** with 0.
185 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
186 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
188 ** For example, if the WHERE clause expression used these VDBE
189 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
190 ** would map those cursor numbers into bits 0 through 5.
192 ** Note that the mapping is not necessarily ordered. In the example
193 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
194 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
195 ** does not really matter. What is important is that sparse cursor
196 ** numbers all get mapped into bit numbers that begin with 0 and contain
197 ** no gaps.
199 struct WhereMaskSet {
200 int n; /* Number of assigned cursor values */
201 int ix[BMS]; /* Cursor assigned to each bit */
205 ** A WhereCost object records a lookup strategy and the estimated
206 ** cost of pursuing that strategy.
208 struct WhereCost {
209 WherePlan plan; /* The lookup strategy */
210 double rCost; /* Overall cost of pursuing this search strategy */
211 Bitmask used; /* Bitmask of cursors used by this plan */
215 ** Bitmasks for the operators that indices are able to exploit. An
216 ** OR-ed combination of these values can be used when searching for
217 ** terms in the where clause.
219 #define WO_IN 0x001
220 #define WO_EQ 0x002
221 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
222 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
223 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
224 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
225 #define WO_MATCH 0x040
226 #define WO_ISNULL 0x080
227 #define WO_OR 0x100 /* Two or more OR-connected terms */
228 #define WO_AND 0x200 /* Two or more AND-connected terms */
229 #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
230 #define WO_NOOP 0x800 /* This term does not restrict search space */
232 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
233 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
236 ** Value for wsFlags returned by bestIndex() and stored in
237 ** WhereLevel.wsFlags. These flags determine which search
238 ** strategies are appropriate.
240 ** The least significant 12 bits is reserved as a mask for WO_ values above.
241 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
242 ** But if the table is the right table of a left join, WhereLevel.wsFlags
243 ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
244 ** the "op" parameter to findTerm when we are resolving equality constraints.
245 ** ISNULL constraints will then not be used on the right table of a left
246 ** join. Tickets #2177 and #2189.
248 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
249 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
250 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
251 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
252 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
253 #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
254 #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
255 #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
256 #define WHERE_IN_ABLE 0x080f1000 /* Able to support an IN operator */
257 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
258 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
259 #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
260 #define WHERE_IDX_ONLY 0x00400000 /* Use index only - omit table */
261 #define WHERE_ORDERED 0x00800000 /* Output will appear in correct order */
262 #define WHERE_REVERSE 0x01000000 /* Scan in reverse order */
263 #define WHERE_UNIQUE 0x02000000 /* Selects no more than one row */
264 #define WHERE_ALL_UNIQUE 0x04000000 /* This and all prior have one row */
265 #define WHERE_OB_UNIQUE 0x00004000 /* Values in ORDER BY columns are
266 ** different for every output row */
267 #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
268 #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
269 #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
270 #define WHERE_DISTINCT 0x40000000 /* Correct order for DISTINCT */
271 #define WHERE_COVER_SCAN 0x80000000 /* Full scan of a covering index */
274 ** This module contains many separate subroutines that work together to
275 ** find the best indices to use for accessing a particular table in a query.
276 ** An instance of the following structure holds context information about the
277 ** index search so that it can be more easily passed between the various
278 ** routines.
280 typedef struct WhereBestIdx WhereBestIdx;
281 struct WhereBestIdx {
282 Parse *pParse; /* Parser context */
283 WhereClause *pWC; /* The WHERE clause */
284 struct SrcList_item *pSrc; /* The FROM clause term to search */
285 Bitmask notReady; /* Mask of cursors not available */
286 Bitmask notValid; /* Cursors not available for any purpose */
287 ExprList *pOrderBy; /* The ORDER BY clause */
288 ExprList *pDistinct; /* The select-list if query is DISTINCT */
289 sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
290 int i, n; /* Which loop is being coded; # of loops */
291 WhereLevel *aLevel; /* Info about outer loops */
292 WhereCost cost; /* Lowest cost query plan */
296 ** Return TRUE if the probe cost is less than the baseline cost
298 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
299 if( pProbe->rCost<pBaseline->rCost ) return 1;
300 if( pProbe->rCost>pBaseline->rCost ) return 0;
301 if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
302 if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
303 return 0;
307 ** Initialize a preallocated WhereClause structure.
309 static void whereClauseInit(
310 WhereClause *pWC, /* The WhereClause to be initialized */
311 Parse *pParse, /* The parsing context */
312 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmasks */
313 u16 wctrlFlags /* Might include WHERE_AND_ONLY */
315 pWC->pParse = pParse;
316 pWC->pMaskSet = pMaskSet;
317 pWC->pOuter = 0;
318 pWC->nTerm = 0;
319 pWC->nSlot = ArraySize(pWC->aStatic);
320 pWC->a = pWC->aStatic;
321 pWC->wctrlFlags = wctrlFlags;
324 /* Forward reference */
325 static void whereClauseClear(WhereClause*);
328 ** Deallocate all memory associated with a WhereOrInfo object.
330 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
331 whereClauseClear(&p->wc);
332 sqlite3DbFree(db, p);
336 ** Deallocate all memory associated with a WhereAndInfo object.
338 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
339 whereClauseClear(&p->wc);
340 sqlite3DbFree(db, p);
344 ** Deallocate a WhereClause structure. The WhereClause structure
345 ** itself is not freed. This routine is the inverse of whereClauseInit().
347 static void whereClauseClear(WhereClause *pWC){
348 int i;
349 WhereTerm *a;
350 sqlite3 *db = pWC->pParse->db;
351 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
352 if( a->wtFlags & TERM_DYNAMIC ){
353 sqlite3ExprDelete(db, a->pExpr);
355 if( a->wtFlags & TERM_ORINFO ){
356 whereOrInfoDelete(db, a->u.pOrInfo);
357 }else if( a->wtFlags & TERM_ANDINFO ){
358 whereAndInfoDelete(db, a->u.pAndInfo);
361 if( pWC->a!=pWC->aStatic ){
362 sqlite3DbFree(db, pWC->a);
367 ** Add a single new WhereTerm entry to the WhereClause object pWC.
368 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
369 ** The index in pWC->a[] of the new WhereTerm is returned on success.
370 ** 0 is returned if the new WhereTerm could not be added due to a memory
371 ** allocation error. The memory allocation failure will be recorded in
372 ** the db->mallocFailed flag so that higher-level functions can detect it.
374 ** This routine will increase the size of the pWC->a[] array as necessary.
376 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
377 ** for freeing the expression p is assumed by the WhereClause object pWC.
378 ** This is true even if this routine fails to allocate a new WhereTerm.
380 ** WARNING: This routine might reallocate the space used to store
381 ** WhereTerms. All pointers to WhereTerms should be invalidated after
382 ** calling this routine. Such pointers may be reinitialized by referencing
383 ** the pWC->a[] array.
385 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
386 WhereTerm *pTerm;
387 int idx;
388 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
389 if( pWC->nTerm>=pWC->nSlot ){
390 WhereTerm *pOld = pWC->a;
391 sqlite3 *db = pWC->pParse->db;
392 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
393 if( pWC->a==0 ){
394 if( wtFlags & TERM_DYNAMIC ){
395 sqlite3ExprDelete(db, p);
397 pWC->a = pOld;
398 return 0;
400 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
401 if( pOld!=pWC->aStatic ){
402 sqlite3DbFree(db, pOld);
404 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
406 pTerm = &pWC->a[idx = pWC->nTerm++];
407 pTerm->pExpr = sqlite3ExprSkipCollate(p);
408 pTerm->wtFlags = wtFlags;
409 pTerm->pWC = pWC;
410 pTerm->iParent = -1;
411 return idx;
415 ** This routine identifies subexpressions in the WHERE clause where
416 ** each subexpression is separated by the AND operator or some other
417 ** operator specified in the op parameter. The WhereClause structure
418 ** is filled with pointers to subexpressions. For example:
420 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
421 ** \________/ \_______________/ \________________/
422 ** slot[0] slot[1] slot[2]
424 ** The original WHERE clause in pExpr is unaltered. All this routine
425 ** does is make slot[] entries point to substructure within pExpr.
427 ** In the previous sentence and in the diagram, "slot[]" refers to
428 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
429 ** all terms of the WHERE clause.
431 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
432 pWC->op = (u8)op;
433 if( pExpr==0 ) return;
434 if( pExpr->op!=op ){
435 whereClauseInsert(pWC, pExpr, 0);
436 }else{
437 whereSplit(pWC, pExpr->pLeft, op);
438 whereSplit(pWC, pExpr->pRight, op);
443 ** Initialize an expression mask set (a WhereMaskSet object)
445 #define initMaskSet(P) memset(P, 0, sizeof(*P))
448 ** Return the bitmask for the given cursor number. Return 0 if
449 ** iCursor is not in the set.
451 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
452 int i;
453 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
454 for(i=0; i<pMaskSet->n; i++){
455 if( pMaskSet->ix[i]==iCursor ){
456 return ((Bitmask)1)<<i;
459 return 0;
463 ** Create a new mask for cursor iCursor.
465 ** There is one cursor per table in the FROM clause. The number of
466 ** tables in the FROM clause is limited by a test early in the
467 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
468 ** array will never overflow.
470 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
471 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
472 pMaskSet->ix[pMaskSet->n++] = iCursor;
476 ** This routine walks (recursively) an expression tree and generates
477 ** a bitmask indicating which tables are used in that expression
478 ** tree.
480 ** In order for this routine to work, the calling function must have
481 ** previously invoked sqlite3ResolveExprNames() on the expression. See
482 ** the header comment on that routine for additional information.
483 ** The sqlite3ResolveExprNames() routines looks for column names and
484 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
485 ** the VDBE cursor number of the table. This routine just has to
486 ** translate the cursor numbers into bitmask values and OR all
487 ** the bitmasks together.
489 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
490 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
491 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
492 Bitmask mask = 0;
493 if( p==0 ) return 0;
494 if( p->op==TK_COLUMN ){
495 mask = getMask(pMaskSet, p->iTable);
496 return mask;
498 mask = exprTableUsage(pMaskSet, p->pRight);
499 mask |= exprTableUsage(pMaskSet, p->pLeft);
500 if( ExprHasProperty(p, EP_xIsSelect) ){
501 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
502 }else{
503 mask |= exprListTableUsage(pMaskSet, p->x.pList);
505 return mask;
507 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
508 int i;
509 Bitmask mask = 0;
510 if( pList ){
511 for(i=0; i<pList->nExpr; i++){
512 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
515 return mask;
517 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
518 Bitmask mask = 0;
519 while( pS ){
520 SrcList *pSrc = pS->pSrc;
521 mask |= exprListTableUsage(pMaskSet, pS->pEList);
522 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
523 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
524 mask |= exprTableUsage(pMaskSet, pS->pWhere);
525 mask |= exprTableUsage(pMaskSet, pS->pHaving);
526 if( ALWAYS(pSrc!=0) ){
527 int i;
528 for(i=0; i<pSrc->nSrc; i++){
529 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
530 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
533 pS = pS->pPrior;
535 return mask;
539 ** Return TRUE if the given operator is one of the operators that is
540 ** allowed for an indexable WHERE clause term. The allowed operators are
541 ** "=", "<", ">", "<=", ">=", and "IN".
543 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
544 ** of one of the following forms: column = expression column > expression
545 ** column >= expression column < expression column <= expression
546 ** expression = column expression > column expression >= column
547 ** expression < column expression <= column column IN
548 ** (expression-list) column IN (subquery) column IS NULL
550 static int allowedOp(int op){
551 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
552 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
553 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
554 assert( TK_GE==TK_EQ+4 );
555 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
559 ** Swap two objects of type TYPE.
561 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
564 ** Commute a comparison operator. Expressions of the form "X op Y"
565 ** are converted into "Y op X".
567 ** If left/right precedence rules come into play when determining the
568 ** collating
569 ** side of the comparison, it remains associated with the same side after
570 ** the commutation. So "Y collate NOCASE op X" becomes
571 ** "X op Y". This is because any collation sequence on
572 ** the left hand side of a comparison overrides any collation sequence
573 ** attached to the right. For the same reason the EP_Collate flag
574 ** is not commuted.
576 static void exprCommute(Parse *pParse, Expr *pExpr){
577 u16 expRight = (pExpr->pRight->flags & EP_Collate);
578 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
579 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
580 if( expRight==expLeft ){
581 /* Either X and Y both have COLLATE operator or neither do */
582 if( expRight ){
583 /* Both X and Y have COLLATE operators. Make sure X is always
584 ** used by clearing the EP_Collate flag from Y. */
585 pExpr->pRight->flags &= ~EP_Collate;
586 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
587 /* Neither X nor Y have COLLATE operators, but X has a non-default
588 ** collating sequence. So add the EP_Collate marker on X to cause
589 ** it to be searched first. */
590 pExpr->pLeft->flags |= EP_Collate;
593 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
594 if( pExpr->op>=TK_GT ){
595 assert( TK_LT==TK_GT+2 );
596 assert( TK_GE==TK_LE+2 );
597 assert( TK_GT>TK_EQ );
598 assert( TK_GT<TK_LE );
599 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
600 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
605 ** Translate from TK_xx operator to WO_xx bitmask.
607 static u16 operatorMask(int op){
608 u16 c;
609 assert( allowedOp(op) );
610 if( op==TK_IN ){
611 c = WO_IN;
612 }else if( op==TK_ISNULL ){
613 c = WO_ISNULL;
614 }else{
615 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
616 c = (u16)(WO_EQ<<(op-TK_EQ));
618 assert( op!=TK_ISNULL || c==WO_ISNULL );
619 assert( op!=TK_IN || c==WO_IN );
620 assert( op!=TK_EQ || c==WO_EQ );
621 assert( op!=TK_LT || c==WO_LT );
622 assert( op!=TK_LE || c==WO_LE );
623 assert( op!=TK_GT || c==WO_GT );
624 assert( op!=TK_GE || c==WO_GE );
625 return c;
629 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
630 ** where X is a reference to the iColumn of table iCur and <op> is one of
631 ** the WO_xx operator codes specified by the op parameter.
632 ** Return a pointer to the term. Return 0 if not found.
634 ** The term returned might by Y=<expr> if there is another constraint in
635 ** the WHERE clause that specifies that X=Y. Any such constraints will be
636 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
637 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
638 ** taking up two slots in aEquiv[]. The first slot is for the cursor number
639 ** and the second is for the column number. There are 22 slots in aEquiv[]
640 ** so that means we can look for X plus up to 10 other equivalent values.
641 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
642 ** and ... and A9=A10 and A10=<expr>.
644 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
645 ** then try for the one with no dependencies on <expr> - in other words where
646 ** <expr> is a constant expression of some kind. Only return entries of
647 ** the form "X <op> Y" where Y is a column in another table if no terms of
648 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
649 ** exist, try to return a term that does not use WO_EQUIV.
651 static WhereTerm *findTerm(
652 WhereClause *pWC, /* The WHERE clause to be searched */
653 int iCur, /* Cursor number of LHS */
654 int iColumn, /* Column number of LHS */
655 Bitmask notReady, /* RHS must not overlap with this mask */
656 u32 op, /* Mask of WO_xx values describing operator */
657 Index *pIdx /* Must be compatible with this index, if not NULL */
659 WhereTerm *pTerm; /* Term being examined as possible result */
660 WhereTerm *pResult = 0; /* The answer to return */
661 WhereClause *pWCOrig = pWC; /* Original pWC value */
662 int j, k; /* Loop counters */
663 Expr *pX; /* Pointer to an expression */
664 Parse *pParse; /* Parsing context */
665 int iOrigCol = iColumn; /* Original value of iColumn */
666 int nEquiv = 2; /* Number of entires in aEquiv[] */
667 int iEquiv = 2; /* Number of entries of aEquiv[] processed so far */
668 int aEquiv[22]; /* iCur,iColumn and up to 10 other equivalents */
670 assert( iCur>=0 );
671 aEquiv[0] = iCur;
672 aEquiv[1] = iColumn;
673 for(;;){
674 for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
675 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
676 if( pTerm->leftCursor==iCur
677 && pTerm->u.leftColumn==iColumn
679 if( (pTerm->prereqRight & notReady)==0
680 && (pTerm->eOperator & op & WO_ALL)!=0
682 if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
683 CollSeq *pColl;
684 char idxaff;
686 pX = pTerm->pExpr;
687 pParse = pWC->pParse;
688 idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
689 if( !sqlite3IndexAffinityOk(pX, idxaff) ){
690 continue;
693 /* Figure out the collation sequence required from an index for
694 ** it to be useful for optimising expression pX. Store this
695 ** value in variable pColl.
697 assert(pX->pLeft);
698 pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
699 if( pColl==0 ) pColl = pParse->db->pDfltColl;
701 for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
702 if( NEVER(j>=pIdx->nColumn) ) return 0;
704 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
705 continue;
708 if( pTerm->prereqRight==0 && (pTerm->eOperator&WO_EQ)!=0 ){
709 pResult = pTerm;
710 goto findTerm_success;
711 }else if( pResult==0 ){
712 pResult = pTerm;
715 if( (pTerm->eOperator & WO_EQUIV)!=0
716 && nEquiv<ArraySize(aEquiv)
718 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
719 assert( pX->op==TK_COLUMN );
720 for(j=0; j<nEquiv; j+=2){
721 if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
723 if( j==nEquiv ){
724 aEquiv[j] = pX->iTable;
725 aEquiv[j+1] = pX->iColumn;
726 nEquiv += 2;
732 if( iEquiv>=nEquiv ) break;
733 iCur = aEquiv[iEquiv++];
734 iColumn = aEquiv[iEquiv++];
736 findTerm_success:
737 return pResult;
740 /* Forward reference */
741 static void exprAnalyze(SrcList*, WhereClause*, int);
744 ** Call exprAnalyze on all terms in a WHERE clause.
748 static void exprAnalyzeAll(
749 SrcList *pTabList, /* the FROM clause */
750 WhereClause *pWC /* the WHERE clause to be analyzed */
752 int i;
753 for(i=pWC->nTerm-1; i>=0; i--){
754 exprAnalyze(pTabList, pWC, i);
758 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
760 ** Check to see if the given expression is a LIKE or GLOB operator that
761 ** can be optimized using inequality constraints. Return TRUE if it is
762 ** so and false if not.
764 ** In order for the operator to be optimizible, the RHS must be a string
765 ** literal that does not begin with a wildcard.
767 static int isLikeOrGlob(
768 Parse *pParse, /* Parsing and code generating context */
769 Expr *pExpr, /* Test this expression */
770 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
771 int *pisComplete, /* True if the only wildcard is % in the last character */
772 int *pnoCase /* True if uppercase is equivalent to lowercase */
774 const char *z = 0; /* String on RHS of LIKE operator */
775 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
776 ExprList *pList; /* List of operands to the LIKE operator */
777 int c; /* One character in z[] */
778 int cnt; /* Number of non-wildcard prefix characters */
779 char wc[3]; /* Wildcard characters */
780 sqlite3 *db = pParse->db; /* Database connection */
781 sqlite3_value *pVal = 0;
782 int op; /* Opcode of pRight */
784 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
785 return 0;
787 #ifdef SQLITE_EBCDIC
788 if( *pnoCase ) return 0;
789 #endif
790 pList = pExpr->x.pList;
791 pLeft = pList->a[1].pExpr;
792 if( pLeft->op!=TK_COLUMN
793 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
794 || IsVirtual(pLeft->pTab)
796 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
797 ** be the name of an indexed column with TEXT affinity. */
798 return 0;
800 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
802 pRight = pList->a[0].pExpr;
803 op = pRight->op;
804 if( op==TK_REGISTER ){
805 op = pRight->op2;
807 if( op==TK_VARIABLE ){
808 Vdbe *pReprepare = pParse->pReprepare;
809 int iCol = pRight->iColumn;
810 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
811 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
812 z = (char *)sqlite3_value_text(pVal);
814 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
815 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
816 }else if( op==TK_STRING ){
817 z = pRight->u.zToken;
819 if( z ){
820 cnt = 0;
821 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
822 cnt++;
824 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
825 Expr *pPrefix;
826 *pisComplete = c==wc[0] && z[cnt+1]==0;
827 pPrefix = sqlite3Expr(db, TK_STRING, z);
828 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
829 *ppPrefix = pPrefix;
830 if( op==TK_VARIABLE ){
831 Vdbe *v = pParse->pVdbe;
832 sqlite3VdbeSetVarmask(v, pRight->iColumn);
833 if( *pisComplete && pRight->u.zToken[1] ){
834 /* If the rhs of the LIKE expression is a variable, and the current
835 ** value of the variable means there is no need to invoke the LIKE
836 ** function, then no OP_Variable will be added to the program.
837 ** This causes problems for the sqlite3_bind_parameter_name()
838 ** API. To workaround them, add a dummy OP_Variable here.
840 int r1 = sqlite3GetTempReg(pParse);
841 sqlite3ExprCodeTarget(pParse, pRight, r1);
842 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
843 sqlite3ReleaseTempReg(pParse, r1);
846 }else{
847 z = 0;
851 sqlite3ValueFree(pVal);
852 return (z!=0);
854 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
857 #ifndef SQLITE_OMIT_VIRTUALTABLE
859 ** Check to see if the given expression is of the form
861 ** column MATCH expr
863 ** If it is then return TRUE. If not, return FALSE.
865 static int isMatchOfColumn(
866 Expr *pExpr /* Test this expression */
868 ExprList *pList;
870 if( pExpr->op!=TK_FUNCTION ){
871 return 0;
873 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
874 return 0;
876 pList = pExpr->x.pList;
877 if( pList->nExpr!=2 ){
878 return 0;
880 if( pList->a[1].pExpr->op != TK_COLUMN ){
881 return 0;
883 return 1;
885 #endif /* SQLITE_OMIT_VIRTUALTABLE */
888 ** If the pBase expression originated in the ON or USING clause of
889 ** a join, then transfer the appropriate markings over to derived.
891 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
892 pDerived->flags |= pBase->flags & EP_FromJoin;
893 pDerived->iRightJoinTable = pBase->iRightJoinTable;
896 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
898 ** Analyze a term that consists of two or more OR-connected
899 ** subterms. So in:
901 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
902 ** ^^^^^^^^^^^^^^^^^^^^
904 ** This routine analyzes terms such as the middle term in the above example.
905 ** A WhereOrTerm object is computed and attached to the term under
906 ** analysis, regardless of the outcome of the analysis. Hence:
908 ** WhereTerm.wtFlags |= TERM_ORINFO
909 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
911 ** The term being analyzed must have two or more of OR-connected subterms.
912 ** A single subterm might be a set of AND-connected sub-subterms.
913 ** Examples of terms under analysis:
915 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
916 ** (B) x=expr1 OR expr2=x OR x=expr3
917 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
918 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
919 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
921 ** CASE 1:
923 ** If all subterms are of the form T.C=expr for some single column of C and
924 ** a single table T (as shown in example B above) then create a new virtual
925 ** term that is an equivalent IN expression. In other words, if the term
926 ** being analyzed is:
928 ** x = expr1 OR expr2 = x OR x = expr3
930 ** then create a new virtual term like this:
932 ** x IN (expr1,expr2,expr3)
934 ** CASE 2:
936 ** If all subterms are indexable by a single table T, then set
938 ** WhereTerm.eOperator = WO_OR
939 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
941 ** A subterm is "indexable" if it is of the form
942 ** "T.C <op> <expr>" where C is any column of table T and
943 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
944 ** A subterm is also indexable if it is an AND of two or more
945 ** subsubterms at least one of which is indexable. Indexable AND
946 ** subterms have their eOperator set to WO_AND and they have
947 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
949 ** From another point of view, "indexable" means that the subterm could
950 ** potentially be used with an index if an appropriate index exists.
951 ** This analysis does not consider whether or not the index exists; that
952 ** is something the bestIndex() routine will determine. This analysis
953 ** only looks at whether subterms appropriate for indexing exist.
955 ** All examples A through E above all satisfy case 2. But if a term
956 ** also statisfies case 1 (such as B) we know that the optimizer will
957 ** always prefer case 1, so in that case we pretend that case 2 is not
958 ** satisfied.
960 ** It might be the case that multiple tables are indexable. For example,
961 ** (E) above is indexable on tables P, Q, and R.
963 ** Terms that satisfy case 2 are candidates for lookup by using
964 ** separate indices to find rowids for each subterm and composing
965 ** the union of all rowids using a RowSet object. This is similar
966 ** to "bitmap indices" in other database engines.
968 ** OTHERWISE:
970 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
971 ** zero. This term is not useful for search.
973 static void exprAnalyzeOrTerm(
974 SrcList *pSrc, /* the FROM clause */
975 WhereClause *pWC, /* the complete WHERE clause */
976 int idxTerm /* Index of the OR-term to be analyzed */
978 Parse *pParse = pWC->pParse; /* Parser context */
979 sqlite3 *db = pParse->db; /* Database connection */
980 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
981 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
982 WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
983 int i; /* Loop counters */
984 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
985 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
986 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
987 Bitmask chngToIN; /* Tables that might satisfy case 1 */
988 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
991 ** Break the OR clause into its separate subterms. The subterms are
992 ** stored in a WhereClause structure containing within the WhereOrInfo
993 ** object that is attached to the original OR clause term.
995 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
996 assert( pExpr->op==TK_OR );
997 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
998 if( pOrInfo==0 ) return;
999 pTerm->wtFlags |= TERM_ORINFO;
1000 pOrWc = &pOrInfo->wc;
1001 whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
1002 whereSplit(pOrWc, pExpr, TK_OR);
1003 exprAnalyzeAll(pSrc, pOrWc);
1004 if( db->mallocFailed ) return;
1005 assert( pOrWc->nTerm>=2 );
1008 ** Compute the set of tables that might satisfy cases 1 or 2.
1010 indexable = ~(Bitmask)0;
1011 chngToIN = ~(Bitmask)0;
1012 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1013 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
1014 WhereAndInfo *pAndInfo;
1015 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
1016 chngToIN = 0;
1017 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1018 if( pAndInfo ){
1019 WhereClause *pAndWC;
1020 WhereTerm *pAndTerm;
1021 int j;
1022 Bitmask b = 0;
1023 pOrTerm->u.pAndInfo = pAndInfo;
1024 pOrTerm->wtFlags |= TERM_ANDINFO;
1025 pOrTerm->eOperator = WO_AND;
1026 pAndWC = &pAndInfo->wc;
1027 whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
1028 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1029 exprAnalyzeAll(pSrc, pAndWC);
1030 pAndWC->pOuter = pWC;
1031 testcase( db->mallocFailed );
1032 if( !db->mallocFailed ){
1033 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1034 assert( pAndTerm->pExpr );
1035 if( allowedOp(pAndTerm->pExpr->op) ){
1036 b |= getMask(pMaskSet, pAndTerm->leftCursor);
1040 indexable &= b;
1042 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1043 /* Skip this term for now. We revisit it when we process the
1044 ** corresponding TERM_VIRTUAL term */
1045 }else{
1046 Bitmask b;
1047 b = getMask(pMaskSet, pOrTerm->leftCursor);
1048 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1049 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
1050 b |= getMask(pMaskSet, pOther->leftCursor);
1052 indexable &= b;
1053 if( (pOrTerm->eOperator & WO_EQ)==0 ){
1054 chngToIN = 0;
1055 }else{
1056 chngToIN &= b;
1062 ** Record the set of tables that satisfy case 2. The set might be
1063 ** empty.
1065 pOrInfo->indexable = indexable;
1066 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
1069 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1070 ** we have to do some additional checking to see if case 1 really
1071 ** is satisfied.
1073 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1074 ** that there is no possibility of transforming the OR clause into an
1075 ** IN operator because one or more terms in the OR clause contain
1076 ** something other than == on a column in the single table. The 1-bit
1077 ** case means that every term of the OR clause is of the form
1078 ** "table.column=expr" for some single table. The one bit that is set
1079 ** will correspond to the common table. We still need to check to make
1080 ** sure the same column is used on all terms. The 2-bit case is when
1081 ** the all terms are of the form "table1.column=table2.column". It
1082 ** might be possible to form an IN operator with either table1.column
1083 ** or table2.column as the LHS if either is common to every term of
1084 ** the OR clause.
1086 ** Note that terms of the form "table.column1=table.column2" (the
1087 ** same table on both sizes of the ==) cannot be optimized.
1089 if( chngToIN ){
1090 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1091 int iColumn = -1; /* Column index on lhs of IN operator */
1092 int iCursor = -1; /* Table cursor common to all terms */
1093 int j = 0; /* Loop counter */
1095 /* Search for a table and column that appears on one side or the
1096 ** other of the == operator in every subterm. That table and column
1097 ** will be recorded in iCursor and iColumn. There might not be any
1098 ** such table and column. Set okToChngToIN if an appropriate table
1099 ** and column is found but leave okToChngToIN false if not found.
1101 for(j=0; j<2 && !okToChngToIN; j++){
1102 pOrTerm = pOrWc->a;
1103 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
1104 assert( pOrTerm->eOperator & WO_EQ );
1105 pOrTerm->wtFlags &= ~TERM_OR_OK;
1106 if( pOrTerm->leftCursor==iCursor ){
1107 /* This is the 2-bit case and we are on the second iteration and
1108 ** current term is from the first iteration. So skip this term. */
1109 assert( j==1 );
1110 continue;
1112 if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
1113 /* This term must be of the form t1.a==t2.b where t2 is in the
1114 ** chngToIN set but t1 is not. This term will be either preceeded
1115 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1116 ** and use its inversion. */
1117 testcase( pOrTerm->wtFlags & TERM_COPIED );
1118 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1119 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1120 continue;
1122 iColumn = pOrTerm->u.leftColumn;
1123 iCursor = pOrTerm->leftCursor;
1124 break;
1126 if( i<0 ){
1127 /* No candidate table+column was found. This can only occur
1128 ** on the second iteration */
1129 assert( j==1 );
1130 assert( IsPowerOfTwo(chngToIN) );
1131 assert( chngToIN==getMask(pMaskSet, iCursor) );
1132 break;
1134 testcase( j==1 );
1136 /* We have found a candidate table and column. Check to see if that
1137 ** table and column is common to every term in the OR clause */
1138 okToChngToIN = 1;
1139 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
1140 assert( pOrTerm->eOperator & WO_EQ );
1141 if( pOrTerm->leftCursor!=iCursor ){
1142 pOrTerm->wtFlags &= ~TERM_OR_OK;
1143 }else if( pOrTerm->u.leftColumn!=iColumn ){
1144 okToChngToIN = 0;
1145 }else{
1146 int affLeft, affRight;
1147 /* If the right-hand side is also a column, then the affinities
1148 ** of both right and left sides must be such that no type
1149 ** conversions are required on the right. (Ticket #2249)
1151 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1152 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1153 if( affRight!=0 && affRight!=affLeft ){
1154 okToChngToIN = 0;
1155 }else{
1156 pOrTerm->wtFlags |= TERM_OR_OK;
1162 /* At this point, okToChngToIN is true if original pTerm satisfies
1163 ** case 1. In that case, construct a new virtual term that is
1164 ** pTerm converted into an IN operator.
1166 ** EV: R-00211-15100
1168 if( okToChngToIN ){
1169 Expr *pDup; /* A transient duplicate expression */
1170 ExprList *pList = 0; /* The RHS of the IN operator */
1171 Expr *pLeft = 0; /* The LHS of the IN operator */
1172 Expr *pNew; /* The complete IN operator */
1174 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1175 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
1176 assert( pOrTerm->eOperator & WO_EQ );
1177 assert( pOrTerm->leftCursor==iCursor );
1178 assert( pOrTerm->u.leftColumn==iColumn );
1179 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
1180 pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
1181 pLeft = pOrTerm->pExpr->pLeft;
1183 assert( pLeft!=0 );
1184 pDup = sqlite3ExprDup(db, pLeft, 0);
1185 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
1186 if( pNew ){
1187 int idxNew;
1188 transferJoinMarkings(pNew, pExpr);
1189 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1190 pNew->x.pList = pList;
1191 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1192 testcase( idxNew==0 );
1193 exprAnalyze(pSrc, pWC, idxNew);
1194 pTerm = &pWC->a[idxTerm];
1195 pWC->a[idxNew].iParent = idxTerm;
1196 pTerm->nChild = 1;
1197 }else{
1198 sqlite3ExprListDelete(db, pList);
1200 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
1204 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
1207 ** The input to this routine is an WhereTerm structure with only the
1208 ** "pExpr" field filled in. The job of this routine is to analyze the
1209 ** subexpression and populate all the other fields of the WhereTerm
1210 ** structure.
1212 ** If the expression is of the form "<expr> <op> X" it gets commuted
1213 ** to the standard form of "X <op> <expr>".
1215 ** If the expression is of the form "X <op> Y" where both X and Y are
1216 ** columns, then the original expression is unchanged and a new virtual
1217 ** term of the form "Y <op> X" is added to the WHERE clause and
1218 ** analyzed separately. The original term is marked with TERM_COPIED
1219 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1220 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1221 ** is a commuted copy of a prior term.) The original term has nChild=1
1222 ** and the copy has idxParent set to the index of the original term.
1224 static void exprAnalyze(
1225 SrcList *pSrc, /* the FROM clause */
1226 WhereClause *pWC, /* the WHERE clause */
1227 int idxTerm /* Index of the term to be analyzed */
1229 WhereTerm *pTerm; /* The term to be analyzed */
1230 WhereMaskSet *pMaskSet; /* Set of table index masks */
1231 Expr *pExpr; /* The expression to be analyzed */
1232 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1233 Bitmask prereqAll; /* Prerequesites of pExpr */
1234 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
1235 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1236 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1237 int noCase = 0; /* LIKE/GLOB distinguishes case */
1238 int op; /* Top-level operator. pExpr->op */
1239 Parse *pParse = pWC->pParse; /* Parsing context */
1240 sqlite3 *db = pParse->db; /* Database connection */
1242 if( db->mallocFailed ){
1243 return;
1245 pTerm = &pWC->a[idxTerm];
1246 pMaskSet = pWC->pMaskSet;
1247 pExpr = pTerm->pExpr;
1248 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1249 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
1250 op = pExpr->op;
1251 if( op==TK_IN ){
1252 assert( pExpr->pRight==0 );
1253 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1254 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1255 }else{
1256 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1258 }else if( op==TK_ISNULL ){
1259 pTerm->prereqRight = 0;
1260 }else{
1261 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1263 prereqAll = exprTableUsage(pMaskSet, pExpr);
1264 if( ExprHasProperty(pExpr, EP_FromJoin) ){
1265 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1266 prereqAll |= x;
1267 extraRight = x-1; /* ON clause terms may not be used with an index
1268 ** on left table of a LEFT JOIN. Ticket #3015 */
1270 pTerm->prereqAll = prereqAll;
1271 pTerm->leftCursor = -1;
1272 pTerm->iParent = -1;
1273 pTerm->eOperator = 0;
1274 if( allowedOp(op) ){
1275 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1276 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1277 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
1278 if( pLeft->op==TK_COLUMN ){
1279 pTerm->leftCursor = pLeft->iTable;
1280 pTerm->u.leftColumn = pLeft->iColumn;
1281 pTerm->eOperator = operatorMask(op) & opMask;
1283 if( pRight && pRight->op==TK_COLUMN ){
1284 WhereTerm *pNew;
1285 Expr *pDup;
1286 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
1287 if( pTerm->leftCursor>=0 ){
1288 int idxNew;
1289 pDup = sqlite3ExprDup(db, pExpr, 0);
1290 if( db->mallocFailed ){
1291 sqlite3ExprDelete(db, pDup);
1292 return;
1294 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1295 if( idxNew==0 ) return;
1296 pNew = &pWC->a[idxNew];
1297 pNew->iParent = idxTerm;
1298 pTerm = &pWC->a[idxTerm];
1299 pTerm->nChild = 1;
1300 pTerm->wtFlags |= TERM_COPIED;
1301 if( pExpr->op==TK_EQ
1302 && !ExprHasProperty(pExpr, EP_FromJoin)
1303 && OptimizationEnabled(db, SQLITE_Transitive)
1305 pTerm->eOperator |= WO_EQUIV;
1306 eExtraOp = WO_EQUIV;
1308 }else{
1309 pDup = pExpr;
1310 pNew = pTerm;
1312 exprCommute(pParse, pDup);
1313 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
1314 pNew->leftCursor = pLeft->iTable;
1315 pNew->u.leftColumn = pLeft->iColumn;
1316 testcase( (prereqLeft | extraRight) != prereqLeft );
1317 pNew->prereqRight = prereqLeft | extraRight;
1318 pNew->prereqAll = prereqAll;
1319 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1323 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1324 /* If a term is the BETWEEN operator, create two new virtual terms
1325 ** that define the range that the BETWEEN implements. For example:
1327 ** a BETWEEN b AND c
1329 ** is converted into:
1331 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1333 ** The two new terms are added onto the end of the WhereClause object.
1334 ** The new terms are "dynamic" and are children of the original BETWEEN
1335 ** term. That means that if the BETWEEN term is coded, the children are
1336 ** skipped. Or, if the children are satisfied by an index, the original
1337 ** BETWEEN term is skipped.
1339 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1340 ExprList *pList = pExpr->x.pList;
1341 int i;
1342 static const u8 ops[] = {TK_GE, TK_LE};
1343 assert( pList!=0 );
1344 assert( pList->nExpr==2 );
1345 for(i=0; i<2; i++){
1346 Expr *pNewExpr;
1347 int idxNew;
1348 pNewExpr = sqlite3PExpr(pParse, ops[i],
1349 sqlite3ExprDup(db, pExpr->pLeft, 0),
1350 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
1351 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1352 testcase( idxNew==0 );
1353 exprAnalyze(pSrc, pWC, idxNew);
1354 pTerm = &pWC->a[idxTerm];
1355 pWC->a[idxNew].iParent = idxTerm;
1357 pTerm->nChild = 2;
1359 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1361 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1362 /* Analyze a term that is composed of two or more subterms connected by
1363 ** an OR operator.
1365 else if( pExpr->op==TK_OR ){
1366 assert( pWC->op==TK_AND );
1367 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1368 pTerm = &pWC->a[idxTerm];
1370 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1372 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1373 /* Add constraints to reduce the search space on a LIKE or GLOB
1374 ** operator.
1376 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1378 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1380 ** The last character of the prefix "abc" is incremented to form the
1381 ** termination condition "abd".
1383 if( pWC->op==TK_AND
1384 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1386 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1387 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1388 Expr *pNewExpr1;
1389 Expr *pNewExpr2;
1390 int idxNew1;
1391 int idxNew2;
1392 Token sCollSeqName; /* Name of collating sequence */
1394 pLeft = pExpr->x.pList->a[1].pExpr;
1395 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1396 if( !db->mallocFailed ){
1397 u8 c, *pC; /* Last character before the first wildcard */
1398 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1399 c = *pC;
1400 if( noCase ){
1401 /* The point is to increment the last character before the first
1402 ** wildcard. But if we increment '@', that will push it into the
1403 ** alphabetic range where case conversions will mess up the
1404 ** inequality. To avoid this, make sure to also run the full
1405 ** LIKE on all candidate expressions by clearing the isComplete flag
1407 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
1410 c = sqlite3UpperToLower[c];
1412 *pC = c + 1;
1414 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1415 sCollSeqName.n = 6;
1416 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1417 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1418 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
1419 pStr1, 0);
1420 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
1421 testcase( idxNew1==0 );
1422 exprAnalyze(pSrc, pWC, idxNew1);
1423 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1424 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1425 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
1426 pStr2, 0);
1427 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
1428 testcase( idxNew2==0 );
1429 exprAnalyze(pSrc, pWC, idxNew2);
1430 pTerm = &pWC->a[idxTerm];
1431 if( isComplete ){
1432 pWC->a[idxNew1].iParent = idxTerm;
1433 pWC->a[idxNew2].iParent = idxTerm;
1434 pTerm->nChild = 2;
1437 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1439 #ifndef SQLITE_OMIT_VIRTUALTABLE
1440 /* Add a WO_MATCH auxiliary term to the constraint set if the
1441 ** current expression is of the form: column MATCH expr.
1442 ** This information is used by the xBestIndex methods of
1443 ** virtual tables. The native query optimizer does not attempt
1444 ** to do anything with MATCH functions.
1446 if( isMatchOfColumn(pExpr) ){
1447 int idxNew;
1448 Expr *pRight, *pLeft;
1449 WhereTerm *pNewTerm;
1450 Bitmask prereqColumn, prereqExpr;
1452 pRight = pExpr->x.pList->a[0].pExpr;
1453 pLeft = pExpr->x.pList->a[1].pExpr;
1454 prereqExpr = exprTableUsage(pMaskSet, pRight);
1455 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1456 if( (prereqExpr & prereqColumn)==0 ){
1457 Expr *pNewExpr;
1458 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1459 0, sqlite3ExprDup(db, pRight, 0), 0);
1460 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1461 testcase( idxNew==0 );
1462 pNewTerm = &pWC->a[idxNew];
1463 pNewTerm->prereqRight = prereqExpr;
1464 pNewTerm->leftCursor = pLeft->iTable;
1465 pNewTerm->u.leftColumn = pLeft->iColumn;
1466 pNewTerm->eOperator = WO_MATCH;
1467 pNewTerm->iParent = idxTerm;
1468 pTerm = &pWC->a[idxTerm];
1469 pTerm->nChild = 1;
1470 pTerm->wtFlags |= TERM_COPIED;
1471 pNewTerm->prereqAll = pTerm->prereqAll;
1474 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1476 #ifdef SQLITE_ENABLE_STAT3
1477 /* When sqlite_stat3 histogram data is available an operator of the
1478 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1479 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1480 ** virtual term of that form.
1482 ** Note that the virtual term must be tagged with TERM_VNULL. This
1483 ** TERM_VNULL tag will suppress the not-null check at the beginning
1484 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1485 ** the start of the loop will prevent any results from being returned.
1487 if( pExpr->op==TK_NOTNULL
1488 && pExpr->pLeft->op==TK_COLUMN
1489 && pExpr->pLeft->iColumn>=0
1491 Expr *pNewExpr;
1492 Expr *pLeft = pExpr->pLeft;
1493 int idxNew;
1494 WhereTerm *pNewTerm;
1496 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1497 sqlite3ExprDup(db, pLeft, 0),
1498 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1500 idxNew = whereClauseInsert(pWC, pNewExpr,
1501 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1502 if( idxNew ){
1503 pNewTerm = &pWC->a[idxNew];
1504 pNewTerm->prereqRight = 0;
1505 pNewTerm->leftCursor = pLeft->iTable;
1506 pNewTerm->u.leftColumn = pLeft->iColumn;
1507 pNewTerm->eOperator = WO_GT;
1508 pNewTerm->iParent = idxTerm;
1509 pTerm = &pWC->a[idxTerm];
1510 pTerm->nChild = 1;
1511 pTerm->wtFlags |= TERM_COPIED;
1512 pNewTerm->prereqAll = pTerm->prereqAll;
1515 #endif /* SQLITE_ENABLE_STAT */
1517 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1518 ** an index for tables to the left of the join.
1520 pTerm->prereqRight |= extraRight;
1524 ** This function searches the expression list passed as the second argument
1525 ** for an expression of type TK_COLUMN that refers to the same column and
1526 ** uses the same collation sequence as the iCol'th column of index pIdx.
1527 ** Argument iBase is the cursor number used for the table that pIdx refers
1528 ** to.
1530 ** If such an expression is found, its index in pList->a[] is returned. If
1531 ** no expression is found, -1 is returned.
1533 static int findIndexCol(
1534 Parse *pParse, /* Parse context */
1535 ExprList *pList, /* Expression list to search */
1536 int iBase, /* Cursor for table associated with pIdx */
1537 Index *pIdx, /* Index to match column of */
1538 int iCol /* Column of index to match */
1540 int i;
1541 const char *zColl = pIdx->azColl[iCol];
1543 for(i=0; i<pList->nExpr; i++){
1544 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1545 if( p->op==TK_COLUMN
1546 && p->iColumn==pIdx->aiColumn[iCol]
1547 && p->iTable==iBase
1549 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1550 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
1551 return i;
1556 return -1;
1560 ** This routine determines if pIdx can be used to assist in processing a
1561 ** DISTINCT qualifier. In other words, it tests whether or not using this
1562 ** index for the outer loop guarantees that rows with equal values for
1563 ** all expressions in the pDistinct list are delivered grouped together.
1565 ** For example, the query
1567 ** SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
1569 ** can benefit from any index on columns "b" and "c".
1571 static int isDistinctIndex(
1572 Parse *pParse, /* Parsing context */
1573 WhereClause *pWC, /* The WHERE clause */
1574 Index *pIdx, /* The index being considered */
1575 int base, /* Cursor number for the table pIdx is on */
1576 ExprList *pDistinct, /* The DISTINCT expressions */
1577 int nEqCol /* Number of index columns with == */
1579 Bitmask mask = 0; /* Mask of unaccounted for pDistinct exprs */
1580 int i; /* Iterator variable */
1582 assert( pDistinct!=0 );
1583 if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
1584 testcase( pDistinct->nExpr==BMS-1 );
1586 /* Loop through all the expressions in the distinct list. If any of them
1587 ** are not simple column references, return early. Otherwise, test if the
1588 ** WHERE clause contains a "col=X" clause. If it does, the expression
1589 ** can be ignored. If it does not, and the column does not belong to the
1590 ** same table as index pIdx, return early. Finally, if there is no
1591 ** matching "col=X" expression and the column is on the same table as pIdx,
1592 ** set the corresponding bit in variable mask.
1594 for(i=0; i<pDistinct->nExpr; i++){
1595 WhereTerm *pTerm;
1596 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
1597 if( p->op!=TK_COLUMN ) return 0;
1598 pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
1599 if( pTerm ){
1600 Expr *pX = pTerm->pExpr;
1601 CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
1602 CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
1603 if( p1==p2 ) continue;
1605 if( p->iTable!=base ) return 0;
1606 mask |= (((Bitmask)1) << i);
1609 for(i=nEqCol; mask && i<pIdx->nColumn; i++){
1610 int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
1611 if( iExpr<0 ) break;
1612 mask &= ~(((Bitmask)1) << iExpr);
1615 return (mask==0);
1620 ** Return true if the DISTINCT expression-list passed as the third argument
1621 ** is redundant. A DISTINCT list is redundant if the database contains a
1622 ** UNIQUE index that guarantees that the result of the query will be distinct
1623 ** anyway.
1625 static int isDistinctRedundant(
1626 Parse *pParse,
1627 SrcList *pTabList,
1628 WhereClause *pWC,
1629 ExprList *pDistinct
1631 Table *pTab;
1632 Index *pIdx;
1633 int i;
1634 int iBase;
1636 /* If there is more than one table or sub-select in the FROM clause of
1637 ** this query, then it will not be possible to show that the DISTINCT
1638 ** clause is redundant. */
1639 if( pTabList->nSrc!=1 ) return 0;
1640 iBase = pTabList->a[0].iCursor;
1641 pTab = pTabList->a[0].pTab;
1643 /* If any of the expressions is an IPK column on table iBase, then return
1644 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1645 ** current SELECT is a correlated sub-query.
1647 for(i=0; i<pDistinct->nExpr; i++){
1648 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
1649 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
1652 /* Loop through all indices on the table, checking each to see if it makes
1653 ** the DISTINCT qualifier redundant. It does so if:
1655 ** 1. The index is itself UNIQUE, and
1657 ** 2. All of the columns in the index are either part of the pDistinct
1658 ** list, or else the WHERE clause contains a term of the form "col=X",
1659 ** where X is a constant value. The collation sequences of the
1660 ** comparison and select-list expressions must match those of the index.
1662 ** 3. All of those index columns for which the WHERE clause does not
1663 ** contain a "col=X" term are subject to a NOT NULL constraint.
1665 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1666 if( pIdx->onError==OE_None ) continue;
1667 for(i=0; i<pIdx->nColumn; i++){
1668 int iCol = pIdx->aiColumn[i];
1669 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1670 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
1671 if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
1672 break;
1676 if( i==pIdx->nColumn ){
1677 /* This index implies that the DISTINCT qualifier is redundant. */
1678 return 1;
1682 return 0;
1686 ** Prepare a crude estimate of the logarithm of the input value.
1687 ** The results need not be exact. This is only used for estimating
1688 ** the total cost of performing operations with O(logN) or O(NlogN)
1689 ** complexity. Because N is just a guess, it is no great tragedy if
1690 ** logN is a little off.
1692 static double estLog(double N){
1693 double logN = 1;
1694 double x = 10;
1695 while( N>x ){
1696 logN += 1;
1697 x *= 10;
1699 return logN;
1703 ** Two routines for printing the content of an sqlite3_index_info
1704 ** structure. Used for testing and debugging only. If neither
1705 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1706 ** are no-ops.
1708 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
1709 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1710 int i;
1711 if( !sqlite3WhereTrace ) return;
1712 for(i=0; i<p->nConstraint; i++){
1713 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1715 p->aConstraint[i].iColumn,
1716 p->aConstraint[i].iTermOffset,
1717 p->aConstraint[i].op,
1718 p->aConstraint[i].usable);
1720 for(i=0; i<p->nOrderBy; i++){
1721 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1723 p->aOrderBy[i].iColumn,
1724 p->aOrderBy[i].desc);
1727 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1728 int i;
1729 if( !sqlite3WhereTrace ) return;
1730 for(i=0; i<p->nConstraint; i++){
1731 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1733 p->aConstraintUsage[i].argvIndex,
1734 p->aConstraintUsage[i].omit);
1736 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1737 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1738 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1739 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
1741 #else
1742 #define TRACE_IDX_INPUTS(A)
1743 #define TRACE_IDX_OUTPUTS(A)
1744 #endif
1747 ** Required because bestIndex() is called by bestOrClauseIndex()
1749 static void bestIndex(WhereBestIdx*);
1752 ** This routine attempts to find an scanning strategy that can be used
1753 ** to optimize an 'OR' expression that is part of a WHERE clause.
1755 ** The table associated with FROM clause term pSrc may be either a
1756 ** regular B-Tree table or a virtual table.
1758 static void bestOrClauseIndex(WhereBestIdx *p){
1759 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
1760 WhereClause *pWC = p->pWC; /* The WHERE clause */
1761 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
1762 const int iCur = pSrc->iCursor; /* The cursor of the table */
1763 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
1764 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
1765 WhereTerm *pTerm; /* A single term of the WHERE clause */
1767 /* The OR-clause optimization is disallowed if the INDEXED BY or
1768 ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
1769 if( pSrc->notIndexed || pSrc->pIndex!=0 ){
1770 return;
1772 if( pWC->wctrlFlags & WHERE_AND_ONLY ){
1773 return;
1776 /* Search the WHERE clause terms for a usable WO_OR term. */
1777 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1778 if( (pTerm->eOperator & WO_OR)!=0
1779 && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
1780 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
1782 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
1783 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
1784 WhereTerm *pOrTerm;
1785 int flags = WHERE_MULTI_OR;
1786 double rTotal = 0;
1787 double nRow = 0;
1788 Bitmask used = 0;
1789 WhereBestIdx sBOI;
1791 sBOI = *p;
1792 sBOI.pOrderBy = 0;
1793 sBOI.pDistinct = 0;
1794 sBOI.ppIdxInfo = 0;
1795 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
1796 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
1797 (pOrTerm - pOrWC->a), (pTerm - pWC->a)
1799 if( (pOrTerm->eOperator& WO_AND)!=0 ){
1800 sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
1801 bestIndex(&sBOI);
1802 }else if( pOrTerm->leftCursor==iCur ){
1803 WhereClause tempWC;
1804 tempWC.pParse = pWC->pParse;
1805 tempWC.pMaskSet = pWC->pMaskSet;
1806 tempWC.pOuter = pWC;
1807 tempWC.op = TK_AND;
1808 tempWC.a = pOrTerm;
1809 tempWC.wctrlFlags = 0;
1810 tempWC.nTerm = 1;
1811 sBOI.pWC = &tempWC;
1812 bestIndex(&sBOI);
1813 }else{
1814 continue;
1816 rTotal += sBOI.cost.rCost;
1817 nRow += sBOI.cost.plan.nRow;
1818 used |= sBOI.cost.used;
1819 if( rTotal>=p->cost.rCost ) break;
1822 /* If there is an ORDER BY clause, increase the scan cost to account
1823 ** for the cost of the sort. */
1824 if( p->pOrderBy!=0 ){
1825 WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
1826 rTotal, rTotal+nRow*estLog(nRow)));
1827 rTotal += nRow*estLog(nRow);
1830 /* If the cost of scanning using this OR term for optimization is
1831 ** less than the current cost stored in pCost, replace the contents
1832 ** of pCost. */
1833 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
1834 if( rTotal<p->cost.rCost ){
1835 p->cost.rCost = rTotal;
1836 p->cost.used = used;
1837 p->cost.plan.nRow = nRow;
1838 p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
1839 p->cost.plan.wsFlags = flags;
1840 p->cost.plan.u.pTerm = pTerm;
1844 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1847 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1849 ** Return TRUE if the WHERE clause term pTerm is of a form where it
1850 ** could be used with an index to access pSrc, assuming an appropriate
1851 ** index existed.
1853 static int termCanDriveIndex(
1854 WhereTerm *pTerm, /* WHERE clause term to check */
1855 struct SrcList_item *pSrc, /* Table we are trying to access */
1856 Bitmask notReady /* Tables in outer loops of the join */
1858 char aff;
1859 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
1860 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
1861 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
1862 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1863 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1864 return 1;
1866 #endif
1868 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1870 ** If the query plan for pSrc specified in pCost is a full table scan
1871 ** and indexing is allows (if there is no NOT INDEXED clause) and it
1872 ** possible to construct a transient index that would perform better
1873 ** than a full table scan even when the cost of constructing the index
1874 ** is taken into account, then alter the query plan to use the
1875 ** transient index.
1877 static void bestAutomaticIndex(WhereBestIdx *p){
1878 Parse *pParse = p->pParse; /* The parsing context */
1879 WhereClause *pWC = p->pWC; /* The WHERE clause */
1880 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
1881 double nTableRow; /* Rows in the input table */
1882 double logN; /* log(nTableRow) */
1883 double costTempIdx; /* per-query cost of the transient index */
1884 WhereTerm *pTerm; /* A single term of the WHERE clause */
1885 WhereTerm *pWCEnd; /* End of pWC->a[] */
1886 Table *pTable; /* Table tht might be indexed */
1888 if( pParse->nQueryLoop<=(double)1 ){
1889 /* There is no point in building an automatic index for a single scan */
1890 return;
1892 if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
1893 /* Automatic indices are disabled at run-time */
1894 return;
1896 if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
1897 && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
1899 /* We already have some kind of index in use for this query. */
1900 return;
1902 if( pSrc->viaCoroutine ){
1903 /* Cannot index a co-routine */
1904 return;
1906 if( pSrc->notIndexed ){
1907 /* The NOT INDEXED clause appears in the SQL. */
1908 return;
1910 if( pSrc->isCorrelated ){
1911 /* The source is a correlated sub-query. No point in indexing it. */
1912 return;
1915 assert( pParse->nQueryLoop >= (double)1 );
1916 pTable = pSrc->pTab;
1917 nTableRow = pTable->nRowEst;
1918 logN = estLog(nTableRow);
1919 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
1920 if( costTempIdx>=p->cost.rCost ){
1921 /* The cost of creating the transient table would be greater than
1922 ** doing the full table scan */
1923 return;
1926 /* Search for any equality comparison term */
1927 pWCEnd = &pWC->a[pWC->nTerm];
1928 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1929 if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
1930 WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
1931 p->cost.rCost, costTempIdx));
1932 p->cost.rCost = costTempIdx;
1933 p->cost.plan.nRow = logN + 1;
1934 p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
1935 p->cost.used = pTerm->prereqRight;
1936 break;
1940 #else
1941 # define bestAutomaticIndex(A) /* no-op */
1942 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
1945 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
1947 ** Generate code to construct the Index object for an automatic index
1948 ** and to set up the WhereLevel object pLevel so that the code generator
1949 ** makes use of the automatic index.
1951 static void constructAutomaticIndex(
1952 Parse *pParse, /* The parsing context */
1953 WhereClause *pWC, /* The WHERE clause */
1954 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1955 Bitmask notReady, /* Mask of cursors that are not available */
1956 WhereLevel *pLevel /* Write new index here */
1958 int nColumn; /* Number of columns in the constructed index */
1959 WhereTerm *pTerm; /* A single term of the WHERE clause */
1960 WhereTerm *pWCEnd; /* End of pWC->a[] */
1961 int nByte; /* Byte of memory needed for pIdx */
1962 Index *pIdx; /* Object describing the transient index */
1963 Vdbe *v; /* Prepared statement under construction */
1964 int addrInit; /* Address of the initialization bypass jump */
1965 Table *pTable; /* The table being indexed */
1966 KeyInfo *pKeyinfo; /* Key information for the index */
1967 int addrTop; /* Top of the index fill loop */
1968 int regRecord; /* Register holding an index record */
1969 int n; /* Column counter */
1970 int i; /* Loop counter */
1971 int mxBitCol; /* Maximum column in pSrc->colUsed */
1972 CollSeq *pColl; /* Collating sequence to on a column */
1973 Bitmask idxCols; /* Bitmap of columns used for indexing */
1974 Bitmask extraCols; /* Bitmap of additional columns */
1976 /* Generate code to skip over the creation and initialization of the
1977 ** transient index on 2nd and subsequent iterations of the loop. */
1978 v = pParse->pVdbe;
1979 assert( v!=0 );
1980 addrInit = sqlite3CodeOnce(pParse);
1982 /* Count the number of columns that will be added to the index
1983 ** and used to match WHERE clause constraints */
1984 nColumn = 0;
1985 pTable = pSrc->pTab;
1986 pWCEnd = &pWC->a[pWC->nTerm];
1987 idxCols = 0;
1988 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1989 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1990 int iCol = pTerm->u.leftColumn;
1991 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
1992 testcase( iCol==BMS );
1993 testcase( iCol==BMS-1 );
1994 if( (idxCols & cMask)==0 ){
1995 nColumn++;
1996 idxCols |= cMask;
2000 assert( nColumn>0 );
2001 pLevel->plan.nEq = nColumn;
2003 /* Count the number of additional columns needed to create a
2004 ** covering index. A "covering index" is an index that contains all
2005 ** columns that are needed by the query. With a covering index, the
2006 ** original table never needs to be accessed. Automatic indices must
2007 ** be a covering index because the index will not be updated if the
2008 ** original table changes and the index and table cannot both be used
2009 ** if they go out of sync.
2011 extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
2012 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
2013 testcase( pTable->nCol==BMS-1 );
2014 testcase( pTable->nCol==BMS-2 );
2015 for(i=0; i<mxBitCol; i++){
2016 if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
2018 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
2019 nColumn += pTable->nCol - BMS + 1;
2021 pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
2023 /* Construct the Index object to describe this index */
2024 nByte = sizeof(Index);
2025 nByte += nColumn*sizeof(int); /* Index.aiColumn */
2026 nByte += nColumn*sizeof(char*); /* Index.azColl */
2027 nByte += nColumn; /* Index.aSortOrder */
2028 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
2029 if( pIdx==0 ) return;
2030 pLevel->plan.u.pIdx = pIdx;
2031 pIdx->azColl = (char**)&pIdx[1];
2032 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
2033 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
2034 pIdx->zName = "auto-index";
2035 pIdx->nColumn = nColumn;
2036 pIdx->pTable = pTable;
2037 n = 0;
2038 idxCols = 0;
2039 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
2040 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
2041 int iCol = pTerm->u.leftColumn;
2042 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
2043 if( (idxCols & cMask)==0 ){
2044 Expr *pX = pTerm->pExpr;
2045 idxCols |= cMask;
2046 pIdx->aiColumn[n] = pTerm->u.leftColumn;
2047 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
2048 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
2049 n++;
2053 assert( (u32)n==pLevel->plan.nEq );
2055 /* Add additional columns needed to make the automatic index into
2056 ** a covering index */
2057 for(i=0; i<mxBitCol; i++){
2058 if( extraCols & (((Bitmask)1)<<i) ){
2059 pIdx->aiColumn[n] = i;
2060 pIdx->azColl[n] = "BINARY";
2061 n++;
2064 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
2065 for(i=BMS-1; i<pTable->nCol; i++){
2066 pIdx->aiColumn[n] = i;
2067 pIdx->azColl[n] = "BINARY";
2068 n++;
2071 assert( n==nColumn );
2073 /* Create the automatic index */
2074 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
2075 assert( pLevel->iIdxCur>=0 );
2076 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
2077 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
2078 VdbeComment((v, "for %s", pTable->zName));
2080 /* Fill the automatic index with content */
2081 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
2082 regRecord = sqlite3GetTempReg(pParse);
2083 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
2084 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
2085 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2086 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
2087 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
2088 sqlite3VdbeJumpHere(v, addrTop);
2089 sqlite3ReleaseTempReg(pParse, regRecord);
2091 /* Jump here when skipping the initialization */
2092 sqlite3VdbeJumpHere(v, addrInit);
2094 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
2096 #ifndef SQLITE_OMIT_VIRTUALTABLE
2098 ** Allocate and populate an sqlite3_index_info structure. It is the
2099 ** responsibility of the caller to eventually release the structure
2100 ** by passing the pointer returned by this function to sqlite3_free().
2102 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
2103 Parse *pParse = p->pParse;
2104 WhereClause *pWC = p->pWC;
2105 struct SrcList_item *pSrc = p->pSrc;
2106 ExprList *pOrderBy = p->pOrderBy;
2107 int i, j;
2108 int nTerm;
2109 struct sqlite3_index_constraint *pIdxCons;
2110 struct sqlite3_index_orderby *pIdxOrderBy;
2111 struct sqlite3_index_constraint_usage *pUsage;
2112 WhereTerm *pTerm;
2113 int nOrderBy;
2114 sqlite3_index_info *pIdxInfo;
2116 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
2118 /* Count the number of possible WHERE clause constraints referring
2119 ** to this virtual table */
2120 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2121 if( pTerm->leftCursor != pSrc->iCursor ) continue;
2122 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2123 testcase( pTerm->eOperator & WO_IN );
2124 testcase( pTerm->eOperator & WO_ISNULL );
2125 if( pTerm->eOperator & (WO_ISNULL) ) continue;
2126 if( pTerm->wtFlags & TERM_VNULL ) continue;
2127 nTerm++;
2130 /* If the ORDER BY clause contains only columns in the current
2131 ** virtual table then allocate space for the aOrderBy part of
2132 ** the sqlite3_index_info structure.
2134 nOrderBy = 0;
2135 if( pOrderBy ){
2136 int n = pOrderBy->nExpr;
2137 for(i=0; i<n; i++){
2138 Expr *pExpr = pOrderBy->a[i].pExpr;
2139 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2141 if( i==n){
2142 nOrderBy = n;
2146 /* Allocate the sqlite3_index_info structure
2148 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2149 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2150 + sizeof(*pIdxOrderBy)*nOrderBy );
2151 if( pIdxInfo==0 ){
2152 sqlite3ErrorMsg(pParse, "out of memory");
2153 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
2154 return 0;
2157 /* Initialize the structure. The sqlite3_index_info structure contains
2158 ** many fields that are declared "const" to prevent xBestIndex from
2159 ** changing them. We have to do some funky casting in order to
2160 ** initialize those fields.
2162 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2163 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2164 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2165 *(int*)&pIdxInfo->nConstraint = nTerm;
2166 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2167 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2168 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2169 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2170 pUsage;
2172 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2173 u8 op;
2174 if( pTerm->leftCursor != pSrc->iCursor ) continue;
2175 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2176 testcase( pTerm->eOperator & WO_IN );
2177 testcase( pTerm->eOperator & WO_ISNULL );
2178 if( pTerm->eOperator & (WO_ISNULL) ) continue;
2179 if( pTerm->wtFlags & TERM_VNULL ) continue;
2180 pIdxCons[j].iColumn = pTerm->u.leftColumn;
2181 pIdxCons[j].iTermOffset = i;
2182 op = (u8)pTerm->eOperator & WO_ALL;
2183 if( op==WO_IN ) op = WO_EQ;
2184 pIdxCons[j].op = op;
2185 /* The direct assignment in the previous line is possible only because
2186 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
2187 ** following asserts verify this fact. */
2188 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2189 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2190 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2191 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2192 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2193 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
2194 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
2195 j++;
2197 for(i=0; i<nOrderBy; i++){
2198 Expr *pExpr = pOrderBy->a[i].pExpr;
2199 pIdxOrderBy[i].iColumn = pExpr->iColumn;
2200 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2203 return pIdxInfo;
2207 ** The table object reference passed as the second argument to this function
2208 ** must represent a virtual table. This function invokes the xBestIndex()
2209 ** method of the virtual table with the sqlite3_index_info pointer passed
2210 ** as the argument.
2212 ** If an error occurs, pParse is populated with an error message and a
2213 ** non-zero value is returned. Otherwise, 0 is returned and the output
2214 ** part of the sqlite3_index_info structure is left populated.
2216 ** Whether or not an error is returned, it is the responsibility of the
2217 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2218 ** that this is required.
2220 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
2221 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
2222 int i;
2223 int rc;
2225 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
2226 TRACE_IDX_INPUTS(p);
2227 rc = pVtab->pModule->xBestIndex(pVtab, p);
2228 TRACE_IDX_OUTPUTS(p);
2230 if( rc!=SQLITE_OK ){
2231 if( rc==SQLITE_NOMEM ){
2232 pParse->db->mallocFailed = 1;
2233 }else if( !pVtab->zErrMsg ){
2234 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2235 }else{
2236 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2239 sqlite3_free(pVtab->zErrMsg);
2240 pVtab->zErrMsg = 0;
2242 for(i=0; i<p->nConstraint; i++){
2243 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2244 sqlite3ErrorMsg(pParse,
2245 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2249 return pParse->nErr;
2254 ** Compute the best index for a virtual table.
2256 ** The best index is computed by the xBestIndex method of the virtual
2257 ** table module. This routine is really just a wrapper that sets up
2258 ** the sqlite3_index_info structure that is used to communicate with
2259 ** xBestIndex.
2261 ** In a join, this routine might be called multiple times for the
2262 ** same virtual table. The sqlite3_index_info structure is created
2263 ** and initialized on the first invocation and reused on all subsequent
2264 ** invocations. The sqlite3_index_info structure is also used when
2265 ** code is generated to access the virtual table. The whereInfoDelete()
2266 ** routine takes care of freeing the sqlite3_index_info structure after
2267 ** everybody has finished with it.
2269 static void bestVirtualIndex(WhereBestIdx *p){
2270 Parse *pParse = p->pParse; /* The parsing context */
2271 WhereClause *pWC = p->pWC; /* The WHERE clause */
2272 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
2273 Table *pTab = pSrc->pTab;
2274 sqlite3_index_info *pIdxInfo;
2275 struct sqlite3_index_constraint *pIdxCons;
2276 struct sqlite3_index_constraint_usage *pUsage;
2277 WhereTerm *pTerm;
2278 int i, j;
2279 int nOrderBy;
2280 int bAllowIN; /* Allow IN optimizations */
2281 double rCost;
2283 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
2284 ** malloc in allocateIndexInfo() fails and this function returns leaving
2285 ** wsFlags in an uninitialized state, the caller may behave unpredictably.
2287 memset(&p->cost, 0, sizeof(p->cost));
2288 p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
2290 /* If the sqlite3_index_info structure has not been previously
2291 ** allocated and initialized, then allocate and initialize it now.
2293 pIdxInfo = *p->ppIdxInfo;
2294 if( pIdxInfo==0 ){
2295 *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
2297 if( pIdxInfo==0 ){
2298 return;
2301 /* At this point, the sqlite3_index_info structure that pIdxInfo points
2302 ** to will have been initialized, either during the current invocation or
2303 ** during some prior invocation. Now we just have to customize the
2304 ** details of pIdxInfo for the current invocation and pass it to
2305 ** xBestIndex.
2308 /* The module name must be defined. Also, by this point there must
2309 ** be a pointer to an sqlite3_vtab structure. Otherwise
2310 ** sqlite3ViewGetColumnNames() would have picked up the error.
2312 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
2313 assert( sqlite3GetVTable(pParse->db, pTab) );
2315 /* Try once or twice. On the first attempt, allow IN optimizations.
2316 ** If an IN optimization is accepted by the virtual table xBestIndex
2317 ** method, but the pInfo->aConstrainUsage.omit flag is not set, then
2318 ** the query will not work because it might allow duplicate rows in
2319 ** output. In that case, run the xBestIndex method a second time
2320 ** without the IN constraints. Usually this loop only runs once.
2321 ** The loop will exit using a "break" statement.
2323 for(bAllowIN=1; 1; bAllowIN--){
2324 assert( bAllowIN==0 || bAllowIN==1 );
2326 /* Set the aConstraint[].usable fields and initialize all
2327 ** output variables to zero.
2329 ** aConstraint[].usable is true for constraints where the right-hand
2330 ** side contains only references to tables to the left of the current
2331 ** table. In other words, if the constraint is of the form:
2333 ** column = expr
2335 ** and we are evaluating a join, then the constraint on column is
2336 ** only valid if all tables referenced in expr occur to the left
2337 ** of the table containing column.
2339 ** The aConstraints[] array contains entries for all constraints
2340 ** on the current table. That way we only have to compute it once
2341 ** even though we might try to pick the best index multiple times.
2342 ** For each attempt at picking an index, the order of tables in the
2343 ** join might be different so we have to recompute the usable flag
2344 ** each time.
2346 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2347 pUsage = pIdxInfo->aConstraintUsage;
2348 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
2349 j = pIdxCons->iTermOffset;
2350 pTerm = &pWC->a[j];
2351 if( (pTerm->prereqRight&p->notReady)==0
2352 && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
2354 pIdxCons->usable = 1;
2355 }else{
2356 pIdxCons->usable = 0;
2359 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
2360 if( pIdxInfo->needToFreeIdxStr ){
2361 sqlite3_free(pIdxInfo->idxStr);
2363 pIdxInfo->idxStr = 0;
2364 pIdxInfo->idxNum = 0;
2365 pIdxInfo->needToFreeIdxStr = 0;
2366 pIdxInfo->orderByConsumed = 0;
2367 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
2368 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
2369 nOrderBy = pIdxInfo->nOrderBy;
2370 if( !p->pOrderBy ){
2371 pIdxInfo->nOrderBy = 0;
2374 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
2375 return;
2378 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2379 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
2380 if( pUsage[i].argvIndex>0 ){
2381 j = pIdxCons->iTermOffset;
2382 pTerm = &pWC->a[j];
2383 p->cost.used |= pTerm->prereqRight;
2384 if( (pTerm->eOperator & WO_IN)!=0 ){
2385 if( pUsage[i].omit==0 ){
2386 /* Do not attempt to use an IN constraint if the virtual table
2387 ** says that the equivalent EQ constraint cannot be safely omitted.
2388 ** If we do attempt to use such a constraint, some rows might be
2389 ** repeated in the output. */
2390 break;
2392 /* A virtual table that is constrained by an IN clause may not
2393 ** consume the ORDER BY clause because (1) the order of IN terms
2394 ** is not necessarily related to the order of output terms and
2395 ** (2) Multiple outputs from a single IN value will not merge
2396 ** together. */
2397 pIdxInfo->orderByConsumed = 0;
2401 if( i>=pIdxInfo->nConstraint ) break;
2404 /* The orderByConsumed signal is only valid if all outer loops collectively
2405 ** generate just a single row of output.
2407 if( pIdxInfo->orderByConsumed ){
2408 for(i=0; i<p->i; i++){
2409 if( (p->aLevel[i].plan.wsFlags & WHERE_UNIQUE)==0 ){
2410 pIdxInfo->orderByConsumed = 0;
2415 /* If there is an ORDER BY clause, and the selected virtual table index
2416 ** does not satisfy it, increase the cost of the scan accordingly. This
2417 ** matches the processing for non-virtual tables in bestBtreeIndex().
2419 rCost = pIdxInfo->estimatedCost;
2420 if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
2421 rCost += estLog(rCost)*rCost;
2424 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
2425 ** inital value of lowestCost in this loop. If it is, then the
2426 ** (cost<lowestCost) test below will never be true.
2428 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
2429 ** is defined.
2431 if( (SQLITE_BIG_DBL/((double)2))<rCost ){
2432 p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
2433 }else{
2434 p->cost.rCost = rCost;
2436 p->cost.plan.u.pVtabIdx = pIdxInfo;
2437 if( pIdxInfo->orderByConsumed ){
2438 p->cost.plan.wsFlags |= WHERE_ORDERED;
2439 p->cost.plan.nOBSat = nOrderBy;
2440 }else{
2441 p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
2443 p->cost.plan.nEq = 0;
2444 pIdxInfo->nOrderBy = nOrderBy;
2446 /* Try to find a more efficient access pattern by using multiple indexes
2447 ** to optimize an OR expression within the WHERE clause.
2449 bestOrClauseIndex(p);
2451 #endif /* SQLITE_OMIT_VIRTUALTABLE */
2453 #ifdef SQLITE_ENABLE_STAT3
2455 ** Estimate the location of a particular key among all keys in an
2456 ** index. Store the results in aStat as follows:
2458 ** aStat[0] Est. number of rows less than pVal
2459 ** aStat[1] Est. number of rows equal to pVal
2461 ** Return SQLITE_OK on success.
2463 static int whereKeyStats(
2464 Parse *pParse, /* Database connection */
2465 Index *pIdx, /* Index to consider domain of */
2466 sqlite3_value *pVal, /* Value to consider */
2467 int roundUp, /* Round up if true. Round down if false */
2468 tRowcnt *aStat /* OUT: stats written here */
2470 tRowcnt n;
2471 IndexSample *aSample;
2472 int i, eType;
2473 int isEq = 0;
2474 i64 v;
2475 double r, rS;
2477 assert( roundUp==0 || roundUp==1 );
2478 assert( pIdx->nSample>0 );
2479 if( pVal==0 ) return SQLITE_ERROR;
2480 n = pIdx->aiRowEst[0];
2481 aSample = pIdx->aSample;
2482 eType = sqlite3_value_type(pVal);
2484 if( eType==SQLITE_INTEGER ){
2485 v = sqlite3_value_int64(pVal);
2486 r = (i64)v;
2487 for(i=0; i<pIdx->nSample; i++){
2488 if( aSample[i].eType==SQLITE_NULL ) continue;
2489 if( aSample[i].eType>=SQLITE_TEXT ) break;
2490 if( aSample[i].eType==SQLITE_INTEGER ){
2491 if( aSample[i].u.i>=v ){
2492 isEq = aSample[i].u.i==v;
2493 break;
2495 }else{
2496 assert( aSample[i].eType==SQLITE_FLOAT );
2497 if( aSample[i].u.r>=r ){
2498 isEq = aSample[i].u.r==r;
2499 break;
2503 }else if( eType==SQLITE_FLOAT ){
2504 r = sqlite3_value_double(pVal);
2505 for(i=0; i<pIdx->nSample; i++){
2506 if( aSample[i].eType==SQLITE_NULL ) continue;
2507 if( aSample[i].eType>=SQLITE_TEXT ) break;
2508 if( aSample[i].eType==SQLITE_FLOAT ){
2509 rS = aSample[i].u.r;
2510 }else{
2511 rS = aSample[i].u.i;
2513 if( rS>=r ){
2514 isEq = rS==r;
2515 break;
2518 }else if( eType==SQLITE_NULL ){
2519 i = 0;
2520 if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
2521 }else{
2522 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2523 for(i=0; i<pIdx->nSample; i++){
2524 if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
2525 break;
2528 if( i<pIdx->nSample ){
2529 sqlite3 *db = pParse->db;
2530 CollSeq *pColl;
2531 const u8 *z;
2532 if( eType==SQLITE_BLOB ){
2533 z = (const u8 *)sqlite3_value_blob(pVal);
2534 pColl = db->pDfltColl;
2535 assert( pColl->enc==SQLITE_UTF8 );
2536 }else{
2537 pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
2538 if( pColl==0 ){
2539 return SQLITE_ERROR;
2541 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
2542 if( !z ){
2543 return SQLITE_NOMEM;
2545 assert( z && pColl && pColl->xCmp );
2547 n = sqlite3ValueBytes(pVal, pColl->enc);
2549 for(; i<pIdx->nSample; i++){
2550 int c;
2551 int eSampletype = aSample[i].eType;
2552 if( eSampletype<eType ) continue;
2553 if( eSampletype!=eType ) break;
2554 #ifndef SQLITE_OMIT_UTF16
2555 if( pColl->enc!=SQLITE_UTF8 ){
2556 int nSample;
2557 char *zSample = sqlite3Utf8to16(
2558 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
2560 if( !zSample ){
2561 assert( db->mallocFailed );
2562 return SQLITE_NOMEM;
2564 c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
2565 sqlite3DbFree(db, zSample);
2566 }else
2567 #endif
2569 c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
2571 if( c>=0 ){
2572 if( c==0 ) isEq = 1;
2573 break;
2579 /* At this point, aSample[i] is the first sample that is greater than
2580 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
2581 ** than pVal. If aSample[i]==pVal, then isEq==1.
2583 if( isEq ){
2584 assert( i<pIdx->nSample );
2585 aStat[0] = aSample[i].nLt;
2586 aStat[1] = aSample[i].nEq;
2587 }else{
2588 tRowcnt iLower, iUpper, iGap;
2589 if( i==0 ){
2590 iLower = 0;
2591 iUpper = aSample[0].nLt;
2592 }else{
2593 iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
2594 iLower = aSample[i-1].nEq + aSample[i-1].nLt;
2596 aStat[1] = pIdx->avgEq;
2597 if( iLower>=iUpper ){
2598 iGap = 0;
2599 }else{
2600 iGap = iUpper - iLower;
2602 if( roundUp ){
2603 iGap = (iGap*2)/3;
2604 }else{
2605 iGap = iGap/3;
2607 aStat[0] = iLower + iGap;
2609 return SQLITE_OK;
2611 #endif /* SQLITE_ENABLE_STAT3 */
2614 ** If expression pExpr represents a literal value, set *pp to point to
2615 ** an sqlite3_value structure containing the same value, with affinity
2616 ** aff applied to it, before returning. It is the responsibility of the
2617 ** caller to eventually release this structure by passing it to
2618 ** sqlite3ValueFree().
2620 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
2621 ** is an SQL variable that currently has a non-NULL value bound to it,
2622 ** create an sqlite3_value structure containing this value, again with
2623 ** affinity aff applied to it, instead.
2625 ** If neither of the above apply, set *pp to NULL.
2627 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
2629 #ifdef SQLITE_ENABLE_STAT3
2630 static int valueFromExpr(
2631 Parse *pParse,
2632 Expr *pExpr,
2633 u8 aff,
2634 sqlite3_value **pp
2636 if( pExpr->op==TK_VARIABLE
2637 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
2639 int iVar = pExpr->iColumn;
2640 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
2641 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
2642 return SQLITE_OK;
2644 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
2646 #endif
2649 ** This function is used to estimate the number of rows that will be visited
2650 ** by scanning an index for a range of values. The range may have an upper
2651 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
2652 ** and lower bounds are represented by pLower and pUpper respectively. For
2653 ** example, assuming that index p is on t1(a):
2655 ** ... FROM t1 WHERE a > ? AND a < ? ...
2656 ** |_____| |_____|
2657 ** | |
2658 ** pLower pUpper
2660 ** If either of the upper or lower bound is not present, then NULL is passed in
2661 ** place of the corresponding WhereTerm.
2663 ** The nEq parameter is passed the index of the index column subject to the
2664 ** range constraint. Or, equivalently, the number of equality constraints
2665 ** optimized by the proposed index scan. For example, assuming index p is
2666 ** on t1(a, b), and the SQL query is:
2668 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2670 ** then nEq should be passed the value 1 (as the range restricted column,
2671 ** b, is the second left-most column of the index). Or, if the query is:
2673 ** ... FROM t1 WHERE a > ? AND a < ? ...
2675 ** then nEq should be passed 0.
2677 ** The returned value is an integer divisor to reduce the estimated
2678 ** search space. A return value of 1 means that range constraints are
2679 ** no help at all. A return value of 2 means range constraints are
2680 ** expected to reduce the search space by half. And so forth...
2682 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
2683 ** reduces the search space by a factor of 4. Hence a single constraint (x>?)
2684 ** results in a return of 4 and a range constraint (x>? AND x<?) results
2685 ** in a return of 16.
2687 static int whereRangeScanEst(
2688 Parse *pParse, /* Parsing & code generating context */
2689 Index *p, /* The index containing the range-compared column; "x" */
2690 int nEq, /* index into p->aCol[] of the range-compared column */
2691 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2692 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
2693 double *pRangeDiv /* OUT: Reduce search space by this divisor */
2695 int rc = SQLITE_OK;
2697 #ifdef SQLITE_ENABLE_STAT3
2699 if( nEq==0 && p->nSample ){
2700 sqlite3_value *pRangeVal;
2701 tRowcnt iLower = 0;
2702 tRowcnt iUpper = p->aiRowEst[0];
2703 tRowcnt a[2];
2704 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
2706 if( pLower ){
2707 Expr *pExpr = pLower->pExpr->pRight;
2708 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
2709 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
2710 if( rc==SQLITE_OK
2711 && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
2713 iLower = a[0];
2714 if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
2716 sqlite3ValueFree(pRangeVal);
2718 if( rc==SQLITE_OK && pUpper ){
2719 Expr *pExpr = pUpper->pExpr->pRight;
2720 rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
2721 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
2722 if( rc==SQLITE_OK
2723 && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
2725 iUpper = a[0];
2726 if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
2728 sqlite3ValueFree(pRangeVal);
2730 if( rc==SQLITE_OK ){
2731 if( iUpper<=iLower ){
2732 *pRangeDiv = (double)p->aiRowEst[0];
2733 }else{
2734 *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
2736 WHERETRACE(("range scan regions: %u..%u div=%g\n",
2737 (u32)iLower, (u32)iUpper, *pRangeDiv));
2738 return SQLITE_OK;
2741 #else
2742 UNUSED_PARAMETER(pParse);
2743 UNUSED_PARAMETER(p);
2744 UNUSED_PARAMETER(nEq);
2745 #endif
2746 assert( pLower || pUpper );
2747 *pRangeDiv = (double)1;
2748 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
2749 if( pUpper ) *pRangeDiv *= (double)4;
2750 return rc;
2753 #ifdef SQLITE_ENABLE_STAT3
2755 ** Estimate the number of rows that will be returned based on
2756 ** an equality constraint x=VALUE and where that VALUE occurs in
2757 ** the histogram data. This only works when x is the left-most
2758 ** column of an index and sqlite_stat3 histogram data is available
2759 ** for that index. When pExpr==NULL that means the constraint is
2760 ** "x IS NULL" instead of "x=VALUE".
2762 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2763 ** If unable to make an estimate, leave *pnRow unchanged and return
2764 ** non-zero.
2766 ** This routine can fail if it is unable to load a collating sequence
2767 ** required for string comparison, or if unable to allocate memory
2768 ** for a UTF conversion required for comparison. The error is stored
2769 ** in the pParse structure.
2771 static int whereEqualScanEst(
2772 Parse *pParse, /* Parsing & code generating context */
2773 Index *p, /* The index whose left-most column is pTerm */
2774 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
2775 double *pnRow /* Write the revised row estimate here */
2777 sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
2778 u8 aff; /* Column affinity */
2779 int rc; /* Subfunction return code */
2780 tRowcnt a[2]; /* Statistics */
2782 assert( p->aSample!=0 );
2783 assert( p->nSample>0 );
2784 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
2785 if( pExpr ){
2786 rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
2787 if( rc ) goto whereEqualScanEst_cancel;
2788 }else{
2789 pRhs = sqlite3ValueNew(pParse->db);
2791 if( pRhs==0 ) return SQLITE_NOTFOUND;
2792 rc = whereKeyStats(pParse, p, pRhs, 0, a);
2793 if( rc==SQLITE_OK ){
2794 WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
2795 *pnRow = a[1];
2797 whereEqualScanEst_cancel:
2798 sqlite3ValueFree(pRhs);
2799 return rc;
2801 #endif /* defined(SQLITE_ENABLE_STAT3) */
2803 #ifdef SQLITE_ENABLE_STAT3
2805 ** Estimate the number of rows that will be returned based on
2806 ** an IN constraint where the right-hand side of the IN operator
2807 ** is a list of values. Example:
2809 ** WHERE x IN (1,2,3,4)
2811 ** Write the estimated row count into *pnRow and return SQLITE_OK.
2812 ** If unable to make an estimate, leave *pnRow unchanged and return
2813 ** non-zero.
2815 ** This routine can fail if it is unable to load a collating sequence
2816 ** required for string comparison, or if unable to allocate memory
2817 ** for a UTF conversion required for comparison. The error is stored
2818 ** in the pParse structure.
2820 static int whereInScanEst(
2821 Parse *pParse, /* Parsing & code generating context */
2822 Index *p, /* The index whose left-most column is pTerm */
2823 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
2824 double *pnRow /* Write the revised row estimate here */
2826 int rc = SQLITE_OK; /* Subfunction return code */
2827 double nEst; /* Number of rows for a single term */
2828 double nRowEst = (double)0; /* New estimate of the number of rows */
2829 int i; /* Loop counter */
2831 assert( p->aSample!=0 );
2832 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2833 nEst = p->aiRowEst[0];
2834 rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
2835 nRowEst += nEst;
2837 if( rc==SQLITE_OK ){
2838 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2839 *pnRow = nRowEst;
2840 WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
2842 return rc;
2844 #endif /* defined(SQLITE_ENABLE_STAT3) */
2847 ** Check to see if column iCol of the table with cursor iTab will appear
2848 ** in sorted order according to the current query plan.
2850 ** Return values:
2852 ** 0 iCol is not ordered
2853 ** 1 iCol has only a single value
2854 ** 2 iCol is in ASC order
2855 ** 3 iCol is in DESC order
2857 static int isOrderedColumn(
2858 WhereBestIdx *p,
2859 int iTab,
2860 int iCol
2862 int i, j;
2863 WhereLevel *pLevel = &p->aLevel[p->i-1];
2864 Index *pIdx;
2865 u8 sortOrder;
2866 for(i=p->i-1; i>=0; i--, pLevel--){
2867 if( pLevel->iTabCur!=iTab ) continue;
2868 if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
2869 return 1;
2871 assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
2872 if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
2873 if( iCol<0 ){
2874 sortOrder = 0;
2875 testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
2876 }else{
2877 int n = pIdx->nColumn;
2878 for(j=0; j<n; j++){
2879 if( iCol==pIdx->aiColumn[j] ) break;
2881 if( j>=n ) return 0;
2882 sortOrder = pIdx->aSortOrder[j];
2883 testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
2885 }else{
2886 if( iCol!=(-1) ) return 0;
2887 sortOrder = 0;
2888 testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
2890 if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
2891 assert( sortOrder==0 || sortOrder==1 );
2892 testcase( sortOrder==1 );
2893 sortOrder = 1 - sortOrder;
2895 return sortOrder+2;
2897 return 0;
2901 ** This routine decides if pIdx can be used to satisfy the ORDER BY
2902 ** clause, either in whole or in part. The return value is the
2903 ** cumulative number of terms in the ORDER BY clause that are satisfied
2904 ** by the index pIdx and other indices in outer loops.
2906 ** The table being queried has a cursor number of "base". pIdx is the
2907 ** index that is postulated for use to access the table.
2909 ** The *pbRev value is set to 0 order 1 depending on whether or not
2910 ** pIdx should be run in the forward order or in reverse order.
2912 static int isSortingIndex(
2913 WhereBestIdx *p, /* Best index search context */
2914 Index *pIdx, /* The index we are testing */
2915 int base, /* Cursor number for the table to be sorted */
2916 int *pbRev, /* Set to 1 for reverse-order scan of pIdx */
2917 int *pbObUnique /* ORDER BY column values will different in every row */
2919 int i; /* Number of pIdx terms used */
2920 int j; /* Number of ORDER BY terms satisfied */
2921 int sortOrder = 2; /* 0: forward. 1: backward. 2: unknown */
2922 int nTerm; /* Number of ORDER BY terms */
2923 struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
2924 Table *pTab = pIdx->pTable; /* Table that owns index pIdx */
2925 ExprList *pOrderBy; /* The ORDER BY clause */
2926 Parse *pParse = p->pParse; /* Parser context */
2927 sqlite3 *db = pParse->db; /* Database connection */
2928 int nPriorSat; /* ORDER BY terms satisfied by outer loops */
2929 int seenRowid = 0; /* True if an ORDER BY rowid term is seen */
2930 int uniqueNotNull; /* pIdx is UNIQUE with all terms are NOT NULL */
2931 int outerObUnique; /* Outer loops generate different values in
2932 ** every row for the ORDER BY columns */
2934 if( p->i==0 ){
2935 nPriorSat = 0;
2936 outerObUnique = 1;
2937 }else{
2938 u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
2939 nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
2940 if( (wsFlags & WHERE_ORDERED)==0 ){
2941 /* This loop cannot be ordered unless the next outer loop is
2942 ** also ordered */
2943 return nPriorSat;
2945 if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
2946 /* Only look at the outer-most loop if the OrderByIdxJoin
2947 ** optimization is disabled */
2948 return nPriorSat;
2950 testcase( wsFlags & WHERE_OB_UNIQUE );
2951 testcase( wsFlags & WHERE_ALL_UNIQUE );
2952 outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
2954 pOrderBy = p->pOrderBy;
2955 assert( pOrderBy!=0 );
2956 if( pIdx->bUnordered ){
2957 /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
2958 ** be used for sorting */
2959 return nPriorSat;
2961 nTerm = pOrderBy->nExpr;
2962 uniqueNotNull = pIdx->onError!=OE_None;
2963 assert( nTerm>0 );
2965 /* Argument pIdx must either point to a 'real' named index structure,
2966 ** or an index structure allocated on the stack by bestBtreeIndex() to
2967 ** represent the rowid index that is part of every table. */
2968 assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
2970 /* Match terms of the ORDER BY clause against columns of
2971 ** the index.
2973 ** Note that indices have pIdx->nColumn regular columns plus
2974 ** one additional column containing the rowid. The rowid column
2975 ** of the index is also allowed to match against the ORDER BY
2976 ** clause.
2978 j = nPriorSat;
2979 for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
2980 Expr *pOBExpr; /* The expression of the ORDER BY pOBItem */
2981 CollSeq *pColl; /* The collating sequence of pOBExpr */
2982 int termSortOrder; /* Sort order for this term */
2983 int iColumn; /* The i-th column of the index. -1 for rowid */
2984 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
2985 int isEq; /* Subject to an == or IS NULL constraint */
2986 int isMatch; /* ORDER BY term matches the index term */
2987 const char *zColl; /* Name of collating sequence for i-th index term */
2988 WhereTerm *pConstraint; /* A constraint in the WHERE clause */
2990 /* If the next term of the ORDER BY clause refers to anything other than
2991 ** a column in the "base" table, then this index will not be of any
2992 ** further use in handling the ORDER BY. */
2993 pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
2994 if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
2995 break;
2998 /* Find column number and collating sequence for the next entry
2999 ** in the index */
3000 if( pIdx->zName && i<pIdx->nColumn ){
3001 iColumn = pIdx->aiColumn[i];
3002 if( iColumn==pIdx->pTable->iPKey ){
3003 iColumn = -1;
3005 iSortOrder = pIdx->aSortOrder[i];
3006 zColl = pIdx->azColl[i];
3007 assert( zColl!=0 );
3008 }else{
3009 iColumn = -1;
3010 iSortOrder = 0;
3011 zColl = 0;
3014 /* Check to see if the column number and collating sequence of the
3015 ** index match the column number and collating sequence of the ORDER BY
3016 ** clause entry. Set isMatch to 1 if they both match. */
3017 if( pOBExpr->iColumn==iColumn ){
3018 if( zColl ){
3019 pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
3020 if( !pColl ) pColl = db->pDfltColl;
3021 isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
3022 }else{
3023 isMatch = 1;
3025 }else{
3026 isMatch = 0;
3029 /* termSortOrder is 0 or 1 for whether or not the access loop should
3030 ** run forward or backwards (respectively) in order to satisfy this
3031 ** term of the ORDER BY clause. */
3032 assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
3033 assert( iSortOrder==0 || iSortOrder==1 );
3034 termSortOrder = iSortOrder ^ pOBItem->sortOrder;
3036 /* If X is the column in the index and ORDER BY clause, check to see
3037 ** if there are any X= or X IS NULL constraints in the WHERE clause. */
3038 pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
3039 WO_EQ|WO_ISNULL|WO_IN, pIdx);
3040 if( pConstraint==0 ){
3041 isEq = 0;
3042 }else if( (pConstraint->eOperator & WO_IN)!=0 ){
3043 isEq = 0;
3044 }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
3045 uniqueNotNull = 0;
3046 isEq = 1; /* "X IS NULL" means X has only a single value */
3047 }else if( pConstraint->prereqRight==0 ){
3048 isEq = 1; /* Constraint "X=constant" means X has only a single value */
3049 }else{
3050 Expr *pRight = pConstraint->pExpr->pRight;
3051 if( pRight->op==TK_COLUMN ){
3052 WHERETRACE((" .. isOrderedColumn(tab=%d,col=%d)",
3053 pRight->iTable, pRight->iColumn));
3054 isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
3055 WHERETRACE((" -> isEq=%d\n", isEq));
3057 /* If the constraint is of the form X=Y where Y is an ordered value
3058 ** in an outer loop, then make sure the sort order of Y matches the
3059 ** sort order required for X. */
3060 if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
3061 testcase( isEq==2 );
3062 testcase( isEq==3 );
3063 break;
3065 }else{
3066 isEq = 0; /* "X=expr" places no ordering constraints on X */
3069 if( !isMatch ){
3070 if( isEq==0 ){
3071 break;
3072 }else{
3073 continue;
3075 }else if( isEq!=1 ){
3076 if( sortOrder==2 ){
3077 sortOrder = termSortOrder;
3078 }else if( termSortOrder!=sortOrder ){
3079 break;
3082 j++;
3083 pOBItem++;
3084 if( iColumn<0 ){
3085 seenRowid = 1;
3086 break;
3087 }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
3088 testcase( isEq==0 );
3089 testcase( isEq==2 );
3090 testcase( isEq==3 );
3091 uniqueNotNull = 0;
3094 if( seenRowid ){
3095 uniqueNotNull = 1;
3096 }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
3097 uniqueNotNull = 0;
3100 /* If we have not found at least one ORDER BY term that matches the
3101 ** index, then show no progress. */
3102 if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
3104 /* Either the outer queries must generate rows where there are no two
3105 ** rows with the same values in all ORDER BY columns, or else this
3106 ** loop must generate just a single row of output. Example: Suppose
3107 ** the outer loops generate A=1 and A=1, and this loop generates B=3
3108 ** and B=4. Then without the following test, ORDER BY A,B would
3109 ** generate the wrong order output: 1,3 1,4 1,3 1,4
3111 if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
3112 *pbObUnique = uniqueNotNull;
3114 /* Return the necessary scan order back to the caller */
3115 *pbRev = sortOrder & 1;
3117 /* If there was an "ORDER BY rowid" term that matched, or it is only
3118 ** possible for a single row from this table to match, then skip over
3119 ** any additional ORDER BY terms dealing with this table.
3121 if( uniqueNotNull ){
3122 /* Advance j over additional ORDER BY terms associated with base */
3123 WhereMaskSet *pMS = p->pWC->pMaskSet;
3124 Bitmask m = ~getMask(pMS, base);
3125 while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
3126 j++;
3129 return j;
3133 ** Find the best query plan for accessing a particular table. Write the
3134 ** best query plan and its cost into the p->cost.
3136 ** The lowest cost plan wins. The cost is an estimate of the amount of
3137 ** CPU and disk I/O needed to process the requested result.
3138 ** Factors that influence cost include:
3140 ** * The estimated number of rows that will be retrieved. (The
3141 ** fewer the better.)
3143 ** * Whether or not sorting must occur.
3145 ** * Whether or not there must be separate lookups in the
3146 ** index and in the main table.
3148 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
3149 ** the SQL statement, then this function only considers plans using the
3150 ** named index. If no such plan is found, then the returned cost is
3151 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
3152 ** then the cost is calculated in the usual way.
3154 ** If a NOT INDEXED clause was attached to the table
3155 ** in the SELECT statement, then no indexes are considered. However, the
3156 ** selected plan may still take advantage of the built-in rowid primary key
3157 ** index.
3159 static void bestBtreeIndex(WhereBestIdx *p){
3160 Parse *pParse = p->pParse; /* The parsing context */
3161 WhereClause *pWC = p->pWC; /* The WHERE clause */
3162 struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
3163 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
3164 Index *pProbe; /* An index we are evaluating */
3165 Index *pIdx; /* Copy of pProbe, or zero for IPK index */
3166 int eqTermMask; /* Current mask of valid equality operators */
3167 int idxEqTermMask; /* Index mask of valid equality operators */
3168 Index sPk; /* A fake index object for the primary key */
3169 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
3170 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
3171 int wsFlagMask; /* Allowed flags in p->cost.plan.wsFlag */
3172 int nPriorSat; /* ORDER BY terms satisfied by outer loops */
3173 int nOrderBy; /* Number of ORDER BY terms */
3174 char bSortInit; /* Initializer for bSort in inner loop */
3175 char bDistInit; /* Initializer for bDist in inner loop */
3178 /* Initialize the cost to a worst-case value */
3179 memset(&p->cost, 0, sizeof(p->cost));
3180 p->cost.rCost = SQLITE_BIG_DBL;
3182 /* If the pSrc table is the right table of a LEFT JOIN then we may not
3183 ** use an index to satisfy IS NULL constraints on that table. This is
3184 ** because columns might end up being NULL if the table does not match -
3185 ** a circumstance which the index cannot help us discover. Ticket #2177.
3187 if( pSrc->jointype & JT_LEFT ){
3188 idxEqTermMask = WO_EQ|WO_IN;
3189 }else{
3190 idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
3193 if( pSrc->pIndex ){
3194 /* An INDEXED BY clause specifies a particular index to use */
3195 pIdx = pProbe = pSrc->pIndex;
3196 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
3197 eqTermMask = idxEqTermMask;
3198 }else{
3199 /* There is no INDEXED BY clause. Create a fake Index object in local
3200 ** variable sPk to represent the rowid primary key index. Make this
3201 ** fake index the first in a chain of Index objects with all of the real
3202 ** indices to follow */
3203 Index *pFirst; /* First of real indices on the table */
3204 memset(&sPk, 0, sizeof(Index));
3205 sPk.nColumn = 1;
3206 sPk.aiColumn = &aiColumnPk;
3207 sPk.aiRowEst = aiRowEstPk;
3208 sPk.onError = OE_Replace;
3209 sPk.pTable = pSrc->pTab;
3210 aiRowEstPk[0] = pSrc->pTab->nRowEst;
3211 aiRowEstPk[1] = 1;
3212 pFirst = pSrc->pTab->pIndex;
3213 if( pSrc->notIndexed==0 ){
3214 /* The real indices of the table are only considered if the
3215 ** NOT INDEXED qualifier is omitted from the FROM clause */
3216 sPk.pNext = pFirst;
3218 pProbe = &sPk;
3219 wsFlagMask = ~(
3220 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
3222 eqTermMask = WO_EQ|WO_IN;
3223 pIdx = 0;
3226 nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
3227 if( p->i ){
3228 nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
3229 bSortInit = nPriorSat<nOrderBy;
3230 bDistInit = 0;
3231 }else{
3232 nPriorSat = 0;
3233 bSortInit = nOrderBy>0;
3234 bDistInit = p->pDistinct!=0;
3237 /* Loop over all indices looking for the best one to use
3239 for(; pProbe; pIdx=pProbe=pProbe->pNext){
3240 const tRowcnt * const aiRowEst = pProbe->aiRowEst;
3241 WhereCost pc; /* Cost of using pProbe */
3242 double log10N = (double)1; /* base-10 logarithm of nRow (inexact) */
3244 /* The following variables are populated based on the properties of
3245 ** index being evaluated. They are then used to determine the expected
3246 ** cost and number of rows returned.
3248 ** pc.plan.nEq:
3249 ** Number of equality terms that can be implemented using the index.
3250 ** In other words, the number of initial fields in the index that
3251 ** are used in == or IN or NOT NULL constraints of the WHERE clause.
3253 ** nInMul:
3254 ** The "in-multiplier". This is an estimate of how many seek operations
3255 ** SQLite must perform on the index in question. For example, if the
3256 ** WHERE clause is:
3258 ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
3260 ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
3261 ** set to 9. Given the same schema and either of the following WHERE
3262 ** clauses:
3264 ** WHERE a = 1
3265 ** WHERE a >= 2
3267 ** nInMul is set to 1.
3269 ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
3270 ** the sub-select is assumed to return 25 rows for the purposes of
3271 ** determining nInMul.
3273 ** bInEst:
3274 ** Set to true if there was at least one "x IN (SELECT ...)" term used
3275 ** in determining the value of nInMul. Note that the RHS of the
3276 ** IN operator must be a SELECT, not a value list, for this variable
3277 ** to be true.
3279 ** rangeDiv:
3280 ** An estimate of a divisor by which to reduce the search space due
3281 ** to inequality constraints. In the absence of sqlite_stat3 ANALYZE
3282 ** data, a single inequality reduces the search space to 1/4rd its
3283 ** original size (rangeDiv==4). Two inequalities reduce the search
3284 ** space to 1/16th of its original size (rangeDiv==16).
3286 ** bSort:
3287 ** Boolean. True if there is an ORDER BY clause that will require an
3288 ** external sort (i.e. scanning the index being evaluated will not
3289 ** correctly order records).
3291 ** bDist:
3292 ** Boolean. True if there is a DISTINCT clause that will require an
3293 ** external btree.
3295 ** bLookup:
3296 ** Boolean. True if a table lookup is required for each index entry
3297 ** visited. In other words, true if this is not a covering index.
3298 ** This is always false for the rowid primary key index of a table.
3299 ** For other indexes, it is true unless all the columns of the table
3300 ** used by the SELECT statement are present in the index (such an
3301 ** index is sometimes described as a covering index).
3302 ** For example, given the index on (a, b), the second of the following
3303 ** two queries requires table b-tree lookups in order to find the value
3304 ** of column c, but the first does not because columns a and b are
3305 ** both available in the index.
3307 ** SELECT a, b FROM tbl WHERE a = 1;
3308 ** SELECT a, b, c FROM tbl WHERE a = 1;
3310 int bInEst = 0; /* True if "x IN (SELECT...)" seen */
3311 int nInMul = 1; /* Number of distinct equalities to lookup */
3312 double rangeDiv = (double)1; /* Estimated reduction in search space */
3313 int nBound = 0; /* Number of range constraints seen */
3314 char bSort = bSortInit; /* True if external sort required */
3315 char bDist = bDistInit; /* True if index cannot help with DISTINCT */
3316 char bLookup = 0; /* True if not a covering index */
3317 WhereTerm *pTerm; /* A single term of the WHERE clause */
3318 #ifdef SQLITE_ENABLE_STAT3
3319 WhereTerm *pFirstTerm = 0; /* First term matching the index */
3320 #endif
3322 WHERETRACE((
3323 " %s(%s):\n",
3324 pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
3326 memset(&pc, 0, sizeof(pc));
3327 pc.plan.nOBSat = nPriorSat;
3329 /* Determine the values of pc.plan.nEq and nInMul */
3330 for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
3331 int j = pProbe->aiColumn[pc.plan.nEq];
3332 pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
3333 if( pTerm==0 ) break;
3334 pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
3335 testcase( pTerm->pWC!=pWC );
3336 if( pTerm->eOperator & WO_IN ){
3337 Expr *pExpr = pTerm->pExpr;
3338 pc.plan.wsFlags |= WHERE_COLUMN_IN;
3339 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
3340 /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
3341 nInMul *= 25;
3342 bInEst = 1;
3343 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
3344 /* "x IN (value, value, ...)" */
3345 nInMul *= pExpr->x.pList->nExpr;
3347 }else if( pTerm->eOperator & WO_ISNULL ){
3348 pc.plan.wsFlags |= WHERE_COLUMN_NULL;
3350 #ifdef SQLITE_ENABLE_STAT3
3351 if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
3352 #endif
3353 pc.used |= pTerm->prereqRight;
3356 /* If the index being considered is UNIQUE, and there is an equality
3357 ** constraint for all columns in the index, then this search will find
3358 ** at most a single row. In this case set the WHERE_UNIQUE flag to
3359 ** indicate this to the caller.
3361 ** Otherwise, if the search may find more than one row, test to see if
3362 ** there is a range constraint on indexed column (pc.plan.nEq+1) that
3363 ** can be optimized using the index.
3365 if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
3366 testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
3367 testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
3368 if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
3369 pc.plan.wsFlags |= WHERE_UNIQUE;
3370 if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
3371 pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
3374 }else if( pProbe->bUnordered==0 ){
3375 int j;
3376 j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
3377 if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
3378 WhereTerm *pTop, *pBtm;
3379 pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
3380 pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
3381 whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
3382 if( pTop ){
3383 nBound = 1;
3384 pc.plan.wsFlags |= WHERE_TOP_LIMIT;
3385 pc.used |= pTop->prereqRight;
3386 testcase( pTop->pWC!=pWC );
3388 if( pBtm ){
3389 nBound++;
3390 pc.plan.wsFlags |= WHERE_BTM_LIMIT;
3391 pc.used |= pBtm->prereqRight;
3392 testcase( pBtm->pWC!=pWC );
3394 pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
3398 /* If there is an ORDER BY clause and the index being considered will
3399 ** naturally scan rows in the required order, set the appropriate flags
3400 ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
3401 ** the index will scan rows in a different order, set the bSort
3402 ** variable. */
3403 if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
3404 int bRev = 2;
3405 int bObUnique = 0;
3406 WHERETRACE((" --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
3407 pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
3408 WHERETRACE((" --> after isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
3409 bRev, bObUnique, pc.plan.nOBSat));
3410 if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
3411 pc.plan.wsFlags |= WHERE_ORDERED;
3412 if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
3414 if( nOrderBy==pc.plan.nOBSat ){
3415 bSort = 0;
3416 pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
3418 if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
3421 /* If there is a DISTINCT qualifier and this index will scan rows in
3422 ** order of the DISTINCT expressions, clear bDist and set the appropriate
3423 ** flags in pc.plan.wsFlags. */
3424 if( bDist
3425 && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
3426 && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
3428 bDist = 0;
3429 pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
3432 /* If currently calculating the cost of using an index (not the IPK
3433 ** index), determine if all required column data may be obtained without
3434 ** using the main table (i.e. if the index is a covering
3435 ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
3436 ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true. */
3437 if( pIdx ){
3438 Bitmask m = pSrc->colUsed;
3439 int j;
3440 for(j=0; j<pIdx->nColumn; j++){
3441 int x = pIdx->aiColumn[j];
3442 if( x<BMS-1 ){
3443 m &= ~(((Bitmask)1)<<x);
3446 if( m==0 ){
3447 pc.plan.wsFlags |= WHERE_IDX_ONLY;
3448 }else{
3449 bLookup = 1;
3454 ** Estimate the number of rows of output. For an "x IN (SELECT...)"
3455 ** constraint, do not let the estimate exceed half the rows in the table.
3457 pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
3458 if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
3459 pc.plan.nRow = aiRowEst[0]/2;
3460 nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
3463 #ifdef SQLITE_ENABLE_STAT3
3464 /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
3465 ** and we do not think that values of x are unique and if histogram
3466 ** data is available for column x, then it might be possible
3467 ** to get a better estimate on the number of rows based on
3468 ** VALUE and how common that value is according to the histogram.
3470 if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
3471 && pFirstTerm!=0 && aiRowEst[1]>1 ){
3472 assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
3473 if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
3474 testcase( pFirstTerm->eOperator & WO_EQ );
3475 testcase( pFirstTerm->eOperator & WO_EQUIV );
3476 testcase( pFirstTerm->eOperator & WO_ISNULL );
3477 whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
3478 &pc.plan.nRow);
3479 }else if( bInEst==0 ){
3480 assert( pFirstTerm->eOperator & WO_IN );
3481 whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
3482 &pc.plan.nRow);
3485 #endif /* SQLITE_ENABLE_STAT3 */
3487 /* Adjust the number of output rows and downward to reflect rows
3488 ** that are excluded by range constraints.
3490 pc.plan.nRow = pc.plan.nRow/rangeDiv;
3491 if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
3493 /* Experiments run on real SQLite databases show that the time needed
3494 ** to do a binary search to locate a row in a table or index is roughly
3495 ** log10(N) times the time to move from one row to the next row within
3496 ** a table or index. The actual times can vary, with the size of
3497 ** records being an important factor. Both moves and searches are
3498 ** slower with larger records, presumably because fewer records fit
3499 ** on one page and hence more pages have to be fetched.
3501 ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
3502 ** not give us data on the relative sizes of table and index records.
3503 ** So this computation assumes table records are about twice as big
3504 ** as index records
3506 if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
3507 ==WHERE_IDX_ONLY
3508 && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3509 && sqlite3GlobalConfig.bUseCis
3510 && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
3512 /* This index is not useful for indexing, but it is a covering index.
3513 ** A full-scan of the index might be a little faster than a full-scan
3514 ** of the table, so give this case a cost slightly less than a table
3515 ** scan. */
3516 pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
3517 pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
3518 }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
3519 /* The cost of a full table scan is a number of move operations equal
3520 ** to the number of rows in the table.
3522 ** We add an additional 4x penalty to full table scans. This causes
3523 ** the cost function to err on the side of choosing an index over
3524 ** choosing a full scan. This 4x full-scan penalty is an arguable
3525 ** decision and one which we expect to revisit in the future. But
3526 ** it seems to be working well enough at the moment.
3528 pc.rCost = aiRowEst[0]*4;
3529 pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
3530 if( pIdx ){
3531 pc.plan.wsFlags &= ~WHERE_ORDERED;
3532 pc.plan.nOBSat = nPriorSat;
3534 }else{
3535 log10N = estLog(aiRowEst[0]);
3536 pc.rCost = pc.plan.nRow;
3537 if( pIdx ){
3538 if( bLookup ){
3539 /* For an index lookup followed by a table lookup:
3540 ** nInMul index searches to find the start of each index range
3541 ** + nRow steps through the index
3542 ** + nRow table searches to lookup the table entry using the rowid
3544 pc.rCost += (nInMul + pc.plan.nRow)*log10N;
3545 }else{
3546 /* For a covering index:
3547 ** nInMul index searches to find the initial entry
3548 ** + nRow steps through the index
3550 pc.rCost += nInMul*log10N;
3552 }else{
3553 /* For a rowid primary key lookup:
3554 ** nInMult table searches to find the initial entry for each range
3555 ** + nRow steps through the table
3557 pc.rCost += nInMul*log10N;
3561 /* Add in the estimated cost of sorting the result. Actual experimental
3562 ** measurements of sorting performance in SQLite show that sorting time
3563 ** adds C*N*log10(N) to the cost, where N is the number of rows to be
3564 ** sorted and C is a factor between 1.95 and 4.3. We will split the
3565 ** difference and select C of 3.0.
3567 if( bSort ){
3568 double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
3569 m *= (double)(pc.plan.nOBSat ? 2 : 3);
3570 pc.rCost += pc.plan.nRow*m;
3572 if( bDist ){
3573 pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
3576 /**** Cost of using this index has now been computed ****/
3578 /* If there are additional constraints on this table that cannot
3579 ** be used with the current index, but which might lower the number
3580 ** of output rows, adjust the nRow value accordingly. This only
3581 ** matters if the current index is the least costly, so do not bother
3582 ** with this step if we already know this index will not be chosen.
3583 ** Also, never reduce the output row count below 2 using this step.
3585 ** It is critical that the notValid mask be used here instead of
3586 ** the notReady mask. When computing an "optimal" index, the notReady
3587 ** mask will only have one bit set - the bit for the current table.
3588 ** The notValid mask, on the other hand, always has all bits set for
3589 ** tables that are not in outer loops. If notReady is used here instead
3590 ** of notValid, then a optimal index that depends on inner joins loops
3591 ** might be selected even when there exists an optimal index that has
3592 ** no such dependency.
3594 if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
3595 int k; /* Loop counter */
3596 int nSkipEq = pc.plan.nEq; /* Number of == constraints to skip */
3597 int nSkipRange = nBound; /* Number of < constraints to skip */
3598 Bitmask thisTab; /* Bitmap for pSrc */
3600 thisTab = getMask(pWC->pMaskSet, iCur);
3601 for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
3602 if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
3603 if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
3604 if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
3605 if( nSkipEq ){
3606 /* Ignore the first pc.plan.nEq equality matches since the index
3607 ** has already accounted for these */
3608 nSkipEq--;
3609 }else{
3610 /* Assume each additional equality match reduces the result
3611 ** set size by a factor of 10 */
3612 pc.plan.nRow /= 10;
3614 }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
3615 if( nSkipRange ){
3616 /* Ignore the first nSkipRange range constraints since the index
3617 ** has already accounted for these */
3618 nSkipRange--;
3619 }else{
3620 /* Assume each additional range constraint reduces the result
3621 ** set size by a factor of 3. Indexed range constraints reduce
3622 ** the search space by a larger factor: 4. We make indexed range
3623 ** more selective intentionally because of the subjective
3624 ** observation that indexed range constraints really are more
3625 ** selective in practice, on average. */
3626 pc.plan.nRow /= 3;
3628 }else if( (pTerm->eOperator & WO_NOOP)==0 ){
3629 /* Any other expression lowers the output row count by half */
3630 pc.plan.nRow /= 2;
3633 if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
3637 WHERETRACE((
3638 " nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
3639 " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
3640 " used=0x%llx nOBSat=%d\n",
3641 pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
3642 p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
3643 pc.plan.nOBSat
3646 /* If this index is the best we have seen so far, then record this
3647 ** index and its cost in the p->cost structure.
3649 if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
3650 p->cost = pc;
3651 p->cost.plan.wsFlags &= wsFlagMask;
3652 p->cost.plan.u.pIdx = pIdx;
3655 /* If there was an INDEXED BY clause, then only that one index is
3656 ** considered. */
3657 if( pSrc->pIndex ) break;
3659 /* Reset masks for the next index in the loop */
3660 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
3661 eqTermMask = idxEqTermMask;
3664 /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
3665 ** is set, then reverse the order that the index will be scanned
3666 ** in. This is used for application testing, to help find cases
3667 ** where application behavior depends on the (undefined) order that
3668 ** SQLite outputs rows in in the absence of an ORDER BY clause. */
3669 if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
3670 p->cost.plan.wsFlags |= WHERE_REVERSE;
3673 assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
3674 assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
3675 assert( pSrc->pIndex==0
3676 || p->cost.plan.u.pIdx==0
3677 || p->cost.plan.u.pIdx==pSrc->pIndex
3680 WHERETRACE((" best index is %s cost=%.1f\n",
3681 p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
3682 p->cost.rCost));
3684 bestOrClauseIndex(p);
3685 bestAutomaticIndex(p);
3686 p->cost.plan.wsFlags |= eqTermMask;
3690 ** Find the query plan for accessing table pSrc->pTab. Write the
3691 ** best query plan and its cost into the WhereCost object supplied
3692 ** as the last parameter. This function may calculate the cost of
3693 ** both real and virtual table scans.
3695 ** This function does not take ORDER BY or DISTINCT into account. Nor
3696 ** does it remember the virtual table query plan. All it does is compute
3697 ** the cost while determining if an OR optimization is applicable. The
3698 ** details will be reconsidered later if the optimization is found to be
3699 ** applicable.
3701 static void bestIndex(WhereBestIdx *p){
3702 #ifndef SQLITE_OMIT_VIRTUALTABLE
3703 if( IsVirtual(p->pSrc->pTab) ){
3704 sqlite3_index_info *pIdxInfo = 0;
3705 p->ppIdxInfo = &pIdxInfo;
3706 bestVirtualIndex(p);
3707 assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
3708 if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
3709 sqlite3_free(pIdxInfo->idxStr);
3711 sqlite3DbFree(p->pParse->db, pIdxInfo);
3712 }else
3713 #endif
3715 bestBtreeIndex(p);
3720 ** Disable a term in the WHERE clause. Except, do not disable the term
3721 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
3722 ** or USING clause of that join.
3724 ** Consider the term t2.z='ok' in the following queries:
3726 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
3727 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
3728 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
3730 ** The t2.z='ok' is disabled in the in (2) because it originates
3731 ** in the ON clause. The term is disabled in (3) because it is not part
3732 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
3734 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
3735 ** completely satisfied by indices.
3737 ** Disabling a term causes that term to not be tested in the inner loop
3738 ** of the join. Disabling is an optimization. When terms are satisfied
3739 ** by indices, we disable them to prevent redundant tests in the inner
3740 ** loop. We would get the correct results if nothing were ever disabled,
3741 ** but joins might run a little slower. The trick is to disable as much
3742 ** as we can without disabling too much. If we disabled in (1), we'd get
3743 ** the wrong answer. See ticket #813.
3745 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
3746 if( pTerm
3747 && (pTerm->wtFlags & TERM_CODED)==0
3748 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
3750 pTerm->wtFlags |= TERM_CODED;
3751 if( pTerm->iParent>=0 ){
3752 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
3753 if( (--pOther->nChild)==0 ){
3754 disableTerm(pLevel, pOther);
3761 ** Code an OP_Affinity opcode to apply the column affinity string zAff
3762 ** to the n registers starting at base.
3764 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
3765 ** beginning and end of zAff are ignored. If all entries in zAff are
3766 ** SQLITE_AFF_NONE, then no code gets generated.
3768 ** This routine makes its own copy of zAff so that the caller is free
3769 ** to modify zAff after this routine returns.
3771 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
3772 Vdbe *v = pParse->pVdbe;
3773 if( zAff==0 ){
3774 assert( pParse->db->mallocFailed );
3775 return;
3777 assert( v!=0 );
3779 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
3780 ** and end of the affinity string.
3782 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
3783 n--;
3784 base++;
3785 zAff++;
3787 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
3788 n--;
3791 /* Code the OP_Affinity opcode if there is anything left to do. */
3792 if( n>0 ){
3793 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
3794 sqlite3VdbeChangeP4(v, -1, zAff, n);
3795 sqlite3ExprCacheAffinityChange(pParse, base, n);
3801 ** Generate code for a single equality term of the WHERE clause. An equality
3802 ** term can be either X=expr or X IN (...). pTerm is the term to be
3803 ** coded.
3805 ** The current value for the constraint is left in register iReg.
3807 ** For a constraint of the form X=expr, the expression is evaluated and its
3808 ** result is left on the stack. For constraints of the form X IN (...)
3809 ** this routine sets up a loop that will iterate over all values of X.
3811 static int codeEqualityTerm(
3812 Parse *pParse, /* The parsing context */
3813 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
3814 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
3815 int iEq, /* Index of the equality term within this level */
3816 int iTarget /* Attempt to leave results in this register */
3818 Expr *pX = pTerm->pExpr;
3819 Vdbe *v = pParse->pVdbe;
3820 int iReg; /* Register holding results */
3822 assert( iTarget>0 );
3823 if( pX->op==TK_EQ ){
3824 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
3825 }else if( pX->op==TK_ISNULL ){
3826 iReg = iTarget;
3827 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
3828 #ifndef SQLITE_OMIT_SUBQUERY
3829 }else{
3830 int eType;
3831 int iTab;
3832 struct InLoop *pIn;
3833 u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
3835 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0
3836 && pLevel->plan.u.pIdx->aSortOrder[iEq]
3838 testcase( iEq==0 );
3839 testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
3840 testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
3841 testcase( bRev );
3842 bRev = !bRev;
3844 assert( pX->op==TK_IN );
3845 iReg = iTarget;
3846 eType = sqlite3FindInIndex(pParse, pX, 0);
3847 if( eType==IN_INDEX_INDEX_DESC ){
3848 testcase( bRev );
3849 bRev = !bRev;
3851 iTab = pX->iTable;
3852 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
3853 assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
3854 if( pLevel->u.in.nIn==0 ){
3855 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3857 pLevel->u.in.nIn++;
3858 pLevel->u.in.aInLoop =
3859 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
3860 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
3861 pIn = pLevel->u.in.aInLoop;
3862 if( pIn ){
3863 pIn += pLevel->u.in.nIn - 1;
3864 pIn->iCur = iTab;
3865 if( eType==IN_INDEX_ROWID ){
3866 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
3867 }else{
3868 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
3870 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
3871 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
3872 }else{
3873 pLevel->u.in.nIn = 0;
3875 #endif
3877 disableTerm(pLevel, pTerm);
3878 return iReg;
3882 ** Generate code that will evaluate all == and IN constraints for an
3883 ** index.
3885 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
3886 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
3887 ** The index has as many as three equality constraints, but in this
3888 ** example, the third "c" value is an inequality. So only two
3889 ** constraints are coded. This routine will generate code to evaluate
3890 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
3891 ** in consecutive registers and the index of the first register is returned.
3893 ** In the example above nEq==2. But this subroutine works for any value
3894 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
3895 ** The only thing it does is allocate the pLevel->iMem memory cell and
3896 ** compute the affinity string.
3898 ** This routine always allocates at least one memory cell and returns
3899 ** the index of that memory cell. The code that
3900 ** calls this routine will use that memory cell to store the termination
3901 ** key value of the loop. If one or more IN operators appear, then
3902 ** this routine allocates an additional nEq memory cells for internal
3903 ** use.
3905 ** Before returning, *pzAff is set to point to a buffer containing a
3906 ** copy of the column affinity string of the index allocated using
3907 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
3908 ** with equality constraints that use NONE affinity are set to
3909 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
3911 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
3912 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
3914 ** In the example above, the index on t1(a) has TEXT affinity. But since
3915 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
3916 ** no conversion should be attempted before using a t2.b value as part of
3917 ** a key to search the index. Hence the first byte in the returned affinity
3918 ** string in this example would be set to SQLITE_AFF_NONE.
3920 static int codeAllEqualityTerms(
3921 Parse *pParse, /* Parsing context */
3922 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
3923 WhereClause *pWC, /* The WHERE clause */
3924 Bitmask notReady, /* Which parts of FROM have not yet been coded */
3925 int nExtraReg, /* Number of extra registers to allocate */
3926 char **pzAff /* OUT: Set to point to affinity string */
3928 int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
3929 Vdbe *v = pParse->pVdbe; /* The vm under construction */
3930 Index *pIdx; /* The index being used for this loop */
3931 int iCur = pLevel->iTabCur; /* The cursor of the table */
3932 WhereTerm *pTerm; /* A single constraint term */
3933 int j; /* Loop counter */
3934 int regBase; /* Base register */
3935 int nReg; /* Number of registers to allocate */
3936 char *zAff; /* Affinity string to return */
3938 /* This module is only called on query plans that use an index. */
3939 assert( pLevel->plan.wsFlags & WHERE_INDEXED );
3940 pIdx = pLevel->plan.u.pIdx;
3942 /* Figure out how many memory cells we will need then allocate them.
3944 regBase = pParse->nMem + 1;
3945 nReg = pLevel->plan.nEq + nExtraReg;
3946 pParse->nMem += nReg;
3948 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
3949 if( !zAff ){
3950 pParse->db->mallocFailed = 1;
3953 /* Evaluate the equality constraints
3955 assert( pIdx->nColumn>=nEq );
3956 for(j=0; j<nEq; j++){
3957 int r1;
3958 int k = pIdx->aiColumn[j];
3959 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
3960 if( pTerm==0 ) break;
3961 /* The following true for indices with redundant columns.
3962 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
3963 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
3964 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
3965 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
3966 if( r1!=regBase+j ){
3967 if( nReg==1 ){
3968 sqlite3ReleaseTempReg(pParse, regBase);
3969 regBase = r1;
3970 }else{
3971 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
3974 testcase( pTerm->eOperator & WO_ISNULL );
3975 testcase( pTerm->eOperator & WO_IN );
3976 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
3977 Expr *pRight = pTerm->pExpr->pRight;
3978 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
3979 if( zAff ){
3980 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
3981 zAff[j] = SQLITE_AFF_NONE;
3983 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
3984 zAff[j] = SQLITE_AFF_NONE;
3989 *pzAff = zAff;
3990 return regBase;
3993 #ifndef SQLITE_OMIT_EXPLAIN
3995 ** This routine is a helper for explainIndexRange() below
3997 ** pStr holds the text of an expression that we are building up one term
3998 ** at a time. This routine adds a new term to the end of the expression.
3999 ** Terms are separated by AND so add the "AND" text for second and subsequent
4000 ** terms only.
4002 static void explainAppendTerm(
4003 StrAccum *pStr, /* The text expression being built */
4004 int iTerm, /* Index of this term. First is zero */
4005 const char *zColumn, /* Name of the column */
4006 const char *zOp /* Name of the operator */
4008 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
4009 sqlite3StrAccumAppend(pStr, zColumn, -1);
4010 sqlite3StrAccumAppend(pStr, zOp, 1);
4011 sqlite3StrAccumAppend(pStr, "?", 1);
4015 ** Argument pLevel describes a strategy for scanning table pTab. This
4016 ** function returns a pointer to a string buffer containing a description
4017 ** of the subset of table rows scanned by the strategy in the form of an
4018 ** SQL expression. Or, if all rows are scanned, NULL is returned.
4020 ** For example, if the query:
4022 ** SELECT * FROM t1 WHERE a=1 AND b>2;
4024 ** is run and there is an index on (a, b), then this function returns a
4025 ** string similar to:
4027 ** "a=? AND b>?"
4029 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
4030 ** It is the responsibility of the caller to free the buffer when it is
4031 ** no longer required.
4033 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
4034 WherePlan *pPlan = &pLevel->plan;
4035 Index *pIndex = pPlan->u.pIdx;
4036 int nEq = pPlan->nEq;
4037 int i, j;
4038 Column *aCol = pTab->aCol;
4039 int *aiColumn = pIndex->aiColumn;
4040 StrAccum txt;
4042 if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
4043 return 0;
4045 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
4046 txt.db = db;
4047 sqlite3StrAccumAppend(&txt, " (", 2);
4048 for(i=0; i<nEq; i++){
4049 explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
4052 j = i;
4053 if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
4054 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
4055 explainAppendTerm(&txt, i++, z, ">");
4057 if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
4058 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
4059 explainAppendTerm(&txt, i, z, "<");
4061 sqlite3StrAccumAppend(&txt, ")", 1);
4062 return sqlite3StrAccumFinish(&txt);
4066 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
4067 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
4068 ** record is added to the output to describe the table scan strategy in
4069 ** pLevel.
4071 static void explainOneScan(
4072 Parse *pParse, /* Parse context */
4073 SrcList *pTabList, /* Table list this loop refers to */
4074 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
4075 int iLevel, /* Value for "level" column of output */
4076 int iFrom, /* Value for "from" column of output */
4077 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
4079 if( pParse->explain==2 ){
4080 u32 flags = pLevel->plan.wsFlags;
4081 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
4082 Vdbe *v = pParse->pVdbe; /* VM being constructed */
4083 sqlite3 *db = pParse->db; /* Database handle */
4084 char *zMsg; /* Text to add to EQP output */
4085 sqlite3_int64 nRow; /* Expected number of rows visited by scan */
4086 int iId = pParse->iSelectId; /* Select id (left-most output column) */
4087 int isSearch; /* True for a SEARCH. False for SCAN. */
4089 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
4091 isSearch = (pLevel->plan.nEq>0)
4092 || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
4093 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
4095 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
4096 if( pItem->pSelect ){
4097 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
4098 }else{
4099 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
4102 if( pItem->zAlias ){
4103 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
4105 if( (flags & WHERE_INDEXED)!=0 ){
4106 char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
4107 zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
4108 ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
4109 ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
4110 ((flags & WHERE_TEMP_INDEX)?"":" "),
4111 ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
4112 zWhere
4114 sqlite3DbFree(db, zWhere);
4115 }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
4116 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
4118 if( flags&WHERE_ROWID_EQ ){
4119 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
4120 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
4121 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
4122 }else if( flags&WHERE_BTM_LIMIT ){
4123 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
4124 }else if( flags&WHERE_TOP_LIMIT ){
4125 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
4128 #ifndef SQLITE_OMIT_VIRTUALTABLE
4129 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
4130 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
4131 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
4132 pVtabIdx->idxNum, pVtabIdx->idxStr);
4134 #endif
4135 if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
4136 testcase( wctrlFlags & WHERE_ORDERBY_MIN );
4137 nRow = 1;
4138 }else{
4139 nRow = (sqlite3_int64)pLevel->plan.nRow;
4141 zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
4142 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
4145 #else
4146 # define explainOneScan(u,v,w,x,y,z)
4147 #endif /* SQLITE_OMIT_EXPLAIN */
4151 ** Generate code for the start of the iLevel-th loop in the WHERE clause
4152 ** implementation described by pWInfo.
4154 static Bitmask codeOneLoopStart(
4155 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
4156 int iLevel, /* Which level of pWInfo->a[] should be coded */
4157 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
4158 Bitmask notReady /* Which tables are currently available */
4160 int j, k; /* Loop counters */
4161 int iCur; /* The VDBE cursor for the table */
4162 int addrNxt; /* Where to jump to continue with the next IN case */
4163 int omitTable; /* True if we use the index only */
4164 int bRev; /* True if we need to scan in reverse order */
4165 WhereLevel *pLevel; /* The where level to be coded */
4166 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
4167 WhereTerm *pTerm; /* A WHERE clause term */
4168 Parse *pParse; /* Parsing context */
4169 Vdbe *v; /* The prepared stmt under constructions */
4170 struct SrcList_item *pTabItem; /* FROM clause term being coded */
4171 int addrBrk; /* Jump here to break out of the loop */
4172 int addrCont; /* Jump here to continue with next cycle */
4173 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
4174 int iReleaseReg = 0; /* Temp register to free before returning */
4175 Bitmask newNotReady; /* Return value */
4177 pParse = pWInfo->pParse;
4178 v = pParse->pVdbe;
4179 pWC = pWInfo->pWC;
4180 pLevel = &pWInfo->a[iLevel];
4181 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
4182 iCur = pTabItem->iCursor;
4183 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
4184 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
4185 && (wctrlFlags & WHERE_FORCE_TABLE)==0;
4186 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
4188 /* Create labels for the "break" and "continue" instructions
4189 ** for the current loop. Jump to addrBrk to break out of a loop.
4190 ** Jump to cont to go immediately to the next iteration of the
4191 ** loop.
4193 ** When there is an IN operator, we also have a "addrNxt" label that
4194 ** means to continue with the next IN value combination. When
4195 ** there are no IN operators in the constraints, the "addrNxt" label
4196 ** is the same as "addrBrk".
4198 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
4199 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
4201 /* If this is the right table of a LEFT OUTER JOIN, allocate and
4202 ** initialize a memory cell that records if this table matches any
4203 ** row of the left table of the join.
4205 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
4206 pLevel->iLeftJoin = ++pParse->nMem;
4207 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
4208 VdbeComment((v, "init LEFT JOIN no-match flag"));
4211 /* Special case of a FROM clause subquery implemented as a co-routine */
4212 if( pTabItem->viaCoroutine ){
4213 int regYield = pTabItem->regReturn;
4214 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
4215 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
4216 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
4217 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
4218 pLevel->op = OP_Goto;
4219 }else
4221 #ifndef SQLITE_OMIT_VIRTUALTABLE
4222 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
4223 /* Case 0: The table is a virtual-table. Use the VFilter and VNext
4224 ** to access the data.
4226 int iReg; /* P3 Value for OP_VFilter */
4227 int addrNotFound;
4228 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
4229 int nConstraint = pVtabIdx->nConstraint;
4230 struct sqlite3_index_constraint_usage *aUsage =
4231 pVtabIdx->aConstraintUsage;
4232 const struct sqlite3_index_constraint *aConstraint =
4233 pVtabIdx->aConstraint;
4235 sqlite3ExprCachePush(pParse);
4236 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
4237 addrNotFound = pLevel->addrBrk;
4238 for(j=1; j<=nConstraint; j++){
4239 for(k=0; k<nConstraint; k++){
4240 if( aUsage[k].argvIndex==j ){
4241 int iTarget = iReg+j+1;
4242 pTerm = &pWC->a[aConstraint[k].iTermOffset];
4243 if( pTerm->eOperator & WO_IN ){
4244 codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
4245 addrNotFound = pLevel->addrNxt;
4246 }else{
4247 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
4249 break;
4252 if( k==nConstraint ) break;
4254 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
4255 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
4256 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
4257 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
4258 pVtabIdx->needToFreeIdxStr = 0;
4259 for(j=0; j<nConstraint; j++){
4260 if( aUsage[j].omit ){
4261 int iTerm = aConstraint[j].iTermOffset;
4262 disableTerm(pLevel, &pWC->a[iTerm]);
4265 pLevel->op = OP_VNext;
4266 pLevel->p1 = iCur;
4267 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
4268 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
4269 sqlite3ExprCachePop(pParse, 1);
4270 }else
4271 #endif /* SQLITE_OMIT_VIRTUALTABLE */
4273 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
4274 /* Case 1: We can directly reference a single row using an
4275 ** equality comparison against the ROWID field. Or
4276 ** we reference multiple rows using a "rowid IN (...)"
4277 ** construct.
4279 iReleaseReg = sqlite3GetTempReg(pParse);
4280 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
4281 assert( pTerm!=0 );
4282 assert( pTerm->pExpr!=0 );
4283 assert( omitTable==0 );
4284 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4285 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
4286 addrNxt = pLevel->addrNxt;
4287 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
4288 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
4289 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
4290 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
4291 VdbeComment((v, "pk"));
4292 pLevel->op = OP_Noop;
4293 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
4294 /* Case 2: We have an inequality comparison against the ROWID field.
4296 int testOp = OP_Noop;
4297 int start;
4298 int memEndValue = 0;
4299 WhereTerm *pStart, *pEnd;
4301 assert( omitTable==0 );
4302 pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
4303 pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
4304 if( bRev ){
4305 pTerm = pStart;
4306 pStart = pEnd;
4307 pEnd = pTerm;
4309 if( pStart ){
4310 Expr *pX; /* The expression that defines the start bound */
4311 int r1, rTemp; /* Registers for holding the start boundary */
4313 /* The following constant maps TK_xx codes into corresponding
4314 ** seek opcodes. It depends on a particular ordering of TK_xx
4316 const u8 aMoveOp[] = {
4317 /* TK_GT */ OP_SeekGt,
4318 /* TK_LE */ OP_SeekLe,
4319 /* TK_LT */ OP_SeekLt,
4320 /* TK_GE */ OP_SeekGe
4322 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
4323 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
4324 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
4326 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4327 pX = pStart->pExpr;
4328 assert( pX!=0 );
4329 assert( pStart->leftCursor==iCur );
4330 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
4331 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
4332 VdbeComment((v, "pk"));
4333 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
4334 sqlite3ReleaseTempReg(pParse, rTemp);
4335 disableTerm(pLevel, pStart);
4336 }else{
4337 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
4339 if( pEnd ){
4340 Expr *pX;
4341 pX = pEnd->pExpr;
4342 assert( pX!=0 );
4343 assert( pEnd->leftCursor==iCur );
4344 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4345 memEndValue = ++pParse->nMem;
4346 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
4347 if( pX->op==TK_LT || pX->op==TK_GT ){
4348 testOp = bRev ? OP_Le : OP_Ge;
4349 }else{
4350 testOp = bRev ? OP_Lt : OP_Gt;
4352 disableTerm(pLevel, pEnd);
4354 start = sqlite3VdbeCurrentAddr(v);
4355 pLevel->op = bRev ? OP_Prev : OP_Next;
4356 pLevel->p1 = iCur;
4357 pLevel->p2 = start;
4358 if( pStart==0 && pEnd==0 ){
4359 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4360 }else{
4361 assert( pLevel->p5==0 );
4363 if( testOp!=OP_Noop ){
4364 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
4365 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
4366 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
4367 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
4368 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
4370 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
4371 /* Case 3: A scan using an index.
4373 ** The WHERE clause may contain zero or more equality
4374 ** terms ("==" or "IN" operators) that refer to the N
4375 ** left-most columns of the index. It may also contain
4376 ** inequality constraints (>, <, >= or <=) on the indexed
4377 ** column that immediately follows the N equalities. Only
4378 ** the right-most column can be an inequality - the rest must
4379 ** use the "==" and "IN" operators. For example, if the
4380 ** index is on (x,y,z), then the following clauses are all
4381 ** optimized:
4383 ** x=5
4384 ** x=5 AND y=10
4385 ** x=5 AND y<10
4386 ** x=5 AND y>5 AND y<10
4387 ** x=5 AND y=5 AND z<=10
4389 ** The z<10 term of the following cannot be used, only
4390 ** the x=5 term:
4392 ** x=5 AND z<10
4394 ** N may be zero if there are inequality constraints.
4395 ** If there are no inequality constraints, then N is at
4396 ** least one.
4398 ** This case is also used when there are no WHERE clause
4399 ** constraints but an index is selected anyway, in order
4400 ** to force the output order to conform to an ORDER BY.
4402 static const u8 aStartOp[] = {
4405 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
4406 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
4407 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
4408 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
4409 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
4410 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
4412 static const u8 aEndOp[] = {
4413 OP_Noop, /* 0: (!end_constraints) */
4414 OP_IdxGE, /* 1: (end_constraints && !bRev) */
4415 OP_IdxLT /* 2: (end_constraints && bRev) */
4417 int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
4418 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
4419 int regBase; /* Base register holding constraint values */
4420 int r1; /* Temp register */
4421 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
4422 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
4423 int startEq; /* True if range start uses ==, >= or <= */
4424 int endEq; /* True if range end uses ==, >= or <= */
4425 int start_constraints; /* Start of range is constrained */
4426 int nConstraint; /* Number of constraint terms */
4427 Index *pIdx; /* The index we will be using */
4428 int iIdxCur; /* The VDBE cursor for the index */
4429 int nExtraReg = 0; /* Number of extra registers needed */
4430 int op; /* Instruction opcode */
4431 char *zStartAff; /* Affinity for start of range constraint */
4432 char *zEndAff; /* Affinity for end of range constraint */
4434 pIdx = pLevel->plan.u.pIdx;
4435 iIdxCur = pLevel->iIdxCur;
4436 k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
4438 /* If this loop satisfies a sort order (pOrderBy) request that
4439 ** was passed to this function to implement a "SELECT min(x) ..."
4440 ** query, then the caller will only allow the loop to run for
4441 ** a single iteration. This means that the first row returned
4442 ** should not have a NULL value stored in 'x'. If column 'x' is
4443 ** the first one after the nEq equality constraints in the index,
4444 ** this requires some special handling.
4446 if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
4447 && (pLevel->plan.wsFlags&WHERE_ORDERED)
4448 && (pIdx->nColumn>nEq)
4450 /* assert( pOrderBy->nExpr==1 ); */
4451 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
4452 isMinQuery = 1;
4453 nExtraReg = 1;
4456 /* Find any inequality constraint terms for the start and end
4457 ** of the range.
4459 if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
4460 pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
4461 nExtraReg = 1;
4463 if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
4464 pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
4465 nExtraReg = 1;
4468 /* Generate code to evaluate all constraint terms using == or IN
4469 ** and store the values of those terms in an array of registers
4470 ** starting at regBase.
4472 regBase = codeAllEqualityTerms(
4473 pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
4475 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
4476 addrNxt = pLevel->addrNxt;
4478 /* If we are doing a reverse order scan on an ascending index, or
4479 ** a forward order scan on a descending index, interchange the
4480 ** start and end terms (pRangeStart and pRangeEnd).
4482 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
4483 || (bRev && pIdx->nColumn==nEq)
4485 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
4488 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
4489 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
4490 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
4491 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
4492 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
4493 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
4494 start_constraints = pRangeStart || nEq>0;
4496 /* Seek the index cursor to the start of the range. */
4497 nConstraint = nEq;
4498 if( pRangeStart ){
4499 Expr *pRight = pRangeStart->pExpr->pRight;
4500 sqlite3ExprCode(pParse, pRight, regBase+nEq);
4501 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
4502 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
4504 if( zStartAff ){
4505 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
4506 /* Since the comparison is to be performed with no conversions
4507 ** applied to the operands, set the affinity to apply to pRight to
4508 ** SQLITE_AFF_NONE. */
4509 zStartAff[nEq] = SQLITE_AFF_NONE;
4511 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
4512 zStartAff[nEq] = SQLITE_AFF_NONE;
4515 nConstraint++;
4516 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4517 }else if( isMinQuery ){
4518 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
4519 nConstraint++;
4520 startEq = 0;
4521 start_constraints = 1;
4523 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
4524 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
4525 assert( op!=0 );
4526 testcase( op==OP_Rewind );
4527 testcase( op==OP_Last );
4528 testcase( op==OP_SeekGt );
4529 testcase( op==OP_SeekGe );
4530 testcase( op==OP_SeekLe );
4531 testcase( op==OP_SeekLt );
4532 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
4534 /* Load the value for the inequality constraint at the end of the
4535 ** range (if any).
4537 nConstraint = nEq;
4538 if( pRangeEnd ){
4539 Expr *pRight = pRangeEnd->pExpr->pRight;
4540 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
4541 sqlite3ExprCode(pParse, pRight, regBase+nEq);
4542 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
4543 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
4545 if( zEndAff ){
4546 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
4547 /* Since the comparison is to be performed with no conversions
4548 ** applied to the operands, set the affinity to apply to pRight to
4549 ** SQLITE_AFF_NONE. */
4550 zEndAff[nEq] = SQLITE_AFF_NONE;
4552 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
4553 zEndAff[nEq] = SQLITE_AFF_NONE;
4556 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
4557 nConstraint++;
4558 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
4560 sqlite3DbFree(pParse->db, zStartAff);
4561 sqlite3DbFree(pParse->db, zEndAff);
4563 /* Top of the loop body */
4564 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
4566 /* Check if the index cursor is past the end of the range. */
4567 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
4568 testcase( op==OP_Noop );
4569 testcase( op==OP_IdxGE );
4570 testcase( op==OP_IdxLT );
4571 if( op!=OP_Noop ){
4572 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
4573 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
4576 /* If there are inequality constraints, check that the value
4577 ** of the table column that the inequality contrains is not NULL.
4578 ** If it is, jump to the next iteration of the loop.
4580 r1 = sqlite3GetTempReg(pParse);
4581 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
4582 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
4583 if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
4584 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
4585 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
4587 sqlite3ReleaseTempReg(pParse, r1);
4589 /* Seek the table cursor, if required */
4590 disableTerm(pLevel, pRangeStart);
4591 disableTerm(pLevel, pRangeEnd);
4592 if( !omitTable ){
4593 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
4594 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
4595 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
4596 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
4599 /* Record the instruction used to terminate the loop. Disable
4600 ** WHERE clause terms made redundant by the index range scan.
4602 if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
4603 pLevel->op = OP_Noop;
4604 }else if( bRev ){
4605 pLevel->op = OP_Prev;
4606 }else{
4607 pLevel->op = OP_Next;
4609 pLevel->p1 = iIdxCur;
4610 if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
4611 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4612 }else{
4613 assert( pLevel->p5==0 );
4615 }else
4617 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
4618 if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
4619 /* Case 4: Two or more separately indexed terms connected by OR
4621 ** Example:
4623 ** CREATE TABLE t1(a,b,c,d);
4624 ** CREATE INDEX i1 ON t1(a);
4625 ** CREATE INDEX i2 ON t1(b);
4626 ** CREATE INDEX i3 ON t1(c);
4628 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
4630 ** In the example, there are three indexed terms connected by OR.
4631 ** The top of the loop looks like this:
4633 ** Null 1 # Zero the rowset in reg 1
4635 ** Then, for each indexed term, the following. The arguments to
4636 ** RowSetTest are such that the rowid of the current row is inserted
4637 ** into the RowSet. If it is already present, control skips the
4638 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
4640 ** sqlite3WhereBegin(<term>)
4641 ** RowSetTest # Insert rowid into rowset
4642 ** Gosub 2 A
4643 ** sqlite3WhereEnd()
4645 ** Following the above, code to terminate the loop. Label A, the target
4646 ** of the Gosub above, jumps to the instruction right after the Goto.
4648 ** Null 1 # Zero the rowset in reg 1
4649 ** Goto B # The loop is finished.
4651 ** A: <loop body> # Return data, whatever.
4653 ** Return 2 # Jump back to the Gosub
4655 ** B: <after the loop>
4658 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
4659 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
4660 Index *pCov = 0; /* Potential covering index (or NULL) */
4661 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
4663 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
4664 int regRowset = 0; /* Register for RowSet object */
4665 int regRowid = 0; /* Register holding rowid */
4666 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
4667 int iRetInit; /* Address of regReturn init */
4668 int untestedTerms = 0; /* Some terms not completely tested */
4669 int ii; /* Loop counter */
4670 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
4672 pTerm = pLevel->plan.u.pTerm;
4673 assert( pTerm!=0 );
4674 assert( pTerm->eOperator & WO_OR );
4675 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
4676 pOrWc = &pTerm->u.pOrInfo->wc;
4677 pLevel->op = OP_Return;
4678 pLevel->p1 = regReturn;
4680 /* Set up a new SrcList in pOrTab containing the table being scanned
4681 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
4682 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
4684 if( pWInfo->nLevel>1 ){
4685 int nNotReady; /* The number of notReady tables */
4686 struct SrcList_item *origSrc; /* Original list of tables */
4687 nNotReady = pWInfo->nLevel - iLevel - 1;
4688 pOrTab = sqlite3StackAllocRaw(pParse->db,
4689 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
4690 if( pOrTab==0 ) return notReady;
4691 pOrTab->nAlloc = (i16)(nNotReady + 1);
4692 pOrTab->nSrc = pOrTab->nAlloc;
4693 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
4694 origSrc = pWInfo->pTabList->a;
4695 for(k=1; k<=nNotReady; k++){
4696 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
4698 }else{
4699 pOrTab = pWInfo->pTabList;
4702 /* Initialize the rowset register to contain NULL. An SQL NULL is
4703 ** equivalent to an empty rowset.
4705 ** Also initialize regReturn to contain the address of the instruction
4706 ** immediately following the OP_Return at the bottom of the loop. This
4707 ** is required in a few obscure LEFT JOIN cases where control jumps
4708 ** over the top of the loop into the body of it. In this case the
4709 ** correct response for the end-of-loop code (the OP_Return) is to
4710 ** fall through to the next instruction, just as an OP_Next does if
4711 ** called on an uninitialized cursor.
4713 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
4714 regRowset = ++pParse->nMem;
4715 regRowid = ++pParse->nMem;
4716 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
4718 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
4720 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
4721 ** Then for every term xN, evaluate as the subexpression: xN AND z
4722 ** That way, terms in y that are factored into the disjunction will
4723 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
4725 ** Actually, each subexpression is converted to "xN AND w" where w is
4726 ** the "interesting" terms of z - terms that did not originate in the
4727 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
4728 ** indices.
4730 ** This optimization also only applies if the (x1 OR x2 OR ...) term
4731 ** is not contained in the ON clause of a LEFT JOIN.
4732 ** See ticket http://www.sqlite.org/src/info/f2369304e4
4734 if( pWC->nTerm>1 ){
4735 int iTerm;
4736 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
4737 Expr *pExpr = pWC->a[iTerm].pExpr;
4738 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
4739 if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
4740 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
4741 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4742 pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
4744 if( pAndExpr ){
4745 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
4749 for(ii=0; ii<pOrWc->nTerm; ii++){
4750 WhereTerm *pOrTerm = &pOrWc->a[ii];
4751 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
4752 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
4753 Expr *pOrExpr = pOrTerm->pExpr;
4754 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
4755 pAndExpr->pLeft = pOrExpr;
4756 pOrExpr = pAndExpr;
4758 /* Loop through table entries that match term pOrTerm. */
4759 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
4760 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
4761 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
4762 assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
4763 if( pSubWInfo ){
4764 WhereLevel *pLvl;
4765 explainOneScan(
4766 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
4768 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
4769 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
4770 int r;
4771 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
4772 regRowid, 0);
4773 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
4774 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
4776 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
4778 /* The pSubWInfo->untestedTerms flag means that this OR term
4779 ** contained one or more AND term from a notReady table. The
4780 ** terms from the notReady table could not be tested and will
4781 ** need to be tested later.
4783 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
4785 /* If all of the OR-connected terms are optimized using the same
4786 ** index, and the index is opened using the same cursor number
4787 ** by each call to sqlite3WhereBegin() made by this loop, it may
4788 ** be possible to use that index as a covering index.
4790 ** If the call to sqlite3WhereBegin() above resulted in a scan that
4791 ** uses an index, and this is either the first OR-connected term
4792 ** processed or the index is the same as that used by all previous
4793 ** terms, set pCov to the candidate covering index. Otherwise, set
4794 ** pCov to NULL to indicate that no candidate covering index will
4795 ** be available.
4797 pLvl = &pSubWInfo->a[0];
4798 if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
4799 && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
4800 && (ii==0 || pLvl->plan.u.pIdx==pCov)
4802 assert( pLvl->iIdxCur==iCovCur );
4803 pCov = pLvl->plan.u.pIdx;
4804 }else{
4805 pCov = 0;
4808 /* Finish the loop through table entries that match term pOrTerm. */
4809 sqlite3WhereEnd(pSubWInfo);
4813 pLevel->u.pCovidx = pCov;
4814 if( pCov ) pLevel->iIdxCur = iCovCur;
4815 if( pAndExpr ){
4816 pAndExpr->pLeft = 0;
4817 sqlite3ExprDelete(pParse->db, pAndExpr);
4819 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
4820 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
4821 sqlite3VdbeResolveLabel(v, iLoopBody);
4823 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
4824 if( !untestedTerms ) disableTerm(pLevel, pTerm);
4825 }else
4826 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
4829 /* Case 5: There is no usable index. We must do a complete
4830 ** scan of the entire table.
4832 static const u8 aStep[] = { OP_Next, OP_Prev };
4833 static const u8 aStart[] = { OP_Rewind, OP_Last };
4834 assert( bRev==0 || bRev==1 );
4835 assert( omitTable==0 );
4836 pLevel->op = aStep[bRev];
4837 pLevel->p1 = iCur;
4838 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
4839 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
4841 newNotReady = notReady & ~getMask(pWC->pMaskSet, iCur);
4843 /* Insert code to test every subexpression that can be completely
4844 ** computed using the current set of tables.
4846 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
4847 ** the use of indices become tests that are evaluated against each row of
4848 ** the relevant input tables.
4850 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
4851 Expr *pE;
4852 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
4853 testcase( pTerm->wtFlags & TERM_CODED );
4854 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
4855 if( (pTerm->prereqAll & newNotReady)!=0 ){
4856 testcase( pWInfo->untestedTerms==0
4857 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
4858 pWInfo->untestedTerms = 1;
4859 continue;
4861 pE = pTerm->pExpr;
4862 assert( pE!=0 );
4863 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
4864 continue;
4866 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
4867 pTerm->wtFlags |= TERM_CODED;
4870 /* Insert code to test for implied constraints based on transitivity
4871 ** of the "==" operator.
4873 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
4874 ** and we are coding the t1 loop and the t2 loop has not yet coded,
4875 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
4876 ** the implied "t1.a=123" constraint.
4878 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
4879 Expr *pE;
4880 WhereTerm *pAlt;
4881 Expr sEq;
4882 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
4883 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
4884 if( pTerm->leftCursor!=iCur ) continue;
4885 pE = pTerm->pExpr;
4886 assert( !ExprHasProperty(pE, EP_FromJoin) );
4887 assert( (pTerm->prereqRight & newNotReady)!=0 );
4888 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
4889 if( pAlt==0 ) continue;
4890 if( pAlt->wtFlags & (TERM_CODED) ) continue;
4891 VdbeNoopComment((v, "begin transitive constraint"));
4892 sEq = *pAlt->pExpr;
4893 sEq.pLeft = pE->pLeft;
4894 sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
4897 /* For a LEFT OUTER JOIN, generate code that will record the fact that
4898 ** at least one row of the right table has matched the left table.
4900 if( pLevel->iLeftJoin ){
4901 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
4902 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
4903 VdbeComment((v, "record LEFT JOIN hit"));
4904 sqlite3ExprCacheClear(pParse);
4905 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
4906 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
4907 testcase( pTerm->wtFlags & TERM_CODED );
4908 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
4909 if( (pTerm->prereqAll & newNotReady)!=0 ){
4910 assert( pWInfo->untestedTerms );
4911 continue;
4913 assert( pTerm->pExpr );
4914 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
4915 pTerm->wtFlags |= TERM_CODED;
4918 sqlite3ReleaseTempReg(pParse, iReleaseReg);
4920 return newNotReady;
4923 #if defined(SQLITE_TEST)
4925 ** The following variable holds a text description of query plan generated
4926 ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
4927 ** overwrites the previous. This information is used for testing and
4928 ** analysis only.
4930 char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
4931 static int nQPlan = 0; /* Next free slow in _query_plan[] */
4933 #endif /* SQLITE_TEST */
4937 ** Free a WhereInfo structure
4939 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
4940 if( ALWAYS(pWInfo) ){
4941 int i;
4942 for(i=0; i<pWInfo->nLevel; i++){
4943 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
4944 if( pInfo ){
4945 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
4946 if( pInfo->needToFreeIdxStr ){
4947 sqlite3_free(pInfo->idxStr);
4949 sqlite3DbFree(db, pInfo);
4951 if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
4952 Index *pIdx = pWInfo->a[i].plan.u.pIdx;
4953 if( pIdx ){
4954 sqlite3DbFree(db, pIdx->zColAff);
4955 sqlite3DbFree(db, pIdx);
4959 whereClauseClear(pWInfo->pWC);
4960 sqlite3DbFree(db, pWInfo);
4966 ** Generate the beginning of the loop used for WHERE clause processing.
4967 ** The return value is a pointer to an opaque structure that contains
4968 ** information needed to terminate the loop. Later, the calling routine
4969 ** should invoke sqlite3WhereEnd() with the return value of this function
4970 ** in order to complete the WHERE clause processing.
4972 ** If an error occurs, this routine returns NULL.
4974 ** The basic idea is to do a nested loop, one loop for each table in
4975 ** the FROM clause of a select. (INSERT and UPDATE statements are the
4976 ** same as a SELECT with only a single table in the FROM clause.) For
4977 ** example, if the SQL is this:
4979 ** SELECT * FROM t1, t2, t3 WHERE ...;
4981 ** Then the code generated is conceptually like the following:
4983 ** foreach row1 in t1 do \ Code generated
4984 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
4985 ** foreach row3 in t3 do /
4986 ** ...
4987 ** end \ Code generated
4988 ** end |-- by sqlite3WhereEnd()
4989 ** end /
4991 ** Note that the loops might not be nested in the order in which they
4992 ** appear in the FROM clause if a different order is better able to make
4993 ** use of indices. Note also that when the IN operator appears in
4994 ** the WHERE clause, it might result in additional nested loops for
4995 ** scanning through all values on the right-hand side of the IN.
4997 ** There are Btree cursors associated with each table. t1 uses cursor
4998 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
4999 ** And so forth. This routine generates code to open those VDBE cursors
5000 ** and sqlite3WhereEnd() generates the code to close them.
5002 ** The code that sqlite3WhereBegin() generates leaves the cursors named
5003 ** in pTabList pointing at their appropriate entries. The [...] code
5004 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
5005 ** data from the various tables of the loop.
5007 ** If the WHERE clause is empty, the foreach loops must each scan their
5008 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
5009 ** the tables have indices and there are terms in the WHERE clause that
5010 ** refer to those indices, a complete table scan can be avoided and the
5011 ** code will run much faster. Most of the work of this routine is checking
5012 ** to see if there are indices that can be used to speed up the loop.
5014 ** Terms of the WHERE clause are also used to limit which rows actually
5015 ** make it to the "..." in the middle of the loop. After each "foreach",
5016 ** terms of the WHERE clause that use only terms in that loop and outer
5017 ** loops are evaluated and if false a jump is made around all subsequent
5018 ** inner loops (or around the "..." if the test occurs within the inner-
5019 ** most loop)
5021 ** OUTER JOINS
5023 ** An outer join of tables t1 and t2 is conceptally coded as follows:
5025 ** foreach row1 in t1 do
5026 ** flag = 0
5027 ** foreach row2 in t2 do
5028 ** start:
5029 ** ...
5030 ** flag = 1
5031 ** end
5032 ** if flag==0 then
5033 ** move the row2 cursor to a null row
5034 ** goto start
5035 ** fi
5036 ** end
5038 ** ORDER BY CLAUSE PROCESSING
5040 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
5041 ** if there is one. If there is no ORDER BY clause or if this routine
5042 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
5044 ** If an index can be used so that the natural output order of the table
5045 ** scan is correct for the ORDER BY clause, then that index is used and
5046 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr. This
5047 ** is an optimization that prevents an unnecessary sort of the result set
5048 ** if an index appropriate for the ORDER BY clause already exists.
5050 ** If the where clause loops cannot be arranged to provide the correct
5051 ** output order, then WhereInfo.nOBSat is 0.
5053 WhereInfo *sqlite3WhereBegin(
5054 Parse *pParse, /* The parser context */
5055 SrcList *pTabList, /* A list of all tables to be scanned */
5056 Expr *pWhere, /* The WHERE clause */
5057 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
5058 ExprList *pDistinct, /* The select-list for DISTINCT queries - or NULL */
5059 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5060 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
5062 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
5063 int nTabList; /* Number of elements in pTabList */
5064 WhereInfo *pWInfo; /* Will become the return value of this function */
5065 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
5066 Bitmask notReady; /* Cursors that are not yet positioned */
5067 WhereBestIdx sWBI; /* Best index search context */
5068 WhereMaskSet *pMaskSet; /* The expression mask set */
5069 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
5070 int iFrom; /* First unused FROM clause element */
5071 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
5072 int ii; /* Loop counter */
5073 sqlite3 *db; /* Database connection */
5076 /* Variable initialization */
5077 memset(&sWBI, 0, sizeof(sWBI));
5078 sWBI.pParse = pParse;
5080 /* The number of tables in the FROM clause is limited by the number of
5081 ** bits in a Bitmask
5083 testcase( pTabList->nSrc==BMS );
5084 if( pTabList->nSrc>BMS ){
5085 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
5086 return 0;
5089 /* This function normally generates a nested loop for all tables in
5090 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5091 ** only generate code for the first table in pTabList and assume that
5092 ** any cursors associated with subsequent tables are uninitialized.
5094 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5096 /* Allocate and initialize the WhereInfo structure that will become the
5097 ** return value. A single allocation is used to store the WhereInfo
5098 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5099 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5100 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5101 ** some architectures. Hence the ROUND8() below.
5103 db = pParse->db;
5104 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
5105 pWInfo = sqlite3DbMallocZero(db,
5106 nByteWInfo +
5107 sizeof(WhereClause) +
5108 sizeof(WhereMaskSet)
5110 if( db->mallocFailed ){
5111 sqlite3DbFree(db, pWInfo);
5112 pWInfo = 0;
5113 goto whereBeginError;
5115 pWInfo->nLevel = nTabList;
5116 pWInfo->pParse = pParse;
5117 pWInfo->pTabList = pTabList;
5118 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
5119 pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
5120 pWInfo->wctrlFlags = wctrlFlags;
5121 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
5122 pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
5123 sWBI.aLevel = pWInfo->a;
5125 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5126 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5127 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
5129 /* Split the WHERE clause into separate subexpressions where each
5130 ** subexpression is separated by an AND operator.
5132 initMaskSet(pMaskSet);
5133 whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
5134 sqlite3ExprCodeConstants(pParse, pWhere);
5135 whereSplit(sWBI.pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
5137 /* Special case: a WHERE clause that is constant. Evaluate the
5138 ** expression and either jump over all of the code or fall thru.
5140 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
5141 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
5142 pWhere = 0;
5145 /* Assign a bit from the bitmask to every term in the FROM clause.
5147 ** When assigning bitmask values to FROM clause cursors, it must be
5148 ** the case that if X is the bitmask for the N-th FROM clause term then
5149 ** the bitmask for all FROM clause terms to the left of the N-th term
5150 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5151 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5152 ** of the join. Subtracting one from the right table bitmask gives a
5153 ** bitmask for all tables to the left of the join. Knowing the bitmask
5154 ** for all tables to the left of a left join is important. Ticket #3015.
5156 ** Note that bitmasks are created for all pTabList->nSrc tables in
5157 ** pTabList, not just the first nTabList tables. nTabList is normally
5158 ** equal to pTabList->nSrc but might be shortened to 1 if the
5159 ** WHERE_ONETABLE_ONLY flag is set.
5161 for(ii=0; ii<pTabList->nSrc; ii++){
5162 createMask(pMaskSet, pTabList->a[ii].iCursor);
5164 #ifndef NDEBUG
5166 Bitmask toTheLeft = 0;
5167 for(ii=0; ii<pTabList->nSrc; ii++){
5168 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
5169 assert( (m-1)==toTheLeft );
5170 toTheLeft |= m;
5173 #endif
5175 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5176 ** add new virtual terms onto the end of the WHERE clause. We do not
5177 ** want to analyze these virtual terms, so start analyzing at the end
5178 ** and work forward so that the added virtual terms are never processed.
5180 exprAnalyzeAll(pTabList, sWBI.pWC);
5181 if( db->mallocFailed ){
5182 goto whereBeginError;
5185 /* Check if the DISTINCT qualifier, if there is one, is redundant.
5186 ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
5187 ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
5189 if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
5190 pDistinct = 0;
5191 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5194 /* Chose the best index to use for each table in the FROM clause.
5196 ** This loop fills in the following fields:
5198 ** pWInfo->a[].pIdx The index to use for this level of the loop.
5199 ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
5200 ** pWInfo->a[].nEq The number of == and IN constraints
5201 ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
5202 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
5203 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
5204 ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
5206 ** This loop also figures out the nesting order of tables in the FROM
5207 ** clause.
5209 sWBI.notValid = ~(Bitmask)0;
5210 sWBI.pOrderBy = pOrderBy;
5211 sWBI.n = nTabList;
5212 sWBI.pDistinct = pDistinct;
5213 andFlags = ~0;
5214 WHERETRACE(("*** Optimizer Start ***\n"));
5215 for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
5216 WhereCost bestPlan; /* Most efficient plan seen so far */
5217 Index *pIdx; /* Index for FROM table at pTabItem */
5218 int j; /* For looping over FROM tables */
5219 int bestJ = -1; /* The value of j */
5220 Bitmask m; /* Bitmask value for j or bestJ */
5221 int isOptimal; /* Iterator for optimal/non-optimal search */
5222 int ckOptimal; /* Do the optimal scan check */
5223 int nUnconstrained; /* Number tables without INDEXED BY */
5224 Bitmask notIndexed; /* Mask of tables that cannot use an index */
5226 memset(&bestPlan, 0, sizeof(bestPlan));
5227 bestPlan.rCost = SQLITE_BIG_DBL;
5228 WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
5230 /* Loop through the remaining entries in the FROM clause to find the
5231 ** next nested loop. The loop tests all FROM clause entries
5232 ** either once or twice.
5234 ** The first test is always performed if there are two or more entries
5235 ** remaining and never performed if there is only one FROM clause entry
5236 ** to choose from. The first test looks for an "optimal" scan. In
5237 ** this context an optimal scan is one that uses the same strategy
5238 ** for the given FROM clause entry as would be selected if the entry
5239 ** were used as the innermost nested loop. In other words, a table
5240 ** is chosen such that the cost of running that table cannot be reduced
5241 ** by waiting for other tables to run first. This "optimal" test works
5242 ** by first assuming that the FROM clause is on the inner loop and finding
5243 ** its query plan, then checking to see if that query plan uses any
5244 ** other FROM clause terms that are sWBI.notValid. If no notValid terms
5245 ** are used then the "optimal" query plan works.
5247 ** Note that the WhereCost.nRow parameter for an optimal scan might
5248 ** not be as small as it would be if the table really were the innermost
5249 ** join. The nRow value can be reduced by WHERE clause constraints
5250 ** that do not use indices. But this nRow reduction only happens if the
5251 ** table really is the innermost join.
5253 ** The second loop iteration is only performed if no optimal scan
5254 ** strategies were found by the first iteration. This second iteration
5255 ** is used to search for the lowest cost scan overall.
5257 ** Without the optimal scan step (the first iteration) a suboptimal
5258 ** plan might be chosen for queries like this:
5260 ** CREATE TABLE t1(a, b);
5261 ** CREATE TABLE t2(c, d);
5262 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
5264 ** The best strategy is to iterate through table t1 first. However it
5265 ** is not possible to determine this with a simple greedy algorithm.
5266 ** Since the cost of a linear scan through table t2 is the same
5267 ** as the cost of a linear scan through table t1, a simple greedy
5268 ** algorithm may choose to use t2 for the outer loop, which is a much
5269 ** costlier approach.
5271 nUnconstrained = 0;
5272 notIndexed = 0;
5274 /* The optimal scan check only occurs if there are two or more tables
5275 ** available to be reordered */
5276 if( iFrom==nTabList-1 ){
5277 ckOptimal = 0; /* Common case of just one table in the FROM clause */
5278 }else{
5279 ckOptimal = -1;
5280 for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
5281 m = getMask(pMaskSet, sWBI.pSrc->iCursor);
5282 if( (m & sWBI.notValid)==0 ){
5283 if( j==iFrom ) iFrom++;
5284 continue;
5286 if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
5287 if( ++ckOptimal ) break;
5288 if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
5291 assert( ckOptimal==0 || ckOptimal==1 );
5293 for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
5294 for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
5295 if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
5296 /* This break and one like it in the ckOptimal computation loop
5297 ** above prevent table reordering across LEFT and CROSS JOINs.
5298 ** The LEFT JOIN case is necessary for correctness. The prohibition
5299 ** against reordering across a CROSS JOIN is an SQLite feature that
5300 ** allows the developer to control table reordering */
5301 break;
5303 m = getMask(pMaskSet, sWBI.pSrc->iCursor);
5304 if( (m & sWBI.notValid)==0 ){
5305 assert( j>iFrom );
5306 continue;
5308 sWBI.notReady = (isOptimal ? m : sWBI.notValid);
5309 if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
5311 WHERETRACE((" === trying table %d (%s) with isOptimal=%d ===\n",
5312 j, sWBI.pSrc->pTab->zName, isOptimal));
5313 assert( sWBI.pSrc->pTab );
5314 #ifndef SQLITE_OMIT_VIRTUALTABLE
5315 if( IsVirtual(sWBI.pSrc->pTab) ){
5316 sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
5317 bestVirtualIndex(&sWBI);
5318 }else
5319 #endif
5321 bestBtreeIndex(&sWBI);
5323 assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
5325 /* If an INDEXED BY clause is present, then the plan must use that
5326 ** index if it uses any index at all */
5327 assert( sWBI.pSrc->pIndex==0
5328 || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
5329 || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
5331 if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
5332 notIndexed |= m;
5334 if( isOptimal ){
5335 pWInfo->a[j].rOptCost = sWBI.cost.rCost;
5336 }else if( ckOptimal ){
5337 /* If two or more tables have nearly the same outer loop cost, but
5338 ** very different inner loop (optimal) cost, we want to choose
5339 ** for the outer loop that table which benefits the least from
5340 ** being in the inner loop. The following code scales the
5341 ** outer loop cost estimate to accomplish that. */
5342 WHERETRACE((" scaling cost from %.1f to %.1f\n",
5343 sWBI.cost.rCost,
5344 sWBI.cost.rCost/pWInfo->a[j].rOptCost));
5345 sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
5348 /* Conditions under which this table becomes the best so far:
5350 ** (1) The table must not depend on other tables that have not
5351 ** yet run. (In other words, it must not depend on tables
5352 ** in inner loops.)
5354 ** (2) (This rule was removed on 2012-11-09. The scaling of the
5355 ** cost using the optimal scan cost made this rule obsolete.)
5357 ** (3) All tables have an INDEXED BY clause or this table lacks an
5358 ** INDEXED BY clause or this table uses the specific
5359 ** index specified by its INDEXED BY clause. This rule ensures
5360 ** that a best-so-far is always selected even if an impossible
5361 ** combination of INDEXED BY clauses are given. The error
5362 ** will be detected and relayed back to the application later.
5363 ** The NEVER() comes about because rule (2) above prevents
5364 ** An indexable full-table-scan from reaching rule (3).
5366 ** (4) The plan cost must be lower than prior plans, where "cost"
5367 ** is defined by the compareCost() function above.
5369 if( (sWBI.cost.used&sWBI.notValid)==0 /* (1) */
5370 && (nUnconstrained==0 || sWBI.pSrc->pIndex==0 /* (3) */
5371 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
5372 && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan)) /* (4) */
5374 WHERETRACE((" === table %d (%s) is best so far\n"
5375 " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
5376 j, sWBI.pSrc->pTab->zName,
5377 sWBI.cost.rCost, sWBI.cost.plan.nRow,
5378 sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
5379 bestPlan = sWBI.cost;
5380 bestJ = j;
5383 /* In a join like "w JOIN x LEFT JOIN y JOIN z" make sure that
5384 ** table y (and not table z) is always the next inner loop inside
5385 ** of table x. */
5386 if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
5389 assert( bestJ>=0 );
5390 assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
5391 assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
5392 testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
5393 testcase( bestJ>iFrom && bestJ<nTabList-1
5394 && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
5395 WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
5396 " cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
5397 bestJ, pTabList->a[bestJ].pTab->zName,
5398 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
5399 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
5400 if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
5401 assert( pWInfo->eDistinct==0 );
5402 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5404 andFlags &= bestPlan.plan.wsFlags;
5405 pLevel->plan = bestPlan.plan;
5406 pLevel->iTabCur = pTabList->a[bestJ].iCursor;
5407 testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
5408 testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
5409 if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
5410 if( (wctrlFlags & WHERE_ONETABLE_ONLY)
5411 && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0
5413 pLevel->iIdxCur = iIdxCur;
5414 }else{
5415 pLevel->iIdxCur = pParse->nTab++;
5417 }else{
5418 pLevel->iIdxCur = -1;
5420 sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
5421 pLevel->iFrom = (u8)bestJ;
5422 if( bestPlan.plan.nRow>=(double)1 ){
5423 pParse->nQueryLoop *= bestPlan.plan.nRow;
5426 /* Check that if the table scanned by this loop iteration had an
5427 ** INDEXED BY clause attached to it, that the named index is being
5428 ** used for the scan. If not, then query compilation has failed.
5429 ** Return an error.
5431 pIdx = pTabList->a[bestJ].pIndex;
5432 if( pIdx ){
5433 if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
5434 sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
5435 goto whereBeginError;
5436 }else{
5437 /* If an INDEXED BY clause is used, the bestIndex() function is
5438 ** guaranteed to find the index specified in the INDEXED BY clause
5439 ** if it find an index at all. */
5440 assert( bestPlan.plan.u.pIdx==pIdx );
5444 WHERETRACE(("*** Optimizer Finished ***\n"));
5445 if( pParse->nErr || db->mallocFailed ){
5446 goto whereBeginError;
5448 if( nTabList ){
5449 pLevel--;
5450 pWInfo->nOBSat = pLevel->plan.nOBSat;
5451 }else{
5452 pWInfo->nOBSat = 0;
5455 /* If the total query only selects a single row, then the ORDER BY
5456 ** clause is irrelevant.
5458 if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
5459 assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
5460 pWInfo->nOBSat = pOrderBy->nExpr;
5463 /* If the caller is an UPDATE or DELETE statement that is requesting
5464 ** to use a one-pass algorithm, determine if this is appropriate.
5465 ** The one-pass algorithm only works if the WHERE clause constraints
5466 ** the statement to update a single row.
5468 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
5469 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
5470 pWInfo->okOnePass = 1;
5471 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
5474 /* Open all tables in the pTabList and any indices selected for
5475 ** searching those tables.
5477 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
5478 notReady = ~(Bitmask)0;
5479 pWInfo->nRowOut = (double)1;
5480 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
5481 Table *pTab; /* Table to open */
5482 int iDb; /* Index of database containing table/index */
5483 struct SrcList_item *pTabItem;
5485 pTabItem = &pTabList->a[pLevel->iFrom];
5486 pTab = pTabItem->pTab;
5487 pWInfo->nRowOut *= pLevel->plan.nRow;
5488 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
5489 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
5490 /* Do nothing */
5491 }else
5492 #ifndef SQLITE_OMIT_VIRTUALTABLE
5493 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
5494 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
5495 int iCur = pTabItem->iCursor;
5496 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
5497 }else if( IsVirtual(pTab) ){
5498 /* noop */
5499 }else
5500 #endif
5501 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
5502 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
5503 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
5504 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
5505 testcase( pTab->nCol==BMS-1 );
5506 testcase( pTab->nCol==BMS );
5507 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
5508 Bitmask b = pTabItem->colUsed;
5509 int n = 0;
5510 for(; b; b=b>>1, n++){}
5511 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5512 SQLITE_INT_TO_PTR(n), P4_INT32);
5513 assert( n<=pTab->nCol );
5515 }else{
5516 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
5518 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
5519 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
5520 constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
5521 }else
5522 #endif
5523 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
5524 Index *pIx = pLevel->plan.u.pIdx;
5525 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
5526 int iIndexCur = pLevel->iIdxCur;
5527 assert( pIx->pSchema==pTab->pSchema );
5528 assert( iIndexCur>=0 );
5529 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
5530 (char*)pKey, P4_KEYINFO_HANDOFF);
5531 VdbeComment((v, "%s", pIx->zName));
5533 sqlite3CodeVerifySchema(pParse, iDb);
5534 notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
5536 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
5537 if( db->mallocFailed ) goto whereBeginError;
5539 /* Generate the code to do the search. Each iteration of the for
5540 ** loop below generates code for a single nested loop of the VM
5541 ** program.
5543 notReady = ~(Bitmask)0;
5544 for(ii=0; ii<nTabList; ii++){
5545 pLevel = &pWInfo->a[ii];
5546 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
5547 notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
5548 pWInfo->iContinue = pLevel->addrCont;
5551 #ifdef SQLITE_TEST /* For testing and debugging use only */
5552 /* Record in the query plan information about the current table
5553 ** and the index used to access it (if any). If the table itself
5554 ** is not used, its name is just '{}'. If no index is used
5555 ** the index is listed as "{}". If the primary key is used the
5556 ** index name is '*'.
5558 for(ii=0; ii<nTabList; ii++){
5559 char *z;
5560 int n;
5561 int w;
5562 struct SrcList_item *pTabItem;
5564 pLevel = &pWInfo->a[ii];
5565 w = pLevel->plan.wsFlags;
5566 pTabItem = &pTabList->a[pLevel->iFrom];
5567 z = pTabItem->zAlias;
5568 if( z==0 ) z = pTabItem->pTab->zName;
5569 n = sqlite3Strlen30(z);
5570 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
5571 if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
5572 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
5573 nQPlan += 2;
5574 }else{
5575 memcpy(&sqlite3_query_plan[nQPlan], z, n);
5576 nQPlan += n;
5578 sqlite3_query_plan[nQPlan++] = ' ';
5580 testcase( w & WHERE_ROWID_EQ );
5581 testcase( w & WHERE_ROWID_RANGE );
5582 if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
5583 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
5584 nQPlan += 2;
5585 }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
5586 n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
5587 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
5588 memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
5589 nQPlan += n;
5590 sqlite3_query_plan[nQPlan++] = ' ';
5592 }else{
5593 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
5594 nQPlan += 3;
5597 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
5598 sqlite3_query_plan[--nQPlan] = 0;
5600 sqlite3_query_plan[nQPlan] = 0;
5601 nQPlan = 0;
5602 #endif /* SQLITE_TEST // Testing and debugging use only */
5604 /* Record the continuation address in the WhereInfo structure. Then
5605 ** clean up and return.
5607 return pWInfo;
5609 /* Jump here if malloc fails */
5610 whereBeginError:
5611 if( pWInfo ){
5612 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5613 whereInfoFree(db, pWInfo);
5615 return 0;
5619 ** Generate the end of the WHERE loop. See comments on
5620 ** sqlite3WhereBegin() for additional information.
5622 void sqlite3WhereEnd(WhereInfo *pWInfo){
5623 Parse *pParse = pWInfo->pParse;
5624 Vdbe *v = pParse->pVdbe;
5625 int i;
5626 WhereLevel *pLevel;
5627 SrcList *pTabList = pWInfo->pTabList;
5628 sqlite3 *db = pParse->db;
5630 /* Generate loop termination code.
5632 sqlite3ExprCacheClear(pParse);
5633 for(i=pWInfo->nLevel-1; i>=0; i--){
5634 pLevel = &pWInfo->a[i];
5635 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
5636 if( pLevel->op!=OP_Noop ){
5637 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
5638 sqlite3VdbeChangeP5(v, pLevel->p5);
5640 if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
5641 struct InLoop *pIn;
5642 int j;
5643 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
5644 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
5645 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
5646 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
5647 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
5649 sqlite3DbFree(db, pLevel->u.in.aInLoop);
5651 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
5652 if( pLevel->iLeftJoin ){
5653 int addr;
5654 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
5655 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
5656 || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
5657 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
5658 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
5660 if( pLevel->iIdxCur>=0 ){
5661 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
5663 if( pLevel->op==OP_Return ){
5664 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
5665 }else{
5666 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
5668 sqlite3VdbeJumpHere(v, addr);
5672 /* The "break" point is here, just past the end of the outer loop.
5673 ** Set it.
5675 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
5677 /* Close all of the cursors that were opened by sqlite3WhereBegin.
5679 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
5680 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
5681 Index *pIdx = 0;
5682 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
5683 Table *pTab = pTabItem->pTab;
5684 assert( pTab!=0 );
5685 if( (pTab->tabFlags & TF_Ephemeral)==0
5686 && pTab->pSelect==0
5687 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
5689 int ws = pLevel->plan.wsFlags;
5690 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
5691 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
5693 if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
5694 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
5698 /* If this scan uses an index, make code substitutions to read data
5699 ** from the index in preference to the table. Sometimes, this means
5700 ** the table need never be read from. This is a performance boost,
5701 ** as the vdbe level waits until the table is read before actually
5702 ** seeking the table cursor to the record corresponding to the current
5703 ** position in the index.
5705 ** Calls to the code generator in between sqlite3WhereBegin and
5706 ** sqlite3WhereEnd will have created code that references the table
5707 ** directly. This loop scans all that code looking for opcodes
5708 ** that reference the table and converts them into opcodes that
5709 ** reference the index.
5711 if( pLevel->plan.wsFlags & WHERE_INDEXED ){
5712 pIdx = pLevel->plan.u.pIdx;
5713 }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
5714 pIdx = pLevel->u.pCovidx;
5716 if( pIdx && !db->mallocFailed){
5717 int k, j, last;
5718 VdbeOp *pOp;
5720 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
5721 last = sqlite3VdbeCurrentAddr(v);
5722 for(k=pWInfo->iTop; k<last; k++, pOp++){
5723 if( pOp->p1!=pLevel->iTabCur ) continue;
5724 if( pOp->opcode==OP_Column ){
5725 for(j=0; j<pIdx->nColumn; j++){
5726 if( pOp->p2==pIdx->aiColumn[j] ){
5727 pOp->p2 = j;
5728 pOp->p1 = pLevel->iIdxCur;
5729 break;
5732 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
5733 || j<pIdx->nColumn );
5734 }else if( pOp->opcode==OP_Rowid ){
5735 pOp->p1 = pLevel->iIdxCur;
5736 pOp->opcode = OP_IdxRowid;
5742 /* Final cleanup
5744 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
5745 whereInfoFree(db, pWInfo);
5746 return;