blob: ae9bf85fab2513716bb9a14228e2a9ee315fd12a [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This module contains C code that generates VDBE code used to process
drh909626d2008-05-30 14:58:37 +000013** the WHERE clause of SQL statements. This module is responsible for
drh51669862004-12-18 18:40:26 +000014** 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".
drh75897232000-05-29 14:26:00 +000018*/
19#include "sqliteInt.h"
20
21/*
drh51147ba2005-07-23 22:59:55 +000022** Trace output macros
23*/
24#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
mlcreech3a00f902008-03-04 17:45:01 +000025int sqlite3WhereTrace = 0;
drhe8f52c52008-07-12 14:52:20 +000026#endif
drh85799a42009-04-07 13:48:11 +000027#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
mlcreech3a00f902008-03-04 17:45:01 +000028# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
drh51147ba2005-07-23 22:59:55 +000029#else
drh4f0c5872007-03-26 22:05:01 +000030# define WHERETRACE(X)
drh51147ba2005-07-23 22:59:55 +000031#endif
32
drh0fcef5e2005-07-19 17:38:22 +000033/* Forward reference
34*/
35typedef struct WhereClause WhereClause;
drh111a6a72008-12-21 03:51:16 +000036typedef struct WhereMaskSet WhereMaskSet;
drh700a2262008-12-17 19:22:15 +000037typedef struct WhereOrInfo WhereOrInfo;
38typedef struct WhereAndInfo WhereAndInfo;
drh111a6a72008-12-21 03:51:16 +000039typedef struct WhereCost WhereCost;
drh0aa74ed2005-07-16 13:33:20 +000040
41/*
drh75897232000-05-29 14:26:00 +000042** The query generator uses an array of instances of this structure to
43** help it analyze the subexpressions of the WHERE clause. Each WHERE
drh61495262009-04-22 15:32:59 +000044** clause subexpression is separated from the others by AND operators,
45** usually, or sometimes subexpressions separated by OR.
drh51669862004-12-18 18:40:26 +000046**
drh0fcef5e2005-07-19 17:38:22 +000047** All WhereTerms are collected into a single WhereClause structure.
48** The following identity holds:
drh51669862004-12-18 18:40:26 +000049**
drh0fcef5e2005-07-19 17:38:22 +000050** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +000051**
drh0fcef5e2005-07-19 17:38:22 +000052** When a term is of the form:
53**
54** X <op> <expr>
55**
56** where X is a column name and <op> is one of certain operators,
drh700a2262008-12-17 19:22:15 +000057** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
58** cursor number and column number for X. WhereTerm.eOperator records
drh51147ba2005-07-23 22:59:55 +000059** the <op> using a bitmask encoding defined by WO_xxx below. The
60** use of a bitmask encoding for the operator allows us to search
61** quickly for terms that match any of several different operators.
drh0fcef5e2005-07-19 17:38:22 +000062**
drh700a2262008-12-17 19:22:15 +000063** A WhereTerm might also be two or more subterms connected by OR:
64**
65** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
66**
67** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
68** and the WhereTerm.u.pOrInfo field points to auxiliary information that
69** is collected about the
70**
71** If a term in the WHERE clause does not match either of the two previous
72** categories, then eOperator==0. The WhereTerm.pExpr field is still set
73** to the original subexpression content and wtFlags is set up appropriately
74** but no other fields in the WhereTerm object are meaningful.
75**
76** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
drh111a6a72008-12-21 03:51:16 +000077** but they do so indirectly. A single WhereMaskSet structure translates
drh51669862004-12-18 18:40:26 +000078** cursor number into bits and the translated bit is stored in the prereq
79** fields. The translation is used in order to maximize the number of
80** bits that will fit in a Bitmask. The VDBE cursor numbers might be
81** spread out over the non-negative integers. For example, the cursor
drh111a6a72008-12-21 03:51:16 +000082** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
drh51669862004-12-18 18:40:26 +000083** translates these sparse cursor numbers into consecutive integers
84** beginning with 0 in order to make the best possible use of the available
85** bits in the Bitmask. So, in the example above, the cursor numbers
86** would be mapped into integers 0 through 7.
drh6a1e0712008-12-05 15:24:15 +000087**
88** The number of terms in a join is limited by the number of bits
89** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
90** is only able to process joins with 64 or fewer tables.
drh75897232000-05-29 14:26:00 +000091*/
drh0aa74ed2005-07-16 13:33:20 +000092typedef struct WhereTerm WhereTerm;
93struct WhereTerm {
drh165be382008-12-05 02:36:33 +000094 Expr *pExpr; /* Pointer to the subexpression that is this term */
drhec1724e2008-12-09 01:32:03 +000095 int iParent; /* Disable pWC->a[iParent] when this term disabled */
96 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
drh700a2262008-12-17 19:22:15 +000097 union {
98 int leftColumn; /* Column number of X in "X <op> <expr>" */
99 WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
100 WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
101 } u;
drhb52076c2006-01-23 13:22:09 +0000102 u16 eOperator; /* A WO_xx value describing <op> */
drh165be382008-12-05 02:36:33 +0000103 u8 wtFlags; /* TERM_xxx bit flags. See below */
drh45b1ee42005-08-02 17:48:22 +0000104 u8 nChild; /* Number of children that must disable us */
drh0fcef5e2005-07-19 17:38:22 +0000105 WhereClause *pWC; /* The clause this term is part of */
drh165be382008-12-05 02:36:33 +0000106 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
107 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
drh75897232000-05-29 14:26:00 +0000108};
109
110/*
drh165be382008-12-05 02:36:33 +0000111** Allowed values of WhereTerm.wtFlags
drh0aa74ed2005-07-16 13:33:20 +0000112*/
drh633e6d52008-07-28 19:34:53 +0000113#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
drh6c30be82005-07-29 15:10:17 +0000114#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
115#define TERM_CODED 0x04 /* This term is already coded */
drh45b1ee42005-08-02 17:48:22 +0000116#define TERM_COPIED 0x08 /* Has a child */
drh700a2262008-12-17 19:22:15 +0000117#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
118#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
119#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
drh0aa74ed2005-07-16 13:33:20 +0000120
121/*
122** An instance of the following structure holds all information about a
123** WHERE clause. Mostly this is a container for one or more WhereTerms.
124*/
drh0aa74ed2005-07-16 13:33:20 +0000125struct WhereClause {
drhfe05af82005-07-21 03:14:59 +0000126 Parse *pParse; /* The parser context */
drh111a6a72008-12-21 03:51:16 +0000127 WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
danielk1977e672c8e2009-05-22 15:43:26 +0000128 Bitmask vmask; /* Bitmask identifying virtual table cursors */
drh29435252008-12-28 18:35:08 +0000129 u8 op; /* Split operator. TK_AND or TK_OR */
drh0aa74ed2005-07-16 13:33:20 +0000130 int nTerm; /* Number of terms */
131 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000132 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
drh50d654d2009-06-03 01:24:54 +0000133#if defined(SQLITE_SMALL_STACK)
134 WhereTerm aStatic[1]; /* Initial static space for a[] */
135#else
136 WhereTerm aStatic[8]; /* Initial static space for a[] */
137#endif
drhe23399f2005-07-22 00:31:39 +0000138};
139
140/*
drh700a2262008-12-17 19:22:15 +0000141** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
142** a dynamically allocated instance of the following structure.
143*/
144struct WhereOrInfo {
drh111a6a72008-12-21 03:51:16 +0000145 WhereClause wc; /* Decomposition into subterms */
drh1a58fe02008-12-20 02:06:13 +0000146 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
drh700a2262008-12-17 19:22:15 +0000147};
148
149/*
150** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
151** a dynamically allocated instance of the following structure.
152*/
153struct WhereAndInfo {
drh29435252008-12-28 18:35:08 +0000154 WhereClause wc; /* The subexpression broken out */
drh700a2262008-12-17 19:22:15 +0000155};
156
157/*
drh6a3ea0e2003-05-02 14:32:12 +0000158** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000159** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000160**
161** The VDBE cursor numbers are small integers contained in
162** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
163** clause, the cursor numbers might not begin with 0 and they might
164** contain gaps in the numbering sequence. But we want to make maximum
165** use of the bits in our bitmasks. This structure provides a mapping
166** from the sparse cursor numbers into consecutive integers beginning
167** with 0.
168**
drh111a6a72008-12-21 03:51:16 +0000169** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
drh51669862004-12-18 18:40:26 +0000170** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
171**
172** For example, if the WHERE clause expression used these VDBE
drh111a6a72008-12-21 03:51:16 +0000173** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
drh51669862004-12-18 18:40:26 +0000174** would map those cursor numbers into bits 0 through 5.
175**
176** Note that the mapping is not necessarily ordered. In the example
177** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
178** 57->5, 73->4. Or one of 719 other combinations might be used. It
179** does not really matter. What is important is that sparse cursor
180** numbers all get mapped into bit numbers that begin with 0 and contain
181** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000182*/
drh111a6a72008-12-21 03:51:16 +0000183struct WhereMaskSet {
drh1398ad32005-01-19 23:24:50 +0000184 int n; /* Number of assigned cursor values */
danielk197723432972008-11-17 16:42:00 +0000185 int ix[BMS]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000186};
187
drh111a6a72008-12-21 03:51:16 +0000188/*
189** A WhereCost object records a lookup strategy and the estimated
190** cost of pursuing that strategy.
191*/
192struct WhereCost {
193 WherePlan plan; /* The lookup strategy */
194 double rCost; /* Overall cost of pursuing this search strategy */
195 double nRow; /* Estimated number of output rows */
dan5236ac12009-08-13 07:09:33 +0000196 Bitmask used; /* Bitmask of cursors used by this plan */
drh111a6a72008-12-21 03:51:16 +0000197};
drh0aa74ed2005-07-16 13:33:20 +0000198
drh6a3ea0e2003-05-02 14:32:12 +0000199/*
drh51147ba2005-07-23 22:59:55 +0000200** Bitmasks for the operators that indices are able to exploit. An
201** OR-ed combination of these values can be used when searching for
202** terms in the where clause.
203*/
drh165be382008-12-05 02:36:33 +0000204#define WO_IN 0x001
205#define WO_EQ 0x002
drh51147ba2005-07-23 22:59:55 +0000206#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
207#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
208#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
209#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
drh165be382008-12-05 02:36:33 +0000210#define WO_MATCH 0x040
211#define WO_ISNULL 0x080
drh700a2262008-12-17 19:22:15 +0000212#define WO_OR 0x100 /* Two or more OR-connected terms */
213#define WO_AND 0x200 /* Two or more AND-connected terms */
drh51147ba2005-07-23 22:59:55 +0000214
drhec1724e2008-12-09 01:32:03 +0000215#define WO_ALL 0xfff /* Mask of all possible WO_* values */
drh1a58fe02008-12-20 02:06:13 +0000216#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
drhec1724e2008-12-09 01:32:03 +0000217
drh51147ba2005-07-23 22:59:55 +0000218/*
drh700a2262008-12-17 19:22:15 +0000219** Value for wsFlags returned by bestIndex() and stored in
220** WhereLevel.wsFlags. These flags determine which search
221** strategies are appropriate.
drhf2d315d2007-01-25 16:56:06 +0000222**
drh165be382008-12-05 02:36:33 +0000223** The least significant 12 bits is reserved as a mask for WO_ values above.
drh700a2262008-12-17 19:22:15 +0000224** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
225** But if the table is the right table of a left join, WhereLevel.wsFlags
226** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
drhf2d315d2007-01-25 16:56:06 +0000227** the "op" parameter to findTerm when we are resolving equality constraints.
228** ISNULL constraints will then not be used on the right table of a left
229** join. Tickets #2177 and #2189.
drh51147ba2005-07-23 22:59:55 +0000230*/
drh165be382008-12-05 02:36:33 +0000231#define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
232#define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
drh46619d62009-04-24 14:51:42 +0000233#define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
drh165be382008-12-05 02:36:33 +0000234#define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
235#define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
drh46619d62009-04-24 14:51:42 +0000236#define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
237#define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
drh8b307fb2010-04-06 15:57:05 +0000238#define WHERE_NOT_FULLSCAN 0x000f3000 /* Does not do a full table scan */
drh46619d62009-04-24 14:51:42 +0000239#define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
drh165be382008-12-05 02:36:33 +0000240#define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
241#define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
242#define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
243#define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
244#define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
245#define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
246#define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
247#define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
drh8b307fb2010-04-06 15:57:05 +0000248#define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
drh51147ba2005-07-23 22:59:55 +0000249
250/*
drh0aa74ed2005-07-16 13:33:20 +0000251** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000252*/
drh7b4fc6a2007-02-06 13:26:32 +0000253static void whereClauseInit(
254 WhereClause *pWC, /* The WhereClause to be initialized */
255 Parse *pParse, /* The parsing context */
drh111a6a72008-12-21 03:51:16 +0000256 WhereMaskSet *pMaskSet /* Mapping from table cursor numbers to bitmasks */
drh7b4fc6a2007-02-06 13:26:32 +0000257){
drhfe05af82005-07-21 03:14:59 +0000258 pWC->pParse = pParse;
drh7b4fc6a2007-02-06 13:26:32 +0000259 pWC->pMaskSet = pMaskSet;
drh0aa74ed2005-07-16 13:33:20 +0000260 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000261 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000262 pWC->a = pWC->aStatic;
danielk1977e672c8e2009-05-22 15:43:26 +0000263 pWC->vmask = 0;
drh0aa74ed2005-07-16 13:33:20 +0000264}
265
drh700a2262008-12-17 19:22:15 +0000266/* Forward reference */
267static void whereClauseClear(WhereClause*);
268
269/*
270** Deallocate all memory associated with a WhereOrInfo object.
271*/
272static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000273 whereClauseClear(&p->wc);
274 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000275}
276
277/*
278** Deallocate all memory associated with a WhereAndInfo object.
279*/
280static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000281 whereClauseClear(&p->wc);
282 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000283}
284
drh0aa74ed2005-07-16 13:33:20 +0000285/*
286** Deallocate a WhereClause structure. The WhereClause structure
287** itself is not freed. This routine is the inverse of whereClauseInit().
288*/
289static void whereClauseClear(WhereClause *pWC){
290 int i;
291 WhereTerm *a;
drh633e6d52008-07-28 19:34:53 +0000292 sqlite3 *db = pWC->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000293 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000294 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000295 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000296 }
drh700a2262008-12-17 19:22:15 +0000297 if( a->wtFlags & TERM_ORINFO ){
298 whereOrInfoDelete(db, a->u.pOrInfo);
299 }else if( a->wtFlags & TERM_ANDINFO ){
300 whereAndInfoDelete(db, a->u.pAndInfo);
301 }
drh0aa74ed2005-07-16 13:33:20 +0000302 }
303 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000304 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000305 }
306}
307
308/*
drh6a1e0712008-12-05 15:24:15 +0000309** Add a single new WhereTerm entry to the WhereClause object pWC.
310** The new WhereTerm object is constructed from Expr p and with wtFlags.
311** The index in pWC->a[] of the new WhereTerm is returned on success.
312** 0 is returned if the new WhereTerm could not be added due to a memory
313** allocation error. The memory allocation failure will be recorded in
314** the db->mallocFailed flag so that higher-level functions can detect it.
315**
316** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000317**
drh165be382008-12-05 02:36:33 +0000318** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000319** for freeing the expression p is assumed by the WhereClause object pWC.
320** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000321**
drh9eb20282005-08-24 03:52:18 +0000322** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000323** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000324** calling this routine. Such pointers may be reinitialized by referencing
325** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000326*/
drhec1724e2008-12-09 01:32:03 +0000327static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000328 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000329 int idx;
drhe9cdcea2010-07-22 22:40:03 +0000330 testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
drh0aa74ed2005-07-16 13:33:20 +0000331 if( pWC->nTerm>=pWC->nSlot ){
332 WhereTerm *pOld = pWC->a;
drh633e6d52008-07-28 19:34:53 +0000333 sqlite3 *db = pWC->pParse->db;
334 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000335 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000336 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000337 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000338 }
drhf998b732007-11-26 13:36:00 +0000339 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000340 return 0;
341 }
drh0aa74ed2005-07-16 13:33:20 +0000342 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
343 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000344 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000345 }
drh6a1e0712008-12-05 15:24:15 +0000346 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000347 }
drh6a1e0712008-12-05 15:24:15 +0000348 pTerm = &pWC->a[idx = pWC->nTerm++];
drh0fcef5e2005-07-19 17:38:22 +0000349 pTerm->pExpr = p;
drh165be382008-12-05 02:36:33 +0000350 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000351 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000352 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000353 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000354}
drh75897232000-05-29 14:26:00 +0000355
356/*
drh51669862004-12-18 18:40:26 +0000357** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000358** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000359** operator specified in the op parameter. The WhereClause structure
360** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000361**
drh51669862004-12-18 18:40:26 +0000362** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
363** \________/ \_______________/ \________________/
364** slot[0] slot[1] slot[2]
365**
366** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000367** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000368**
drh51147ba2005-07-23 22:59:55 +0000369** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000370** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000371** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000372*/
drh6c30be82005-07-29 15:10:17 +0000373static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
drh29435252008-12-28 18:35:08 +0000374 pWC->op = (u8)op;
drh0aa74ed2005-07-16 13:33:20 +0000375 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000376 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000377 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000378 }else{
drh6c30be82005-07-29 15:10:17 +0000379 whereSplit(pWC, pExpr->pLeft, op);
380 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000381 }
drh75897232000-05-29 14:26:00 +0000382}
383
384/*
drh61495262009-04-22 15:32:59 +0000385** Initialize an expression mask set (a WhereMaskSet object)
drh6a3ea0e2003-05-02 14:32:12 +0000386*/
387#define initMaskSet(P) memset(P, 0, sizeof(*P))
388
389/*
drh1398ad32005-01-19 23:24:50 +0000390** Return the bitmask for the given cursor number. Return 0 if
391** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000392*/
drh111a6a72008-12-21 03:51:16 +0000393static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000394 int i;
drh3500ed62009-05-05 15:46:43 +0000395 assert( pMaskSet->n<=sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000396 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000397 if( pMaskSet->ix[i]==iCursor ){
398 return ((Bitmask)1)<<i;
399 }
drh6a3ea0e2003-05-02 14:32:12 +0000400 }
drh6a3ea0e2003-05-02 14:32:12 +0000401 return 0;
402}
403
404/*
drh1398ad32005-01-19 23:24:50 +0000405** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000406**
407** There is one cursor per table in the FROM clause. The number of
408** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000409** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000410** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000411*/
drh111a6a72008-12-21 03:51:16 +0000412static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000413 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000414 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000415}
416
417/*
drh75897232000-05-29 14:26:00 +0000418** This routine walks (recursively) an expression tree and generates
419** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000420** tree.
drh75897232000-05-29 14:26:00 +0000421**
422** In order for this routine to work, the calling function must have
drh7d10d5a2008-08-20 16:35:10 +0000423** previously invoked sqlite3ResolveExprNames() on the expression. See
drh75897232000-05-29 14:26:00 +0000424** the header comment on that routine for additional information.
drh7d10d5a2008-08-20 16:35:10 +0000425** The sqlite3ResolveExprNames() routines looks for column names and
drh6a3ea0e2003-05-02 14:32:12 +0000426** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
drh51147ba2005-07-23 22:59:55 +0000427** the VDBE cursor number of the table. This routine just has to
428** translate the cursor numbers into bitmask values and OR all
429** the bitmasks together.
drh75897232000-05-29 14:26:00 +0000430*/
drh111a6a72008-12-21 03:51:16 +0000431static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
432static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
433static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000434 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000435 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000436 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000437 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000438 return mask;
drh75897232000-05-29 14:26:00 +0000439 }
danielk1977b3bce662005-01-29 08:32:43 +0000440 mask = exprTableUsage(pMaskSet, p->pRight);
441 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000442 if( ExprHasProperty(p, EP_xIsSelect) ){
443 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
444 }else{
445 mask |= exprListTableUsage(pMaskSet, p->x.pList);
446 }
danielk1977b3bce662005-01-29 08:32:43 +0000447 return mask;
448}
drh111a6a72008-12-21 03:51:16 +0000449static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000450 int i;
451 Bitmask mask = 0;
452 if( pList ){
453 for(i=0; i<pList->nExpr; i++){
454 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000455 }
456 }
drh75897232000-05-29 14:26:00 +0000457 return mask;
458}
drh111a6a72008-12-21 03:51:16 +0000459static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000460 Bitmask mask = 0;
461 while( pS ){
462 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000463 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
464 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
465 mask |= exprTableUsage(pMaskSet, pS->pWhere);
466 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha430ae82007-09-12 15:41:01 +0000467 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000468 }
469 return mask;
470}
drh75897232000-05-29 14:26:00 +0000471
472/*
drh487ab3c2001-11-08 00:45:21 +0000473** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000474** allowed for an indexable WHERE clause term. The allowed operators are
drhc27a1ce2002-06-14 20:58:45 +0000475** "=", "<", ">", "<=", ">=", and "IN".
drhe9cdcea2010-07-22 22:40:03 +0000476**
477** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
478** of one of the following forms: column = expression column > expression
479** column >= expression column < expression column <= expression
480** expression = column expression > column expression >= column
481** expression < column expression <= column column IN
482** (expression-list) column IN (subquery) column IS NULL
drh487ab3c2001-11-08 00:45:21 +0000483*/
484static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000485 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
486 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
487 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
488 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000489 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000490}
491
492/*
drh902b9ee2008-12-05 17:17:07 +0000493** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000494*/
495#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
496
497/*
drh909626d2008-05-30 14:58:37 +0000498** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000499** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000500**
501** If a collation sequence is associated with either the left or right
502** side of the comparison, it remains associated with the same side after
503** the commutation. So "Y collate NOCASE op X" becomes
504** "X collate NOCASE op Y". This is because any collation sequence on
505** the left hand side of a comparison overrides any collation sequence
506** attached to the right. For the same reason the EP_ExpCollate flag
507** is not commuted.
drh193bd772004-07-20 18:23:14 +0000508*/
drh7d10d5a2008-08-20 16:35:10 +0000509static void exprCommute(Parse *pParse, Expr *pExpr){
danielk1977eb5453d2007-07-30 14:40:48 +0000510 u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
511 u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
drhfe05af82005-07-21 03:14:59 +0000512 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drh7d10d5a2008-08-20 16:35:10 +0000513 pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
514 pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
drh0fcef5e2005-07-19 17:38:22 +0000515 SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
danielk1977eb5453d2007-07-30 14:40:48 +0000516 pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
517 pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
drh0fcef5e2005-07-19 17:38:22 +0000518 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
519 if( pExpr->op>=TK_GT ){
520 assert( TK_LT==TK_GT+2 );
521 assert( TK_GE==TK_LE+2 );
522 assert( TK_GT>TK_EQ );
523 assert( TK_GT<TK_LE );
524 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
525 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000526 }
drh193bd772004-07-20 18:23:14 +0000527}
528
529/*
drhfe05af82005-07-21 03:14:59 +0000530** Translate from TK_xx operator to WO_xx bitmask.
531*/
drhec1724e2008-12-09 01:32:03 +0000532static u16 operatorMask(int op){
533 u16 c;
drhfe05af82005-07-21 03:14:59 +0000534 assert( allowedOp(op) );
535 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000536 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000537 }else if( op==TK_ISNULL ){
538 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000539 }else{
drhec1724e2008-12-09 01:32:03 +0000540 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
541 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000542 }
drh50b39962006-10-28 00:28:09 +0000543 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000544 assert( op!=TK_IN || c==WO_IN );
545 assert( op!=TK_EQ || c==WO_EQ );
546 assert( op!=TK_LT || c==WO_LT );
547 assert( op!=TK_LE || c==WO_LE );
548 assert( op!=TK_GT || c==WO_GT );
549 assert( op!=TK_GE || c==WO_GE );
550 return c;
drhfe05af82005-07-21 03:14:59 +0000551}
552
553/*
554** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
555** where X is a reference to the iColumn of table iCur and <op> is one of
556** the WO_xx operator codes specified by the op parameter.
557** Return a pointer to the term. Return 0 if not found.
558*/
559static WhereTerm *findTerm(
560 WhereClause *pWC, /* The WHERE clause to be searched */
561 int iCur, /* Cursor number of LHS */
562 int iColumn, /* Column number of LHS */
563 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +0000564 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +0000565 Index *pIdx /* Must be compatible with this index, if not NULL */
566){
567 WhereTerm *pTerm;
568 int k;
drh22c24032008-07-09 13:28:53 +0000569 assert( iCur>=0 );
drhec1724e2008-12-09 01:32:03 +0000570 op &= WO_ALL;
drhfe05af82005-07-21 03:14:59 +0000571 for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
572 if( pTerm->leftCursor==iCur
573 && (pTerm->prereqRight & notReady)==0
drh700a2262008-12-17 19:22:15 +0000574 && pTerm->u.leftColumn==iColumn
drhb52076c2006-01-23 13:22:09 +0000575 && (pTerm->eOperator & op)!=0
drhfe05af82005-07-21 03:14:59 +0000576 ){
drh22c24032008-07-09 13:28:53 +0000577 if( pIdx && pTerm->eOperator!=WO_ISNULL ){
drhfe05af82005-07-21 03:14:59 +0000578 Expr *pX = pTerm->pExpr;
579 CollSeq *pColl;
580 char idxaff;
danielk1977f0113002006-01-24 12:09:17 +0000581 int j;
drhfe05af82005-07-21 03:14:59 +0000582 Parse *pParse = pWC->pParse;
583
584 idxaff = pIdx->pTable->aCol[iColumn].affinity;
585 if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
danielk1977bcbb04e2007-05-29 12:11:29 +0000586
587 /* Figure out the collation sequence required from an index for
588 ** it to be useful for optimising expression pX. Store this
589 ** value in variable pColl.
590 */
591 assert(pX->pLeft);
592 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
danielk197793574162008-12-30 15:26:29 +0000593 assert(pColl || pParse->nErr);
danielk1977bcbb04e2007-05-29 12:11:29 +0000594
drh22c24032008-07-09 13:28:53 +0000595 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
drh34004ce2008-07-11 16:15:17 +0000596 if( NEVER(j>=pIdx->nColumn) ) return 0;
drh22c24032008-07-09 13:28:53 +0000597 }
danielk197793574162008-12-30 15:26:29 +0000598 if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
drhfe05af82005-07-21 03:14:59 +0000599 }
600 return pTerm;
601 }
602 }
603 return 0;
604}
605
drh6c30be82005-07-29 15:10:17 +0000606/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +0000607static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +0000608
609/*
610** Call exprAnalyze on all terms in a WHERE clause.
611**
612**
613*/
614static void exprAnalyzeAll(
615 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +0000616 WhereClause *pWC /* the WHERE clause to be analyzed */
617){
drh6c30be82005-07-29 15:10:17 +0000618 int i;
drh9eb20282005-08-24 03:52:18 +0000619 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +0000620 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +0000621 }
622}
623
drhd2687b72005-08-12 22:56:09 +0000624#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
625/*
626** Check to see if the given expression is a LIKE or GLOB operator that
627** can be optimized using inequality constraints. Return TRUE if it is
628** so and false if not.
629**
630** In order for the operator to be optimizible, the RHS must be a string
631** literal that does not begin with a wildcard.
632*/
633static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +0000634 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +0000635 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +0000636 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +0000637 int *pisComplete, /* True if the only wildcard is % in the last character */
638 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +0000639){
dan937d0de2009-10-15 18:35:38 +0000640 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +0000641 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
642 ExprList *pList; /* List of operands to the LIKE operator */
643 int c; /* One character in z[] */
644 int cnt; /* Number of non-wildcard prefix characters */
645 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +0000646 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +0000647 sqlite3_value *pVal = 0;
648 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +0000649
drh9f504ea2008-02-23 21:55:39 +0000650 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +0000651 return 0;
652 }
drh9f504ea2008-02-23 21:55:39 +0000653#ifdef SQLITE_EBCDIC
654 if( *pnoCase ) return 0;
655#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000656 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +0000657 pLeft = pList->a[1].pExpr;
drhd91ca492009-10-22 20:50:36 +0000658 if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
659 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
660 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +0000661 return 0;
662 }
drhd91ca492009-10-22 20:50:36 +0000663 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +0000664
665 pRight = pList->a[0].pExpr;
666 op = pRight->op;
667 if( op==TK_REGISTER ){
668 op = pRight->op2;
669 }
670 if( op==TK_VARIABLE ){
671 Vdbe *pReprepare = pParse->pReprepare;
672 pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
673 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
674 z = (char *)sqlite3_value_text(pVal);
675 }
dan1d2ce4f2009-10-19 18:11:09 +0000676 sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000677 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
678 }else if( op==TK_STRING ){
679 z = pRight->u.zToken;
680 }
681 if( z ){
shane85095702009-06-15 16:27:08 +0000682 cnt = 0;
drhb7916a72009-05-27 10:31:29 +0000683 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +0000684 cnt++;
685 }
drh93ee23c2010-07-22 12:33:57 +0000686 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +0000687 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +0000688 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +0000689 pPrefix = sqlite3Expr(db, TK_STRING, z);
690 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
691 *ppPrefix = pPrefix;
692 if( op==TK_VARIABLE ){
693 Vdbe *v = pParse->pVdbe;
dan1d2ce4f2009-10-19 18:11:09 +0000694 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +0000695 if( *pisComplete && pRight->u.zToken[1] ){
696 /* If the rhs of the LIKE expression is a variable, and the current
697 ** value of the variable means there is no need to invoke the LIKE
698 ** function, then no OP_Variable will be added to the program.
699 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +0000700 ** API. To workaround them, add a dummy OP_Variable here.
701 */
702 int r1 = sqlite3GetTempReg(pParse);
703 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +0000704 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +0000705 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +0000706 }
707 }
708 }else{
709 z = 0;
shane85095702009-06-15 16:27:08 +0000710 }
drhf998b732007-11-26 13:36:00 +0000711 }
dan937d0de2009-10-15 18:35:38 +0000712
713 sqlite3ValueFree(pVal);
714 return (z!=0);
drhd2687b72005-08-12 22:56:09 +0000715}
716#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
717
drhedb193b2006-06-27 13:20:21 +0000718
719#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +0000720/*
drh7f375902006-06-13 17:38:59 +0000721** Check to see if the given expression is of the form
722**
723** column MATCH expr
724**
725** If it is then return TRUE. If not, return FALSE.
726*/
727static int isMatchOfColumn(
728 Expr *pExpr /* Test this expression */
729){
730 ExprList *pList;
731
732 if( pExpr->op!=TK_FUNCTION ){
733 return 0;
734 }
drh33e619f2009-05-28 01:00:55 +0000735 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +0000736 return 0;
737 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000738 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +0000739 if( pList->nExpr!=2 ){
740 return 0;
741 }
742 if( pList->a[1].pExpr->op != TK_COLUMN ){
743 return 0;
744 }
745 return 1;
746}
drhedb193b2006-06-27 13:20:21 +0000747#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +0000748
749/*
drh54a167d2005-11-26 14:08:07 +0000750** If the pBase expression originated in the ON or USING clause of
751** a join, then transfer the appropriate markings over to derived.
752*/
753static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
754 pDerived->flags |= pBase->flags & EP_FromJoin;
755 pDerived->iRightJoinTable = pBase->iRightJoinTable;
756}
757
drh3e355802007-02-23 23:13:33 +0000758#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
759/*
drh1a58fe02008-12-20 02:06:13 +0000760** Analyze a term that consists of two or more OR-connected
761** subterms. So in:
drh3e355802007-02-23 23:13:33 +0000762**
drh1a58fe02008-12-20 02:06:13 +0000763** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
764** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +0000765**
drh1a58fe02008-12-20 02:06:13 +0000766** This routine analyzes terms such as the middle term in the above example.
767** A WhereOrTerm object is computed and attached to the term under
768** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +0000769**
drh1a58fe02008-12-20 02:06:13 +0000770** WhereTerm.wtFlags |= TERM_ORINFO
771** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +0000772**
drh1a58fe02008-12-20 02:06:13 +0000773** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +0000774** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +0000775** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +0000776**
drh1a58fe02008-12-20 02:06:13 +0000777** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
778** (B) x=expr1 OR expr2=x OR x=expr3
779** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
780** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
781** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
drh3e355802007-02-23 23:13:33 +0000782**
drh1a58fe02008-12-20 02:06:13 +0000783** CASE 1:
784**
785** If all subterms are of the form T.C=expr for some single column of C
786** a single table T (as shown in example B above) then create a new virtual
787** term that is an equivalent IN expression. In other words, if the term
788** being analyzed is:
789**
790** x = expr1 OR expr2 = x OR x = expr3
791**
792** then create a new virtual term like this:
793**
794** x IN (expr1,expr2,expr3)
795**
796** CASE 2:
797**
798** If all subterms are indexable by a single table T, then set
799**
800** WhereTerm.eOperator = WO_OR
801** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
802**
803** A subterm is "indexable" if it is of the form
804** "T.C <op> <expr>" where C is any column of table T and
805** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
806** A subterm is also indexable if it is an AND of two or more
807** subsubterms at least one of which is indexable. Indexable AND
808** subterms have their eOperator set to WO_AND and they have
809** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
810**
811** From another point of view, "indexable" means that the subterm could
812** potentially be used with an index if an appropriate index exists.
813** This analysis does not consider whether or not the index exists; that
814** is something the bestIndex() routine will determine. This analysis
815** only looks at whether subterms appropriate for indexing exist.
816**
817** All examples A through E above all satisfy case 2. But if a term
818** also statisfies case 1 (such as B) we know that the optimizer will
819** always prefer case 1, so in that case we pretend that case 2 is not
820** satisfied.
821**
822** It might be the case that multiple tables are indexable. For example,
823** (E) above is indexable on tables P, Q, and R.
824**
825** Terms that satisfy case 2 are candidates for lookup by using
826** separate indices to find rowids for each subterm and composing
827** the union of all rowids using a RowSet object. This is similar
828** to "bitmap indices" in other database engines.
829**
830** OTHERWISE:
831**
832** If neither case 1 nor case 2 apply, then leave the eOperator set to
833** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +0000834*/
drh1a58fe02008-12-20 02:06:13 +0000835static void exprAnalyzeOrTerm(
836 SrcList *pSrc, /* the FROM clause */
837 WhereClause *pWC, /* the complete WHERE clause */
838 int idxTerm /* Index of the OR-term to be analyzed */
839){
840 Parse *pParse = pWC->pParse; /* Parser context */
841 sqlite3 *db = pParse->db; /* Database connection */
842 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
843 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh111a6a72008-12-21 03:51:16 +0000844 WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
drh1a58fe02008-12-20 02:06:13 +0000845 int i; /* Loop counters */
846 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
847 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
848 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
849 Bitmask chngToIN; /* Tables that might satisfy case 1 */
850 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +0000851
drh1a58fe02008-12-20 02:06:13 +0000852 /*
853 ** Break the OR clause into its separate subterms. The subterms are
854 ** stored in a WhereClause structure containing within the WhereOrInfo
855 ** object that is attached to the original OR clause term.
856 */
857 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
858 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +0000859 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +0000860 if( pOrInfo==0 ) return;
861 pTerm->wtFlags |= TERM_ORINFO;
862 pOrWc = &pOrInfo->wc;
863 whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
864 whereSplit(pOrWc, pExpr, TK_OR);
865 exprAnalyzeAll(pSrc, pOrWc);
866 if( db->mallocFailed ) return;
867 assert( pOrWc->nTerm>=2 );
868
869 /*
870 ** Compute the set of tables that might satisfy cases 1 or 2.
871 */
danielk1977e672c8e2009-05-22 15:43:26 +0000872 indexable = ~(Bitmask)0;
873 chngToIN = ~(pWC->vmask);
drh1a58fe02008-12-20 02:06:13 +0000874 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
875 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +0000876 WhereAndInfo *pAndInfo;
877 assert( pOrTerm->eOperator==0 );
878 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +0000879 chngToIN = 0;
drh29435252008-12-28 18:35:08 +0000880 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
881 if( pAndInfo ){
882 WhereClause *pAndWC;
883 WhereTerm *pAndTerm;
884 int j;
885 Bitmask b = 0;
886 pOrTerm->u.pAndInfo = pAndInfo;
887 pOrTerm->wtFlags |= TERM_ANDINFO;
888 pOrTerm->eOperator = WO_AND;
889 pAndWC = &pAndInfo->wc;
890 whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
891 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
892 exprAnalyzeAll(pSrc, pAndWC);
drh7c2fbde2009-01-07 20:58:57 +0000893 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +0000894 if( !db->mallocFailed ){
895 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
896 assert( pAndTerm->pExpr );
897 if( allowedOp(pAndTerm->pExpr->op) ){
898 b |= getMask(pMaskSet, pAndTerm->leftCursor);
899 }
drh29435252008-12-28 18:35:08 +0000900 }
901 }
902 indexable &= b;
903 }
drh1a58fe02008-12-20 02:06:13 +0000904 }else if( pOrTerm->wtFlags & TERM_COPIED ){
905 /* Skip this term for now. We revisit it when we process the
906 ** corresponding TERM_VIRTUAL term */
907 }else{
908 Bitmask b;
909 b = getMask(pMaskSet, pOrTerm->leftCursor);
910 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
911 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
912 b |= getMask(pMaskSet, pOther->leftCursor);
913 }
914 indexable &= b;
915 if( pOrTerm->eOperator!=WO_EQ ){
916 chngToIN = 0;
917 }else{
918 chngToIN &= b;
919 }
920 }
drh3e355802007-02-23 23:13:33 +0000921 }
drh1a58fe02008-12-20 02:06:13 +0000922
923 /*
924 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +0000925 ** empty.
drh1a58fe02008-12-20 02:06:13 +0000926 */
927 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +0000928 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +0000929
930 /*
931 ** chngToIN holds a set of tables that *might* satisfy case 1. But
932 ** we have to do some additional checking to see if case 1 really
933 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +0000934 **
935 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
936 ** that there is no possibility of transforming the OR clause into an
937 ** IN operator because one or more terms in the OR clause contain
938 ** something other than == on a column in the single table. The 1-bit
939 ** case means that every term of the OR clause is of the form
940 ** "table.column=expr" for some single table. The one bit that is set
941 ** will correspond to the common table. We still need to check to make
942 ** sure the same column is used on all terms. The 2-bit case is when
943 ** the all terms are of the form "table1.column=table2.column". It
944 ** might be possible to form an IN operator with either table1.column
945 ** or table2.column as the LHS if either is common to every term of
946 ** the OR clause.
947 **
948 ** Note that terms of the form "table.column1=table.column2" (the
949 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +0000950 */
951 if( chngToIN ){
952 int okToChngToIN = 0; /* True if the conversion to IN is valid */
953 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +0000954 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +0000955 int j = 0; /* Loop counter */
956
957 /* Search for a table and column that appears on one side or the
958 ** other of the == operator in every subterm. That table and column
959 ** will be recorded in iCursor and iColumn. There might not be any
960 ** such table and column. Set okToChngToIN if an appropriate table
961 ** and column is found but leave okToChngToIN false if not found.
962 */
963 for(j=0; j<2 && !okToChngToIN; j++){
964 pOrTerm = pOrWc->a;
965 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
966 assert( pOrTerm->eOperator==WO_EQ );
967 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +0000968 if( pOrTerm->leftCursor==iCursor ){
969 /* This is the 2-bit case and we are on the second iteration and
970 ** current term is from the first iteration. So skip this term. */
971 assert( j==1 );
972 continue;
973 }
974 if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
975 /* This term must be of the form t1.a==t2.b where t2 is in the
976 ** chngToIN set but t1 is not. This term will be either preceeded
977 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
978 ** and use its inversion. */
979 testcase( pOrTerm->wtFlags & TERM_COPIED );
980 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
981 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
982 continue;
983 }
drh1a58fe02008-12-20 02:06:13 +0000984 iColumn = pOrTerm->u.leftColumn;
985 iCursor = pOrTerm->leftCursor;
986 break;
987 }
988 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +0000989 /* No candidate table+column was found. This can only occur
990 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +0000991 assert( j==1 );
992 assert( (chngToIN&(chngToIN-1))==0 );
drh4e8be3b2009-06-08 17:11:08 +0000993 assert( chngToIN==getMask(pMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +0000994 break;
995 }
drh4e8be3b2009-06-08 17:11:08 +0000996 testcase( j==1 );
997
998 /* We have found a candidate table and column. Check to see if that
999 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001000 okToChngToIN = 1;
1001 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
1002 assert( pOrTerm->eOperator==WO_EQ );
1003 if( pOrTerm->leftCursor!=iCursor ){
1004 pOrTerm->wtFlags &= ~TERM_OR_OK;
1005 }else if( pOrTerm->u.leftColumn!=iColumn ){
1006 okToChngToIN = 0;
1007 }else{
1008 int affLeft, affRight;
1009 /* If the right-hand side is also a column, then the affinities
1010 ** of both right and left sides must be such that no type
1011 ** conversions are required on the right. (Ticket #2249)
1012 */
1013 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1014 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1015 if( affRight!=0 && affRight!=affLeft ){
1016 okToChngToIN = 0;
1017 }else{
1018 pOrTerm->wtFlags |= TERM_OR_OK;
1019 }
1020 }
1021 }
1022 }
1023
1024 /* At this point, okToChngToIN is true if original pTerm satisfies
1025 ** case 1. In that case, construct a new virtual term that is
1026 ** pTerm converted into an IN operator.
drhe9cdcea2010-07-22 22:40:03 +00001027 **
1028 ** EV: R-00211-15100
drh1a58fe02008-12-20 02:06:13 +00001029 */
1030 if( okToChngToIN ){
1031 Expr *pDup; /* A transient duplicate expression */
1032 ExprList *pList = 0; /* The RHS of the IN operator */
1033 Expr *pLeft = 0; /* The LHS of the IN operator */
1034 Expr *pNew; /* The complete IN operator */
1035
1036 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1037 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
1038 assert( pOrTerm->eOperator==WO_EQ );
1039 assert( pOrTerm->leftCursor==iCursor );
1040 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001041 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drhb7916a72009-05-27 10:31:29 +00001042 pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001043 pLeft = pOrTerm->pExpr->pLeft;
1044 }
1045 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001046 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001047 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001048 if( pNew ){
1049 int idxNew;
1050 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001051 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1052 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001053 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1054 testcase( idxNew==0 );
1055 exprAnalyze(pSrc, pWC, idxNew);
1056 pTerm = &pWC->a[idxTerm];
1057 pWC->a[idxNew].iParent = idxTerm;
1058 pTerm->nChild = 1;
1059 }else{
1060 sqlite3ExprListDelete(db, pList);
1061 }
1062 pTerm->eOperator = 0; /* case 1 trumps case 2 */
1063 }
drh3e355802007-02-23 23:13:33 +00001064 }
drh3e355802007-02-23 23:13:33 +00001065}
1066#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001067
drh1a58fe02008-12-20 02:06:13 +00001068
drh54a167d2005-11-26 14:08:07 +00001069/*
drh0aa74ed2005-07-16 13:33:20 +00001070** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001071** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001072** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001073** structure.
drh51147ba2005-07-23 22:59:55 +00001074**
1075** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001076** to the standard form of "X <op> <expr>".
1077**
1078** If the expression is of the form "X <op> Y" where both X and Y are
1079** columns, then the original expression is unchanged and a new virtual
1080** term of the form "Y <op> X" is added to the WHERE clause and
1081** analyzed separately. The original term is marked with TERM_COPIED
1082** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1083** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1084** is a commuted copy of a prior term.) The original term has nChild=1
1085** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001086*/
drh0fcef5e2005-07-19 17:38:22 +00001087static void exprAnalyze(
1088 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001089 WhereClause *pWC, /* the WHERE clause */
1090 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001091){
drh1a58fe02008-12-20 02:06:13 +00001092 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001093 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001094 Expr *pExpr; /* The expression to be analyzed */
1095 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1096 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001097 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001098 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1099 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1100 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001101 int op; /* Top-level operator. pExpr->op */
1102 Parse *pParse = pWC->pParse; /* Parsing context */
1103 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001104
drhf998b732007-11-26 13:36:00 +00001105 if( db->mallocFailed ){
1106 return;
1107 }
1108 pTerm = &pWC->a[idxTerm];
1109 pMaskSet = pWC->pMaskSet;
1110 pExpr = pTerm->pExpr;
drh0fcef5e2005-07-19 17:38:22 +00001111 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001112 op = pExpr->op;
1113 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001114 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001115 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1116 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1117 }else{
1118 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1119 }
drh50b39962006-10-28 00:28:09 +00001120 }else if( op==TK_ISNULL ){
1121 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001122 }else{
1123 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1124 }
drh22d6a532005-09-19 21:05:48 +00001125 prereqAll = exprTableUsage(pMaskSet, pExpr);
1126 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001127 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1128 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001129 extraRight = x-1; /* ON clause terms may not be used with an index
1130 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001131 }
1132 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001133 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001134 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001135 pTerm->eOperator = 0;
drh50b39962006-10-28 00:28:09 +00001136 if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
drh0fcef5e2005-07-19 17:38:22 +00001137 Expr *pLeft = pExpr->pLeft;
1138 Expr *pRight = pExpr->pRight;
1139 if( pLeft->op==TK_COLUMN ){
1140 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001141 pTerm->u.leftColumn = pLeft->iColumn;
drh50b39962006-10-28 00:28:09 +00001142 pTerm->eOperator = operatorMask(op);
drh75897232000-05-29 14:26:00 +00001143 }
drh0fcef5e2005-07-19 17:38:22 +00001144 if( pRight && pRight->op==TK_COLUMN ){
1145 WhereTerm *pNew;
1146 Expr *pDup;
1147 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001148 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001149 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001150 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001151 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001152 return;
1153 }
drh9eb20282005-08-24 03:52:18 +00001154 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1155 if( idxNew==0 ) return;
1156 pNew = &pWC->a[idxNew];
1157 pNew->iParent = idxTerm;
1158 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001159 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001160 pTerm->wtFlags |= TERM_COPIED;
drh0fcef5e2005-07-19 17:38:22 +00001161 }else{
1162 pDup = pExpr;
1163 pNew = pTerm;
1164 }
drh7d10d5a2008-08-20 16:35:10 +00001165 exprCommute(pParse, pDup);
drh0fcef5e2005-07-19 17:38:22 +00001166 pLeft = pDup->pLeft;
1167 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001168 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001169 testcase( (prereqLeft | extraRight) != prereqLeft );
1170 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001171 pNew->prereqAll = prereqAll;
drhb52076c2006-01-23 13:22:09 +00001172 pNew->eOperator = operatorMask(pDup->op);
drh75897232000-05-29 14:26:00 +00001173 }
1174 }
drhed378002005-07-28 23:12:08 +00001175
drhd2687b72005-08-12 22:56:09 +00001176#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001177 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001178 ** that define the range that the BETWEEN implements. For example:
1179 **
1180 ** a BETWEEN b AND c
1181 **
1182 ** is converted into:
1183 **
1184 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1185 **
1186 ** The two new terms are added onto the end of the WhereClause object.
1187 ** The new terms are "dynamic" and are children of the original BETWEEN
1188 ** term. That means that if the BETWEEN term is coded, the children are
1189 ** skipped. Or, if the children are satisfied by an index, the original
1190 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001191 */
drh29435252008-12-28 18:35:08 +00001192 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001193 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001194 int i;
1195 static const u8 ops[] = {TK_GE, TK_LE};
1196 assert( pList!=0 );
1197 assert( pList->nExpr==2 );
1198 for(i=0; i<2; i++){
1199 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001200 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001201 pNewExpr = sqlite3PExpr(pParse, ops[i],
1202 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001203 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drh9eb20282005-08-24 03:52:18 +00001204 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001205 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001206 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001207 pTerm = &pWC->a[idxTerm];
1208 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001209 }
drh45b1ee42005-08-02 17:48:22 +00001210 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001211 }
drhd2687b72005-08-12 22:56:09 +00001212#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001213
danielk19771576cd92006-01-14 08:02:28 +00001214#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001215 /* Analyze a term that is composed of two or more subterms connected by
1216 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001217 */
1218 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001219 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001220 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001221 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001222 }
drhd2687b72005-08-12 22:56:09 +00001223#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1224
1225#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1226 /* Add constraints to reduce the search space on a LIKE or GLOB
1227 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001228 **
1229 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1230 **
1231 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1232 **
1233 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001234 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001235 */
dan937d0de2009-10-15 18:35:38 +00001236 if( pWC->op==TK_AND
1237 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1238 ){
drh1d452e12009-11-01 19:26:59 +00001239 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1240 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1241 Expr *pNewExpr1;
1242 Expr *pNewExpr2;
1243 int idxNew1;
1244 int idxNew2;
drh8342e492010-07-22 17:49:52 +00001245 CollSeq *pColl; /* Collating sequence to use */
drh9eb20282005-08-24 03:52:18 +00001246
danielk19776ab3a2e2009-02-19 14:39:25 +00001247 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001248 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001249 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001250 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001251 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001252 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001253 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001254 /* The point is to increment the last character before the first
1255 ** wildcard. But if we increment '@', that will push it into the
1256 ** alphabetic range where case conversions will mess up the
1257 ** inequality. To avoid this, make sure to also run the full
1258 ** LIKE on all candidate expressions by clearing the isComplete flag
1259 */
drhe9cdcea2010-07-22 22:40:03 +00001260 if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
1261
drh254993e2009-06-08 19:44:36 +00001262
drh02a50b72008-05-26 18:33:40 +00001263 c = sqlite3UpperToLower[c];
1264 }
drh9f504ea2008-02-23 21:55:39 +00001265 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001266 }
drh8342e492010-07-22 17:49:52 +00001267 pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
1268 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1269 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
1270 pStr1, 0);
drh9eb20282005-08-24 03:52:18 +00001271 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001272 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001273 exprAnalyze(pSrc, pWC, idxNew1);
drh8342e492010-07-22 17:49:52 +00001274 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1275 sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
1276 pStr2, 0);
drh9eb20282005-08-24 03:52:18 +00001277 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001278 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001279 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001280 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001281 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001282 pWC->a[idxNew1].iParent = idxTerm;
1283 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001284 pTerm->nChild = 2;
1285 }
1286 }
1287#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001288
1289#ifndef SQLITE_OMIT_VIRTUALTABLE
1290 /* Add a WO_MATCH auxiliary term to the constraint set if the
1291 ** current expression is of the form: column MATCH expr.
1292 ** This information is used by the xBestIndex methods of
1293 ** virtual tables. The native query optimizer does not attempt
1294 ** to do anything with MATCH functions.
1295 */
1296 if( isMatchOfColumn(pExpr) ){
1297 int idxNew;
1298 Expr *pRight, *pLeft;
1299 WhereTerm *pNewTerm;
1300 Bitmask prereqColumn, prereqExpr;
1301
danielk19776ab3a2e2009-02-19 14:39:25 +00001302 pRight = pExpr->x.pList->a[0].pExpr;
1303 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001304 prereqExpr = exprTableUsage(pMaskSet, pRight);
1305 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1306 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001307 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001308 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1309 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001310 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001311 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001312 pNewTerm = &pWC->a[idxNew];
1313 pNewTerm->prereqRight = prereqExpr;
1314 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001315 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001316 pNewTerm->eOperator = WO_MATCH;
1317 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001318 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001319 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001320 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001321 pNewTerm->prereqAll = pTerm->prereqAll;
1322 }
1323 }
1324#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001325
1326 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1327 ** an index for tables to the left of the join.
1328 */
1329 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001330}
1331
drh7b4fc6a2007-02-06 13:26:32 +00001332/*
1333** Return TRUE if any of the expressions in pList->a[iFirst...] contain
1334** a reference to any table other than the iBase table.
1335*/
1336static int referencesOtherTables(
1337 ExprList *pList, /* Search expressions in ths list */
drh111a6a72008-12-21 03:51:16 +00001338 WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
drh7b4fc6a2007-02-06 13:26:32 +00001339 int iFirst, /* Be searching with the iFirst-th expression */
1340 int iBase /* Ignore references to this table */
1341){
1342 Bitmask allowed = ~getMask(pMaskSet, iBase);
1343 while( iFirst<pList->nExpr ){
1344 if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
1345 return 1;
1346 }
1347 }
1348 return 0;
1349}
1350
drh0fcef5e2005-07-19 17:38:22 +00001351
drh75897232000-05-29 14:26:00 +00001352/*
drh51669862004-12-18 18:40:26 +00001353** This routine decides if pIdx can be used to satisfy the ORDER BY
1354** clause. If it can, it returns 1. If pIdx cannot satisfy the
1355** ORDER BY clause, this routine returns 0.
1356**
1357** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
1358** left-most table in the FROM clause of that same SELECT statement and
1359** the table has a cursor number of "base". pIdx is an index on pTab.
1360**
1361** nEqCol is the number of columns of pIdx that are used as equality
1362** constraints. Any of these columns may be missing from the ORDER BY
1363** clause and the match can still be a success.
1364**
drh51669862004-12-18 18:40:26 +00001365** All terms of the ORDER BY that match against the index must be either
1366** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
1367** index do not need to satisfy this constraint.) The *pbRev value is
1368** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
1369** the ORDER BY clause is all ASC.
1370*/
1371static int isSortingIndex(
1372 Parse *pParse, /* Parsing context */
drh111a6a72008-12-21 03:51:16 +00001373 WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
drh51669862004-12-18 18:40:26 +00001374 Index *pIdx, /* The index we are testing */
drh74161702006-02-24 02:53:49 +00001375 int base, /* Cursor number for the table to be sorted */
drh51669862004-12-18 18:40:26 +00001376 ExprList *pOrderBy, /* The ORDER BY clause */
1377 int nEqCol, /* Number of index columns with == constraints */
1378 int *pbRev /* Set to 1 if ORDER BY is DESC */
1379){
drhb46b5772005-08-29 16:40:52 +00001380 int i, j; /* Loop counters */
drh85eeb692005-12-21 03:16:42 +00001381 int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
drhb46b5772005-08-29 16:40:52 +00001382 int nTerm; /* Number of ORDER BY terms */
1383 struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
drh51669862004-12-18 18:40:26 +00001384 sqlite3 *db = pParse->db;
1385
1386 assert( pOrderBy!=0 );
1387 nTerm = pOrderBy->nExpr;
1388 assert( nTerm>0 );
1389
dan5236ac12009-08-13 07:09:33 +00001390 /* Argument pIdx must either point to a 'real' named index structure,
1391 ** or an index structure allocated on the stack by bestBtreeIndex() to
1392 ** represent the rowid index that is part of every table. */
1393 assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
1394
drh51669862004-12-18 18:40:26 +00001395 /* Match terms of the ORDER BY clause against columns of
1396 ** the index.
drhcc192542006-12-20 03:24:19 +00001397 **
1398 ** Note that indices have pIdx->nColumn regular columns plus
1399 ** one additional column containing the rowid. The rowid column
1400 ** of the index is also allowed to match against the ORDER BY
1401 ** clause.
drh51669862004-12-18 18:40:26 +00001402 */
drhcc192542006-12-20 03:24:19 +00001403 for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
drh51669862004-12-18 18:40:26 +00001404 Expr *pExpr; /* The expression of the ORDER BY pTerm */
1405 CollSeq *pColl; /* The collating sequence of pExpr */
drh85eeb692005-12-21 03:16:42 +00001406 int termSortOrder; /* Sort order for this term */
drhcc192542006-12-20 03:24:19 +00001407 int iColumn; /* The i-th column of the index. -1 for rowid */
1408 int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
1409 const char *zColl; /* Name of the collating sequence for i-th index term */
drh51669862004-12-18 18:40:26 +00001410
1411 pExpr = pTerm->pExpr;
1412 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
1413 /* Can not use an index sort on anything that is not a column in the
1414 ** left-most table of the FROM clause */
drh7b4fc6a2007-02-06 13:26:32 +00001415 break;
drh51669862004-12-18 18:40:26 +00001416 }
1417 pColl = sqlite3ExprCollSeq(pParse, pExpr);
drhcc192542006-12-20 03:24:19 +00001418 if( !pColl ){
1419 pColl = db->pDfltColl;
1420 }
dan5236ac12009-08-13 07:09:33 +00001421 if( pIdx->zName && i<pIdx->nColumn ){
drhcc192542006-12-20 03:24:19 +00001422 iColumn = pIdx->aiColumn[i];
1423 if( iColumn==pIdx->pTable->iPKey ){
1424 iColumn = -1;
1425 }
1426 iSortOrder = pIdx->aSortOrder[i];
1427 zColl = pIdx->azColl[i];
1428 }else{
1429 iColumn = -1;
1430 iSortOrder = 0;
1431 zColl = pColl->zName;
1432 }
1433 if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
drh9012bcb2004-12-19 00:11:35 +00001434 /* Term j of the ORDER BY clause does not match column i of the index */
1435 if( i<nEqCol ){
drh51669862004-12-18 18:40:26 +00001436 /* If an index column that is constrained by == fails to match an
1437 ** ORDER BY term, that is OK. Just ignore that column of the index
1438 */
1439 continue;
drhff354e92008-06-25 02:47:57 +00001440 }else if( i==pIdx->nColumn ){
1441 /* Index column i is the rowid. All other terms match. */
1442 break;
drh51669862004-12-18 18:40:26 +00001443 }else{
1444 /* If an index column fails to match and is not constrained by ==
1445 ** then the index cannot satisfy the ORDER BY constraint.
1446 */
1447 return 0;
1448 }
1449 }
dan5236ac12009-08-13 07:09:33 +00001450 assert( pIdx->aSortOrder!=0 || iColumn==-1 );
drh85eeb692005-12-21 03:16:42 +00001451 assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
drhcc192542006-12-20 03:24:19 +00001452 assert( iSortOrder==0 || iSortOrder==1 );
1453 termSortOrder = iSortOrder ^ pTerm->sortOrder;
drh51669862004-12-18 18:40:26 +00001454 if( i>nEqCol ){
drh85eeb692005-12-21 03:16:42 +00001455 if( termSortOrder!=sortOrder ){
drh51669862004-12-18 18:40:26 +00001456 /* Indices can only be used if all ORDER BY terms past the
1457 ** equality constraints are all either DESC or ASC. */
1458 return 0;
1459 }
1460 }else{
drh85eeb692005-12-21 03:16:42 +00001461 sortOrder = termSortOrder;
drh51669862004-12-18 18:40:26 +00001462 }
1463 j++;
1464 pTerm++;
drh7b4fc6a2007-02-06 13:26:32 +00001465 if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
drhcc192542006-12-20 03:24:19 +00001466 /* If the indexed column is the primary key and everything matches
drh7b4fc6a2007-02-06 13:26:32 +00001467 ** so far and none of the ORDER BY terms to the right reference other
1468 ** tables in the join, then we are assured that the index can be used
1469 ** to sort because the primary key is unique and so none of the other
1470 ** columns will make any difference
drhcc192542006-12-20 03:24:19 +00001471 */
1472 j = nTerm;
1473 }
drh51669862004-12-18 18:40:26 +00001474 }
1475
drhcc192542006-12-20 03:24:19 +00001476 *pbRev = sortOrder!=0;
drh8718f522005-08-13 16:13:04 +00001477 if( j>=nTerm ){
drhcc192542006-12-20 03:24:19 +00001478 /* All terms of the ORDER BY clause are covered by this index so
1479 ** this index can be used for sorting. */
1480 return 1;
1481 }
drh7b4fc6a2007-02-06 13:26:32 +00001482 if( pIdx->onError!=OE_None && i==pIdx->nColumn
1483 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
drhcc192542006-12-20 03:24:19 +00001484 /* All terms of this index match some prefix of the ORDER BY clause
drh7b4fc6a2007-02-06 13:26:32 +00001485 ** and the index is UNIQUE and no terms on the tail of the ORDER BY
1486 ** clause reference other tables in a join. If this is all true then
1487 ** the order by clause is superfluous. */
drh51669862004-12-18 18:40:26 +00001488 return 1;
1489 }
1490 return 0;
1491}
1492
1493/*
drhb6fb62d2005-09-20 08:47:20 +00001494** Prepare a crude estimate of the logarithm of the input value.
drh28c4cf42005-07-27 20:41:43 +00001495** The results need not be exact. This is only used for estimating
drh909626d2008-05-30 14:58:37 +00001496** the total cost of performing operations with O(logN) or O(NlogN)
drh28c4cf42005-07-27 20:41:43 +00001497** complexity. Because N is just a guess, it is no great tragedy if
1498** logN is a little off.
drh28c4cf42005-07-27 20:41:43 +00001499*/
1500static double estLog(double N){
drhb37df7b2005-10-13 02:09:49 +00001501 double logN = 1;
1502 double x = 10;
drh28c4cf42005-07-27 20:41:43 +00001503 while( N>x ){
drhb37df7b2005-10-13 02:09:49 +00001504 logN += 1;
drh28c4cf42005-07-27 20:41:43 +00001505 x *= 10;
1506 }
1507 return logN;
1508}
1509
drh6d209d82006-06-27 01:54:26 +00001510/*
1511** Two routines for printing the content of an sqlite3_index_info
1512** structure. Used for testing and debugging only. If neither
1513** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
1514** are no-ops.
1515*/
drh77a2a5e2007-04-06 01:04:39 +00001516#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
drh6d209d82006-06-27 01:54:26 +00001517static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
1518 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001519 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001520 for(i=0; i<p->nConstraint; i++){
1521 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
1522 i,
1523 p->aConstraint[i].iColumn,
1524 p->aConstraint[i].iTermOffset,
1525 p->aConstraint[i].op,
1526 p->aConstraint[i].usable);
1527 }
1528 for(i=0; i<p->nOrderBy; i++){
1529 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
1530 i,
1531 p->aOrderBy[i].iColumn,
1532 p->aOrderBy[i].desc);
1533 }
1534}
1535static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
1536 int i;
mlcreech3a00f902008-03-04 17:45:01 +00001537 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00001538 for(i=0; i<p->nConstraint; i++){
1539 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
1540 i,
1541 p->aConstraintUsage[i].argvIndex,
1542 p->aConstraintUsage[i].omit);
1543 }
1544 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
1545 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
1546 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
1547 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
1548}
1549#else
1550#define TRACE_IDX_INPUTS(A)
1551#define TRACE_IDX_OUTPUTS(A)
1552#endif
1553
danielk19771d461462009-04-21 09:02:45 +00001554/*
1555** Required because bestIndex() is called by bestOrClauseIndex()
1556*/
1557static void bestIndex(
1558 Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
1559
1560/*
1561** This routine attempts to find an scanning strategy that can be used
1562** to optimize an 'OR' expression that is part of a WHERE clause.
1563**
1564** The table associated with FROM clause term pSrc may be either a
1565** regular B-Tree table or a virtual table.
1566*/
1567static void bestOrClauseIndex(
1568 Parse *pParse, /* The parsing context */
1569 WhereClause *pWC, /* The WHERE clause */
1570 struct SrcList_item *pSrc, /* The FROM clause term to search */
1571 Bitmask notReady, /* Mask of cursors that are not available */
1572 ExprList *pOrderBy, /* The ORDER BY clause */
1573 WhereCost *pCost /* Lowest cost query plan */
1574){
1575#ifndef SQLITE_OMIT_OR_OPTIMIZATION
1576 const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
1577 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
1578 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
1579 WhereTerm *pTerm; /* A single term of the WHERE clause */
1580
drhed754ce2010-04-15 01:04:54 +00001581 /* No OR-clause optimization allowed if the NOT INDEXED clause is used */
1582 if( pSrc->notIndexed ){
1583 return;
1584 }
1585
danielk19771d461462009-04-21 09:02:45 +00001586 /* Search the WHERE clause terms for a usable WO_OR term. */
1587 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
1588 if( pTerm->eOperator==WO_OR
1589 && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
1590 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
1591 ){
1592 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
1593 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
1594 WhereTerm *pOrTerm;
1595 int flags = WHERE_MULTI_OR;
1596 double rTotal = 0;
1597 double nRow = 0;
dan5236ac12009-08-13 07:09:33 +00001598 Bitmask used = 0;
danielk19771d461462009-04-21 09:02:45 +00001599
1600 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
1601 WhereCost sTermCost;
1602 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
1603 (pOrTerm - pOrWC->a), (pTerm - pWC->a)
1604 ));
1605 if( pOrTerm->eOperator==WO_AND ){
1606 WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
1607 bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
1608 }else if( pOrTerm->leftCursor==iCur ){
1609 WhereClause tempWC;
1610 tempWC.pParse = pWC->pParse;
1611 tempWC.pMaskSet = pWC->pMaskSet;
1612 tempWC.op = TK_AND;
1613 tempWC.a = pOrTerm;
1614 tempWC.nTerm = 1;
1615 bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
1616 }else{
1617 continue;
1618 }
1619 rTotal += sTermCost.rCost;
1620 nRow += sTermCost.nRow;
dan5236ac12009-08-13 07:09:33 +00001621 used |= sTermCost.used;
danielk19771d461462009-04-21 09:02:45 +00001622 if( rTotal>=pCost->rCost ) break;
1623 }
1624
1625 /* If there is an ORDER BY clause, increase the scan cost to account
1626 ** for the cost of the sort. */
1627 if( pOrderBy!=0 ){
drhed754ce2010-04-15 01:04:54 +00001628 WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
1629 rTotal, rTotal+nRow*estLog(nRow)));
danielk19771d461462009-04-21 09:02:45 +00001630 rTotal += nRow*estLog(nRow);
danielk19771d461462009-04-21 09:02:45 +00001631 }
1632
1633 /* If the cost of scanning using this OR term for optimization is
1634 ** less than the current cost stored in pCost, replace the contents
1635 ** of pCost. */
1636 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
1637 if( rTotal<pCost->rCost ){
1638 pCost->rCost = rTotal;
1639 pCost->nRow = nRow;
dan5236ac12009-08-13 07:09:33 +00001640 pCost->used = used;
danielk19771d461462009-04-21 09:02:45 +00001641 pCost->plan.wsFlags = flags;
1642 pCost->plan.u.pTerm = pTerm;
1643 }
1644 }
1645 }
1646#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1647}
1648
drhc6339082010-04-07 16:54:58 +00001649#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001650/*
drh4139c992010-04-07 14:59:45 +00001651** Return TRUE if the WHERE clause term pTerm is of a form where it
1652** could be used with an index to access pSrc, assuming an appropriate
1653** index existed.
1654*/
1655static int termCanDriveIndex(
1656 WhereTerm *pTerm, /* WHERE clause term to check */
1657 struct SrcList_item *pSrc, /* Table we are trying to access */
1658 Bitmask notReady /* Tables in outer loops of the join */
1659){
1660 char aff;
1661 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
1662 if( pTerm->eOperator!=WO_EQ ) return 0;
1663 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
1664 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
1665 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
1666 return 1;
1667}
drhc6339082010-04-07 16:54:58 +00001668#endif
drh4139c992010-04-07 14:59:45 +00001669
drhc6339082010-04-07 16:54:58 +00001670#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh4139c992010-04-07 14:59:45 +00001671/*
drh8b307fb2010-04-06 15:57:05 +00001672** If the query plan for pSrc specified in pCost is a full table scan
drh4139c992010-04-07 14:59:45 +00001673** and indexing is allows (if there is no NOT INDEXED clause) and it
drh8b307fb2010-04-06 15:57:05 +00001674** possible to construct a transient index that would perform better
1675** than a full table scan even when the cost of constructing the index
1676** is taken into account, then alter the query plan to use the
1677** transient index.
1678*/
drhc6339082010-04-07 16:54:58 +00001679static void bestAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001680 Parse *pParse, /* The parsing context */
1681 WhereClause *pWC, /* The WHERE clause */
1682 struct SrcList_item *pSrc, /* The FROM clause term to search */
1683 Bitmask notReady, /* Mask of cursors that are not available */
1684 WhereCost *pCost /* Lowest cost query plan */
1685){
1686 double nTableRow; /* Rows in the input table */
1687 double logN; /* log(nTableRow) */
1688 double costTempIdx; /* per-query cost of the transient index */
1689 WhereTerm *pTerm; /* A single term of the WHERE clause */
1690 WhereTerm *pWCEnd; /* End of pWC->a[] */
drh424aab82010-04-06 18:28:20 +00001691 Table *pTable; /* Table tht might be indexed */
drh8b307fb2010-04-06 15:57:05 +00001692
drhc6339082010-04-07 16:54:58 +00001693 if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
1694 /* Automatic indices are disabled at run-time */
1695 return;
1696 }
drh8b307fb2010-04-06 15:57:05 +00001697 if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
1698 /* We already have some kind of index in use for this query. */
1699 return;
1700 }
1701 if( pSrc->notIndexed ){
1702 /* The NOT INDEXED clause appears in the SQL. */
1703 return;
1704 }
1705
1706 assert( pParse->nQueryLoop >= (double)1 );
drh8bd54122010-04-08 15:00:59 +00001707 pTable = pSrc->pTab;
1708 nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
drh8b307fb2010-04-06 15:57:05 +00001709 logN = estLog(nTableRow);
1710 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
1711 if( costTempIdx>=pCost->rCost ){
1712 /* The cost of creating the transient table would be greater than
1713 ** doing the full table scan */
1714 return;
1715 }
1716
1717 /* Search for any equality comparison term */
1718 pWCEnd = &pWC->a[pWC->nTerm];
1719 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001720 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh8b307fb2010-04-06 15:57:05 +00001721 WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
1722 pCost->rCost, costTempIdx));
1723 pCost->rCost = costTempIdx;
1724 pCost->nRow = logN + 1;
1725 pCost->plan.wsFlags = WHERE_TEMP_INDEX;
1726 pCost->used = pTerm->prereqRight;
1727 break;
1728 }
1729 }
1730}
drhc6339082010-04-07 16:54:58 +00001731#else
1732# define bestAutomaticIndex(A,B,C,D,E) /* no-op */
1733#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001734
drhc6339082010-04-07 16:54:58 +00001735
1736#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00001737/*
drhc6339082010-04-07 16:54:58 +00001738** Generate code to construct the Index object for an automatic index
1739** and to set up the WhereLevel object pLevel so that the code generator
1740** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00001741*/
drhc6339082010-04-07 16:54:58 +00001742static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00001743 Parse *pParse, /* The parsing context */
1744 WhereClause *pWC, /* The WHERE clause */
1745 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
1746 Bitmask notReady, /* Mask of cursors that are not available */
1747 WhereLevel *pLevel /* Write new index here */
1748){
1749 int nColumn; /* Number of columns in the constructed index */
1750 WhereTerm *pTerm; /* A single term of the WHERE clause */
1751 WhereTerm *pWCEnd; /* End of pWC->a[] */
1752 int nByte; /* Byte of memory needed for pIdx */
1753 Index *pIdx; /* Object describing the transient index */
1754 Vdbe *v; /* Prepared statement under construction */
1755 int regIsInit; /* Register set by initialization */
1756 int addrInit; /* Address of the initialization bypass jump */
1757 Table *pTable; /* The table being indexed */
1758 KeyInfo *pKeyinfo; /* Key information for the index */
1759 int addrTop; /* Top of the index fill loop */
1760 int regRecord; /* Register holding an index record */
1761 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00001762 int i; /* Loop counter */
1763 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00001764 CollSeq *pColl; /* Collating sequence to on a column */
drh4139c992010-04-07 14:59:45 +00001765 Bitmask idxCols; /* Bitmap of columns used for indexing */
1766 Bitmask extraCols; /* Bitmap of additional columns */
drh8b307fb2010-04-06 15:57:05 +00001767
1768 /* Generate code to skip over the creation and initialization of the
1769 ** transient index on 2nd and subsequent iterations of the loop. */
1770 v = pParse->pVdbe;
1771 assert( v!=0 );
1772 regIsInit = ++pParse->nMem;
1773 addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
1774 sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
1775
drh4139c992010-04-07 14:59:45 +00001776 /* Count the number of columns that will be added to the index
1777 ** and used to match WHERE clause constraints */
drh8b307fb2010-04-06 15:57:05 +00001778 nColumn = 0;
drh424aab82010-04-06 18:28:20 +00001779 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00001780 pWCEnd = &pWC->a[pWC->nTerm];
drh4139c992010-04-07 14:59:45 +00001781 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001782 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001783 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
1784 int iCol = pTerm->u.leftColumn;
drh0013e722010-04-08 00:40:15 +00001785 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
drh52ff8ea2010-04-08 14:15:56 +00001786 testcase( iCol==BMS );
1787 testcase( iCol==BMS-1 );
drh0013e722010-04-08 00:40:15 +00001788 if( (idxCols & cMask)==0 ){
1789 nColumn++;
1790 idxCols |= cMask;
1791 }
drh8b307fb2010-04-06 15:57:05 +00001792 }
1793 }
1794 assert( nColumn>0 );
drh424aab82010-04-06 18:28:20 +00001795 pLevel->plan.nEq = nColumn;
drh4139c992010-04-07 14:59:45 +00001796
1797 /* Count the number of additional columns needed to create a
1798 ** covering index. A "covering index" is an index that contains all
1799 ** columns that are needed by the query. With a covering index, the
1800 ** original table never needs to be accessed. Automatic indices must
1801 ** be a covering index because the index will not be updated if the
1802 ** original table changes and the index and table cannot both be used
1803 ** if they go out of sync.
1804 */
drh0013e722010-04-08 00:40:15 +00001805 extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
drh4139c992010-04-07 14:59:45 +00001806 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00001807 testcase( pTable->nCol==BMS-1 );
1808 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00001809 for(i=0; i<mxBitCol; i++){
drh67ae0cb2010-04-08 14:38:51 +00001810 if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
drh4139c992010-04-07 14:59:45 +00001811 }
1812 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
1813 nColumn += pTable->nCol - BMS + 1;
1814 }
1815 pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
drh8b307fb2010-04-06 15:57:05 +00001816
1817 /* Construct the Index object to describe this index */
1818 nByte = sizeof(Index);
1819 nByte += nColumn*sizeof(int); /* Index.aiColumn */
1820 nByte += nColumn*sizeof(char*); /* Index.azColl */
1821 nByte += nColumn; /* Index.aSortOrder */
1822 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
1823 if( pIdx==0 ) return;
1824 pLevel->plan.u.pIdx = pIdx;
1825 pIdx->azColl = (char**)&pIdx[1];
1826 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
1827 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
1828 pIdx->zName = "auto-index";
1829 pIdx->nColumn = nColumn;
drh424aab82010-04-06 18:28:20 +00001830 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00001831 n = 0;
drh0013e722010-04-08 00:40:15 +00001832 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00001833 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00001834 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00001835 int iCol = pTerm->u.leftColumn;
1836 Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
1837 if( (idxCols & cMask)==0 ){
1838 Expr *pX = pTerm->pExpr;
1839 idxCols |= cMask;
1840 pIdx->aiColumn[n] = pTerm->u.leftColumn;
1841 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
1842 pIdx->azColl[n] = pColl->zName;
1843 n++;
1844 }
drh8b307fb2010-04-06 15:57:05 +00001845 }
1846 }
shaneh5eba1f62010-07-02 17:05:03 +00001847 assert( (u32)n==pLevel->plan.nEq );
drh4139c992010-04-07 14:59:45 +00001848
drhc6339082010-04-07 16:54:58 +00001849 /* Add additional columns needed to make the automatic index into
1850 ** a covering index */
drh4139c992010-04-07 14:59:45 +00001851 for(i=0; i<mxBitCol; i++){
drh67ae0cb2010-04-08 14:38:51 +00001852 if( extraCols & (((Bitmask)1)<<i) ){
drh4139c992010-04-07 14:59:45 +00001853 pIdx->aiColumn[n] = i;
1854 pIdx->azColl[n] = "BINARY";
1855 n++;
1856 }
1857 }
1858 if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
1859 for(i=BMS-1; i<pTable->nCol; i++){
1860 pIdx->aiColumn[n] = i;
1861 pIdx->azColl[n] = "BINARY";
1862 n++;
1863 }
1864 }
1865 assert( n==nColumn );
drh8b307fb2010-04-06 15:57:05 +00001866
drhc6339082010-04-07 16:54:58 +00001867 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00001868 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
1869 assert( pLevel->iIdxCur>=0 );
drha21a64d2010-04-06 22:33:55 +00001870 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
drh8b307fb2010-04-06 15:57:05 +00001871 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
drha21a64d2010-04-06 22:33:55 +00001872 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00001873
drhc6339082010-04-07 16:54:58 +00001874 /* Fill the automatic index with content */
drh8b307fb2010-04-06 15:57:05 +00001875 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
1876 regRecord = sqlite3GetTempReg(pParse);
1877 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
1878 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
1879 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1880 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
drha21a64d2010-04-06 22:33:55 +00001881 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00001882 sqlite3VdbeJumpHere(v, addrTop);
1883 sqlite3ReleaseTempReg(pParse, regRecord);
1884
1885 /* Jump here when skipping the initialization */
1886 sqlite3VdbeJumpHere(v, addrInit);
1887}
drhc6339082010-04-07 16:54:58 +00001888#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00001889
drh9eff6162006-06-12 21:59:13 +00001890#ifndef SQLITE_OMIT_VIRTUALTABLE
1891/*
danielk19771d461462009-04-21 09:02:45 +00001892** Allocate and populate an sqlite3_index_info structure. It is the
1893** responsibility of the caller to eventually release the structure
1894** by passing the pointer returned by this function to sqlite3_free().
1895*/
1896static sqlite3_index_info *allocateIndexInfo(
1897 Parse *pParse,
1898 WhereClause *pWC,
1899 struct SrcList_item *pSrc,
1900 ExprList *pOrderBy
1901){
1902 int i, j;
1903 int nTerm;
1904 struct sqlite3_index_constraint *pIdxCons;
1905 struct sqlite3_index_orderby *pIdxOrderBy;
1906 struct sqlite3_index_constraint_usage *pUsage;
1907 WhereTerm *pTerm;
1908 int nOrderBy;
1909 sqlite3_index_info *pIdxInfo;
1910
1911 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
1912
1913 /* Count the number of possible WHERE clause constraints referring
1914 ** to this virtual table */
1915 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1916 if( pTerm->leftCursor != pSrc->iCursor ) continue;
1917 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
1918 testcase( pTerm->eOperator==WO_IN );
1919 testcase( pTerm->eOperator==WO_ISNULL );
1920 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
1921 nTerm++;
1922 }
1923
1924 /* If the ORDER BY clause contains only columns in the current
1925 ** virtual table then allocate space for the aOrderBy part of
1926 ** the sqlite3_index_info structure.
1927 */
1928 nOrderBy = 0;
1929 if( pOrderBy ){
1930 for(i=0; i<pOrderBy->nExpr; i++){
1931 Expr *pExpr = pOrderBy->a[i].pExpr;
1932 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
1933 }
1934 if( i==pOrderBy->nExpr ){
1935 nOrderBy = pOrderBy->nExpr;
1936 }
1937 }
1938
1939 /* Allocate the sqlite3_index_info structure
1940 */
1941 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
1942 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
1943 + sizeof(*pIdxOrderBy)*nOrderBy );
1944 if( pIdxInfo==0 ){
1945 sqlite3ErrorMsg(pParse, "out of memory");
1946 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
1947 return 0;
1948 }
1949
1950 /* Initialize the structure. The sqlite3_index_info structure contains
1951 ** many fields that are declared "const" to prevent xBestIndex from
1952 ** changing them. We have to do some funky casting in order to
1953 ** initialize those fields.
1954 */
1955 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
1956 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
1957 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1958 *(int*)&pIdxInfo->nConstraint = nTerm;
1959 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
1960 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
1961 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
1962 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
1963 pUsage;
1964
1965 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1966 if( pTerm->leftCursor != pSrc->iCursor ) continue;
1967 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
1968 testcase( pTerm->eOperator==WO_IN );
1969 testcase( pTerm->eOperator==WO_ISNULL );
1970 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
1971 pIdxCons[j].iColumn = pTerm->u.leftColumn;
1972 pIdxCons[j].iTermOffset = i;
1973 pIdxCons[j].op = (u8)pTerm->eOperator;
1974 /* The direct assignment in the previous line is possible only because
1975 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
1976 ** following asserts verify this fact. */
1977 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
1978 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
1979 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
1980 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
1981 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1982 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
1983 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
1984 j++;
1985 }
1986 for(i=0; i<nOrderBy; i++){
1987 Expr *pExpr = pOrderBy->a[i].pExpr;
1988 pIdxOrderBy[i].iColumn = pExpr->iColumn;
1989 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
1990 }
1991
1992 return pIdxInfo;
1993}
1994
1995/*
1996** The table object reference passed as the second argument to this function
1997** must represent a virtual table. This function invokes the xBestIndex()
1998** method of the virtual table with the sqlite3_index_info pointer passed
1999** as the argument.
2000**
2001** If an error occurs, pParse is populated with an error message and a
2002** non-zero value is returned. Otherwise, 0 is returned and the output
2003** part of the sqlite3_index_info structure is left populated.
2004**
2005** Whether or not an error is returned, it is the responsibility of the
2006** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2007** that this is required.
2008*/
2009static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002010 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002011 int i;
2012 int rc;
2013
danielk19771d461462009-04-21 09:02:45 +00002014 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
2015 TRACE_IDX_INPUTS(p);
2016 rc = pVtab->pModule->xBestIndex(pVtab, p);
2017 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002018
2019 if( rc!=SQLITE_OK ){
2020 if( rc==SQLITE_NOMEM ){
2021 pParse->db->mallocFailed = 1;
2022 }else if( !pVtab->zErrMsg ){
2023 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2024 }else{
2025 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2026 }
2027 }
drhb9755982010-07-24 16:34:37 +00002028 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002029 pVtab->zErrMsg = 0;
2030
2031 for(i=0; i<p->nConstraint; i++){
2032 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2033 sqlite3ErrorMsg(pParse,
2034 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2035 }
2036 }
2037
2038 return pParse->nErr;
2039}
2040
2041
2042/*
drh7f375902006-06-13 17:38:59 +00002043** Compute the best index for a virtual table.
2044**
2045** The best index is computed by the xBestIndex method of the virtual
2046** table module. This routine is really just a wrapper that sets up
2047** the sqlite3_index_info structure that is used to communicate with
2048** xBestIndex.
2049**
2050** In a join, this routine might be called multiple times for the
2051** same virtual table. The sqlite3_index_info structure is created
2052** and initialized on the first invocation and reused on all subsequent
2053** invocations. The sqlite3_index_info structure is also used when
2054** code is generated to access the virtual table. The whereInfoDelete()
2055** routine takes care of freeing the sqlite3_index_info structure after
2056** everybody has finished with it.
drh9eff6162006-06-12 21:59:13 +00002057*/
danielk19771d461462009-04-21 09:02:45 +00002058static void bestVirtualIndex(
2059 Parse *pParse, /* The parsing context */
2060 WhereClause *pWC, /* The WHERE clause */
2061 struct SrcList_item *pSrc, /* The FROM clause term to search */
2062 Bitmask notReady, /* Mask of cursors that are not available */
2063 ExprList *pOrderBy, /* The order by clause */
2064 WhereCost *pCost, /* Lowest cost query plan */
2065 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
drh9eff6162006-06-12 21:59:13 +00002066){
2067 Table *pTab = pSrc->pTab;
2068 sqlite3_index_info *pIdxInfo;
2069 struct sqlite3_index_constraint *pIdxCons;
drh9eff6162006-06-12 21:59:13 +00002070 struct sqlite3_index_constraint_usage *pUsage;
2071 WhereTerm *pTerm;
2072 int i, j;
2073 int nOrderBy;
danc26c0042010-03-27 09:44:42 +00002074 double rCost;
drh9eff6162006-06-12 21:59:13 +00002075
danielk19776eacd282009-04-29 11:50:53 +00002076 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
2077 ** malloc in allocateIndexInfo() fails and this function returns leaving
2078 ** wsFlags in an uninitialized state, the caller may behave unpredictably.
2079 */
drh6a863cd2009-05-06 18:42:21 +00002080 memset(pCost, 0, sizeof(*pCost));
danielk19776eacd282009-04-29 11:50:53 +00002081 pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
2082
drh9eff6162006-06-12 21:59:13 +00002083 /* If the sqlite3_index_info structure has not been previously
danielk19771d461462009-04-21 09:02:45 +00002084 ** allocated and initialized, then allocate and initialize it now.
drh9eff6162006-06-12 21:59:13 +00002085 */
2086 pIdxInfo = *ppIdxInfo;
2087 if( pIdxInfo==0 ){
danielk19771d461462009-04-21 09:02:45 +00002088 *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
drh9eff6162006-06-12 21:59:13 +00002089 }
danielk1977732dc552009-04-21 17:23:04 +00002090 if( pIdxInfo==0 ){
2091 return;
2092 }
drh9eff6162006-06-12 21:59:13 +00002093
drh7f375902006-06-13 17:38:59 +00002094 /* At this point, the sqlite3_index_info structure that pIdxInfo points
2095 ** to will have been initialized, either during the current invocation or
2096 ** during some prior invocation. Now we just have to customize the
2097 ** details of pIdxInfo for the current invocation and pass it to
2098 ** xBestIndex.
2099 */
2100
danielk1977935ed5e2007-03-30 09:13:13 +00002101 /* The module name must be defined. Also, by this point there must
2102 ** be a pointer to an sqlite3_vtab structure. Otherwise
2103 ** sqlite3ViewGetColumnNames() would have picked up the error.
2104 */
drh9eff6162006-06-12 21:59:13 +00002105 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
danielk1977595a5232009-07-24 17:58:53 +00002106 assert( sqlite3GetVTable(pParse->db, pTab) );
drh9eff6162006-06-12 21:59:13 +00002107
2108 /* Set the aConstraint[].usable fields and initialize all
drh7f375902006-06-13 17:38:59 +00002109 ** output variables to zero.
2110 **
2111 ** aConstraint[].usable is true for constraints where the right-hand
2112 ** side contains only references to tables to the left of the current
2113 ** table. In other words, if the constraint is of the form:
2114 **
2115 ** column = expr
2116 **
2117 ** and we are evaluating a join, then the constraint on column is
2118 ** only valid if all tables referenced in expr occur to the left
2119 ** of the table containing column.
2120 **
2121 ** The aConstraints[] array contains entries for all constraints
2122 ** on the current table. That way we only have to compute it once
2123 ** even though we might try to pick the best index multiple times.
2124 ** For each attempt at picking an index, the order of tables in the
2125 ** join might be different so we have to recompute the usable flag
2126 ** each time.
drh9eff6162006-06-12 21:59:13 +00002127 */
2128 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2129 pUsage = pIdxInfo->aConstraintUsage;
2130 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
2131 j = pIdxCons->iTermOffset;
2132 pTerm = &pWC->a[j];
dan5236ac12009-08-13 07:09:33 +00002133 pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
drh9eff6162006-06-12 21:59:13 +00002134 }
2135 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
drh4be8b512006-06-13 23:51:34 +00002136 if( pIdxInfo->needToFreeIdxStr ){
2137 sqlite3_free(pIdxInfo->idxStr);
2138 }
2139 pIdxInfo->idxStr = 0;
2140 pIdxInfo->idxNum = 0;
2141 pIdxInfo->needToFreeIdxStr = 0;
drh9eff6162006-06-12 21:59:13 +00002142 pIdxInfo->orderByConsumed = 0;
shanefbd60f82009-02-04 03:59:25 +00002143 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
2144 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
drh9eff6162006-06-12 21:59:13 +00002145 nOrderBy = pIdxInfo->nOrderBy;
danielk19771d461462009-04-21 09:02:45 +00002146 if( !pOrderBy ){
2147 pIdxInfo->nOrderBy = 0;
drh9eff6162006-06-12 21:59:13 +00002148 }
danielk197774cdba42006-06-19 12:02:58 +00002149
danielk19771d461462009-04-21 09:02:45 +00002150 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
2151 return;
danielk197739359dc2008-03-17 09:36:44 +00002152 }
2153
dan5236ac12009-08-13 07:09:33 +00002154 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
2155 for(i=0; i<pIdxInfo->nConstraint; i++){
2156 if( pUsage[i].argvIndex>0 ){
2157 pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
2158 }
2159 }
2160
danc26c0042010-03-27 09:44:42 +00002161 /* If there is an ORDER BY clause, and the selected virtual table index
2162 ** does not satisfy it, increase the cost of the scan accordingly. This
2163 ** matches the processing for non-virtual tables in bestBtreeIndex().
2164 */
2165 rCost = pIdxInfo->estimatedCost;
2166 if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
2167 rCost += estLog(rCost)*rCost;
2168 }
2169
danielk19771d461462009-04-21 09:02:45 +00002170 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
2171 ** inital value of lowestCost in this loop. If it is, then the
2172 ** (cost<lowestCost) test below will never be true.
2173 **
2174 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
2175 ** is defined.
2176 */
danc26c0042010-03-27 09:44:42 +00002177 if( (SQLITE_BIG_DBL/((double)2))<rCost ){
danielk19771d461462009-04-21 09:02:45 +00002178 pCost->rCost = (SQLITE_BIG_DBL/((double)2));
2179 }else{
danc26c0042010-03-27 09:44:42 +00002180 pCost->rCost = rCost;
danielk19771d461462009-04-21 09:02:45 +00002181 }
danielk19771d461462009-04-21 09:02:45 +00002182 pCost->plan.u.pVtabIdx = pIdxInfo;
drh5901b572009-06-10 19:33:28 +00002183 if( pIdxInfo->orderByConsumed ){
danielk19771d461462009-04-21 09:02:45 +00002184 pCost->plan.wsFlags |= WHERE_ORDERBY;
2185 }
2186 pCost->plan.nEq = 0;
2187 pIdxInfo->nOrderBy = nOrderBy;
2188
2189 /* Try to find a more efficient access pattern by using multiple indexes
2190 ** to optimize an OR expression within the WHERE clause.
2191 */
2192 bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
drh9eff6162006-06-12 21:59:13 +00002193}
2194#endif /* SQLITE_OMIT_VIRTUALTABLE */
2195
drh28c4cf42005-07-27 20:41:43 +00002196/*
dan02fa4692009-08-17 17:06:58 +00002197** Argument pIdx is a pointer to an index structure that has an array of
2198** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
2199** stored in Index.aSample. The domain of values stored in said column
2200** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
2201** Region 0 contains all values smaller than the first sample value. Region
2202** 1 contains values larger than or equal to the value of the first sample,
2203** but smaller than the value of the second. And so on.
2204**
2205** If successful, this function determines which of the regions value
drh98cdf622009-08-20 18:14:42 +00002206** pVal lies in, sets *piRegion to the region index (a value between 0
2207** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
dan02fa4692009-08-17 17:06:58 +00002208** Or, if an OOM occurs while converting text values between encodings,
drh98cdf622009-08-20 18:14:42 +00002209** SQLITE_NOMEM is returned and *piRegion is undefined.
dan02fa4692009-08-17 17:06:58 +00002210*/
dan69188d92009-08-19 08:18:32 +00002211#ifdef SQLITE_ENABLE_STAT2
dan02fa4692009-08-17 17:06:58 +00002212static int whereRangeRegion(
2213 Parse *pParse, /* Database connection */
2214 Index *pIdx, /* Index to consider domain of */
2215 sqlite3_value *pVal, /* Value to consider */
2216 int *piRegion /* OUT: Region of domain in which value lies */
2217){
drhdaf4a9f2009-08-20 20:05:55 +00002218 if( ALWAYS(pVal) ){
dan02fa4692009-08-17 17:06:58 +00002219 IndexSample *aSample = pIdx->aSample;
2220 int i = 0;
2221 int eType = sqlite3_value_type(pVal);
2222
2223 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
2224 double r = sqlite3_value_double(pVal);
2225 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
2226 if( aSample[i].eType==SQLITE_NULL ) continue;
2227 if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
2228 }
drhcdaca552009-08-20 13:45:07 +00002229 }else{
dan02fa4692009-08-17 17:06:58 +00002230 sqlite3 *db = pParse->db;
2231 CollSeq *pColl;
2232 const u8 *z;
2233 int n;
drhcdaca552009-08-20 13:45:07 +00002234
2235 /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
2236 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
2237
dan02fa4692009-08-17 17:06:58 +00002238 if( eType==SQLITE_BLOB ){
2239 z = (const u8 *)sqlite3_value_blob(pVal);
2240 pColl = db->pDfltColl;
dane275dc32009-08-18 16:24:58 +00002241 assert( pColl->enc==SQLITE_UTF8 );
dan02fa4692009-08-17 17:06:58 +00002242 }else{
drh9aeda792009-08-20 02:34:15 +00002243 pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
2244 if( pColl==0 ){
2245 sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
2246 *pIdx->azColl);
dane275dc32009-08-18 16:24:58 +00002247 return SQLITE_ERROR;
2248 }
dan02fa4692009-08-17 17:06:58 +00002249 z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
dane275dc32009-08-18 16:24:58 +00002250 if( !z ){
2251 return SQLITE_NOMEM;
2252 }
dan02fa4692009-08-17 17:06:58 +00002253 assert( z && pColl && pColl->xCmp );
2254 }
2255 n = sqlite3ValueBytes(pVal, pColl->enc);
2256
2257 for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
dane275dc32009-08-18 16:24:58 +00002258 int r;
dan02fa4692009-08-17 17:06:58 +00002259 int eSampletype = aSample[i].eType;
2260 if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
2261 if( (eSampletype!=eType) ) break;
dane83c4f32009-09-21 16:34:24 +00002262#ifndef SQLITE_OMIT_UTF16
2263 if( pColl->enc!=SQLITE_UTF8 ){
dane275dc32009-08-18 16:24:58 +00002264 int nSample;
2265 char *zSample = sqlite3Utf8to16(
dan02fa4692009-08-17 17:06:58 +00002266 db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
2267 );
dane275dc32009-08-18 16:24:58 +00002268 if( !zSample ){
2269 assert( db->mallocFailed );
2270 return SQLITE_NOMEM;
2271 }
2272 r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
2273 sqlite3DbFree(db, zSample);
dane83c4f32009-09-21 16:34:24 +00002274 }else
2275#endif
2276 {
2277 r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
dan02fa4692009-08-17 17:06:58 +00002278 }
dane275dc32009-08-18 16:24:58 +00002279 if( r>0 ) break;
dan02fa4692009-08-17 17:06:58 +00002280 }
2281 }
2282
drha8f57612009-08-25 16:28:14 +00002283 assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
dan02fa4692009-08-17 17:06:58 +00002284 *piRegion = i;
2285 }
2286 return SQLITE_OK;
2287}
dan69188d92009-08-19 08:18:32 +00002288#endif /* #ifdef SQLITE_ENABLE_STAT2 */
dan02fa4692009-08-17 17:06:58 +00002289
2290/*
dan937d0de2009-10-15 18:35:38 +00002291** If expression pExpr represents a literal value, set *pp to point to
2292** an sqlite3_value structure containing the same value, with affinity
2293** aff applied to it, before returning. It is the responsibility of the
2294** caller to eventually release this structure by passing it to
2295** sqlite3ValueFree().
2296**
2297** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
2298** is an SQL variable that currently has a non-NULL value bound to it,
2299** create an sqlite3_value structure containing this value, again with
2300** affinity aff applied to it, instead.
2301**
2302** If neither of the above apply, set *pp to NULL.
2303**
2304** If an error occurs, return an error code. Otherwise, SQLITE_OK.
2305*/
danf7b0b0a2009-10-19 15:52:32 +00002306#ifdef SQLITE_ENABLE_STAT2
dan937d0de2009-10-15 18:35:38 +00002307static int valueFromExpr(
2308 Parse *pParse,
2309 Expr *pExpr,
2310 u8 aff,
2311 sqlite3_value **pp
2312){
drhb4138de2009-10-19 22:41:06 +00002313 /* The evalConstExpr() function will have already converted any TK_VARIABLE
2314 ** expression involved in an comparison into a TK_REGISTER. */
2315 assert( pExpr->op!=TK_VARIABLE );
2316 if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
dan937d0de2009-10-15 18:35:38 +00002317 int iVar = pExpr->iColumn;
dan1d2ce4f2009-10-19 18:11:09 +00002318 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
dan937d0de2009-10-15 18:35:38 +00002319 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
2320 return SQLITE_OK;
2321 }
2322 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
2323}
danf7b0b0a2009-10-19 15:52:32 +00002324#endif
dan937d0de2009-10-15 18:35:38 +00002325
2326/*
dan02fa4692009-08-17 17:06:58 +00002327** This function is used to estimate the number of rows that will be visited
2328** by scanning an index for a range of values. The range may have an upper
2329** bound, a lower bound, or both. The WHERE clause terms that set the upper
2330** and lower bounds are represented by pLower and pUpper respectively. For
2331** example, assuming that index p is on t1(a):
2332**
2333** ... FROM t1 WHERE a > ? AND a < ? ...
2334** |_____| |_____|
2335** | |
2336** pLower pUpper
2337**
drh98cdf622009-08-20 18:14:42 +00002338** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002339** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002340**
2341** The nEq parameter is passed the index of the index column subject to the
2342** range constraint. Or, equivalently, the number of equality constraints
2343** optimized by the proposed index scan. For example, assuming index p is
2344** on t1(a, b), and the SQL query is:
2345**
2346** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2347**
2348** then nEq should be passed the value 1 (as the range restricted column,
2349** b, is the second left-most column of the index). Or, if the query is:
2350**
2351** ... FROM t1 WHERE a > ? AND a < ? ...
2352**
2353** then nEq should be passed 0.
2354**
drh98cdf622009-08-20 18:14:42 +00002355** The returned value is an integer between 1 and 100, inclusive. A return
dan02fa4692009-08-17 17:06:58 +00002356** value of 1 indicates that the proposed range scan is expected to visit
drh98cdf622009-08-20 18:14:42 +00002357** approximately 1/100th (1%) of the rows selected by the nEq equality
2358** constraints (if any). A return value of 100 indicates that it is expected
2359** that the range scan will visit every row (100%) selected by the equality
dan02fa4692009-08-17 17:06:58 +00002360** constraints.
drh98cdf622009-08-20 18:14:42 +00002361**
2362** In the absence of sqlite_stat2 ANALYZE data, each range inequality
2363** reduces the search space by 2/3rds. Hence a single constraint (x>?)
2364** results in a return of 33 and a range constraint (x>? AND x<?) results
2365** in a return of 11.
dan02fa4692009-08-17 17:06:58 +00002366*/
2367static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002368 Parse *pParse, /* Parsing & code generating context */
2369 Index *p, /* The index containing the range-compared column; "x" */
2370 int nEq, /* index into p->aCol[] of the range-compared column */
2371 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2372 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
2373 int *piEst /* OUT: Return value */
dan02fa4692009-08-17 17:06:58 +00002374){
dan69188d92009-08-19 08:18:32 +00002375 int rc = SQLITE_OK;
2376
2377#ifdef SQLITE_ENABLE_STAT2
dan02fa4692009-08-17 17:06:58 +00002378
2379 if( nEq==0 && p->aSample ){
dan937d0de2009-10-15 18:35:38 +00002380 sqlite3_value *pLowerVal = 0;
2381 sqlite3_value *pUpperVal = 0;
dan02fa4692009-08-17 17:06:58 +00002382 int iEst;
drh011cfca2009-08-25 15:56:51 +00002383 int iLower = 0;
2384 int iUpper = SQLITE_INDEX_SAMPLES;
dan937d0de2009-10-15 18:35:38 +00002385 u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
drh98cdf622009-08-20 18:14:42 +00002386
dan02fa4692009-08-17 17:06:58 +00002387 if( pLower ){
2388 Expr *pExpr = pLower->pExpr->pRight;
dan937d0de2009-10-15 18:35:38 +00002389 rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
dan02fa4692009-08-17 17:06:58 +00002390 }
drh98cdf622009-08-20 18:14:42 +00002391 if( rc==SQLITE_OK && pUpper ){
dan02fa4692009-08-17 17:06:58 +00002392 Expr *pExpr = pUpper->pExpr->pRight;
dan937d0de2009-10-15 18:35:38 +00002393 rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
drh98cdf622009-08-20 18:14:42 +00002394 }
2395
2396 if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
2397 sqlite3ValueFree(pLowerVal);
2398 sqlite3ValueFree(pUpperVal);
2399 goto range_est_fallback;
2400 }else if( pLowerVal==0 ){
2401 rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
drh011cfca2009-08-25 15:56:51 +00002402 if( pLower ) iLower = iUpper/2;
drh98cdf622009-08-20 18:14:42 +00002403 }else if( pUpperVal==0 ){
2404 rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
drh011cfca2009-08-25 15:56:51 +00002405 if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
drh98cdf622009-08-20 18:14:42 +00002406 }else{
2407 rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
2408 if( rc==SQLITE_OK ){
2409 rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
dan02fa4692009-08-17 17:06:58 +00002410 }
2411 }
2412
dan02fa4692009-08-17 17:06:58 +00002413 iEst = iUpper - iLower;
drha8f57612009-08-25 16:28:14 +00002414 testcase( iEst==SQLITE_INDEX_SAMPLES );
2415 assert( iEst<=SQLITE_INDEX_SAMPLES );
2416 if( iEst<1 ){
drh98cdf622009-08-20 18:14:42 +00002417 iEst = 1;
2418 }
dan02fa4692009-08-17 17:06:58 +00002419
2420 sqlite3ValueFree(pLowerVal);
2421 sqlite3ValueFree(pUpperVal);
drh98cdf622009-08-20 18:14:42 +00002422 *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
dan02fa4692009-08-17 17:06:58 +00002423 return rc;
2424 }
drh98cdf622009-08-20 18:14:42 +00002425range_est_fallback:
drh3f022182009-09-09 16:10:50 +00002426#else
2427 UNUSED_PARAMETER(pParse);
2428 UNUSED_PARAMETER(p);
2429 UNUSED_PARAMETER(nEq);
dan69188d92009-08-19 08:18:32 +00002430#endif
dan02fa4692009-08-17 17:06:58 +00002431 assert( pLower || pUpper );
drh98cdf622009-08-20 18:14:42 +00002432 if( pLower && pUpper ){
2433 *piEst = 11;
2434 }else{
2435 *piEst = 33;
2436 }
dan02fa4692009-08-17 17:06:58 +00002437 return rc;
2438}
2439
2440
2441/*
drh111a6a72008-12-21 03:51:16 +00002442** Find the query plan for accessing a particular table. Write the
2443** best query plan and its cost into the WhereCost object supplied as the
2444** last parameter.
drh51147ba2005-07-23 22:59:55 +00002445**
drh111a6a72008-12-21 03:51:16 +00002446** The lowest cost plan wins. The cost is an estimate of the amount of
2447** CPU and disk I/O need to process the request using the selected plan.
drh51147ba2005-07-23 22:59:55 +00002448** Factors that influence cost include:
2449**
2450** * The estimated number of rows that will be retrieved. (The
2451** fewer the better.)
2452**
2453** * Whether or not sorting must occur.
2454**
2455** * Whether or not there must be separate lookups in the
2456** index and in the main table.
2457**
danielk1977e2d7b242009-02-23 17:33:49 +00002458** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
2459** the SQL statement, then this function only considers plans using the
drh296a4832009-03-22 20:36:18 +00002460** named index. If no such plan is found, then the returned cost is
2461** SQLITE_BIG_DBL. If a plan is found that uses the named index,
danielk197785574e32008-10-06 05:32:18 +00002462** then the cost is calculated in the usual way.
2463**
danielk1977e2d7b242009-02-23 17:33:49 +00002464** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
2465** in the SELECT statement, then no indexes are considered. However, the
2466** selected plan may still take advantage of the tables built-in rowid
danielk197785574e32008-10-06 05:32:18 +00002467** index.
drhfe05af82005-07-21 03:14:59 +00002468*/
danielk19771d461462009-04-21 09:02:45 +00002469static void bestBtreeIndex(
drhfe05af82005-07-21 03:14:59 +00002470 Parse *pParse, /* The parsing context */
2471 WhereClause *pWC, /* The WHERE clause */
2472 struct SrcList_item *pSrc, /* The FROM clause term to search */
2473 Bitmask notReady, /* Mask of cursors that are not available */
drh111a6a72008-12-21 03:51:16 +00002474 ExprList *pOrderBy, /* The ORDER BY clause */
2475 WhereCost *pCost /* Lowest cost query plan */
drhfe05af82005-07-21 03:14:59 +00002476){
drh51147ba2005-07-23 22:59:55 +00002477 int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
2478 Index *pProbe; /* An index we are evaluating */
dan5236ac12009-08-13 07:09:33 +00002479 Index *pIdx; /* Copy of pProbe, or zero for IPK index */
2480 int eqTermMask; /* Current mask of valid equality operators */
2481 int idxEqTermMask; /* Index mask of valid equality operators */
drhcdaca552009-08-20 13:45:07 +00002482 Index sPk; /* A fake index object for the primary key */
2483 unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
2484 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
2485 int wsFlagMask; /* Allowed flags in pCost->plan.wsFlag */
drhfe05af82005-07-21 03:14:59 +00002486
drhcdaca552009-08-20 13:45:07 +00002487 /* Initialize the cost to a worst-case value */
drh111a6a72008-12-21 03:51:16 +00002488 memset(pCost, 0, sizeof(*pCost));
drh111a6a72008-12-21 03:51:16 +00002489 pCost->rCost = SQLITE_BIG_DBL;
drh51147ba2005-07-23 22:59:55 +00002490
drhc49de5d2007-01-19 01:06:01 +00002491 /* If the pSrc table is the right table of a LEFT JOIN then we may not
2492 ** use an index to satisfy IS NULL constraints on that table. This is
2493 ** because columns might end up being NULL if the table does not match -
2494 ** a circumstance which the index cannot help us discover. Ticket #2177.
2495 */
dan5236ac12009-08-13 07:09:33 +00002496 if( pSrc->jointype & JT_LEFT ){
2497 idxEqTermMask = WO_EQ|WO_IN;
drhc49de5d2007-01-19 01:06:01 +00002498 }else{
dan5236ac12009-08-13 07:09:33 +00002499 idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
drhc49de5d2007-01-19 01:06:01 +00002500 }
2501
danielk197785574e32008-10-06 05:32:18 +00002502 if( pSrc->pIndex ){
drhcdaca552009-08-20 13:45:07 +00002503 /* An INDEXED BY clause specifies a particular index to use */
dan5236ac12009-08-13 07:09:33 +00002504 pIdx = pProbe = pSrc->pIndex;
2505 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
2506 eqTermMask = idxEqTermMask;
2507 }else{
drhcdaca552009-08-20 13:45:07 +00002508 /* There is no INDEXED BY clause. Create a fake Index object to
2509 ** represent the primary key */
2510 Index *pFirst; /* Any other index on the table */
2511 memset(&sPk, 0, sizeof(Index));
2512 sPk.nColumn = 1;
2513 sPk.aiColumn = &aiColumnPk;
2514 sPk.aiRowEst = aiRowEstPk;
2515 aiRowEstPk[1] = 1;
2516 sPk.onError = OE_Replace;
2517 sPk.pTable = pSrc->pTab;
2518 pFirst = pSrc->pTab->pIndex;
dan5236ac12009-08-13 07:09:33 +00002519 if( pSrc->notIndexed==0 ){
drhcdaca552009-08-20 13:45:07 +00002520 sPk.pNext = pFirst;
dan5236ac12009-08-13 07:09:33 +00002521 }
drhcdaca552009-08-20 13:45:07 +00002522 /* The aiRowEstPk[0] is an estimate of the total number of rows in the
2523 ** table. Get this information from the ANALYZE information if it is
2524 ** available. If not available, assume the table 1 million rows in size.
2525 */
2526 if( pFirst ){
2527 assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
2528 aiRowEstPk[0] = pFirst->aiRowEst[0];
2529 }else{
2530 aiRowEstPk[0] = 1000000;
dan5236ac12009-08-13 07:09:33 +00002531 }
drhcdaca552009-08-20 13:45:07 +00002532 pProbe = &sPk;
dan5236ac12009-08-13 07:09:33 +00002533 wsFlagMask = ~(
2534 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
2535 );
2536 eqTermMask = WO_EQ|WO_IN;
2537 pIdx = 0;
danielk197785574e32008-10-06 05:32:18 +00002538 }
drh51147ba2005-07-23 22:59:55 +00002539
drhcdaca552009-08-20 13:45:07 +00002540 /* Loop over all indices looking for the best one to use
2541 */
dan5236ac12009-08-13 07:09:33 +00002542 for(; pProbe; pIdx=pProbe=pProbe->pNext){
2543 const unsigned int * const aiRowEst = pProbe->aiRowEst;
2544 double cost; /* Cost of using pProbe */
2545 double nRow; /* Estimated number of rows in result set */
2546 int rev; /* True to scan in reverse order */
2547 int wsFlags = 0;
2548 Bitmask used = 0;
2549
2550 /* The following variables are populated based on the properties of
2551 ** scan being evaluated. They are then used to determine the expected
2552 ** cost and number of rows returned.
2553 **
2554 ** nEq:
2555 ** Number of equality terms that can be implemented using the index.
2556 **
2557 ** nInMul:
2558 ** The "in-multiplier". This is an estimate of how many seek operations
2559 ** SQLite must perform on the index in question. For example, if the
2560 ** WHERE clause is:
2561 **
2562 ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
2563 **
2564 ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
2565 ** set to 9. Given the same schema and either of the following WHERE
2566 ** clauses:
2567 **
2568 ** WHERE a = 1
2569 ** WHERE a >= 2
2570 **
2571 ** nInMul is set to 1.
2572 **
2573 ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
2574 ** the sub-select is assumed to return 25 rows for the purposes of
2575 ** determining nInMul.
2576 **
2577 ** bInEst:
2578 ** Set to true if there was at least one "x IN (SELECT ...)" term used
2579 ** in determining the value of nInMul.
2580 **
drhed754ce2010-04-15 01:04:54 +00002581 ** estBound:
drh98cdf622009-08-20 18:14:42 +00002582 ** An estimate on the amount of the table that must be searched. A
2583 ** value of 100 means the entire table is searched. Range constraints
2584 ** might reduce this to a value less than 100 to indicate that only
2585 ** a fraction of the table needs searching. In the absence of
2586 ** sqlite_stat2 ANALYZE data, a single inequality reduces the search
2587 ** space to 1/3rd its original size. So an x>? constraint reduces
drhed754ce2010-04-15 01:04:54 +00002588 ** estBound to 33. Two constraints (x>? AND x<?) reduce estBound to 11.
dan5236ac12009-08-13 07:09:33 +00002589 **
2590 ** bSort:
2591 ** Boolean. True if there is an ORDER BY clause that will require an
2592 ** external sort (i.e. scanning the index being evaluated will not
2593 ** correctly order records).
2594 **
2595 ** bLookup:
2596 ** Boolean. True if for each index entry visited a lookup on the
2597 ** corresponding table b-tree is required. This is always false
2598 ** for the rowid index. For other indexes, it is true unless all the
2599 ** columns of the table used by the SELECT statement are present in
2600 ** the index (such an index is sometimes described as a covering index).
2601 ** For example, given the index on (a, b), the second of the following
2602 ** two queries requires table b-tree lookups, but the first does not.
2603 **
2604 ** SELECT a, b FROM tbl WHERE a = 1;
2605 ** SELECT a, b, c FROM tbl WHERE a = 1;
drhfe05af82005-07-21 03:14:59 +00002606 */
dan5236ac12009-08-13 07:09:33 +00002607 int nEq;
2608 int bInEst = 0;
2609 int nInMul = 1;
drhed754ce2010-04-15 01:04:54 +00002610 int estBound = 100;
2611 int nBound = 0; /* Number of range constraints seen */
dan5236ac12009-08-13 07:09:33 +00002612 int bSort = 0;
2613 int bLookup = 0;
drh1e0f4a82010-04-14 19:01:44 +00002614 WhereTerm *pTerm; /* A single term of the WHERE clause */
dan5236ac12009-08-13 07:09:33 +00002615
2616 /* Determine the values of nEq and nInMul */
2617 for(nEq=0; nEq<pProbe->nColumn; nEq++){
dan5236ac12009-08-13 07:09:33 +00002618 int j = pProbe->aiColumn[nEq];
2619 pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
drhfe05af82005-07-21 03:14:59 +00002620 if( pTerm==0 ) break;
dan5236ac12009-08-13 07:09:33 +00002621 wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
drhb52076c2006-01-23 13:22:09 +00002622 if( pTerm->eOperator & WO_IN ){
drha6110402005-07-28 20:51:19 +00002623 Expr *pExpr = pTerm->pExpr;
drh165be382008-12-05 02:36:33 +00002624 wsFlags |= WHERE_COLUMN_IN;
danielk19776ab3a2e2009-02-19 14:39:25 +00002625 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
dan5236ac12009-08-13 07:09:33 +00002626 nInMul *= 25;
2627 bInEst = 1;
drha7d2db12010-07-14 20:23:52 +00002628 }else if( ALWAYS(pExpr->x.pList) ){
dan5236ac12009-08-13 07:09:33 +00002629 nInMul *= pExpr->x.pList->nExpr + 1;
drhfe05af82005-07-21 03:14:59 +00002630 }
drh46619d62009-04-24 14:51:42 +00002631 }else if( pTerm->eOperator & WO_ISNULL ){
2632 wsFlags |= WHERE_COLUMN_NULL;
drhfe05af82005-07-21 03:14:59 +00002633 }
dan5236ac12009-08-13 07:09:33 +00002634 used |= pTerm->prereqRight;
drhfe05af82005-07-21 03:14:59 +00002635 }
dan5236ac12009-08-13 07:09:33 +00002636
drhed754ce2010-04-15 01:04:54 +00002637 /* Determine the value of estBound. */
dan5236ac12009-08-13 07:09:33 +00002638 if( nEq<pProbe->nColumn ){
2639 int j = pProbe->aiColumn[nEq];
2640 if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
2641 WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
2642 WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
drhed754ce2010-04-15 01:04:54 +00002643 whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
dan5236ac12009-08-13 07:09:33 +00002644 if( pTop ){
drhed754ce2010-04-15 01:04:54 +00002645 nBound = 1;
dan5236ac12009-08-13 07:09:33 +00002646 wsFlags |= WHERE_TOP_LIMIT;
dan5236ac12009-08-13 07:09:33 +00002647 used |= pTop->prereqRight;
2648 }
2649 if( pBtm ){
drhed754ce2010-04-15 01:04:54 +00002650 nBound++;
dan5236ac12009-08-13 07:09:33 +00002651 wsFlags |= WHERE_BTM_LIMIT;
dan5236ac12009-08-13 07:09:33 +00002652 used |= pBtm->prereqRight;
2653 }
2654 wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
2655 }
2656 }else if( pProbe->onError!=OE_None ){
drh46619d62009-04-24 14:51:42 +00002657 testcase( wsFlags & WHERE_COLUMN_IN );
2658 testcase( wsFlags & WHERE_COLUMN_NULL );
2659 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
2660 wsFlags |= WHERE_UNIQUE;
2661 }
drh943af3c2005-07-29 19:43:58 +00002662 }
drhfe05af82005-07-21 03:14:59 +00002663
dan5236ac12009-08-13 07:09:33 +00002664 /* If there is an ORDER BY clause and the index being considered will
2665 ** naturally scan rows in the required order, set the appropriate flags
2666 ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
2667 ** will scan rows in a different order, set the bSort variable. */
drh28c4cf42005-07-27 20:41:43 +00002668 if( pOrderBy ){
drh46619d62009-04-24 14:51:42 +00002669 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
dan5236ac12009-08-13 07:09:33 +00002670 && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
drh46619d62009-04-24 14:51:42 +00002671 ){
dan5236ac12009-08-13 07:09:33 +00002672 wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
2673 wsFlags |= (rev ? WHERE_REVERSE : 0);
drh28c4cf42005-07-27 20:41:43 +00002674 }else{
dan5236ac12009-08-13 07:09:33 +00002675 bSort = 1;
drh51147ba2005-07-23 22:59:55 +00002676 }
drhfe05af82005-07-21 03:14:59 +00002677 }
2678
dan5236ac12009-08-13 07:09:33 +00002679 /* If currently calculating the cost of using an index (not the IPK
2680 ** index), determine if all required column data may be obtained without
drh4139c992010-04-07 14:59:45 +00002681 ** using the main table (i.e. if the index is a covering
dan5236ac12009-08-13 07:09:33 +00002682 ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
2683 ** wsFlags. Otherwise, set the bLookup variable to true. */
2684 if( pIdx && wsFlags ){
drhfe05af82005-07-21 03:14:59 +00002685 Bitmask m = pSrc->colUsed;
2686 int j;
dan5236ac12009-08-13 07:09:33 +00002687 for(j=0; j<pIdx->nColumn; j++){
2688 int x = pIdx->aiColumn[j];
drhfe05af82005-07-21 03:14:59 +00002689 if( x<BMS-1 ){
2690 m &= ~(((Bitmask)1)<<x);
2691 }
2692 }
2693 if( m==0 ){
drh165be382008-12-05 02:36:33 +00002694 wsFlags |= WHERE_IDX_ONLY;
dan5236ac12009-08-13 07:09:33 +00002695 }else{
2696 bLookup = 1;
drhfe05af82005-07-21 03:14:59 +00002697 }
2698 }
2699
drh1e0f4a82010-04-14 19:01:44 +00002700 /*
drhcdaca552009-08-20 13:45:07 +00002701 ** Estimate the number of rows of output. For an IN operator,
2702 ** do not let the estimate exceed half the rows in the table.
2703 */
dan5236ac12009-08-13 07:09:33 +00002704 nRow = (double)(aiRowEst[nEq] * nInMul);
2705 if( bInEst && nRow*2>aiRowEst[0] ){
2706 nRow = aiRowEst[0]/2;
shanecea72b22009-09-07 04:38:36 +00002707 nInMul = (int)(nRow / aiRowEst[nEq]);
dan5236ac12009-08-13 07:09:33 +00002708 }
drhcdaca552009-08-20 13:45:07 +00002709
2710 /* Assume constant cost to access a row and logarithmic cost to
2711 ** do a binary search. Hence, the initial cost is the number of output
2712 ** rows plus log2(table-size) times the number of binary searches.
2713 */
dan5236ac12009-08-13 07:09:33 +00002714 cost = nRow + nInMul*estLog(aiRowEst[0]);
drhcdaca552009-08-20 13:45:07 +00002715
2716 /* Adjust the number of rows and the cost downward to reflect rows
2717 ** that are excluded by range constraints.
2718 */
drhed754ce2010-04-15 01:04:54 +00002719 nRow = (nRow * (double)estBound) / (double)100;
2720 cost = (cost * (double)estBound) / (double)100;
drhcdaca552009-08-20 13:45:07 +00002721
2722 /* Add in the estimated cost of sorting the result
2723 */
dan5236ac12009-08-13 07:09:33 +00002724 if( bSort ){
2725 cost += cost*estLog(cost);
2726 }
drhcdaca552009-08-20 13:45:07 +00002727
2728 /* If all information can be taken directly from the index, we avoid
2729 ** doing table lookups. This reduces the cost by half. (Not really -
2730 ** this needs to be fixed.)
2731 */
dan5236ac12009-08-13 07:09:33 +00002732 if( pIdx && bLookup==0 ){
drhcdaca552009-08-20 13:45:07 +00002733 cost /= (double)2;
dan5236ac12009-08-13 07:09:33 +00002734 }
drhcdaca552009-08-20 13:45:07 +00002735 /**** Cost of using this index has now been computed ****/
dan5236ac12009-08-13 07:09:33 +00002736
drh1e0f4a82010-04-14 19:01:44 +00002737 /* If there are additional constraints on this table that cannot
2738 ** be used with the current index, but which might lower the number
2739 ** of output rows, adjust the nRow value accordingly. This only
2740 ** matters if the current index is the least costly, so do not bother
2741 ** with this step if we already know this index will not be chosen.
drhed754ce2010-04-15 01:04:54 +00002742 ** Also, never reduce the output row count below 2 using this step.
drhed808ac2010-04-15 13:29:37 +00002743 **
2744 ** Do not reduce the output row count if pSrc is the only table that
2745 ** is notReady; if notReady is a power of two. This will be the case
2746 ** when the main sqlite3WhereBegin() loop is scanning for a table with
2747 ** and "optimal" index, and on such a scan the output row count
2748 ** reduction is not valid because it does not update the "pCost->used"
2749 ** bitmap. The notReady bitmap will also be a power of two when we
2750 ** are scanning for the last table in a 64-way join. We are willing
2751 ** to bypass this optimization in that corner case.
drh1e0f4a82010-04-14 19:01:44 +00002752 */
drhed808ac2010-04-15 13:29:37 +00002753 if( nRow>2 && cost<=pCost->rCost && (notReady & (notReady-1))!=0 ){
2754 int k; /* Loop counter */
2755 int nSkipEq = nEq; /* Number of == constraints to skip */
2756 int nSkipRange = nBound; /* Number of < constraints to skip */
2757 Bitmask thisTab; /* Bitmap for pSrc */
2758
2759 thisTab = getMask(pWC->pMaskSet, iCur);
drh1e0f4a82010-04-14 19:01:44 +00002760 for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
2761 if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
2762 if( (pTerm->prereqAll & notReady)!=thisTab ) continue;
2763 if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
drhed754ce2010-04-15 01:04:54 +00002764 if( nSkipEq ){
drh1e0f4a82010-04-14 19:01:44 +00002765 /* Ignore the first nEq equality matches since the index
2766 ** has already accounted for these */
drhed754ce2010-04-15 01:04:54 +00002767 nSkipEq--;
drh1e0f4a82010-04-14 19:01:44 +00002768 }else{
2769 /* Assume each additional equality match reduces the result
2770 ** set size by a factor of 10 */
2771 nRow /= 10;
2772 }
drhed754ce2010-04-15 01:04:54 +00002773 }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
2774 if( nSkipRange ){
2775 /* Ignore the first nBound range constraints since the index
2776 ** has already accounted for these */
2777 nSkipRange--;
2778 }else{
2779 /* Assume each additional range constraint reduces the result
2780 ** set size by a factor of 3 */
2781 nRow /= 3;
2782 }
drh1e0f4a82010-04-14 19:01:44 +00002783 }else{
2784 /* Any other expression lowers the output row count by half */
2785 nRow /= 2;
2786 }
2787 }
2788 if( nRow<2 ) nRow = 2;
2789 }
2790
2791
dan5236ac12009-08-13 07:09:33 +00002792 WHERETRACE((
drhed754ce2010-04-15 01:04:54 +00002793 "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
drh8b307fb2010-04-06 15:57:05 +00002794 " notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
dan5236ac12009-08-13 07:09:33 +00002795 pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
drhed754ce2010-04-15 01:04:54 +00002796 nEq, nInMul, estBound, bSort, bLookup, wsFlags,
2797 notReady, nRow, cost, used
dan5236ac12009-08-13 07:09:33 +00002798 ));
2799
drhcdaca552009-08-20 13:45:07 +00002800 /* If this index is the best we have seen so far, then record this
2801 ** index and its cost in the pCost structure.
2802 */
drh1e0f4a82010-04-14 19:01:44 +00002803 if( (!pIdx || wsFlags)
drhed754ce2010-04-15 01:04:54 +00002804 && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow))
drh1e0f4a82010-04-14 19:01:44 +00002805 ){
drh111a6a72008-12-21 03:51:16 +00002806 pCost->rCost = cost;
2807 pCost->nRow = nRow;
dan5236ac12009-08-13 07:09:33 +00002808 pCost->used = used;
2809 pCost->plan.wsFlags = (wsFlags&wsFlagMask);
drh111a6a72008-12-21 03:51:16 +00002810 pCost->plan.nEq = nEq;
dan5236ac12009-08-13 07:09:33 +00002811 pCost->plan.u.pIdx = pIdx;
drhfe05af82005-07-21 03:14:59 +00002812 }
dan5236ac12009-08-13 07:09:33 +00002813
drhcdaca552009-08-20 13:45:07 +00002814 /* If there was an INDEXED BY clause, then only that one index is
2815 ** considered. */
dan5236ac12009-08-13 07:09:33 +00002816 if( pSrc->pIndex ) break;
drhcdaca552009-08-20 13:45:07 +00002817
2818 /* Reset masks for the next index in the loop */
dan5236ac12009-08-13 07:09:33 +00002819 wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
2820 eqTermMask = idxEqTermMask;
drhfe05af82005-07-21 03:14:59 +00002821 }
2822
dan5236ac12009-08-13 07:09:33 +00002823 /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
2824 ** is set, then reverse the order that the index will be scanned
2825 ** in. This is used for application testing, to help find cases
2826 ** where application behaviour depends on the (undefined) order that
2827 ** SQLite outputs rows in in the absence of an ORDER BY clause. */
2828 if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
2829 pCost->plan.wsFlags |= WHERE_REVERSE;
2830 }
2831
2832 assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
2833 assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
2834 assert( pSrc->pIndex==0
2835 || pCost->plan.u.pIdx==0
2836 || pCost->plan.u.pIdx==pSrc->pIndex
2837 );
2838
2839 WHERETRACE(("best index is: %s\n",
drh1e0f4a82010-04-14 19:01:44 +00002840 ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
2841 pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
dan5236ac12009-08-13 07:09:33 +00002842 ));
2843
2844 bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
drhc6339082010-04-07 16:54:58 +00002845 bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
drh111a6a72008-12-21 03:51:16 +00002846 pCost->plan.wsFlags |= eqTermMask;
drhfe05af82005-07-21 03:14:59 +00002847}
2848
danielk19771d461462009-04-21 09:02:45 +00002849/*
2850** Find the query plan for accessing table pSrc->pTab. Write the
2851** best query plan and its cost into the WhereCost object supplied
2852** as the last parameter. This function may calculate the cost of
2853** both real and virtual table scans.
2854*/
2855static void bestIndex(
2856 Parse *pParse, /* The parsing context */
2857 WhereClause *pWC, /* The WHERE clause */
2858 struct SrcList_item *pSrc, /* The FROM clause term to search */
2859 Bitmask notReady, /* Mask of cursors that are not available */
2860 ExprList *pOrderBy, /* The ORDER BY clause */
2861 WhereCost *pCost /* Lowest cost query plan */
2862){
shanee26fa4c2009-06-16 14:15:22 +00002863#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19771d461462009-04-21 09:02:45 +00002864 if( IsVirtual(pSrc->pTab) ){
2865 sqlite3_index_info *p = 0;
2866 bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
2867 if( p->needToFreeIdxStr ){
2868 sqlite3_free(p->idxStr);
2869 }
2870 sqlite3DbFree(pParse->db, p);
shanee26fa4c2009-06-16 14:15:22 +00002871 }else
2872#endif
2873 {
danielk19771d461462009-04-21 09:02:45 +00002874 bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
2875 }
2876}
drhb6c29892004-11-22 19:12:19 +00002877
2878/*
drh2ffb1182004-07-19 19:14:01 +00002879** Disable a term in the WHERE clause. Except, do not disable the term
2880** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2881** or USING clause of that join.
2882**
2883** Consider the term t2.z='ok' in the following queries:
2884**
2885** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2886** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2887** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2888**
drh23bf66d2004-12-14 03:34:34 +00002889** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002890** in the ON clause. The term is disabled in (3) because it is not part
2891** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2892**
drhe9cdcea2010-07-22 22:40:03 +00002893** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
2894** completely satisfied by indices.
2895**
drh2ffb1182004-07-19 19:14:01 +00002896** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002897** of the join. Disabling is an optimization. When terms are satisfied
2898** by indices, we disable them to prevent redundant tests in the inner
2899** loop. We would get the correct results if nothing were ever disabled,
2900** but joins might run a little slower. The trick is to disable as much
2901** as we can without disabling too much. If we disabled in (1), we'd get
2902** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002903*/
drh0fcef5e2005-07-19 17:38:22 +00002904static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2905 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002906 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002907 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
2908 ){
drh165be382008-12-05 02:36:33 +00002909 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002910 if( pTerm->iParent>=0 ){
2911 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2912 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002913 disableTerm(pLevel, pOther);
2914 }
drh0fcef5e2005-07-19 17:38:22 +00002915 }
drh2ffb1182004-07-19 19:14:01 +00002916 }
2917}
2918
2919/*
dan69f8bb92009-08-13 19:21:16 +00002920** Code an OP_Affinity opcode to apply the column affinity string zAff
2921** to the n registers starting at base.
2922**
drh039fc322009-11-17 18:31:47 +00002923** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2924** beginning and end of zAff are ignored. If all entries in zAff are
2925** SQLITE_AFF_NONE, then no code gets generated.
2926**
2927** This routine makes its own copy of zAff so that the caller is free
2928** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002929*/
dan69f8bb92009-08-13 19:21:16 +00002930static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2931 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002932 if( zAff==0 ){
2933 assert( pParse->db->mallocFailed );
2934 return;
2935 }
dan69f8bb92009-08-13 19:21:16 +00002936 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002937
2938 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2939 ** and end of the affinity string.
2940 */
2941 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2942 n--;
2943 base++;
2944 zAff++;
2945 }
2946 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2947 n--;
2948 }
2949
2950 /* Code the OP_Affinity opcode if there is anything left to do. */
2951 if( n>0 ){
2952 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2953 sqlite3VdbeChangeP4(v, -1, zAff, n);
2954 sqlite3ExprCacheAffinityChange(pParse, base, n);
2955 }
drh94a11212004-09-25 13:12:14 +00002956}
2957
drhe8b97272005-07-19 22:22:12 +00002958
2959/*
drh51147ba2005-07-23 22:59:55 +00002960** Generate code for a single equality term of the WHERE clause. An equality
2961** term can be either X=expr or X IN (...). pTerm is the term to be
2962** coded.
2963**
drh1db639c2008-01-17 02:36:28 +00002964** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002965**
2966** For a constraint of the form X=expr, the expression is evaluated and its
2967** result is left on the stack. For constraints of the form X IN (...)
2968** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002969*/
drh678ccce2008-03-31 18:19:54 +00002970static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002971 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002972 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh1db639c2008-01-17 02:36:28 +00002973 WhereLevel *pLevel, /* When level of the FROM clause we are working on */
drh678ccce2008-03-31 18:19:54 +00002974 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002975){
drh0fcef5e2005-07-19 17:38:22 +00002976 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002977 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002978 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002979
danielk19772d605492008-10-01 08:43:03 +00002980 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002981 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002982 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002983 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002984 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002985 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002986#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002987 }else{
danielk19779a96b662007-11-29 17:05:18 +00002988 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002989 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002990 struct InLoop *pIn;
danielk1977b3bce662005-01-29 08:32:43 +00002991
drh50b39962006-10-28 00:28:09 +00002992 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002993 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002994 eType = sqlite3FindInIndex(pParse, pX, 0);
danielk1977b3bce662005-01-29 08:32:43 +00002995 iTab = pX->iTable;
drh66a51672008-01-03 00:01:23 +00002996 sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh111a6a72008-12-21 03:51:16 +00002997 assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
2998 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002999 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00003000 }
drh111a6a72008-12-21 03:51:16 +00003001 pLevel->u.in.nIn++;
3002 pLevel->u.in.aInLoop =
3003 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
3004 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
3005 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00003006 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00003007 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00003008 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00003009 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00003010 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00003011 }else{
drhb3190c12008-12-08 21:37:14 +00003012 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00003013 }
3014 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
drha6110402005-07-28 20:51:19 +00003015 }else{
drh111a6a72008-12-21 03:51:16 +00003016 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00003017 }
danielk1977b3bce662005-01-29 08:32:43 +00003018#endif
drh94a11212004-09-25 13:12:14 +00003019 }
drh0fcef5e2005-07-19 17:38:22 +00003020 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00003021 return iReg;
drh94a11212004-09-25 13:12:14 +00003022}
3023
drh51147ba2005-07-23 22:59:55 +00003024/*
3025** Generate code that will evaluate all == and IN constraints for an
drh039fc322009-11-17 18:31:47 +00003026** index.
drh51147ba2005-07-23 22:59:55 +00003027**
3028** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
3029** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
3030** The index has as many as three equality constraints, but in this
3031** example, the third "c" value is an inequality. So only two
3032** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00003033** a==5 and b IN (1,2,3). The current values for a and b will be stored
3034** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00003035**
3036** In the example above nEq==2. But this subroutine works for any value
3037** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00003038** The only thing it does is allocate the pLevel->iMem memory cell and
3039** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00003040**
drh700a2262008-12-17 19:22:15 +00003041** This routine always allocates at least one memory cell and returns
3042** the index of that memory cell. The code that
3043** calls this routine will use that memory cell to store the termination
drh51147ba2005-07-23 22:59:55 +00003044** key value of the loop. If one or more IN operators appear, then
3045** this routine allocates an additional nEq memory cells for internal
3046** use.
dan69f8bb92009-08-13 19:21:16 +00003047**
3048** Before returning, *pzAff is set to point to a buffer containing a
3049** copy of the column affinity string of the index allocated using
3050** sqlite3DbMalloc(). Except, entries in the copy of the string associated
3051** with equality constraints that use NONE affinity are set to
3052** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
3053**
3054** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
3055** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
3056**
3057** In the example above, the index on t1(a) has TEXT affinity. But since
3058** the right hand side of the equality constraint (t2.b) has NONE affinity,
3059** no conversion should be attempted before using a t2.b value as part of
3060** a key to search the index. Hence the first byte in the returned affinity
3061** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00003062*/
drh1db639c2008-01-17 02:36:28 +00003063static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00003064 Parse *pParse, /* Parsing context */
3065 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
3066 WhereClause *pWC, /* The WHERE clause */
drh1db639c2008-01-17 02:36:28 +00003067 Bitmask notReady, /* Which parts of FROM have not yet been coded */
dan69f8bb92009-08-13 19:21:16 +00003068 int nExtraReg, /* Number of extra registers to allocate */
3069 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00003070){
drh111a6a72008-12-21 03:51:16 +00003071 int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
3072 Vdbe *v = pParse->pVdbe; /* The vm under construction */
3073 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00003074 int iCur = pLevel->iTabCur; /* The cursor of the table */
3075 WhereTerm *pTerm; /* A single constraint term */
3076 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00003077 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00003078 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00003079 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00003080
drh111a6a72008-12-21 03:51:16 +00003081 /* This module is only called on query plans that use an index. */
3082 assert( pLevel->plan.wsFlags & WHERE_INDEXED );
3083 pIdx = pLevel->plan.u.pIdx;
3084
drh51147ba2005-07-23 22:59:55 +00003085 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00003086 */
drh700a2262008-12-17 19:22:15 +00003087 regBase = pParse->nMem + 1;
drh6df2acd2008-12-28 16:55:25 +00003088 nReg = pLevel->plan.nEq + nExtraReg;
3089 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00003090
dan69f8bb92009-08-13 19:21:16 +00003091 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
3092 if( !zAff ){
3093 pParse->db->mallocFailed = 1;
3094 }
3095
drh51147ba2005-07-23 22:59:55 +00003096 /* Evaluate the equality constraints
3097 */
drhc49de5d2007-01-19 01:06:01 +00003098 assert( pIdx->nColumn>=nEq );
3099 for(j=0; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00003100 int r1;
drh51147ba2005-07-23 22:59:55 +00003101 int k = pIdx->aiColumn[j];
drh111a6a72008-12-21 03:51:16 +00003102 pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
drh34004ce2008-07-11 16:15:17 +00003103 if( NEVER(pTerm==0) ) break;
drhbe837bd2010-04-30 21:03:24 +00003104 /* The following true for indices with redundant columns.
3105 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
3106 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drhe9cdcea2010-07-22 22:40:03 +00003107 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh678ccce2008-03-31 18:19:54 +00003108 r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
3109 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00003110 if( nReg==1 ){
3111 sqlite3ReleaseTempReg(pParse, regBase);
3112 regBase = r1;
3113 }else{
3114 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
3115 }
drh678ccce2008-03-31 18:19:54 +00003116 }
drh981642f2008-04-19 14:40:43 +00003117 testcase( pTerm->eOperator & WO_ISNULL );
3118 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00003119 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00003120 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00003121 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00003122 if( zAff ){
3123 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
3124 zAff[j] = SQLITE_AFF_NONE;
3125 }
3126 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
3127 zAff[j] = SQLITE_AFF_NONE;
3128 }
dan69f8bb92009-08-13 19:21:16 +00003129 }
drh51147ba2005-07-23 22:59:55 +00003130 }
3131 }
dan69f8bb92009-08-13 19:21:16 +00003132 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00003133 return regBase;
drh51147ba2005-07-23 22:59:55 +00003134}
3135
drh111a6a72008-12-21 03:51:16 +00003136/*
3137** Generate code for the start of the iLevel-th loop in the WHERE clause
3138** implementation described by pWInfo.
3139*/
3140static Bitmask codeOneLoopStart(
3141 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3142 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh336a5302009-04-24 15:46:21 +00003143 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
drh111a6a72008-12-21 03:51:16 +00003144 Bitmask notReady /* Which tables are currently available */
3145){
3146 int j, k; /* Loop counters */
3147 int iCur; /* The VDBE cursor for the table */
3148 int addrNxt; /* Where to jump to continue with the next IN case */
3149 int omitTable; /* True if we use the index only */
3150 int bRev; /* True if we need to scan in reverse order */
3151 WhereLevel *pLevel; /* The where level to be coded */
3152 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3153 WhereTerm *pTerm; /* A WHERE clause term */
3154 Parse *pParse; /* Parsing context */
3155 Vdbe *v; /* The prepared stmt under constructions */
3156 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003157 int addrBrk; /* Jump here to break out of the loop */
3158 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003159 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3160 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00003161
3162 pParse = pWInfo->pParse;
3163 v = pParse->pVdbe;
3164 pWC = pWInfo->pWC;
3165 pLevel = &pWInfo->a[iLevel];
3166 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3167 iCur = pTabItem->iCursor;
3168 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
danielk19771d461462009-04-21 09:02:45 +00003169 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
drh336a5302009-04-24 15:46:21 +00003170 && (wctrlFlags & WHERE_FORCE_TABLE)==0;
drh111a6a72008-12-21 03:51:16 +00003171
3172 /* Create labels for the "break" and "continue" instructions
3173 ** for the current loop. Jump to addrBrk to break out of a loop.
3174 ** Jump to cont to go immediately to the next iteration of the
3175 ** loop.
3176 **
3177 ** When there is an IN operator, we also have a "addrNxt" label that
3178 ** means to continue with the next IN value combination. When
3179 ** there are no IN operators in the constraints, the "addrNxt" label
3180 ** is the same as "addrBrk".
3181 */
3182 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3183 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3184
3185 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3186 ** initialize a memory cell that records if this table matches any
3187 ** row of the left table of the join.
3188 */
3189 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3190 pLevel->iLeftJoin = ++pParse->nMem;
3191 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3192 VdbeComment((v, "init LEFT JOIN no-match flag"));
3193 }
3194
3195#ifndef SQLITE_OMIT_VIRTUALTABLE
3196 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3197 /* Case 0: The table is a virtual-table. Use the VFilter and VNext
3198 ** to access the data.
3199 */
3200 int iReg; /* P3 Value for OP_VFilter */
3201 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
3202 int nConstraint = pVtabIdx->nConstraint;
3203 struct sqlite3_index_constraint_usage *aUsage =
3204 pVtabIdx->aConstraintUsage;
3205 const struct sqlite3_index_constraint *aConstraint =
3206 pVtabIdx->aConstraint;
3207
drha62bb8d2009-11-23 21:23:45 +00003208 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003209 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh111a6a72008-12-21 03:51:16 +00003210 for(j=1; j<=nConstraint; j++){
3211 for(k=0; k<nConstraint; k++){
3212 if( aUsage[k].argvIndex==j ){
3213 int iTerm = aConstraint[k].iTermOffset;
drh111a6a72008-12-21 03:51:16 +00003214 sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
3215 break;
3216 }
3217 }
3218 if( k==nConstraint ) break;
3219 }
drh111a6a72008-12-21 03:51:16 +00003220 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
3221 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
3222 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
3223 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
drh111a6a72008-12-21 03:51:16 +00003224 pVtabIdx->needToFreeIdxStr = 0;
3225 for(j=0; j<nConstraint; j++){
3226 if( aUsage[j].omit ){
3227 int iTerm = aConstraint[j].iTermOffset;
3228 disableTerm(pLevel, &pWC->a[iTerm]);
3229 }
3230 }
3231 pLevel->op = OP_VNext;
3232 pLevel->p1 = iCur;
3233 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003234 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00003235 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00003236 }else
3237#endif /* SQLITE_OMIT_VIRTUALTABLE */
3238
3239 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
3240 /* Case 1: We can directly reference a single row using an
3241 ** equality comparison against the ROWID field. Or
3242 ** we reference multiple rows using a "rowid IN (...)"
3243 ** construct.
3244 */
danielk19771d461462009-04-21 09:02:45 +00003245 iReleaseReg = sqlite3GetTempReg(pParse);
drh111a6a72008-12-21 03:51:16 +00003246 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
3247 assert( pTerm!=0 );
3248 assert( pTerm->pExpr!=0 );
3249 assert( pTerm->leftCursor==iCur );
3250 assert( omitTable==0 );
drhe9cdcea2010-07-22 22:40:03 +00003251 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
danielk19771d461462009-04-21 09:02:45 +00003252 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003253 addrNxt = pLevel->addrNxt;
danielk19771d461462009-04-21 09:02:45 +00003254 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
3255 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003256 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003257 VdbeComment((v, "pk"));
3258 pLevel->op = OP_Noop;
3259 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
3260 /* Case 2: We have an inequality comparison against the ROWID field.
3261 */
3262 int testOp = OP_Noop;
3263 int start;
3264 int memEndValue = 0;
3265 WhereTerm *pStart, *pEnd;
3266
3267 assert( omitTable==0 );
3268 pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
3269 pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
3270 if( bRev ){
3271 pTerm = pStart;
3272 pStart = pEnd;
3273 pEnd = pTerm;
3274 }
3275 if( pStart ){
3276 Expr *pX; /* The expression that defines the start bound */
3277 int r1, rTemp; /* Registers for holding the start boundary */
3278
3279 /* The following constant maps TK_xx codes into corresponding
3280 ** seek opcodes. It depends on a particular ordering of TK_xx
3281 */
3282 const u8 aMoveOp[] = {
3283 /* TK_GT */ OP_SeekGt,
3284 /* TK_LE */ OP_SeekLe,
3285 /* TK_LT */ OP_SeekLt,
3286 /* TK_GE */ OP_SeekGe
3287 };
3288 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3289 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3290 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3291
drhe9cdcea2010-07-22 22:40:03 +00003292 testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003293 pX = pStart->pExpr;
3294 assert( pX!=0 );
3295 assert( pStart->leftCursor==iCur );
3296 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3297 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
3298 VdbeComment((v, "pk"));
3299 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3300 sqlite3ReleaseTempReg(pParse, rTemp);
3301 disableTerm(pLevel, pStart);
3302 }else{
3303 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
3304 }
3305 if( pEnd ){
3306 Expr *pX;
3307 pX = pEnd->pExpr;
3308 assert( pX!=0 );
3309 assert( pEnd->leftCursor==iCur );
drhe9cdcea2010-07-22 22:40:03 +00003310 testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003311 memEndValue = ++pParse->nMem;
3312 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3313 if( pX->op==TK_LT || pX->op==TK_GT ){
3314 testOp = bRev ? OP_Le : OP_Ge;
3315 }else{
3316 testOp = bRev ? OP_Lt : OP_Gt;
3317 }
3318 disableTerm(pLevel, pEnd);
3319 }
3320 start = sqlite3VdbeCurrentAddr(v);
3321 pLevel->op = bRev ? OP_Prev : OP_Next;
3322 pLevel->p1 = iCur;
3323 pLevel->p2 = start;
drhafc266a2010-03-31 17:47:44 +00003324 if( pStart==0 && pEnd==0 ){
3325 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3326 }else{
3327 assert( pLevel->p5==0 );
3328 }
danielk19771d461462009-04-21 09:02:45 +00003329 if( testOp!=OP_Noop ){
3330 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3331 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003332 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003333 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
3334 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003335 }
3336 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
3337 /* Case 3: A scan using an index.
3338 **
3339 ** The WHERE clause may contain zero or more equality
3340 ** terms ("==" or "IN" operators) that refer to the N
3341 ** left-most columns of the index. It may also contain
3342 ** inequality constraints (>, <, >= or <=) on the indexed
3343 ** column that immediately follows the N equalities. Only
3344 ** the right-most column can be an inequality - the rest must
3345 ** use the "==" and "IN" operators. For example, if the
3346 ** index is on (x,y,z), then the following clauses are all
3347 ** optimized:
3348 **
3349 ** x=5
3350 ** x=5 AND y=10
3351 ** x=5 AND y<10
3352 ** x=5 AND y>5 AND y<10
3353 ** x=5 AND y=5 AND z<=10
3354 **
3355 ** The z<10 term of the following cannot be used, only
3356 ** the x=5 term:
3357 **
3358 ** x=5 AND z<10
3359 **
3360 ** N may be zero if there are inequality constraints.
3361 ** If there are no inequality constraints, then N is at
3362 ** least one.
3363 **
3364 ** This case is also used when there are no WHERE clause
3365 ** constraints but an index is selected anyway, in order
3366 ** to force the output order to conform to an ORDER BY.
3367 */
3368 int aStartOp[] = {
3369 0,
3370 0,
3371 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3372 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
3373 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
3374 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
3375 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
3376 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
3377 };
3378 int aEndOp[] = {
3379 OP_Noop, /* 0: (!end_constraints) */
3380 OP_IdxGE, /* 1: (end_constraints && !bRev) */
3381 OP_IdxLT /* 2: (end_constraints && bRev) */
3382 };
3383 int nEq = pLevel->plan.nEq;
3384 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
3385 int regBase; /* Base register holding constraint values */
3386 int r1; /* Temp register */
3387 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3388 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3389 int startEq; /* True if range start uses ==, >= or <= */
3390 int endEq; /* True if range end uses ==, >= or <= */
3391 int start_constraints; /* Start of range is constrained */
3392 int nConstraint; /* Number of constraint terms */
3393 Index *pIdx; /* The index we will be using */
3394 int iIdxCur; /* The VDBE cursor for the index */
drh6df2acd2008-12-28 16:55:25 +00003395 int nExtraReg = 0; /* Number of extra registers needed */
3396 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003397 char *zStartAff; /* Affinity for start of range constraint */
3398 char *zEndAff; /* Affinity for end of range constraint */
drh111a6a72008-12-21 03:51:16 +00003399
3400 pIdx = pLevel->plan.u.pIdx;
3401 iIdxCur = pLevel->iIdxCur;
3402 k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
3403
drh111a6a72008-12-21 03:51:16 +00003404 /* If this loop satisfies a sort order (pOrderBy) request that
3405 ** was passed to this function to implement a "SELECT min(x) ..."
3406 ** query, then the caller will only allow the loop to run for
3407 ** a single iteration. This means that the first row returned
3408 ** should not have a NULL value stored in 'x'. If column 'x' is
3409 ** the first one after the nEq equality constraints in the index,
3410 ** this requires some special handling.
3411 */
3412 if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
3413 && (pLevel->plan.wsFlags&WHERE_ORDERBY)
3414 && (pIdx->nColumn>nEq)
3415 ){
3416 /* assert( pOrderBy->nExpr==1 ); */
3417 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
3418 isMinQuery = 1;
drh6df2acd2008-12-28 16:55:25 +00003419 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003420 }
3421
3422 /* Find any inequality constraint terms for the start and end
3423 ** of the range.
3424 */
3425 if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
3426 pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
drh6df2acd2008-12-28 16:55:25 +00003427 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003428 }
3429 if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
3430 pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
drh6df2acd2008-12-28 16:55:25 +00003431 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003432 }
3433
drh6df2acd2008-12-28 16:55:25 +00003434 /* Generate code to evaluate all constraint terms using == or IN
3435 ** and store the values of those terms in an array of registers
3436 ** starting at regBase.
3437 */
dan69f8bb92009-08-13 19:21:16 +00003438 regBase = codeAllEqualityTerms(
dan6ac43392010-06-09 15:47:11 +00003439 pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
dan69f8bb92009-08-13 19:21:16 +00003440 );
dan6ac43392010-06-09 15:47:11 +00003441 zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
drh6df2acd2008-12-28 16:55:25 +00003442 addrNxt = pLevel->addrNxt;
3443
drh111a6a72008-12-21 03:51:16 +00003444 /* If we are doing a reverse order scan on an ascending index, or
3445 ** a forward order scan on a descending index, interchange the
3446 ** start and end terms (pRangeStart and pRangeEnd).
3447 */
drh0eb77d02010-07-03 01:44:27 +00003448 if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
drh111a6a72008-12-21 03:51:16 +00003449 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3450 }
3451
3452 testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
3453 testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
3454 testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
3455 testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
3456 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3457 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3458 start_constraints = pRangeStart || nEq>0;
3459
3460 /* Seek the index cursor to the start of the range. */
3461 nConstraint = nEq;
3462 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003463 Expr *pRight = pRangeStart->pExpr->pRight;
3464 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh2f2855b2009-11-18 01:25:26 +00003465 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
dan6ac43392010-06-09 15:47:11 +00003466 if( zStartAff ){
3467 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003468 /* Since the comparison is to be performed with no conversions
3469 ** applied to the operands, set the affinity to apply to pRight to
3470 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003471 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003472 }
dan6ac43392010-06-09 15:47:11 +00003473 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3474 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003475 }
3476 }
drh111a6a72008-12-21 03:51:16 +00003477 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003478 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003479 }else if( isMinQuery ){
3480 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3481 nConstraint++;
3482 startEq = 0;
3483 start_constraints = 1;
3484 }
dan6ac43392010-06-09 15:47:11 +00003485 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003486 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3487 assert( op!=0 );
3488 testcase( op==OP_Rewind );
3489 testcase( op==OP_Last );
3490 testcase( op==OP_SeekGt );
3491 testcase( op==OP_SeekGe );
3492 testcase( op==OP_SeekLe );
3493 testcase( op==OP_SeekLt );
drh8cff69d2009-11-12 19:59:44 +00003494 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh111a6a72008-12-21 03:51:16 +00003495
3496 /* Load the value for the inequality constraint at the end of the
3497 ** range (if any).
3498 */
3499 nConstraint = nEq;
3500 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003501 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003502 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003503 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh2f2855b2009-11-18 01:25:26 +00003504 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
dan6ac43392010-06-09 15:47:11 +00003505 if( zEndAff ){
3506 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003507 /* Since the comparison is to be performed with no conversions
3508 ** applied to the operands, set the affinity to apply to pRight to
3509 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003510 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003511 }
dan6ac43392010-06-09 15:47:11 +00003512 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
3513 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003514 }
3515 }
dan6ac43392010-06-09 15:47:11 +00003516 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003517 nConstraint++;
drhe9cdcea2010-07-22 22:40:03 +00003518 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003519 }
dan6ac43392010-06-09 15:47:11 +00003520 sqlite3DbFree(pParse->db, zStartAff);
3521 sqlite3DbFree(pParse->db, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003522
3523 /* Top of the loop body */
3524 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3525
3526 /* Check if the index cursor is past the end of the range. */
3527 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3528 testcase( op==OP_Noop );
3529 testcase( op==OP_IdxGE );
3530 testcase( op==OP_IdxLT );
drh6df2acd2008-12-28 16:55:25 +00003531 if( op!=OP_Noop ){
drh8cff69d2009-11-12 19:59:44 +00003532 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh6df2acd2008-12-28 16:55:25 +00003533 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3534 }
drh111a6a72008-12-21 03:51:16 +00003535
3536 /* If there are inequality constraints, check that the value
3537 ** of the table column that the inequality contrains is not NULL.
3538 ** If it is, jump to the next iteration of the loop.
3539 */
3540 r1 = sqlite3GetTempReg(pParse);
3541 testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
3542 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
3543 if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
3544 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3545 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3546 }
danielk19771d461462009-04-21 09:02:45 +00003547 sqlite3ReleaseTempReg(pParse, r1);
drh111a6a72008-12-21 03:51:16 +00003548
3549 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003550 disableTerm(pLevel, pRangeStart);
3551 disableTerm(pLevel, pRangeEnd);
danielk19771d461462009-04-21 09:02:45 +00003552 if( !omitTable ){
3553 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3554 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003555 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003556 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh111a6a72008-12-21 03:51:16 +00003557 }
drh111a6a72008-12-21 03:51:16 +00003558
3559 /* Record the instruction used to terminate the loop. Disable
3560 ** WHERE clause terms made redundant by the index range scan.
3561 */
3562 pLevel->op = bRev ? OP_Prev : OP_Next;
3563 pLevel->p1 = iIdxCur;
drhdd5f5a62008-12-23 13:35:23 +00003564 }else
3565
drh23d04d52008-12-23 23:56:22 +00003566#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drhdd5f5a62008-12-23 13:35:23 +00003567 if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
drh111a6a72008-12-21 03:51:16 +00003568 /* Case 4: Two or more separately indexed terms connected by OR
3569 **
3570 ** Example:
3571 **
3572 ** CREATE TABLE t1(a,b,c,d);
3573 ** CREATE INDEX i1 ON t1(a);
3574 ** CREATE INDEX i2 ON t1(b);
3575 ** CREATE INDEX i3 ON t1(c);
3576 **
3577 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3578 **
3579 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003580 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003581 **
drh1b26c7c2009-04-22 02:15:47 +00003582 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003583 **
danielk19771d461462009-04-21 09:02:45 +00003584 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003585 ** RowSetTest are such that the rowid of the current row is inserted
3586 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003587 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003588 **
danielk19771d461462009-04-21 09:02:45 +00003589 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003590 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003591 ** Gosub 2 A
3592 ** sqlite3WhereEnd()
3593 **
3594 ** Following the above, code to terminate the loop. Label A, the target
3595 ** of the Gosub above, jumps to the instruction right after the Goto.
3596 **
drh1b26c7c2009-04-22 02:15:47 +00003597 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003598 ** Goto B # The loop is finished.
3599 **
3600 ** A: <loop body> # Return data, whatever.
3601 **
3602 ** Return 2 # Jump back to the Gosub
3603 **
3604 ** B: <after the loop>
3605 **
drh111a6a72008-12-21 03:51:16 +00003606 */
drh111a6a72008-12-21 03:51:16 +00003607 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
danielk19771d461462009-04-21 09:02:45 +00003608 WhereTerm *pFinal; /* Final subterm within the OR-clause. */
drhc01a3c12009-12-16 22:10:49 +00003609 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
danielk19771d461462009-04-21 09:02:45 +00003610
3611 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003612 int regRowset = 0; /* Register for RowSet object */
3613 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003614 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3615 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003616 int untestedTerms = 0; /* Some terms not completely tested */
danielk19771d461462009-04-21 09:02:45 +00003617 int ii;
drh111a6a72008-12-21 03:51:16 +00003618
3619 pTerm = pLevel->plan.u.pTerm;
3620 assert( pTerm!=0 );
3621 assert( pTerm->eOperator==WO_OR );
3622 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3623 pOrWc = &pTerm->u.pOrInfo->wc;
danielk19771d461462009-04-21 09:02:45 +00003624 pFinal = &pOrWc->a[pOrWc->nTerm-1];
drhc01a3c12009-12-16 22:10:49 +00003625 pLevel->op = OP_Return;
3626 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003627
drhc01a3c12009-12-16 22:10:49 +00003628 /* Set up a new SrcList ni pOrTab containing the table being scanned
3629 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3630 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3631 */
3632 if( pWInfo->nLevel>1 ){
3633 int nNotReady; /* The number of notReady tables */
3634 struct SrcList_item *origSrc; /* Original list of tables */
3635 nNotReady = pWInfo->nLevel - iLevel - 1;
3636 pOrTab = sqlite3StackAllocRaw(pParse->db,
3637 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3638 if( pOrTab==0 ) return notReady;
shaneh46aae3c2009-12-31 19:06:23 +00003639 pOrTab->nAlloc = (i16)(nNotReady + 1);
3640 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003641 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3642 origSrc = pWInfo->pTabList->a;
3643 for(k=1; k<=nNotReady; k++){
3644 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3645 }
3646 }else{
3647 pOrTab = pWInfo->pTabList;
3648 }
danielk19771d461462009-04-21 09:02:45 +00003649
drh1b26c7c2009-04-22 02:15:47 +00003650 /* Initialize the rowset register to contain NULL. An SQL NULL is
3651 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003652 **
3653 ** Also initialize regReturn to contain the address of the instruction
3654 ** immediately following the OP_Return at the bottom of the loop. This
3655 ** is required in a few obscure LEFT JOIN cases where control jumps
3656 ** over the top of the loop into the body of it. In this case the
3657 ** correct response for the end-of-loop code (the OP_Return) is to
3658 ** fall through to the next instruction, just as an OP_Next does if
3659 ** called on an uninitialized cursor.
3660 */
drh336a5302009-04-24 15:46:21 +00003661 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
3662 regRowset = ++pParse->nMem;
3663 regRowid = ++pParse->nMem;
3664 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3665 }
danielk19771d461462009-04-21 09:02:45 +00003666 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3667
danielk19771d461462009-04-21 09:02:45 +00003668 for(ii=0; ii<pOrWc->nTerm; ii++){
3669 WhereTerm *pOrTerm = &pOrWc->a[ii];
3670 if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
3671 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
danielk19771d461462009-04-21 09:02:45 +00003672 /* Loop through table entries that match term pOrTerm. */
drhc01a3c12009-12-16 22:10:49 +00003673 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
3674 WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
3675 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
danielk19771d461462009-04-21 09:02:45 +00003676 if( pSubWInfo ){
drh336a5302009-04-24 15:46:21 +00003677 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
3678 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3679 int r;
3680 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drhb6da74e2009-12-24 16:00:28 +00003681 regRowid);
drh8cff69d2009-11-12 19:59:44 +00003682 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3683 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh336a5302009-04-24 15:46:21 +00003684 }
danielk19771d461462009-04-21 09:02:45 +00003685 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3686
drhc01a3c12009-12-16 22:10:49 +00003687 /* The pSubWInfo->untestedTerms flag means that this OR term
3688 ** contained one or more AND term from a notReady table. The
3689 ** terms from the notReady table could not be tested and will
3690 ** need to be tested later.
3691 */
3692 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3693
danielk19771d461462009-04-21 09:02:45 +00003694 /* Finish the loop through table entries that match term pOrTerm. */
3695 sqlite3WhereEnd(pSubWInfo);
3696 }
drhdd5f5a62008-12-23 13:35:23 +00003697 }
3698 }
danielk19771d461462009-04-21 09:02:45 +00003699 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003700 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3701 sqlite3VdbeResolveLabel(v, iLoopBody);
3702
drhc01a3c12009-12-16 22:10:49 +00003703 if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
3704 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003705 }else
drh23d04d52008-12-23 23:56:22 +00003706#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003707
3708 {
drh111a6a72008-12-21 03:51:16 +00003709 /* Case 5: There is no usable index. We must do a complete
3710 ** scan of the entire table.
3711 */
drh699b3d42009-02-23 16:52:07 +00003712 static const u8 aStep[] = { OP_Next, OP_Prev };
3713 static const u8 aStart[] = { OP_Rewind, OP_Last };
3714 assert( bRev==0 || bRev==1 );
drh111a6a72008-12-21 03:51:16 +00003715 assert( omitTable==0 );
drh699b3d42009-02-23 16:52:07 +00003716 pLevel->op = aStep[bRev];
drh111a6a72008-12-21 03:51:16 +00003717 pLevel->p1 = iCur;
drh699b3d42009-02-23 16:52:07 +00003718 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh111a6a72008-12-21 03:51:16 +00003719 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3720 }
3721 notReady &= ~getMask(pWC->pMaskSet, iCur);
3722
3723 /* Insert code to test every subexpression that can be completely
3724 ** computed using the current set of tables.
drhe9cdcea2010-07-22 22:40:03 +00003725 **
3726 ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
3727 ** the use of indices become tests that are evaluated against each row of
3728 ** the relevant input tables.
drh111a6a72008-12-21 03:51:16 +00003729 */
3730 k = 0;
3731 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3732 Expr *pE;
drhe9cdcea2010-07-22 22:40:03 +00003733 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003734 testcase( pTerm->wtFlags & TERM_CODED );
3735 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhc01a3c12009-12-16 22:10:49 +00003736 if( (pTerm->prereqAll & notReady)!=0 ){
3737 testcase( pWInfo->untestedTerms==0
3738 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3739 pWInfo->untestedTerms = 1;
3740 continue;
3741 }
drh111a6a72008-12-21 03:51:16 +00003742 pE = pTerm->pExpr;
3743 assert( pE!=0 );
3744 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3745 continue;
3746 }
drh111a6a72008-12-21 03:51:16 +00003747 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003748 k = 1;
3749 pTerm->wtFlags |= TERM_CODED;
3750 }
3751
3752 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3753 ** at least one row of the right table has matched the left table.
3754 */
3755 if( pLevel->iLeftJoin ){
3756 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3757 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3758 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003759 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003760 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drhe9cdcea2010-07-22 22:40:03 +00003761 testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
drh111a6a72008-12-21 03:51:16 +00003762 testcase( pTerm->wtFlags & TERM_CODED );
3763 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drhc01a3c12009-12-16 22:10:49 +00003764 if( (pTerm->prereqAll & notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003765 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003766 continue;
3767 }
drh111a6a72008-12-21 03:51:16 +00003768 assert( pTerm->pExpr );
3769 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3770 pTerm->wtFlags |= TERM_CODED;
3771 }
3772 }
danielk19771d461462009-04-21 09:02:45 +00003773 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00003774
drh111a6a72008-12-21 03:51:16 +00003775 return notReady;
3776}
3777
drh549c8b62005-09-19 13:15:23 +00003778#if defined(SQLITE_TEST)
drh84bfda42005-07-15 13:05:21 +00003779/*
3780** The following variable holds a text description of query plan generated
3781** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
3782** overwrites the previous. This information is used for testing and
3783** analysis only.
3784*/
3785char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
3786static int nQPlan = 0; /* Next free slow in _query_plan[] */
3787
3788#endif /* SQLITE_TEST */
3789
3790
drh9eff6162006-06-12 21:59:13 +00003791/*
3792** Free a WhereInfo structure
3793*/
drh10fe8402008-10-11 16:47:35 +00003794static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00003795 if( ALWAYS(pWInfo) ){
drh9eff6162006-06-12 21:59:13 +00003796 int i;
3797 for(i=0; i<pWInfo->nLevel; i++){
drh4be8b512006-06-13 23:51:34 +00003798 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
3799 if( pInfo ){
danielk19771d461462009-04-21 09:02:45 +00003800 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
danielk197780442942008-12-24 11:25:39 +00003801 if( pInfo->needToFreeIdxStr ){
3802 sqlite3_free(pInfo->idxStr);
danielk1977be229652009-03-20 14:18:51 +00003803 }
drh633e6d52008-07-28 19:34:53 +00003804 sqlite3DbFree(db, pInfo);
danielk1977be8a7832006-06-13 15:00:54 +00003805 }
drh8b307fb2010-04-06 15:57:05 +00003806 if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
drha21a64d2010-04-06 22:33:55 +00003807 Index *pIdx = pWInfo->a[i].plan.u.pIdx;
3808 if( pIdx ){
3809 sqlite3DbFree(db, pIdx->zColAff);
3810 sqlite3DbFree(db, pIdx);
3811 }
drh8b307fb2010-04-06 15:57:05 +00003812 }
drh9eff6162006-06-12 21:59:13 +00003813 }
drh111a6a72008-12-21 03:51:16 +00003814 whereClauseClear(pWInfo->pWC);
drh633e6d52008-07-28 19:34:53 +00003815 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00003816 }
3817}
3818
drh94a11212004-09-25 13:12:14 +00003819
3820/*
drhe3184742002-06-19 14:27:05 +00003821** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00003822** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00003823** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00003824** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00003825** in order to complete the WHERE clause processing.
3826**
3827** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00003828**
3829** The basic idea is to do a nested loop, one loop for each table in
3830** the FROM clause of a select. (INSERT and UPDATE statements are the
3831** same as a SELECT with only a single table in the FROM clause.) For
3832** example, if the SQL is this:
3833**
3834** SELECT * FROM t1, t2, t3 WHERE ...;
3835**
3836** Then the code generated is conceptually like the following:
3837**
3838** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00003839** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00003840** foreach row3 in t3 do /
3841** ...
3842** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00003843** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00003844** end /
3845**
drh29dda4a2005-07-21 18:23:20 +00003846** Note that the loops might not be nested in the order in which they
3847** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00003848** use of indices. Note also that when the IN operator appears in
3849** the WHERE clause, it might result in additional nested loops for
3850** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00003851**
drhc27a1ce2002-06-14 20:58:45 +00003852** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00003853** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
3854** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00003855** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00003856**
drhe6f85e72004-12-25 01:03:13 +00003857** The code that sqlite3WhereBegin() generates leaves the cursors named
3858** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00003859** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00003860** data from the various tables of the loop.
3861**
drhc27a1ce2002-06-14 20:58:45 +00003862** If the WHERE clause is empty, the foreach loops must each scan their
3863** entire tables. Thus a three-way join is an O(N^3) operation. But if
3864** the tables have indices and there are terms in the WHERE clause that
3865** refer to those indices, a complete table scan can be avoided and the
3866** code will run much faster. Most of the work of this routine is checking
3867** to see if there are indices that can be used to speed up the loop.
3868**
3869** Terms of the WHERE clause are also used to limit which rows actually
3870** make it to the "..." in the middle of the loop. After each "foreach",
3871** terms of the WHERE clause that use only terms in that loop and outer
3872** loops are evaluated and if false a jump is made around all subsequent
3873** inner loops (or around the "..." if the test occurs within the inner-
3874** most loop)
3875**
3876** OUTER JOINS
3877**
3878** An outer join of tables t1 and t2 is conceptally coded as follows:
3879**
3880** foreach row1 in t1 do
3881** flag = 0
3882** foreach row2 in t2 do
3883** start:
3884** ...
3885** flag = 1
3886** end
drhe3184742002-06-19 14:27:05 +00003887** if flag==0 then
3888** move the row2 cursor to a null row
3889** goto start
3890** fi
drhc27a1ce2002-06-14 20:58:45 +00003891** end
3892**
drhe3184742002-06-19 14:27:05 +00003893** ORDER BY CLAUSE PROCESSING
3894**
3895** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
3896** if there is one. If there is no ORDER BY clause or if this routine
3897** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
3898**
3899** If an index can be used so that the natural output order of the table
3900** scan is correct for the ORDER BY clause, then that index is used and
3901** *ppOrderBy is set to NULL. This is an optimization that prevents an
3902** unnecessary sort of the result set if an index appropriate for the
3903** ORDER BY clause already exists.
3904**
3905** If the where clause loops cannot be arranged to provide the correct
3906** output order, then the *ppOrderBy is unchanged.
drh75897232000-05-29 14:26:00 +00003907*/
danielk19774adee202004-05-08 08:23:19 +00003908WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00003909 Parse *pParse, /* The parser context */
3910 SrcList *pTabList, /* A list of all tables to be scanned */
3911 Expr *pWhere, /* The WHERE clause */
danielk1977a9d1ccb2008-01-05 17:39:29 +00003912 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
drh336a5302009-04-24 15:46:21 +00003913 u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
drh75897232000-05-29 14:26:00 +00003914){
3915 int i; /* Loop counter */
danielk1977be229652009-03-20 14:18:51 +00003916 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00003917 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00003918 WhereInfo *pWInfo; /* Will become the return value of this function */
3919 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00003920 Bitmask notReady; /* Cursors that are not yet positioned */
drh111a6a72008-12-21 03:51:16 +00003921 WhereMaskSet *pMaskSet; /* The expression mask set */
drh111a6a72008-12-21 03:51:16 +00003922 WhereClause *pWC; /* Decomposition of the WHERE clause */
drh9012bcb2004-12-19 00:11:35 +00003923 struct SrcList_item *pTabItem; /* A single entry from pTabList */
3924 WhereLevel *pLevel; /* A single level in the pWInfo list */
drh29dda4a2005-07-21 18:23:20 +00003925 int iFrom; /* First unused FROM clause element */
drh111a6a72008-12-21 03:51:16 +00003926 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
drh17435752007-08-16 04:30:38 +00003927 sqlite3 *db; /* Database connection */
drh75897232000-05-29 14:26:00 +00003928
drh29dda4a2005-07-21 18:23:20 +00003929 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00003930 ** bits in a Bitmask
3931 */
drh67ae0cb2010-04-08 14:38:51 +00003932 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00003933 if( pTabList->nSrc>BMS ){
3934 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00003935 return 0;
3936 }
3937
drhc01a3c12009-12-16 22:10:49 +00003938 /* This function normally generates a nested loop for all tables in
3939 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
3940 ** only generate code for the first table in pTabList and assume that
3941 ** any cursors associated with subsequent tables are uninitialized.
3942 */
3943 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
3944
drh75897232000-05-29 14:26:00 +00003945 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00003946 ** return value. A single allocation is used to store the WhereInfo
3947 ** struct, the contents of WhereInfo.a[], the WhereClause structure
3948 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
3949 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
3950 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00003951 */
drh17435752007-08-16 04:30:38 +00003952 db = pParse->db;
drhc01a3c12009-12-16 22:10:49 +00003953 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
danielk1977be229652009-03-20 14:18:51 +00003954 pWInfo = sqlite3DbMallocZero(db,
3955 nByteWInfo +
3956 sizeof(WhereClause) +
3957 sizeof(WhereMaskSet)
3958 );
drh17435752007-08-16 04:30:38 +00003959 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00003960 sqlite3DbFree(db, pWInfo);
3961 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00003962 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00003963 }
drhc01a3c12009-12-16 22:10:49 +00003964 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00003965 pWInfo->pParse = pParse;
3966 pWInfo->pTabList = pTabList;
danielk19774adee202004-05-08 08:23:19 +00003967 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
danielk1977be229652009-03-20 14:18:51 +00003968 pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
drh6df2acd2008-12-28 16:55:25 +00003969 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00003970 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh111a6a72008-12-21 03:51:16 +00003971 pMaskSet = (WhereMaskSet*)&pWC[1];
drh08192d52002-04-30 19:20:28 +00003972
drh111a6a72008-12-21 03:51:16 +00003973 /* Split the WHERE clause into separate subexpressions where each
3974 ** subexpression is separated by an AND operator.
3975 */
3976 initMaskSet(pMaskSet);
3977 whereClauseInit(pWC, pParse, pMaskSet);
3978 sqlite3ExprCodeConstants(pParse, pWhere);
drhe9cdcea2010-07-22 22:40:03 +00003979 whereSplit(pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
drh111a6a72008-12-21 03:51:16 +00003980
drh08192d52002-04-30 19:20:28 +00003981 /* Special case: a WHERE clause that is constant. Evaluate the
3982 ** expression and either jump over all of the code or fall thru.
3983 */
drhc01a3c12009-12-16 22:10:49 +00003984 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
drh35573352008-01-08 23:54:25 +00003985 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
drhdf199a22002-06-14 22:38:41 +00003986 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00003987 }
drh75897232000-05-29 14:26:00 +00003988
drh42165be2008-03-26 14:56:34 +00003989 /* Assign a bit from the bitmask to every term in the FROM clause.
3990 **
3991 ** When assigning bitmask values to FROM clause cursors, it must be
3992 ** the case that if X is the bitmask for the N-th FROM clause term then
3993 ** the bitmask for all FROM clause terms to the left of the N-th term
3994 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
3995 ** its Expr.iRightJoinTable value to find the bitmask of the right table
3996 ** of the join. Subtracting one from the right table bitmask gives a
3997 ** bitmask for all tables to the left of the join. Knowing the bitmask
3998 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00003999 **
4000 ** Configure the WhereClause.vmask variable so that bits that correspond
4001 ** to virtual table cursors are set. This is used to selectively disable
4002 ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
4003 ** with virtual tables.
drhc01a3c12009-12-16 22:10:49 +00004004 **
4005 ** Note that bitmasks are created for all pTabList->nSrc tables in
4006 ** pTabList, not just the first nTabList tables. nTabList is normally
4007 ** equal to pTabList->nSrc but might be shortened to 1 if the
4008 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00004009 */
danielk1977e672c8e2009-05-22 15:43:26 +00004010 assert( pWC->vmask==0 && pMaskSet->n==0 );
drh42165be2008-03-26 14:56:34 +00004011 for(i=0; i<pTabList->nSrc; i++){
drh111a6a72008-12-21 03:51:16 +00004012 createMask(pMaskSet, pTabList->a[i].iCursor);
shanee26fa4c2009-06-16 14:15:22 +00004013#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2c1a0c52009-06-11 17:04:28 +00004014 if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
danielk1977e672c8e2009-05-22 15:43:26 +00004015 pWC->vmask |= ((Bitmask)1 << i);
4016 }
shanee26fa4c2009-06-16 14:15:22 +00004017#endif
drh42165be2008-03-26 14:56:34 +00004018 }
4019#ifndef NDEBUG
4020 {
4021 Bitmask toTheLeft = 0;
4022 for(i=0; i<pTabList->nSrc; i++){
drh111a6a72008-12-21 03:51:16 +00004023 Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
drh42165be2008-03-26 14:56:34 +00004024 assert( (m-1)==toTheLeft );
4025 toTheLeft |= m;
4026 }
4027 }
4028#endif
4029
drh29dda4a2005-07-21 18:23:20 +00004030 /* Analyze all of the subexpressions. Note that exprAnalyze() might
4031 ** add new virtual terms onto the end of the WHERE clause. We do not
4032 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00004033 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00004034 */
drh111a6a72008-12-21 03:51:16 +00004035 exprAnalyzeAll(pTabList, pWC);
drh17435752007-08-16 04:30:38 +00004036 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00004037 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00004038 }
drh75897232000-05-29 14:26:00 +00004039
drh29dda4a2005-07-21 18:23:20 +00004040 /* Chose the best index to use for each table in the FROM clause.
4041 **
drh51147ba2005-07-23 22:59:55 +00004042 ** This loop fills in the following fields:
4043 **
4044 ** pWInfo->a[].pIdx The index to use for this level of the loop.
drh165be382008-12-05 02:36:33 +00004045 ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
drh51147ba2005-07-23 22:59:55 +00004046 ** pWInfo->a[].nEq The number of == and IN constraints
danielk197785574e32008-10-06 05:32:18 +00004047 ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
drh51147ba2005-07-23 22:59:55 +00004048 ** pWInfo->a[].iTabCur The VDBE cursor for the database table
4049 ** pWInfo->a[].iIdxCur The VDBE cursor for the index
drh111a6a72008-12-21 03:51:16 +00004050 ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
drh51147ba2005-07-23 22:59:55 +00004051 **
4052 ** This loop also figures out the nesting order of tables in the FROM
4053 ** clause.
drh75897232000-05-29 14:26:00 +00004054 */
drhfe05af82005-07-21 03:14:59 +00004055 notReady = ~(Bitmask)0;
drh9012bcb2004-12-19 00:11:35 +00004056 pTabItem = pTabList->a;
4057 pLevel = pWInfo->a;
drh943af3c2005-07-29 19:43:58 +00004058 andFlags = ~0;
drh4f0c5872007-03-26 22:05:01 +00004059 WHERETRACE(("*** Optimizer Start ***\n"));
drhc01a3c12009-12-16 22:10:49 +00004060 for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
drh111a6a72008-12-21 03:51:16 +00004061 WhereCost bestPlan; /* Most efficient plan seen so far */
drh29dda4a2005-07-21 18:23:20 +00004062 Index *pIdx; /* Index for FROM table at pTabItem */
drh29dda4a2005-07-21 18:23:20 +00004063 int j; /* For looping over FROM tables */
dan5236ac12009-08-13 07:09:33 +00004064 int bestJ = -1; /* The value of j */
drh29dda4a2005-07-21 18:23:20 +00004065 Bitmask m; /* Bitmask value for j or bestJ */
dan5236ac12009-08-13 07:09:33 +00004066 int isOptimal; /* Iterator for optimal/non-optimal search */
drh5e377d92010-08-04 21:17:16 +00004067 int nUnconstrained; /* Number tables without INDEXED BY */
drhaa0ba432010-08-05 02:52:32 +00004068 Bitmask notIndexed; /* Mask of tables that cannot use an index */
drh29dda4a2005-07-21 18:23:20 +00004069
drh111a6a72008-12-21 03:51:16 +00004070 memset(&bestPlan, 0, sizeof(bestPlan));
4071 bestPlan.rCost = SQLITE_BIG_DBL;
drhdf26fd52006-06-06 11:45:54 +00004072
dan5236ac12009-08-13 07:09:33 +00004073 /* Loop through the remaining entries in the FROM clause to find the
drhed754ce2010-04-15 01:04:54 +00004074 ** next nested loop. The loop tests all FROM clause entries
dan5236ac12009-08-13 07:09:33 +00004075 ** either once or twice.
4076 **
drhed754ce2010-04-15 01:04:54 +00004077 ** The first test is always performed if there are two or more entries
4078 ** remaining and never performed if there is only one FROM clause entry
4079 ** to choose from. The first test looks for an "optimal" scan. In
dan5236ac12009-08-13 07:09:33 +00004080 ** this context an optimal scan is one that uses the same strategy
4081 ** for the given FROM clause entry as would be selected if the entry
drhd0015162009-08-21 13:22:25 +00004082 ** were used as the innermost nested loop. In other words, a table
4083 ** is chosen such that the cost of running that table cannot be reduced
drhed754ce2010-04-15 01:04:54 +00004084 ** by waiting for other tables to run first. This "optimal" test works
4085 ** by first assuming that the FROM clause is on the inner loop and finding
4086 ** its query plan, then checking to see if that query plan uses any
4087 ** other FROM clause terms that are notReady. If no notReady terms are
4088 ** used then the "optimal" query plan works.
dan5236ac12009-08-13 07:09:33 +00004089 **
drhed754ce2010-04-15 01:04:54 +00004090 ** The second loop iteration is only performed if no optimal scan
4091 ** strategies were found by the first loop. This 2nd iteration is used to
4092 ** search for the lowest cost scan overall.
dan5236ac12009-08-13 07:09:33 +00004093 **
4094 ** Previous versions of SQLite performed only the second iteration -
4095 ** the next outermost loop was always that with the lowest overall
4096 ** cost. However, this meant that SQLite could select the wrong plan
4097 ** for scripts such as the following:
4098 **
4099 ** CREATE TABLE t1(a, b);
4100 ** CREATE TABLE t2(c, d);
4101 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
4102 **
4103 ** The best strategy is to iterate through table t1 first. However it
4104 ** is not possible to determine this with a simple greedy algorithm.
4105 ** However, since the cost of a linear scan through table t2 is the same
4106 ** as the cost of a linear scan through table t1, a simple greedy
4107 ** algorithm may choose to use t2 for the outer loop, which is a much
4108 ** costlier approach.
4109 */
drh5e377d92010-08-04 21:17:16 +00004110 nUnconstrained = 0;
drhaa0ba432010-08-05 02:52:32 +00004111 notIndexed = 0;
drhed754ce2010-04-15 01:04:54 +00004112 for(isOptimal=(iFrom<nTabList-1); isOptimal>=0; isOptimal--){
drhaa0ba432010-08-05 02:52:32 +00004113 Bitmask mask; /* Mask of tables not yet ready */
drhc01a3c12009-12-16 22:10:49 +00004114 for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
dan5236ac12009-08-13 07:09:33 +00004115 int doNotReorder; /* True if this table should not be reordered */
4116 WhereCost sCost; /* Cost information from best[Virtual]Index() */
4117 ExprList *pOrderBy; /* ORDER BY clause for index to optimize */
4118
4119 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
4120 if( j!=iFrom && doNotReorder ) break;
4121 m = getMask(pMaskSet, pTabItem->iCursor);
4122 if( (m & notReady)==0 ){
4123 if( j==iFrom ) iFrom++;
4124 continue;
4125 }
drhed754ce2010-04-15 01:04:54 +00004126 mask = (isOptimal ? m : notReady);
dan5236ac12009-08-13 07:09:33 +00004127 pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
drh5e377d92010-08-04 21:17:16 +00004128 if( pTabItem->pIndex==0 ) nUnconstrained++;
dan5236ac12009-08-13 07:09:33 +00004129
4130 assert( pTabItem->pTab );
drh9eff6162006-06-12 21:59:13 +00004131#ifndef SQLITE_OMIT_VIRTUALTABLE
dan5236ac12009-08-13 07:09:33 +00004132 if( IsVirtual(pTabItem->pTab) ){
4133 sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
4134 bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
4135 }else
drh9eff6162006-06-12 21:59:13 +00004136#endif
dan5236ac12009-08-13 07:09:33 +00004137 {
4138 bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
4139 }
4140 assert( isOptimal || (sCost.used&notReady)==0 );
4141
drhaa0ba432010-08-05 02:52:32 +00004142 /* If an INDEXED BY clause is present, then the plan must use that
4143 ** index if it uses any index at all */
4144 assert( pTabItem->pIndex==0
4145 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
4146 || sCost.plan.u.pIdx==pTabItem->pIndex );
4147
4148 if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
4149 notIndexed |= m;
4150 }
4151
drh5e377d92010-08-04 21:17:16 +00004152 /* Conditions under which this table becomes the best so far:
4153 **
4154 ** (1) The table must not depend on other tables that have not
4155 ** yet run.
4156 **
4157 ** (2) A full-table-scan plan cannot supercede another plan unless
drhaa0ba432010-08-05 02:52:32 +00004158 ** it is an "optimal" plan as defined above.
drh5e377d92010-08-04 21:17:16 +00004159 **
drhaa0ba432010-08-05 02:52:32 +00004160 ** (3) All tables have an INDEXED BY clause or this table lacks an
drh5e377d92010-08-04 21:17:16 +00004161 ** INDEXED BY clause or this table uses the specific
drhaa0ba432010-08-05 02:52:32 +00004162 ** index specified by its INDEXED BY clause. This rule ensures
4163 ** that a best-so-far is always selected even if an impossible
4164 ** combination of INDEXED BY clauses are given. The error
4165 ** will be detected and relayed back to the application later.
4166 ** The NEVER() comes about because rule (2) above prevents
4167 ** An indexable full-table-scan from reaching rule (3).
4168 **
4169 ** (4) The plan cost must be lower than prior plans or else the
4170 ** cost must be the same and the number of rows must be lower.
drh5e377d92010-08-04 21:17:16 +00004171 */
4172 if( (sCost.used&notReady)==0 /* (1) */
drhaa0ba432010-08-05 02:52:32 +00004173 && (bestJ<0 || (notIndexed&m)!=0 /* (2) */
drh5e377d92010-08-04 21:17:16 +00004174 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
drhaa0ba432010-08-05 02:52:32 +00004175 && (nUnconstrained==0 || pTabItem->pIndex==0 /* (3) */
4176 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
4177 && (bestJ<0 || sCost.rCost<bestPlan.rCost /* (4) */
drh5e377d92010-08-04 21:17:16 +00004178 || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow))
dan5236ac12009-08-13 07:09:33 +00004179 ){
drhed754ce2010-04-15 01:04:54 +00004180 WHERETRACE(("... best so far with cost=%g and nRow=%g\n",
4181 sCost.rCost, sCost.nRow));
dan5236ac12009-08-13 07:09:33 +00004182 bestPlan = sCost;
4183 bestJ = j;
4184 }
4185 if( doNotReorder ) break;
drh9eff6162006-06-12 21:59:13 +00004186 }
drh29dda4a2005-07-21 18:23:20 +00004187 }
dan5236ac12009-08-13 07:09:33 +00004188 assert( bestJ>=0 );
danielk1977992347f2008-12-30 09:45:45 +00004189 assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
drhcb041342008-06-12 00:07:29 +00004190 WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
drh3dec2232005-09-10 15:28:09 +00004191 pLevel-pWInfo->a));
drh111a6a72008-12-21 03:51:16 +00004192 if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
drhfe05af82005-07-21 03:14:59 +00004193 *ppOrderBy = 0;
drhc4a3c772001-04-04 11:48:57 +00004194 }
drh111a6a72008-12-21 03:51:16 +00004195 andFlags &= bestPlan.plan.wsFlags;
4196 pLevel->plan = bestPlan.plan;
drh8b307fb2010-04-06 15:57:05 +00004197 testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
4198 testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
4199 if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
drh9012bcb2004-12-19 00:11:35 +00004200 pLevel->iIdxCur = pParse->nTab++;
drhfe05af82005-07-21 03:14:59 +00004201 }else{
4202 pLevel->iIdxCur = -1;
drh6b563442001-11-07 16:48:26 +00004203 }
drh111a6a72008-12-21 03:51:16 +00004204 notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
shaned87897d2009-01-30 05:40:27 +00004205 pLevel->iFrom = (u8)bestJ;
drh8b307fb2010-04-06 15:57:05 +00004206 if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow;
danielk197785574e32008-10-06 05:32:18 +00004207
4208 /* Check that if the table scanned by this loop iteration had an
4209 ** INDEXED BY clause attached to it, that the named index is being
4210 ** used for the scan. If not, then query compilation has failed.
4211 ** Return an error.
4212 */
4213 pIdx = pTabList->a[bestJ].pIndex;
drh171256c2009-01-08 03:11:19 +00004214 if( pIdx ){
4215 if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
4216 sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
4217 goto whereBeginError;
4218 }else{
4219 /* If an INDEXED BY clause is used, the bestIndex() function is
4220 ** guaranteed to find the index specified in the INDEXED BY clause
4221 ** if it find an index at all. */
4222 assert( bestPlan.plan.u.pIdx==pIdx );
4223 }
danielk197785574e32008-10-06 05:32:18 +00004224 }
drh75897232000-05-29 14:26:00 +00004225 }
drh4f0c5872007-03-26 22:05:01 +00004226 WHERETRACE(("*** Optimizer Finished ***\n"));
danielk19771d461462009-04-21 09:02:45 +00004227 if( pParse->nErr || db->mallocFailed ){
danielk197780442942008-12-24 11:25:39 +00004228 goto whereBeginError;
4229 }
drh75897232000-05-29 14:26:00 +00004230
drh943af3c2005-07-29 19:43:58 +00004231 /* If the total query only selects a single row, then the ORDER BY
4232 ** clause is irrelevant.
4233 */
4234 if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
4235 *ppOrderBy = 0;
4236 }
4237
drh08c88eb2008-04-10 13:33:18 +00004238 /* If the caller is an UPDATE or DELETE statement that is requesting
4239 ** to use a one-pass algorithm, determine if this is appropriate.
4240 ** The one-pass algorithm only works if the WHERE clause constraints
4241 ** the statement to update a single row.
4242 */
drh165be382008-12-05 02:36:33 +00004243 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
4244 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00004245 pWInfo->okOnePass = 1;
drh111a6a72008-12-21 03:51:16 +00004246 pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
drh08c88eb2008-04-10 13:33:18 +00004247 }
4248
drh9012bcb2004-12-19 00:11:35 +00004249 /* Open all tables in the pTabList and any indices selected for
4250 ** searching those tables.
4251 */
4252 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
drh8b307fb2010-04-06 15:57:05 +00004253 notReady = ~(Bitmask)0;
drhc01a3c12009-12-16 22:10:49 +00004254 for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00004255 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00004256 int iDb; /* Index of database containing table/index */
drh9012bcb2004-12-19 00:11:35 +00004257
drhecc92422005-09-10 16:46:12 +00004258#ifndef SQLITE_OMIT_EXPLAIN
4259 if( pParse->explain==2 ){
4260 char *zMsg;
4261 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
danielk19771e536952007-08-16 10:09:01 +00004262 zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
drhecc92422005-09-10 16:46:12 +00004263 if( pItem->zAlias ){
drh633e6d52008-07-28 19:34:53 +00004264 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
drhecc92422005-09-10 16:46:12 +00004265 }
drh8b307fb2010-04-06 15:57:05 +00004266 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
4267 zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg);
4268 }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
drh111a6a72008-12-21 03:51:16 +00004269 zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
4270 zMsg, pLevel->plan.u.pIdx->zName);
drh46129af2008-12-30 16:18:47 +00004271 }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
4272 zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
drh111a6a72008-12-21 03:51:16 +00004273 }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
drh633e6d52008-07-28 19:34:53 +00004274 zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
drhecc92422005-09-10 16:46:12 +00004275 }
drh9eff6162006-06-12 21:59:13 +00004276#ifndef SQLITE_OMIT_VIRTUALTABLE
drh111a6a72008-12-21 03:51:16 +00004277 else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
4278 sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
drh633e6d52008-07-28 19:34:53 +00004279 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drh111a6a72008-12-21 03:51:16 +00004280 pVtabIdx->idxNum, pVtabIdx->idxStr);
drh9eff6162006-06-12 21:59:13 +00004281 }
4282#endif
drh111a6a72008-12-21 03:51:16 +00004283 if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
drh633e6d52008-07-28 19:34:53 +00004284 zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
drhe2b39092006-04-21 09:38:36 +00004285 }
drh66a51672008-01-03 00:01:23 +00004286 sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
drhecc92422005-09-10 16:46:12 +00004287 }
4288#endif /* SQLITE_OMIT_EXPLAIN */
drh29dda4a2005-07-21 18:23:20 +00004289 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00004290 pTab = pTabItem->pTab;
drh424aab82010-04-06 18:28:20 +00004291 pLevel->iTabCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00004292 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh424aab82010-04-06 18:28:20 +00004293 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00004294 /* Do nothing */
4295 }else
drh9eff6162006-06-12 21:59:13 +00004296#ifndef SQLITE_OMIT_VIRTUALTABLE
drh111a6a72008-12-21 03:51:16 +00004297 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00004298 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00004299 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00004300 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drh9eff6162006-06-12 21:59:13 +00004301 }else
4302#endif
drh6df2acd2008-12-28 16:55:25 +00004303 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
4304 && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
drh08c88eb2008-04-10 13:33:18 +00004305 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
4306 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drh67ae0cb2010-04-08 14:38:51 +00004307 testcase( pTab->nCol==BMS-1 );
4308 testcase( pTab->nCol==BMS );
danielk197723432972008-11-17 16:42:00 +00004309 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
danielk19779792eef2006-01-13 15:58:43 +00004310 Bitmask b = pTabItem->colUsed;
4311 int n = 0;
drh74161702006-02-24 02:53:49 +00004312 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00004313 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
4314 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00004315 assert( n<=pTab->nCol );
4316 }
danielk1977c00da102006-01-07 13:21:04 +00004317 }else{
4318 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00004319 }
drhc6339082010-04-07 16:54:58 +00004320#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00004321 if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
drhc6339082010-04-07 16:54:58 +00004322 constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
4323 }else
4324#endif
4325 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
drh111a6a72008-12-21 03:51:16 +00004326 Index *pIx = pLevel->plan.u.pIdx;
danielk1977b3bf5562006-01-10 17:58:23 +00004327 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
drh111a6a72008-12-21 03:51:16 +00004328 int iIdxCur = pLevel->iIdxCur;
danielk1977da184232006-01-05 11:34:32 +00004329 assert( pIx->pSchema==pTab->pSchema );
drh111a6a72008-12-21 03:51:16 +00004330 assert( iIdxCur>=0 );
danielk1977207872a2008-01-03 07:54:23 +00004331 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00004332 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00004333 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00004334 }
danielk1977da184232006-01-05 11:34:32 +00004335 sqlite3CodeVerifySchema(pParse, iDb);
drh8b307fb2010-04-06 15:57:05 +00004336 notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00004337 }
4338 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00004339 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00004340
drh29dda4a2005-07-21 18:23:20 +00004341 /* Generate the code to do the search. Each iteration of the for
4342 ** loop below generates code for a single nested loop of the VM
4343 ** program.
drh75897232000-05-29 14:26:00 +00004344 */
drhfe05af82005-07-21 03:14:59 +00004345 notReady = ~(Bitmask)0;
drhc01a3c12009-12-16 22:10:49 +00004346 for(i=0; i<nTabList; i++){
drh111a6a72008-12-21 03:51:16 +00004347 notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
drh813f31e2009-01-06 00:08:02 +00004348 pWInfo->iContinue = pWInfo->a[i].addrCont;
drh75897232000-05-29 14:26:00 +00004349 }
drh7ec764a2005-07-21 03:48:20 +00004350
4351#ifdef SQLITE_TEST /* For testing and debugging use only */
4352 /* Record in the query plan information about the current table
4353 ** and the index used to access it (if any). If the table itself
4354 ** is not used, its name is just '{}'. If no index is used
4355 ** the index is listed as "{}". If the primary key is used the
4356 ** index name is '*'.
4357 */
drhc01a3c12009-12-16 22:10:49 +00004358 for(i=0; i<nTabList; i++){
drh7ec764a2005-07-21 03:48:20 +00004359 char *z;
4360 int n;
drh7ec764a2005-07-21 03:48:20 +00004361 pLevel = &pWInfo->a[i];
drh29dda4a2005-07-21 18:23:20 +00004362 pTabItem = &pTabList->a[pLevel->iFrom];
drh7ec764a2005-07-21 03:48:20 +00004363 z = pTabItem->zAlias;
4364 if( z==0 ) z = pTabItem->pTab->zName;
drhea678832008-12-10 19:26:22 +00004365 n = sqlite3Strlen30(z);
drh7ec764a2005-07-21 03:48:20 +00004366 if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
drh111a6a72008-12-21 03:51:16 +00004367 if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
drh5bb3eb92007-05-04 13:15:55 +00004368 memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
drh7ec764a2005-07-21 03:48:20 +00004369 nQPlan += 2;
4370 }else{
drh5bb3eb92007-05-04 13:15:55 +00004371 memcpy(&sqlite3_query_plan[nQPlan], z, n);
drh7ec764a2005-07-21 03:48:20 +00004372 nQPlan += n;
4373 }
4374 sqlite3_query_plan[nQPlan++] = ' ';
4375 }
drh111a6a72008-12-21 03:51:16 +00004376 testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
4377 testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
4378 if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
drh5bb3eb92007-05-04 13:15:55 +00004379 memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
drh7ec764a2005-07-21 03:48:20 +00004380 nQPlan += 2;
drh111a6a72008-12-21 03:51:16 +00004381 }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
4382 n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
drh7ec764a2005-07-21 03:48:20 +00004383 if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
drh111a6a72008-12-21 03:51:16 +00004384 memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
drh7ec764a2005-07-21 03:48:20 +00004385 nQPlan += n;
4386 sqlite3_query_plan[nQPlan++] = ' ';
4387 }
drh111a6a72008-12-21 03:51:16 +00004388 }else{
4389 memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
4390 nQPlan += 3;
drh7ec764a2005-07-21 03:48:20 +00004391 }
4392 }
4393 while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
4394 sqlite3_query_plan[--nQPlan] = 0;
4395 }
4396 sqlite3_query_plan[nQPlan] = 0;
4397 nQPlan = 0;
4398#endif /* SQLITE_TEST // Testing and debugging use only */
4399
drh29dda4a2005-07-21 18:23:20 +00004400 /* Record the continuation address in the WhereInfo structure. Then
4401 ** clean up and return.
4402 */
drh75897232000-05-29 14:26:00 +00004403 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00004404
4405 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00004406whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00004407 if( pWInfo ){
4408 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
4409 whereInfoFree(db, pWInfo);
4410 }
drhe23399f2005-07-22 00:31:39 +00004411 return 0;
drh75897232000-05-29 14:26:00 +00004412}
4413
4414/*
drhc27a1ce2002-06-14 20:58:45 +00004415** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00004416** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00004417*/
danielk19774adee202004-05-08 08:23:19 +00004418void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00004419 Parse *pParse = pWInfo->pParse;
4420 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00004421 int i;
drh6b563442001-11-07 16:48:26 +00004422 WhereLevel *pLevel;
drhad3cab52002-05-24 02:04:32 +00004423 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00004424 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00004425
drh9012bcb2004-12-19 00:11:35 +00004426 /* Generate loop termination code.
4427 */
drhceea3322009-04-23 13:22:42 +00004428 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00004429 for(i=pWInfo->nLevel-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00004430 pLevel = &pWInfo->a[i];
drhb3190c12008-12-08 21:37:14 +00004431 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00004432 if( pLevel->op!=OP_Noop ){
drh66a51672008-01-03 00:01:23 +00004433 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
drhd1d38482008-10-07 23:46:38 +00004434 sqlite3VdbeChangeP5(v, pLevel->p5);
drh19a775c2000-06-05 18:54:46 +00004435 }
drh111a6a72008-12-21 03:51:16 +00004436 if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00004437 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00004438 int j;
drhb3190c12008-12-08 21:37:14 +00004439 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00004440 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00004441 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
4442 sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
4443 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00004444 }
drh111a6a72008-12-21 03:51:16 +00004445 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00004446 }
drhb3190c12008-12-08 21:37:14 +00004447 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhad2d8302002-05-24 20:31:36 +00004448 if( pLevel->iLeftJoin ){
4449 int addr;
drh3c84ddf2008-01-09 02:15:38 +00004450 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
drh35451c62009-11-12 04:26:39 +00004451 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
4452 || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
4453 if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
4454 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
4455 }
drh9012bcb2004-12-19 00:11:35 +00004456 if( pLevel->iIdxCur>=0 ){
drh3c84ddf2008-01-09 02:15:38 +00004457 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00004458 }
drh336a5302009-04-24 15:46:21 +00004459 if( pLevel->op==OP_Return ){
4460 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
4461 }else{
4462 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
4463 }
drhd654be82005-09-20 17:42:23 +00004464 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00004465 }
drh19a775c2000-06-05 18:54:46 +00004466 }
drh9012bcb2004-12-19 00:11:35 +00004467
4468 /* The "break" point is here, just past the end of the outer loop.
4469 ** Set it.
4470 */
danielk19774adee202004-05-08 08:23:19 +00004471 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00004472
drh29dda4a2005-07-21 18:23:20 +00004473 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00004474 */
drhc01a3c12009-12-16 22:10:49 +00004475 assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
4476 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
drh29dda4a2005-07-21 18:23:20 +00004477 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00004478 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00004479 assert( pTab!=0 );
drh4139c992010-04-07 14:59:45 +00004480 if( (pTab->tabFlags & TF_Ephemeral)==0
4481 && pTab->pSelect==0
4482 && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
4483 ){
drh8b307fb2010-04-06 15:57:05 +00004484 int ws = pLevel->plan.wsFlags;
4485 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00004486 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
4487 }
drhf12cde52010-04-08 17:28:00 +00004488 if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
drh6df2acd2008-12-28 16:55:25 +00004489 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
4490 }
drh9012bcb2004-12-19 00:11:35 +00004491 }
4492
danielk197721de2e72007-11-29 17:43:27 +00004493 /* If this scan uses an index, make code substitutions to read data
4494 ** from the index in preference to the table. Sometimes, this means
4495 ** the table need never be read from. This is a performance boost,
4496 ** as the vdbe level waits until the table is read before actually
4497 ** seeking the table cursor to the record corresponding to the current
4498 ** position in the index.
drh9012bcb2004-12-19 00:11:35 +00004499 **
4500 ** Calls to the code generator in between sqlite3WhereBegin and
4501 ** sqlite3WhereEnd will have created code that references the table
4502 ** directly. This loop scans all that code looking for opcodes
4503 ** that reference the table and converts them into opcodes that
4504 ** reference the index.
4505 */
drh125feff2009-06-06 15:17:27 +00004506 if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
danielk1977f0113002006-01-24 12:09:17 +00004507 int k, j, last;
drh9012bcb2004-12-19 00:11:35 +00004508 VdbeOp *pOp;
drh111a6a72008-12-21 03:51:16 +00004509 Index *pIdx = pLevel->plan.u.pIdx;
drh9012bcb2004-12-19 00:11:35 +00004510
4511 assert( pIdx!=0 );
4512 pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
4513 last = sqlite3VdbeCurrentAddr(v);
danielk1977f0113002006-01-24 12:09:17 +00004514 for(k=pWInfo->iTop; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00004515 if( pOp->p1!=pLevel->iTabCur ) continue;
4516 if( pOp->opcode==OP_Column ){
drh9012bcb2004-12-19 00:11:35 +00004517 for(j=0; j<pIdx->nColumn; j++){
4518 if( pOp->p2==pIdx->aiColumn[j] ){
4519 pOp->p2 = j;
danielk197721de2e72007-11-29 17:43:27 +00004520 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00004521 break;
4522 }
4523 }
drh35451c62009-11-12 04:26:39 +00004524 assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
4525 || j<pIdx->nColumn );
drhf0863fe2005-06-12 21:35:51 +00004526 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00004527 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00004528 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00004529 }
4530 }
drh6b563442001-11-07 16:48:26 +00004531 }
drh19a775c2000-06-05 18:54:46 +00004532 }
drh9012bcb2004-12-19 00:11:35 +00004533
4534 /* Final cleanup
4535 */
drhf12cde52010-04-08 17:28:00 +00004536 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
4537 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00004538 return;
4539}