blob: fb097d2af40ec84a3374c8fec4c1efedd0b5fb58 [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
drh7924f3e2011-02-09 03:04:27 +000021
22/*
drh51147ba2005-07-23 22:59:55 +000023** Trace output macros
24*/
25#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
drhcef4fc82012-09-21 22:50:45 +000026/***/ int sqlite3WhereTrace = 0;
drhe8f52c52008-07-12 14:52:20 +000027#endif
drhcef4fc82012-09-21 22:50:45 +000028#if defined(SQLITE_DEBUG) \
29 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
drh3b48e8c2013-06-12 20:18:16 +000030# define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
drhd15cb172013-05-21 19:23:10 +000031# define WHERETRACE_ENABLED 1
drh51147ba2005-07-23 22:59:55 +000032#else
drh3b48e8c2013-06-12 20:18:16 +000033# define WHERETRACE(K,X)
drh51147ba2005-07-23 22:59:55 +000034#endif
35
drh4a6fc352013-08-07 01:18:38 +000036/* Forward references
drh0fcef5e2005-07-19 17:38:22 +000037*/
38typedef struct WhereClause WhereClause;
drh111a6a72008-12-21 03:51:16 +000039typedef struct WhereMaskSet WhereMaskSet;
drh700a2262008-12-17 19:22:15 +000040typedef struct WhereOrInfo WhereOrInfo;
41typedef struct WhereAndInfo WhereAndInfo;
drh6f328482013-06-05 23:39:34 +000042typedef struct WhereLevel WhereLevel;
drhf1b5f5b2013-05-02 00:15:01 +000043typedef struct WhereLoop WhereLoop;
44typedef struct WherePath WherePath;
45typedef struct WhereTerm WhereTerm;
drh1c8148f2013-05-04 20:25:23 +000046typedef struct WhereLoopBuilder WhereLoopBuilder;
47typedef struct WhereScan WhereScan;
drhaa32e3c2013-07-16 21:31:23 +000048typedef struct WhereOrCost WhereOrCost;
49typedef struct WhereOrSet WhereOrSet;
drhc63367e2013-06-10 20:46:50 +000050
51/*
52** Cost X is tracked as 10*log2(X) stored in a 16-bit integer. The
drh3b48e8c2013-06-12 20:18:16 +000053** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
54** (Virtual tables can return a larger cost, but let's assume they do not.)
55** So all costs can be stored in a 16-bit unsigned integer without risk
56** of overflow.
57**
drh4a6fc352013-08-07 01:18:38 +000058** Costs are estimates, so no effort is made to compute 10*log2(X) exactly.
59** Instead, a close estimate is used. Any value of X<=1 is stored as 0.
60** X=2 is 10. X=3 is 16. X=1000 is 99. etc.
drh3b48e8c2013-06-12 20:18:16 +000061**
drhe1e2e9a2013-06-13 15:16:53 +000062** The tool/wherecosttest.c source file implements a command-line program
drh4a6fc352013-08-07 01:18:38 +000063** that will convert WhereCosts to integers, convert integers to WhereCosts
64** and do addition and multiplication on WhereCost values. The wherecosttest
65** command-line program is a useful utility to have around when working with
66** this module.
drhc63367e2013-06-10 20:46:50 +000067*/
68typedef unsigned short int WhereCost;
drhf1b5f5b2013-05-02 00:15:01 +000069
70/*
drhf0030762013-06-14 13:27:01 +000071** This object contains information needed to implement a single nested
drh3b48e8c2013-06-12 20:18:16 +000072** loop in WHERE clause.
drh6f328482013-06-05 23:39:34 +000073**
drh3b48e8c2013-06-12 20:18:16 +000074** Contrast this object with WhereLoop. This object describes the
75** implementation of the loop. WhereLoop describes the algorithm.
76** This object contains a pointer to the WhereLoop algorithm as one of
77** its elements.
78**
79** The WhereInfo object contains a single instance of this object for
80** each term in the FROM clause (which is to say, for each of the
81** nested loops as implemented). The order of WhereLevel objects determines
82** the loop nested order, with WhereInfo.a[0] being the outer loop and
83** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
drh6f328482013-06-05 23:39:34 +000084*/
85struct WhereLevel {
86 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
87 int iTabCur; /* The VDBE cursor used to access the table */
88 int iIdxCur; /* The VDBE cursor used to access pIdx */
89 int addrBrk; /* Jump here to break out of the loop */
90 int addrNxt; /* Jump here to start the next IN combination */
91 int addrCont; /* Jump here to continue with the next loop cycle */
92 int addrFirst; /* First instruction of interior of the loop */
drhcc04afd2013-08-22 02:56:28 +000093 int addrBody; /* Beginning of the body of this loop */
drhe217efc2013-06-12 03:48:41 +000094 u8 iFrom; /* Which entry in the FROM clause */
drh6f328482013-06-05 23:39:34 +000095 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
96 int p1, p2; /* Operands of the opcode used to ends the loop */
drh37ca0482013-06-12 17:17:45 +000097 union { /* Information that depends on pWLoop->wsFlags */
drh6f328482013-06-05 23:39:34 +000098 struct {
99 int nIn; /* Number of entries in aInLoop[] */
100 struct InLoop {
101 int iCur; /* The VDBE cursor used by this IN operator */
102 int addrInTop; /* Top of the IN loop */
103 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
104 } *aInLoop; /* Information about each nested IN operator */
drh37ca0482013-06-12 17:17:45 +0000105 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
drh6f328482013-06-05 23:39:34 +0000106 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
107 } u;
108 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
drh0259bc32013-09-09 19:37:46 +0000109 Bitmask notReady; /* FROM entries not usable at this level */
drh6f328482013-06-05 23:39:34 +0000110};
111
112/*
drh3b48e8c2013-06-12 20:18:16 +0000113** Each instance of this object represents an algorithm for evaluating one
114** term of a join. Every term of the FROM clause will have at least
115** one corresponding WhereLoop object (unless INDEXED BY constraints
116** prevent a query solution - which is an error) and many terms of the
117** FROM clause will have multiple WhereLoop objects, each describing a
118** potential way of implementing that FROM-clause term, together with
119** dependencies and cost estimates for using the chosen algorithm.
120**
121** Query planning consists of building up a collection of these WhereLoop
122** objects, then computing a particular sequence of WhereLoop objects, with
123** one WhereLoop object per FROM clause term, that satisfy all dependencies
124** and that minimize the overall cost.
drhf1b5f5b2013-05-02 00:15:01 +0000125*/
126struct WhereLoop {
127 Bitmask prereq; /* Bitmask of other loops that must run first */
drha18f3d22013-05-08 03:05:41 +0000128 Bitmask maskSelf; /* Bitmask identifying table iTab */
drhd15cb172013-05-21 19:23:10 +0000129#ifdef SQLITE_DEBUG
130 char cId; /* Symbolic ID of this loop for debugging use */
131#endif
drh7ba39a92013-05-30 17:43:19 +0000132 u8 iTab; /* Position in FROM clause of table for this loop */
drh23f98da2013-05-21 15:52:07 +0000133 u8 iSortIdx; /* Sorting index number. 0==None */
drh4efc9292013-06-06 23:02:03 +0000134 WhereCost rSetup; /* One-time setup cost (ex: create transient index) */
135 WhereCost rRun; /* Cost of running each loop */
136 WhereCost nOut; /* Estimated number of output rows */
drh5346e952013-05-08 14:14:26 +0000137 union {
138 struct { /* Information for internal btree tables */
139 int nEq; /* Number of equality constraints */
140 Index *pIndex; /* Index used, or NULL */
141 } btree;
drh6b7157b2013-05-10 02:00:35 +0000142 struct { /* Information for virtual tables */
drh5346e952013-05-08 14:14:26 +0000143 int idxNum; /* Index number */
drh6b7157b2013-05-10 02:00:35 +0000144 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
145 u8 isOrdered; /* True if satisfies ORDER BY */
drh3bd26f02013-05-24 14:52:03 +0000146 u16 omitMask; /* Terms that may be omitted */
drh5346e952013-05-08 14:14:26 +0000147 char *idxStr; /* Index identifier string */
148 } vtab;
149 } u;
drha2014152013-06-07 00:29:23 +0000150 u32 wsFlags; /* WHERE_* flags describing the plan */
151 u16 nLTerm; /* Number of entries in aLTerm[] */
152 /**** whereLoopXfer() copies fields above ***********************/
153# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
154 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
drh4efc9292013-06-06 23:02:03 +0000155 WhereTerm **aLTerm; /* WhereTerms used */
drhf1b5f5b2013-05-02 00:15:01 +0000156 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
drh4efc9292013-06-06 23:02:03 +0000157 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
drhf1b5f5b2013-05-02 00:15:01 +0000158};
159
drhaa32e3c2013-07-16 21:31:23 +0000160/* This object holds the prerequisites and the cost of running a
161** subquery on one operand of an OR operator in the WHERE clause.
162** See WhereOrSet for additional information
163*/
164struct WhereOrCost {
165 Bitmask prereq; /* Prerequisites */
166 WhereCost rRun; /* Cost of running this subquery */
167 WhereCost nOut; /* Number of outputs for this subquery */
168};
169
170/* The WhereOrSet object holds a set of possible WhereOrCosts that
drh4a6fc352013-08-07 01:18:38 +0000171** correspond to the subquery(s) of OR-clause processing. Only the
172** best N_OR_COST elements are retained.
drhaa32e3c2013-07-16 21:31:23 +0000173*/
174#define N_OR_COST 3
175struct WhereOrSet {
176 u16 n; /* Number of valid a[] entries */
177 WhereOrCost a[N_OR_COST]; /* Set of best costs */
178};
179
180
drh4efc9292013-06-06 23:02:03 +0000181/* Forward declaration of methods */
182static int whereLoopResize(sqlite3*, WhereLoop*, int);
183
drhf1b5f5b2013-05-02 00:15:01 +0000184/*
185** Each instance of this object holds a sequence of WhereLoop objects
drh3b48e8c2013-06-12 20:18:16 +0000186** that implement some or all of a query plan.
187**
dan51576f42013-07-02 10:06:15 +0000188** Think of each WhereLoop object as a node in a graph with arcs
drhe56dd3a2013-08-30 17:50:35 +0000189** showing dependencies and costs for travelling between nodes. (That is
drh3b48e8c2013-06-12 20:18:16 +0000190** not a completely accurate description because WhereLoop costs are a
drhe56dd3a2013-08-30 17:50:35 +0000191** vector, not a scalar, and because dependencies are many-to-one, not
drh3b48e8c2013-06-12 20:18:16 +0000192** one-to-one as are graph nodes. But it is a useful visualization aid.)
193** Then a WherePath object is a path through the graph that visits some
194** or all of the WhereLoop objects once.
195**
196** The "solver" works by creating the N best WherePath objects of length
197** 1. Then using those as a basis to compute the N best WherePath objects
198** of length 2. And so forth until the length of WherePaths equals the
199** number of nodes in the FROM clause. The best (lowest cost) WherePath
200** at the end is the choosen query plan.
drhf1b5f5b2013-05-02 00:15:01 +0000201*/
202struct WherePath {
203 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
drh319f6772013-05-14 15:31:07 +0000204 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
drh4efc9292013-06-06 23:02:03 +0000205 WhereCost nRow; /* Estimated number of rows generated by this path */
206 WhereCost rCost; /* Total cost of this path */
drh6b7157b2013-05-10 02:00:35 +0000207 u8 isOrdered; /* True if this path satisfies ORDER BY */
208 u8 isOrderedValid; /* True if the isOrdered field is valid */
drha18f3d22013-05-08 03:05:41 +0000209 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
drhf1b5f5b2013-05-02 00:15:01 +0000210};
drh0aa74ed2005-07-16 13:33:20 +0000211
212/*
drh75897232000-05-29 14:26:00 +0000213** The query generator uses an array of instances of this structure to
214** help it analyze the subexpressions of the WHERE clause. Each WHERE
drh61495262009-04-22 15:32:59 +0000215** clause subexpression is separated from the others by AND operators,
216** usually, or sometimes subexpressions separated by OR.
drh51669862004-12-18 18:40:26 +0000217**
drh0fcef5e2005-07-19 17:38:22 +0000218** All WhereTerms are collected into a single WhereClause structure.
219** The following identity holds:
drh51669862004-12-18 18:40:26 +0000220**
drh0fcef5e2005-07-19 17:38:22 +0000221** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
drh51669862004-12-18 18:40:26 +0000222**
drh0fcef5e2005-07-19 17:38:22 +0000223** When a term is of the form:
224**
225** X <op> <expr>
226**
227** where X is a column name and <op> is one of certain operators,
drh700a2262008-12-17 19:22:15 +0000228** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
229** cursor number and column number for X. WhereTerm.eOperator records
drh51147ba2005-07-23 22:59:55 +0000230** the <op> using a bitmask encoding defined by WO_xxx below. The
231** use of a bitmask encoding for the operator allows us to search
232** quickly for terms that match any of several different operators.
drh0fcef5e2005-07-19 17:38:22 +0000233**
drh700a2262008-12-17 19:22:15 +0000234** A WhereTerm might also be two or more subterms connected by OR:
235**
236** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
237**
drh4a6fc352013-08-07 01:18:38 +0000238** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
drh700a2262008-12-17 19:22:15 +0000239** and the WhereTerm.u.pOrInfo field points to auxiliary information that
drh4a6fc352013-08-07 01:18:38 +0000240** is collected about the OR clause.
drh700a2262008-12-17 19:22:15 +0000241**
242** If a term in the WHERE clause does not match either of the two previous
243** categories, then eOperator==0. The WhereTerm.pExpr field is still set
244** to the original subexpression content and wtFlags is set up appropriately
245** but no other fields in the WhereTerm object are meaningful.
246**
247** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
drh111a6a72008-12-21 03:51:16 +0000248** but they do so indirectly. A single WhereMaskSet structure translates
drh51669862004-12-18 18:40:26 +0000249** cursor number into bits and the translated bit is stored in the prereq
250** fields. The translation is used in order to maximize the number of
251** bits that will fit in a Bitmask. The VDBE cursor numbers might be
252** spread out over the non-negative integers. For example, the cursor
drh111a6a72008-12-21 03:51:16 +0000253** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
drh51669862004-12-18 18:40:26 +0000254** translates these sparse cursor numbers into consecutive integers
255** beginning with 0 in order to make the best possible use of the available
256** bits in the Bitmask. So, in the example above, the cursor numbers
257** would be mapped into integers 0 through 7.
drh6a1e0712008-12-05 15:24:15 +0000258**
259** The number of terms in a join is limited by the number of bits
260** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
261** is only able to process joins with 64 or fewer tables.
drh75897232000-05-29 14:26:00 +0000262*/
drh0aa74ed2005-07-16 13:33:20 +0000263struct WhereTerm {
drh165be382008-12-05 02:36:33 +0000264 Expr *pExpr; /* Pointer to the subexpression that is this term */
drhec1724e2008-12-09 01:32:03 +0000265 int iParent; /* Disable pWC->a[iParent] when this term disabled */
266 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
drh700a2262008-12-17 19:22:15 +0000267 union {
268 int leftColumn; /* Column number of X in "X <op> <expr>" */
drh7a5bcc02013-01-16 17:08:58 +0000269 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
270 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
drh700a2262008-12-17 19:22:15 +0000271 } u;
drhb52076c2006-01-23 13:22:09 +0000272 u16 eOperator; /* A WO_xx value describing <op> */
drh165be382008-12-05 02:36:33 +0000273 u8 wtFlags; /* TERM_xxx bit flags. See below */
drh45b1ee42005-08-02 17:48:22 +0000274 u8 nChild; /* Number of children that must disable us */
drh0fcef5e2005-07-19 17:38:22 +0000275 WhereClause *pWC; /* The clause this term is part of */
drh165be382008-12-05 02:36:33 +0000276 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
277 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
drh75897232000-05-29 14:26:00 +0000278};
279
280/*
drh165be382008-12-05 02:36:33 +0000281** Allowed values of WhereTerm.wtFlags
drh0aa74ed2005-07-16 13:33:20 +0000282*/
drh633e6d52008-07-28 19:34:53 +0000283#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
drh6c30be82005-07-29 15:10:17 +0000284#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
285#define TERM_CODED 0x04 /* This term is already coded */
drh45b1ee42005-08-02 17:48:22 +0000286#define TERM_COPIED 0x08 /* Has a child */
drh700a2262008-12-17 19:22:15 +0000287#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
288#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
289#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
drh1435a9a2013-08-27 23:15:44 +0000290#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh59b61882011-02-11 02:43:14 +0000291# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
292#else
drhd3ed7342011-09-21 00:09:41 +0000293# define TERM_VNULL 0x00 /* Disabled if not using stat3 */
drh59b61882011-02-11 02:43:14 +0000294#endif
drh0aa74ed2005-07-16 13:33:20 +0000295
296/*
drh1c8148f2013-05-04 20:25:23 +0000297** An instance of the WhereScan object is used as an iterator for locating
298** terms in the WHERE clause that are useful to the query planner.
299*/
300struct WhereScan {
drh1c8148f2013-05-04 20:25:23 +0000301 WhereClause *pOrigWC; /* Original, innermost WhereClause */
302 WhereClause *pWC; /* WhereClause currently being scanned */
drh7ba39a92013-05-30 17:43:19 +0000303 char *zCollName; /* Required collating sequence, if not NULL */
drh1c8148f2013-05-04 20:25:23 +0000304 char idxaff; /* Must match this affinity, if zCollName!=NULL */
305 unsigned char nEquiv; /* Number of entries in aEquiv[] */
306 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
307 u32 opMask; /* Acceptable operators */
308 int k; /* Resume scanning at this->pWC->a[this->k] */
309 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
310};
311
312/*
drh0aa74ed2005-07-16 13:33:20 +0000313** An instance of the following structure holds all information about a
314** WHERE clause. Mostly this is a container for one or more WhereTerms.
drh8871ef52011-10-07 13:33:10 +0000315**
316** Explanation of pOuter: For a WHERE clause of the form
317**
318** a AND ((b AND c) OR (d AND e)) AND f
319**
320** There are separate WhereClause objects for the whole clause and for
321** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
322** subclauses points to the WhereClause object for the whole clause.
drh0aa74ed2005-07-16 13:33:20 +0000323*/
drh0aa74ed2005-07-16 13:33:20 +0000324struct WhereClause {
drh70d18342013-06-06 19:16:33 +0000325 WhereInfo *pWInfo; /* WHERE clause processing context */
drh8871ef52011-10-07 13:33:10 +0000326 WhereClause *pOuter; /* Outer conjunction */
drh29435252008-12-28 18:35:08 +0000327 u8 op; /* Split operator. TK_AND or TK_OR */
drh0aa74ed2005-07-16 13:33:20 +0000328 int nTerm; /* Number of terms */
329 int nSlot; /* Number of entries in a[] */
drh51147ba2005-07-23 22:59:55 +0000330 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
drh50d654d2009-06-03 01:24:54 +0000331#if defined(SQLITE_SMALL_STACK)
332 WhereTerm aStatic[1]; /* Initial static space for a[] */
333#else
334 WhereTerm aStatic[8]; /* Initial static space for a[] */
335#endif
drhe23399f2005-07-22 00:31:39 +0000336};
337
338/*
drh700a2262008-12-17 19:22:15 +0000339** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
340** a dynamically allocated instance of the following structure.
341*/
342struct WhereOrInfo {
drh111a6a72008-12-21 03:51:16 +0000343 WhereClause wc; /* Decomposition into subterms */
drh1a58fe02008-12-20 02:06:13 +0000344 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
drh700a2262008-12-17 19:22:15 +0000345};
346
347/*
348** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
349** a dynamically allocated instance of the following structure.
350*/
351struct WhereAndInfo {
drh29435252008-12-28 18:35:08 +0000352 WhereClause wc; /* The subexpression broken out */
drh700a2262008-12-17 19:22:15 +0000353};
354
355/*
drh6a3ea0e2003-05-02 14:32:12 +0000356** An instance of the following structure keeps track of a mapping
drh0aa74ed2005-07-16 13:33:20 +0000357** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
drh51669862004-12-18 18:40:26 +0000358**
359** The VDBE cursor numbers are small integers contained in
360** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
361** clause, the cursor numbers might not begin with 0 and they might
362** contain gaps in the numbering sequence. But we want to make maximum
363** use of the bits in our bitmasks. This structure provides a mapping
364** from the sparse cursor numbers into consecutive integers beginning
365** with 0.
366**
drh111a6a72008-12-21 03:51:16 +0000367** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
drh51669862004-12-18 18:40:26 +0000368** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
369**
370** For example, if the WHERE clause expression used these VDBE
drh111a6a72008-12-21 03:51:16 +0000371** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
drh51669862004-12-18 18:40:26 +0000372** would map those cursor numbers into bits 0 through 5.
373**
374** Note that the mapping is not necessarily ordered. In the example
375** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
376** 57->5, 73->4. Or one of 719 other combinations might be used. It
377** does not really matter. What is important is that sparse cursor
378** numbers all get mapped into bit numbers that begin with 0 and contain
379** no gaps.
drh6a3ea0e2003-05-02 14:32:12 +0000380*/
drh111a6a72008-12-21 03:51:16 +0000381struct WhereMaskSet {
drh1398ad32005-01-19 23:24:50 +0000382 int n; /* Number of assigned cursor values */
danielk197723432972008-11-17 16:42:00 +0000383 int ix[BMS]; /* Cursor assigned to each bit */
drh6a3ea0e2003-05-02 14:32:12 +0000384};
385
drh111a6a72008-12-21 03:51:16 +0000386/*
drh3b48e8c2013-06-12 20:18:16 +0000387** This object is a convenience wrapper holding all information needed
388** to construct WhereLoop objects for a particular query.
drh1c8148f2013-05-04 20:25:23 +0000389*/
390struct WhereLoopBuilder {
391 WhereInfo *pWInfo; /* Information about this WHERE */
drh1c8148f2013-05-04 20:25:23 +0000392 WhereClause *pWC; /* WHERE clause terms */
drh1c8148f2013-05-04 20:25:23 +0000393 ExprList *pOrderBy; /* ORDER BY clause */
394 WhereLoop *pNew; /* Template WhereLoop */
drhaa32e3c2013-07-16 21:31:23 +0000395 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
drh1435a9a2013-08-27 23:15:44 +0000396#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +0000397 UnpackedRecord *pRec; /* Probe for stat4 (if required) */
398 int nRecValid; /* Number of valid fields currently in pRec */
dan7a419232013-08-06 20:01:43 +0000399#endif
drh1c8148f2013-05-04 20:25:23 +0000400};
401
402/*
drh70d18342013-06-06 19:16:33 +0000403** The WHERE clause processing routine has two halves. The
404** first part does the start of the WHERE loop and the second
405** half does the tail of the WHERE loop. An instance of
406** this structure is returned by the first half and passed
407** into the second half to give some continuity.
drh3b48e8c2013-06-12 20:18:16 +0000408**
409** An instance of this object holds the complete state of the query
410** planner.
drh70d18342013-06-06 19:16:33 +0000411*/
412struct WhereInfo {
413 Parse *pParse; /* Parsing and code generating context */
414 SrcList *pTabList; /* List of tables in the join */
415 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
drh6457a352013-06-21 00:35:37 +0000416 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
drh4f402f22013-06-11 18:59:38 +0000417 WhereLoop *pLoops; /* List of all WhereLoop objects */
drh70d18342013-06-06 19:16:33 +0000418 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
drh4f402f22013-06-11 18:59:38 +0000419 WhereCost nRowOut; /* Estimated number of output rows */
drh70d18342013-06-06 19:16:33 +0000420 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
drh4f402f22013-06-11 18:59:38 +0000421 u8 bOBSat; /* ORDER BY satisfied by indices */
drh70d18342013-06-06 19:16:33 +0000422 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
423 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
424 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
drhfd636c72013-06-21 02:05:06 +0000425 u8 nLevel; /* Number of nested loop */
drh70d18342013-06-06 19:16:33 +0000426 int iTop; /* The very beginning of the WHERE loop */
427 int iContinue; /* Jump here to continue with next record */
428 int iBreak; /* Jump here to break out of the loop */
drh4f402f22013-06-11 18:59:38 +0000429 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
drh70d18342013-06-06 19:16:33 +0000430 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
431 WhereClause sWC; /* Decomposition of the WHERE clause */
drh70d18342013-06-06 19:16:33 +0000432 WhereLevel a[1]; /* Information about each nest loop in WHERE */
433};
434
435/*
drh3b48e8c2013-06-12 20:18:16 +0000436** Bitmasks for the operators on WhereTerm objects. These are all
437** operators that are of interest to the query planner. An
drh51147ba2005-07-23 22:59:55 +0000438** OR-ed combination of these values can be used when searching for
drh3b48e8c2013-06-12 20:18:16 +0000439** particular WhereTerms within a WhereClause.
drh51147ba2005-07-23 22:59:55 +0000440*/
drh165be382008-12-05 02:36:33 +0000441#define WO_IN 0x001
442#define WO_EQ 0x002
drh51147ba2005-07-23 22:59:55 +0000443#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
444#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
445#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
446#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
drh165be382008-12-05 02:36:33 +0000447#define WO_MATCH 0x040
448#define WO_ISNULL 0x080
drh700a2262008-12-17 19:22:15 +0000449#define WO_OR 0x100 /* Two or more OR-connected terms */
450#define WO_AND 0x200 /* Two or more AND-connected terms */
drh7a5bcc02013-01-16 17:08:58 +0000451#define WO_EQUIV 0x400 /* Of the form A==B, both columns */
drh534230c2011-01-22 00:10:45 +0000452#define WO_NOOP 0x800 /* This term does not restrict search space */
drh51147ba2005-07-23 22:59:55 +0000453
drhec1724e2008-12-09 01:32:03 +0000454#define WO_ALL 0xfff /* Mask of all possible WO_* values */
drh1a58fe02008-12-20 02:06:13 +0000455#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
drhec1724e2008-12-09 01:32:03 +0000456
drh51147ba2005-07-23 22:59:55 +0000457/*
drh3b48e8c2013-06-12 20:18:16 +0000458** These are definitions of bits in the WhereLoop.wsFlags field.
459** The particular combination of bits in each WhereLoop help to
460** determine the algorithm that WhereLoop represents.
drh51147ba2005-07-23 22:59:55 +0000461*/
drhbe4fe3a2013-07-01 10:38:35 +0000462#define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
drh6fa978d2013-05-30 19:29:19 +0000463#define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
464#define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
465#define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
drhef71c1f2013-06-04 12:58:02 +0000466#define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
drh6fa978d2013-05-30 19:29:19 +0000467#define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
468#define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
469#define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
470#define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
471#define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
472#define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
473#define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
474#define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
drh7699d1c2013-06-04 12:42:29 +0000475#define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
drh6fa978d2013-05-30 19:29:19 +0000476#define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
drh986b3872013-06-28 21:12:20 +0000477#define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
drh51147ba2005-07-23 22:59:55 +0000478
drhc63367e2013-06-10 20:46:50 +0000479
480/* Convert a WhereCost value (10 times log2(X)) into its integer value X.
drh3b48e8c2013-06-12 20:18:16 +0000481** A rough approximation is used. The value returned is not exact.
drhc63367e2013-06-10 20:46:50 +0000482*/
483static u64 whereCostToInt(WhereCost x){
484 u64 n;
drh12ffbc72013-06-13 14:51:53 +0000485 if( x<10 ) return 1;
drhc63367e2013-06-10 20:46:50 +0000486 n = x%10;
487 x /= 10;
488 if( n>=5 ) n -= 2;
489 else if( n>=1 ) n -= 1;
490 if( x>=3 ) return (n+8)<<(x-3);
491 return (n+8)>>(3-x);
492}
493
drh51147ba2005-07-23 22:59:55 +0000494/*
drh6f328482013-06-05 23:39:34 +0000495** Return the estimated number of output rows from a WHERE clause
496*/
drhc63367e2013-06-10 20:46:50 +0000497u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
498 return whereCostToInt(pWInfo->nRowOut);
drh6f328482013-06-05 23:39:34 +0000499}
500
501/*
502** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
503** WHERE clause returns outputs for DISTINCT processing.
504*/
505int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
506 return pWInfo->eDistinct;
507}
508
509/*
510** Return TRUE if the WHERE clause returns rows in ORDER BY order.
511** Return FALSE if the output needs to be sorted.
512*/
513int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
drh4f402f22013-06-11 18:59:38 +0000514 return pWInfo->bOBSat!=0;
drh6f328482013-06-05 23:39:34 +0000515}
516
517/*
518** Return the VDBE address or label to jump to in order to continue
519** immediately with the next row of a WHERE clause.
520*/
521int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
522 return pWInfo->iContinue;
523}
524
525/*
526** Return the VDBE address or label to jump to in order to break
527** out of a WHERE loop.
528*/
529int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
530 return pWInfo->iBreak;
531}
532
533/*
534** Return TRUE if an UPDATE or DELETE statement can operate directly on
535** the rowids returned by a WHERE clause. Return FALSE if doing an
536** UPDATE or DELETE might change subsequent WHERE clause results.
537*/
538int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
539 return pWInfo->okOnePass;
540}
541
542/*
drhaa32e3c2013-07-16 21:31:23 +0000543** Move the content of pSrc into pDest
544*/
545static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
546 pDest->n = pSrc->n;
547 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
548}
549
550/*
551** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
552**
553** The new entry might overwrite an existing entry, or it might be
554** appended, or it might be discarded. Do whatever is the right thing
555** so that pSet keeps the N_OR_COST best entries seen so far.
556*/
557static int whereOrInsert(
558 WhereOrSet *pSet, /* The WhereOrSet to be updated */
559 Bitmask prereq, /* Prerequisites of the new entry */
560 WhereCost rRun, /* Run-cost of the new entry */
561 WhereCost nOut /* Number of outputs for the new entry */
562){
563 u16 i;
564 WhereOrCost *p;
565 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
566 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
567 goto whereOrInsert_done;
568 }
569 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
570 return 0;
571 }
572 }
573 if( pSet->n<N_OR_COST ){
574 p = &pSet->a[pSet->n++];
575 p->nOut = nOut;
576 }else{
577 p = pSet->a;
578 for(i=1; i<pSet->n; i++){
579 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
580 }
581 if( p->rRun<=rRun ) return 0;
582 }
583whereOrInsert_done:
584 p->prereq = prereq;
585 p->rRun = rRun;
586 if( p->nOut>nOut ) p->nOut = nOut;
587 return 1;
588}
589
590/*
drh0aa74ed2005-07-16 13:33:20 +0000591** Initialize a preallocated WhereClause structure.
drh75897232000-05-29 14:26:00 +0000592*/
drh7b4fc6a2007-02-06 13:26:32 +0000593static void whereClauseInit(
594 WhereClause *pWC, /* The WhereClause to be initialized */
drh70d18342013-06-06 19:16:33 +0000595 WhereInfo *pWInfo /* The WHERE processing context */
drh7b4fc6a2007-02-06 13:26:32 +0000596){
drh70d18342013-06-06 19:16:33 +0000597 pWC->pWInfo = pWInfo;
drh8871ef52011-10-07 13:33:10 +0000598 pWC->pOuter = 0;
drh0aa74ed2005-07-16 13:33:20 +0000599 pWC->nTerm = 0;
drhcad651e2007-04-20 12:22:01 +0000600 pWC->nSlot = ArraySize(pWC->aStatic);
drh0aa74ed2005-07-16 13:33:20 +0000601 pWC->a = pWC->aStatic;
602}
603
drh700a2262008-12-17 19:22:15 +0000604/* Forward reference */
605static void whereClauseClear(WhereClause*);
606
607/*
608** Deallocate all memory associated with a WhereOrInfo object.
609*/
610static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000611 whereClauseClear(&p->wc);
612 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000613}
614
615/*
616** Deallocate all memory associated with a WhereAndInfo object.
617*/
618static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
drh5bd98ae2009-01-07 18:24:03 +0000619 whereClauseClear(&p->wc);
620 sqlite3DbFree(db, p);
drh700a2262008-12-17 19:22:15 +0000621}
622
drh0aa74ed2005-07-16 13:33:20 +0000623/*
624** Deallocate a WhereClause structure. The WhereClause structure
625** itself is not freed. This routine is the inverse of whereClauseInit().
626*/
627static void whereClauseClear(WhereClause *pWC){
628 int i;
629 WhereTerm *a;
drh70d18342013-06-06 19:16:33 +0000630 sqlite3 *db = pWC->pWInfo->pParse->db;
drh0aa74ed2005-07-16 13:33:20 +0000631 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
drh165be382008-12-05 02:36:33 +0000632 if( a->wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000633 sqlite3ExprDelete(db, a->pExpr);
drh0aa74ed2005-07-16 13:33:20 +0000634 }
drh700a2262008-12-17 19:22:15 +0000635 if( a->wtFlags & TERM_ORINFO ){
636 whereOrInfoDelete(db, a->u.pOrInfo);
637 }else if( a->wtFlags & TERM_ANDINFO ){
638 whereAndInfoDelete(db, a->u.pAndInfo);
639 }
drh0aa74ed2005-07-16 13:33:20 +0000640 }
641 if( pWC->a!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000642 sqlite3DbFree(db, pWC->a);
drh0aa74ed2005-07-16 13:33:20 +0000643 }
644}
645
646/*
drh6a1e0712008-12-05 15:24:15 +0000647** Add a single new WhereTerm entry to the WhereClause object pWC.
648** The new WhereTerm object is constructed from Expr p and with wtFlags.
649** The index in pWC->a[] of the new WhereTerm is returned on success.
650** 0 is returned if the new WhereTerm could not be added due to a memory
651** allocation error. The memory allocation failure will be recorded in
652** the db->mallocFailed flag so that higher-level functions can detect it.
653**
654** This routine will increase the size of the pWC->a[] array as necessary.
drh9eb20282005-08-24 03:52:18 +0000655**
drh165be382008-12-05 02:36:33 +0000656** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
drh6a1e0712008-12-05 15:24:15 +0000657** for freeing the expression p is assumed by the WhereClause object pWC.
658** This is true even if this routine fails to allocate a new WhereTerm.
drhb63a53d2007-03-31 01:34:44 +0000659**
drh9eb20282005-08-24 03:52:18 +0000660** WARNING: This routine might reallocate the space used to store
drh909626d2008-05-30 14:58:37 +0000661** WhereTerms. All pointers to WhereTerms should be invalidated after
drh9eb20282005-08-24 03:52:18 +0000662** calling this routine. Such pointers may be reinitialized by referencing
663** the pWC->a[] array.
drh0aa74ed2005-07-16 13:33:20 +0000664*/
drhec1724e2008-12-09 01:32:03 +0000665static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
drh0aa74ed2005-07-16 13:33:20 +0000666 WhereTerm *pTerm;
drh9eb20282005-08-24 03:52:18 +0000667 int idx;
drh39759742013-08-02 23:40:45 +0000668 testcase( wtFlags & TERM_VIRTUAL );
drh0aa74ed2005-07-16 13:33:20 +0000669 if( pWC->nTerm>=pWC->nSlot ){
670 WhereTerm *pOld = pWC->a;
drh70d18342013-06-06 19:16:33 +0000671 sqlite3 *db = pWC->pWInfo->pParse->db;
drh633e6d52008-07-28 19:34:53 +0000672 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drhb63a53d2007-03-31 01:34:44 +0000673 if( pWC->a==0 ){
drh165be382008-12-05 02:36:33 +0000674 if( wtFlags & TERM_DYNAMIC ){
drh633e6d52008-07-28 19:34:53 +0000675 sqlite3ExprDelete(db, p);
drhb63a53d2007-03-31 01:34:44 +0000676 }
drhf998b732007-11-26 13:36:00 +0000677 pWC->a = pOld;
drhb63a53d2007-03-31 01:34:44 +0000678 return 0;
679 }
drh0aa74ed2005-07-16 13:33:20 +0000680 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
681 if( pOld!=pWC->aStatic ){
drh633e6d52008-07-28 19:34:53 +0000682 sqlite3DbFree(db, pOld);
drh0aa74ed2005-07-16 13:33:20 +0000683 }
drh6a1e0712008-12-05 15:24:15 +0000684 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh0aa74ed2005-07-16 13:33:20 +0000685 }
drh6a1e0712008-12-05 15:24:15 +0000686 pTerm = &pWC->a[idx = pWC->nTerm++];
drh7ee751d2012-12-19 15:53:51 +0000687 pTerm->pExpr = sqlite3ExprSkipCollate(p);
drh165be382008-12-05 02:36:33 +0000688 pTerm->wtFlags = wtFlags;
drh0fcef5e2005-07-19 17:38:22 +0000689 pTerm->pWC = pWC;
drh45b1ee42005-08-02 17:48:22 +0000690 pTerm->iParent = -1;
drh9eb20282005-08-24 03:52:18 +0000691 return idx;
drh0aa74ed2005-07-16 13:33:20 +0000692}
drh75897232000-05-29 14:26:00 +0000693
694/*
drh51669862004-12-18 18:40:26 +0000695** This routine identifies subexpressions in the WHERE clause where
drhb6fb62d2005-09-20 08:47:20 +0000696** each subexpression is separated by the AND operator or some other
drh6c30be82005-07-29 15:10:17 +0000697** operator specified in the op parameter. The WhereClause structure
698** is filled with pointers to subexpressions. For example:
drh75897232000-05-29 14:26:00 +0000699**
drh51669862004-12-18 18:40:26 +0000700** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
701** \________/ \_______________/ \________________/
702** slot[0] slot[1] slot[2]
703**
704** The original WHERE clause in pExpr is unaltered. All this routine
drh51147ba2005-07-23 22:59:55 +0000705** does is make slot[] entries point to substructure within pExpr.
drh51669862004-12-18 18:40:26 +0000706**
drh51147ba2005-07-23 22:59:55 +0000707** In the previous sentence and in the diagram, "slot[]" refers to
drh902b9ee2008-12-05 17:17:07 +0000708** the WhereClause.a[] array. The slot[] array grows as needed to contain
drh51147ba2005-07-23 22:59:55 +0000709** all terms of the WHERE clause.
drh75897232000-05-29 14:26:00 +0000710*/
drh74f91d42013-06-19 18:01:44 +0000711static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
712 pWC->op = op;
drh0aa74ed2005-07-16 13:33:20 +0000713 if( pExpr==0 ) return;
drh6c30be82005-07-29 15:10:17 +0000714 if( pExpr->op!=op ){
drh0aa74ed2005-07-16 13:33:20 +0000715 whereClauseInsert(pWC, pExpr, 0);
drh75897232000-05-29 14:26:00 +0000716 }else{
drh6c30be82005-07-29 15:10:17 +0000717 whereSplit(pWC, pExpr->pLeft, op);
718 whereSplit(pWC, pExpr->pRight, op);
drh75897232000-05-29 14:26:00 +0000719 }
drh75897232000-05-29 14:26:00 +0000720}
721
722/*
drh3b48e8c2013-06-12 20:18:16 +0000723** Initialize a WhereMaskSet object
drh6a3ea0e2003-05-02 14:32:12 +0000724*/
drhfd5874d2013-06-12 14:52:39 +0000725#define initMaskSet(P) (P)->n=0
drh6a3ea0e2003-05-02 14:32:12 +0000726
727/*
drh1398ad32005-01-19 23:24:50 +0000728** Return the bitmask for the given cursor number. Return 0 if
729** iCursor is not in the set.
drh6a3ea0e2003-05-02 14:32:12 +0000730*/
drh111a6a72008-12-21 03:51:16 +0000731static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
drh6a3ea0e2003-05-02 14:32:12 +0000732 int i;
drhfcd71b62011-04-05 22:08:24 +0000733 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
drh6a3ea0e2003-05-02 14:32:12 +0000734 for(i=0; i<pMaskSet->n; i++){
drh51669862004-12-18 18:40:26 +0000735 if( pMaskSet->ix[i]==iCursor ){
drh7699d1c2013-06-04 12:42:29 +0000736 return MASKBIT(i);
drh51669862004-12-18 18:40:26 +0000737 }
drh6a3ea0e2003-05-02 14:32:12 +0000738 }
drh6a3ea0e2003-05-02 14:32:12 +0000739 return 0;
740}
741
742/*
drh1398ad32005-01-19 23:24:50 +0000743** Create a new mask for cursor iCursor.
drh0fcef5e2005-07-19 17:38:22 +0000744**
745** There is one cursor per table in the FROM clause. The number of
746** tables in the FROM clause is limited by a test early in the
drhb6fb62d2005-09-20 08:47:20 +0000747** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
drh0fcef5e2005-07-19 17:38:22 +0000748** array will never overflow.
drh1398ad32005-01-19 23:24:50 +0000749*/
drh111a6a72008-12-21 03:51:16 +0000750static void createMask(WhereMaskSet *pMaskSet, int iCursor){
drhcad651e2007-04-20 12:22:01 +0000751 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
drh0fcef5e2005-07-19 17:38:22 +0000752 pMaskSet->ix[pMaskSet->n++] = iCursor;
drh1398ad32005-01-19 23:24:50 +0000753}
754
755/*
drh4a6fc352013-08-07 01:18:38 +0000756** These routines walk (recursively) an expression tree and generate
drh75897232000-05-29 14:26:00 +0000757** a bitmask indicating which tables are used in that expression
drh6a3ea0e2003-05-02 14:32:12 +0000758** tree.
drh75897232000-05-29 14:26:00 +0000759*/
drh111a6a72008-12-21 03:51:16 +0000760static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
761static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
762static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
drh51669862004-12-18 18:40:26 +0000763 Bitmask mask = 0;
drh75897232000-05-29 14:26:00 +0000764 if( p==0 ) return 0;
drh967e8b72000-06-21 13:59:10 +0000765 if( p->op==TK_COLUMN ){
drh8feb4b12004-07-19 02:12:14 +0000766 mask = getMask(pMaskSet, p->iTable);
drh8feb4b12004-07-19 02:12:14 +0000767 return mask;
drh75897232000-05-29 14:26:00 +0000768 }
danielk1977b3bce662005-01-29 08:32:43 +0000769 mask = exprTableUsage(pMaskSet, p->pRight);
770 mask |= exprTableUsage(pMaskSet, p->pLeft);
danielk19776ab3a2e2009-02-19 14:39:25 +0000771 if( ExprHasProperty(p, EP_xIsSelect) ){
772 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
773 }else{
774 mask |= exprListTableUsage(pMaskSet, p->x.pList);
775 }
danielk1977b3bce662005-01-29 08:32:43 +0000776 return mask;
777}
drh111a6a72008-12-21 03:51:16 +0000778static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
danielk1977b3bce662005-01-29 08:32:43 +0000779 int i;
780 Bitmask mask = 0;
781 if( pList ){
782 for(i=0; i<pList->nExpr; i++){
783 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
drhdd579122002-04-02 01:58:57 +0000784 }
785 }
drh75897232000-05-29 14:26:00 +0000786 return mask;
787}
drh111a6a72008-12-21 03:51:16 +0000788static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
drha430ae82007-09-12 15:41:01 +0000789 Bitmask mask = 0;
790 while( pS ){
drha464c232011-09-16 19:04:03 +0000791 SrcList *pSrc = pS->pSrc;
drha430ae82007-09-12 15:41:01 +0000792 mask |= exprListTableUsage(pMaskSet, pS->pEList);
drhf5b11382005-09-17 13:07:13 +0000793 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
794 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
795 mask |= exprTableUsage(pMaskSet, pS->pWhere);
796 mask |= exprTableUsage(pMaskSet, pS->pHaving);
drha464c232011-09-16 19:04:03 +0000797 if( ALWAYS(pSrc!=0) ){
drh88501772011-09-16 17:43:06 +0000798 int i;
799 for(i=0; i<pSrc->nSrc; i++){
800 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
801 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
802 }
803 }
drha430ae82007-09-12 15:41:01 +0000804 pS = pS->pPrior;
drhf5b11382005-09-17 13:07:13 +0000805 }
806 return mask;
807}
drh75897232000-05-29 14:26:00 +0000808
809/*
drh487ab3c2001-11-08 00:45:21 +0000810** Return TRUE if the given operator is one of the operators that is
drh51669862004-12-18 18:40:26 +0000811** allowed for an indexable WHERE clause term. The allowed operators are
drh3b48e8c2013-06-12 20:18:16 +0000812** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
drh487ab3c2001-11-08 00:45:21 +0000813*/
814static int allowedOp(int op){
drhfe05af82005-07-21 03:14:59 +0000815 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
816 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
817 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
818 assert( TK_GE==TK_EQ+4 );
drh50b39962006-10-28 00:28:09 +0000819 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
drh487ab3c2001-11-08 00:45:21 +0000820}
821
822/*
drh902b9ee2008-12-05 17:17:07 +0000823** Swap two objects of type TYPE.
drh193bd772004-07-20 18:23:14 +0000824*/
825#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
826
827/*
drh909626d2008-05-30 14:58:37 +0000828** Commute a comparison operator. Expressions of the form "X op Y"
drh0fcef5e2005-07-19 17:38:22 +0000829** are converted into "Y op X".
danielk1977eb5453d2007-07-30 14:40:48 +0000830**
mistachkin48864df2013-03-21 21:20:32 +0000831** If left/right precedence rules come into play when determining the
drh3b48e8c2013-06-12 20:18:16 +0000832** collating sequence, then COLLATE operators are adjusted to ensure
833** that the collating sequence does not change. For example:
834** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
danielk1977eb5453d2007-07-30 14:40:48 +0000835** the left hand side of a comparison overrides any collation sequence
drhae80dde2012-12-06 21:16:43 +0000836** attached to the right. For the same reason the EP_Collate flag
danielk1977eb5453d2007-07-30 14:40:48 +0000837** is not commuted.
drh193bd772004-07-20 18:23:14 +0000838*/
drh7d10d5a2008-08-20 16:35:10 +0000839static void exprCommute(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000840 u16 expRight = (pExpr->pRight->flags & EP_Collate);
841 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
drhfe05af82005-07-21 03:14:59 +0000842 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
drhae80dde2012-12-06 21:16:43 +0000843 if( expRight==expLeft ){
844 /* Either X and Y both have COLLATE operator or neither do */
845 if( expRight ){
846 /* Both X and Y have COLLATE operators. Make sure X is always
847 ** used by clearing the EP_Collate flag from Y. */
848 pExpr->pRight->flags &= ~EP_Collate;
849 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
850 /* Neither X nor Y have COLLATE operators, but X has a non-default
851 ** collating sequence. So add the EP_Collate marker on X to cause
852 ** it to be searched first. */
853 pExpr->pLeft->flags |= EP_Collate;
854 }
855 }
drh0fcef5e2005-07-19 17:38:22 +0000856 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
857 if( pExpr->op>=TK_GT ){
858 assert( TK_LT==TK_GT+2 );
859 assert( TK_GE==TK_LE+2 );
860 assert( TK_GT>TK_EQ );
861 assert( TK_GT<TK_LE );
862 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
863 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
drh193bd772004-07-20 18:23:14 +0000864 }
drh193bd772004-07-20 18:23:14 +0000865}
866
867/*
drhfe05af82005-07-21 03:14:59 +0000868** Translate from TK_xx operator to WO_xx bitmask.
869*/
drhec1724e2008-12-09 01:32:03 +0000870static u16 operatorMask(int op){
871 u16 c;
drhfe05af82005-07-21 03:14:59 +0000872 assert( allowedOp(op) );
873 if( op==TK_IN ){
drh51147ba2005-07-23 22:59:55 +0000874 c = WO_IN;
drh50b39962006-10-28 00:28:09 +0000875 }else if( op==TK_ISNULL ){
876 c = WO_ISNULL;
drhfe05af82005-07-21 03:14:59 +0000877 }else{
drhec1724e2008-12-09 01:32:03 +0000878 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
879 c = (u16)(WO_EQ<<(op-TK_EQ));
drhfe05af82005-07-21 03:14:59 +0000880 }
drh50b39962006-10-28 00:28:09 +0000881 assert( op!=TK_ISNULL || c==WO_ISNULL );
drh51147ba2005-07-23 22:59:55 +0000882 assert( op!=TK_IN || c==WO_IN );
883 assert( op!=TK_EQ || c==WO_EQ );
884 assert( op!=TK_LT || c==WO_LT );
885 assert( op!=TK_LE || c==WO_LE );
886 assert( op!=TK_GT || c==WO_GT );
887 assert( op!=TK_GE || c==WO_GE );
888 return c;
drhfe05af82005-07-21 03:14:59 +0000889}
890
891/*
drh1c8148f2013-05-04 20:25:23 +0000892** Advance to the next WhereTerm that matches according to the criteria
893** established when the pScan object was initialized by whereScanInit().
894** Return NULL if there are no more matching WhereTerms.
895*/
danb2cfc142013-07-05 11:10:54 +0000896static WhereTerm *whereScanNext(WhereScan *pScan){
drh1c8148f2013-05-04 20:25:23 +0000897 int iCur; /* The cursor on the LHS of the term */
898 int iColumn; /* The column on the LHS of the term. -1 for IPK */
899 Expr *pX; /* An expression being tested */
900 WhereClause *pWC; /* Shorthand for pScan->pWC */
901 WhereTerm *pTerm; /* The term being tested */
drh43b85ef2013-06-10 12:34:45 +0000902 int k = pScan->k; /* Where to start scanning */
drh1c8148f2013-05-04 20:25:23 +0000903
904 while( pScan->iEquiv<=pScan->nEquiv ){
905 iCur = pScan->aEquiv[pScan->iEquiv-2];
906 iColumn = pScan->aEquiv[pScan->iEquiv-1];
907 while( (pWC = pScan->pWC)!=0 ){
drh43b85ef2013-06-10 12:34:45 +0000908 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
drh1c8148f2013-05-04 20:25:23 +0000909 if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
910 if( (pTerm->eOperator & WO_EQUIV)!=0
911 && pScan->nEquiv<ArraySize(pScan->aEquiv)
912 ){
913 int j;
914 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
915 assert( pX->op==TK_COLUMN );
916 for(j=0; j<pScan->nEquiv; j+=2){
917 if( pScan->aEquiv[j]==pX->iTable
918 && pScan->aEquiv[j+1]==pX->iColumn ){
919 break;
920 }
921 }
922 if( j==pScan->nEquiv ){
923 pScan->aEquiv[j] = pX->iTable;
924 pScan->aEquiv[j+1] = pX->iColumn;
925 pScan->nEquiv += 2;
926 }
927 }
928 if( (pTerm->eOperator & pScan->opMask)!=0 ){
929 /* Verify the affinity and collating sequence match */
930 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
931 CollSeq *pColl;
drh70d18342013-06-06 19:16:33 +0000932 Parse *pParse = pWC->pWInfo->pParse;
drh1c8148f2013-05-04 20:25:23 +0000933 pX = pTerm->pExpr;
934 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
935 continue;
936 }
937 assert(pX->pLeft);
drh70d18342013-06-06 19:16:33 +0000938 pColl = sqlite3BinaryCompareCollSeq(pParse,
drh1c8148f2013-05-04 20:25:23 +0000939 pX->pLeft, pX->pRight);
drh70d18342013-06-06 19:16:33 +0000940 if( pColl==0 ) pColl = pParse->db->pDfltColl;
drh1c8148f2013-05-04 20:25:23 +0000941 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
942 continue;
943 }
944 }
drha184fb82013-05-08 04:22:59 +0000945 if( (pTerm->eOperator & WO_EQ)!=0
946 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
947 && pX->iTable==pScan->aEquiv[0]
948 && pX->iColumn==pScan->aEquiv[1]
949 ){
950 continue;
951 }
drh43b85ef2013-06-10 12:34:45 +0000952 pScan->k = k+1;
drh1c8148f2013-05-04 20:25:23 +0000953 return pTerm;
954 }
955 }
956 }
drhad01d892013-06-19 13:59:49 +0000957 pScan->pWC = pScan->pWC->pOuter;
drh43b85ef2013-06-10 12:34:45 +0000958 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000959 }
960 pScan->pWC = pScan->pOrigWC;
drh43b85ef2013-06-10 12:34:45 +0000961 k = 0;
drh1c8148f2013-05-04 20:25:23 +0000962 pScan->iEquiv += 2;
963 }
drh1c8148f2013-05-04 20:25:23 +0000964 return 0;
965}
966
967/*
968** Initialize a WHERE clause scanner object. Return a pointer to the
969** first match. Return NULL if there are no matches.
970**
971** The scanner will be searching the WHERE clause pWC. It will look
972** for terms of the form "X <op> <expr>" where X is column iColumn of table
973** iCur. The <op> must be one of the operators described by opMask.
974**
drh3b48e8c2013-06-12 20:18:16 +0000975** If the search is for X and the WHERE clause contains terms of the
976** form X=Y then this routine might also return terms of the form
977** "Y <op> <expr>". The number of levels of transitivity is limited,
978** but is enough to handle most commonly occurring SQL statements.
979**
drh1c8148f2013-05-04 20:25:23 +0000980** If X is not the INTEGER PRIMARY KEY then X must be compatible with
981** index pIdx.
982*/
danb2cfc142013-07-05 11:10:54 +0000983static WhereTerm *whereScanInit(
drh1c8148f2013-05-04 20:25:23 +0000984 WhereScan *pScan, /* The WhereScan object being initialized */
985 WhereClause *pWC, /* The WHERE clause to be scanned */
986 int iCur, /* Cursor to scan for */
987 int iColumn, /* Column to scan for */
988 u32 opMask, /* Operator(s) to scan for */
989 Index *pIdx /* Must be compatible with this index */
990){
991 int j;
992
drhe9d935a2013-06-05 16:19:59 +0000993 /* memset(pScan, 0, sizeof(*pScan)); */
drh1c8148f2013-05-04 20:25:23 +0000994 pScan->pOrigWC = pWC;
995 pScan->pWC = pWC;
996 if( pIdx && iColumn>=0 ){
997 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
998 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
999 if( NEVER(j>=pIdx->nColumn) ) return 0;
1000 }
1001 pScan->zCollName = pIdx->azColl[j];
drhe9d935a2013-06-05 16:19:59 +00001002 }else{
1003 pScan->idxaff = 0;
1004 pScan->zCollName = 0;
drh1c8148f2013-05-04 20:25:23 +00001005 }
1006 pScan->opMask = opMask;
drhe9d935a2013-06-05 16:19:59 +00001007 pScan->k = 0;
drh1c8148f2013-05-04 20:25:23 +00001008 pScan->aEquiv[0] = iCur;
1009 pScan->aEquiv[1] = iColumn;
1010 pScan->nEquiv = 2;
1011 pScan->iEquiv = 2;
1012 return whereScanNext(pScan);
1013}
1014
1015/*
drhfe05af82005-07-21 03:14:59 +00001016** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
1017** where X is a reference to the iColumn of table iCur and <op> is one of
1018** the WO_xx operator codes specified by the op parameter.
1019** Return a pointer to the term. Return 0 if not found.
drh58eb1c02013-01-17 00:08:42 +00001020**
1021** The term returned might by Y=<expr> if there is another constraint in
1022** the WHERE clause that specifies that X=Y. Any such constraints will be
1023** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
1024** aEquiv[] array holds X and all its equivalents, with each SQL variable
1025** taking up two slots in aEquiv[]. The first slot is for the cursor number
1026** and the second is for the column number. There are 22 slots in aEquiv[]
1027** so that means we can look for X plus up to 10 other equivalent values.
1028** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
1029** and ... and A9=A10 and A10=<expr>.
1030**
1031** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
1032** then try for the one with no dependencies on <expr> - in other words where
1033** <expr> is a constant expression of some kind. Only return entries of
1034** the form "X <op> Y" where Y is a column in another table if no terms of
drh459f63e2013-03-06 01:55:27 +00001035** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
1036** exist, try to return a term that does not use WO_EQUIV.
drhfe05af82005-07-21 03:14:59 +00001037*/
1038static WhereTerm *findTerm(
1039 WhereClause *pWC, /* The WHERE clause to be searched */
1040 int iCur, /* Cursor number of LHS */
1041 int iColumn, /* Column number of LHS */
1042 Bitmask notReady, /* RHS must not overlap with this mask */
drhec1724e2008-12-09 01:32:03 +00001043 u32 op, /* Mask of WO_xx values describing operator */
drhfe05af82005-07-21 03:14:59 +00001044 Index *pIdx /* Must be compatible with this index, if not NULL */
1045){
drh1c8148f2013-05-04 20:25:23 +00001046 WhereTerm *pResult = 0;
1047 WhereTerm *p;
1048 WhereScan scan;
drh7a5bcc02013-01-16 17:08:58 +00001049
drh1c8148f2013-05-04 20:25:23 +00001050 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
1051 while( p ){
1052 if( (p->prereqRight & notReady)==0 ){
1053 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
1054 return p;
drhfe05af82005-07-21 03:14:59 +00001055 }
drh1c8148f2013-05-04 20:25:23 +00001056 if( pResult==0 ) pResult = p;
drhfe05af82005-07-21 03:14:59 +00001057 }
drh1c8148f2013-05-04 20:25:23 +00001058 p = whereScanNext(&scan);
drhfe05af82005-07-21 03:14:59 +00001059 }
drh7a5bcc02013-01-16 17:08:58 +00001060 return pResult;
drhfe05af82005-07-21 03:14:59 +00001061}
1062
drh6c30be82005-07-29 15:10:17 +00001063/* Forward reference */
drh7b4fc6a2007-02-06 13:26:32 +00001064static void exprAnalyze(SrcList*, WhereClause*, int);
drh6c30be82005-07-29 15:10:17 +00001065
1066/*
1067** Call exprAnalyze on all terms in a WHERE clause.
drh6c30be82005-07-29 15:10:17 +00001068*/
1069static void exprAnalyzeAll(
1070 SrcList *pTabList, /* the FROM clause */
drh6c30be82005-07-29 15:10:17 +00001071 WhereClause *pWC /* the WHERE clause to be analyzed */
1072){
drh6c30be82005-07-29 15:10:17 +00001073 int i;
drh9eb20282005-08-24 03:52:18 +00001074 for(i=pWC->nTerm-1; i>=0; i--){
drh7b4fc6a2007-02-06 13:26:32 +00001075 exprAnalyze(pTabList, pWC, i);
drh6c30be82005-07-29 15:10:17 +00001076 }
1077}
1078
drhd2687b72005-08-12 22:56:09 +00001079#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1080/*
1081** Check to see if the given expression is a LIKE or GLOB operator that
1082** can be optimized using inequality constraints. Return TRUE if it is
1083** so and false if not.
1084**
1085** In order for the operator to be optimizible, the RHS must be a string
1086** literal that does not begin with a wildcard.
1087*/
1088static int isLikeOrGlob(
drh7d10d5a2008-08-20 16:35:10 +00001089 Parse *pParse, /* Parsing and code generating context */
drhd2687b72005-08-12 22:56:09 +00001090 Expr *pExpr, /* Test this expression */
dan937d0de2009-10-15 18:35:38 +00001091 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
drh9f504ea2008-02-23 21:55:39 +00001092 int *pisComplete, /* True if the only wildcard is % in the last character */
1093 int *pnoCase /* True if uppercase is equivalent to lowercase */
drhd2687b72005-08-12 22:56:09 +00001094){
dan937d0de2009-10-15 18:35:38 +00001095 const char *z = 0; /* String on RHS of LIKE operator */
drh5bd98ae2009-01-07 18:24:03 +00001096 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
1097 ExprList *pList; /* List of operands to the LIKE operator */
1098 int c; /* One character in z[] */
1099 int cnt; /* Number of non-wildcard prefix characters */
1100 char wc[3]; /* Wildcard characters */
drh5bd98ae2009-01-07 18:24:03 +00001101 sqlite3 *db = pParse->db; /* Database connection */
dan937d0de2009-10-15 18:35:38 +00001102 sqlite3_value *pVal = 0;
1103 int op; /* Opcode of pRight */
drhd64fe2f2005-08-28 17:00:23 +00001104
drh9f504ea2008-02-23 21:55:39 +00001105 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
drhd2687b72005-08-12 22:56:09 +00001106 return 0;
1107 }
drh9f504ea2008-02-23 21:55:39 +00001108#ifdef SQLITE_EBCDIC
1109 if( *pnoCase ) return 0;
1110#endif
danielk19776ab3a2e2009-02-19 14:39:25 +00001111 pList = pExpr->x.pList;
drh55ef4d92005-08-14 01:20:37 +00001112 pLeft = pList->a[1].pExpr;
danc68939e2012-03-29 14:29:07 +00001113 if( pLeft->op!=TK_COLUMN
1114 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
1115 || IsVirtual(pLeft->pTab)
1116 ){
drhd91ca492009-10-22 20:50:36 +00001117 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
1118 ** be the name of an indexed column with TEXT affinity. */
drhd2687b72005-08-12 22:56:09 +00001119 return 0;
1120 }
drhd91ca492009-10-22 20:50:36 +00001121 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
dan937d0de2009-10-15 18:35:38 +00001122
1123 pRight = pList->a[0].pExpr;
1124 op = pRight->op;
1125 if( op==TK_REGISTER ){
1126 op = pRight->op2;
1127 }
1128 if( op==TK_VARIABLE ){
1129 Vdbe *pReprepare = pParse->pReprepare;
drha7044002010-09-14 18:22:59 +00001130 int iCol = pRight->iColumn;
drhcf0fd4a2013-08-01 12:21:58 +00001131 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
dan937d0de2009-10-15 18:35:38 +00001132 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
1133 z = (char *)sqlite3_value_text(pVal);
1134 }
drhf9b22ca2011-10-21 16:47:31 +00001135 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
dan937d0de2009-10-15 18:35:38 +00001136 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
1137 }else if( op==TK_STRING ){
1138 z = pRight->u.zToken;
1139 }
1140 if( z ){
shane85095702009-06-15 16:27:08 +00001141 cnt = 0;
drhb7916a72009-05-27 10:31:29 +00001142 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
drh24fb6272009-05-01 21:13:36 +00001143 cnt++;
1144 }
drh93ee23c2010-07-22 12:33:57 +00001145 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
dan937d0de2009-10-15 18:35:38 +00001146 Expr *pPrefix;
drh93ee23c2010-07-22 12:33:57 +00001147 *pisComplete = c==wc[0] && z[cnt+1]==0;
dan937d0de2009-10-15 18:35:38 +00001148 pPrefix = sqlite3Expr(db, TK_STRING, z);
1149 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
1150 *ppPrefix = pPrefix;
1151 if( op==TK_VARIABLE ){
1152 Vdbe *v = pParse->pVdbe;
drhf9b22ca2011-10-21 16:47:31 +00001153 sqlite3VdbeSetVarmask(v, pRight->iColumn);
dan937d0de2009-10-15 18:35:38 +00001154 if( *pisComplete && pRight->u.zToken[1] ){
1155 /* If the rhs of the LIKE expression is a variable, and the current
1156 ** value of the variable means there is no need to invoke the LIKE
1157 ** function, then no OP_Variable will be added to the program.
1158 ** This causes problems for the sqlite3_bind_parameter_name()
drhbec451f2009-10-17 13:13:02 +00001159 ** API. To workaround them, add a dummy OP_Variable here.
1160 */
1161 int r1 = sqlite3GetTempReg(pParse);
1162 sqlite3ExprCodeTarget(pParse, pRight, r1);
dan937d0de2009-10-15 18:35:38 +00001163 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
drhbec451f2009-10-17 13:13:02 +00001164 sqlite3ReleaseTempReg(pParse, r1);
dan937d0de2009-10-15 18:35:38 +00001165 }
1166 }
1167 }else{
1168 z = 0;
shane85095702009-06-15 16:27:08 +00001169 }
drhf998b732007-11-26 13:36:00 +00001170 }
dan937d0de2009-10-15 18:35:38 +00001171
1172 sqlite3ValueFree(pVal);
1173 return (z!=0);
drhd2687b72005-08-12 22:56:09 +00001174}
1175#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1176
drhedb193b2006-06-27 13:20:21 +00001177
1178#ifndef SQLITE_OMIT_VIRTUALTABLE
drhfe05af82005-07-21 03:14:59 +00001179/*
drh7f375902006-06-13 17:38:59 +00001180** Check to see if the given expression is of the form
1181**
1182** column MATCH expr
1183**
1184** If it is then return TRUE. If not, return FALSE.
1185*/
1186static int isMatchOfColumn(
1187 Expr *pExpr /* Test this expression */
1188){
1189 ExprList *pList;
1190
1191 if( pExpr->op!=TK_FUNCTION ){
1192 return 0;
1193 }
drh33e619f2009-05-28 01:00:55 +00001194 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
drh7f375902006-06-13 17:38:59 +00001195 return 0;
1196 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001197 pList = pExpr->x.pList;
drh7f375902006-06-13 17:38:59 +00001198 if( pList->nExpr!=2 ){
1199 return 0;
1200 }
1201 if( pList->a[1].pExpr->op != TK_COLUMN ){
1202 return 0;
1203 }
1204 return 1;
1205}
drhedb193b2006-06-27 13:20:21 +00001206#endif /* SQLITE_OMIT_VIRTUALTABLE */
drh7f375902006-06-13 17:38:59 +00001207
1208/*
drh54a167d2005-11-26 14:08:07 +00001209** If the pBase expression originated in the ON or USING clause of
1210** a join, then transfer the appropriate markings over to derived.
1211*/
1212static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
drhd41d39f2013-08-28 16:27:01 +00001213 if( pDerived ){
1214 pDerived->flags |= pBase->flags & EP_FromJoin;
1215 pDerived->iRightJoinTable = pBase->iRightJoinTable;
1216 }
drh54a167d2005-11-26 14:08:07 +00001217}
1218
drh3e355802007-02-23 23:13:33 +00001219#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1220/*
drh1a58fe02008-12-20 02:06:13 +00001221** Analyze a term that consists of two or more OR-connected
1222** subterms. So in:
drh3e355802007-02-23 23:13:33 +00001223**
drh1a58fe02008-12-20 02:06:13 +00001224** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
1225** ^^^^^^^^^^^^^^^^^^^^
drh3e355802007-02-23 23:13:33 +00001226**
drh1a58fe02008-12-20 02:06:13 +00001227** This routine analyzes terms such as the middle term in the above example.
1228** A WhereOrTerm object is computed and attached to the term under
1229** analysis, regardless of the outcome of the analysis. Hence:
drh3e355802007-02-23 23:13:33 +00001230**
drh1a58fe02008-12-20 02:06:13 +00001231** WhereTerm.wtFlags |= TERM_ORINFO
1232** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
drh3e355802007-02-23 23:13:33 +00001233**
drh1a58fe02008-12-20 02:06:13 +00001234** The term being analyzed must have two or more of OR-connected subterms.
danielk1977fdc40192008-12-29 18:33:32 +00001235** A single subterm might be a set of AND-connected sub-subterms.
drh1a58fe02008-12-20 02:06:13 +00001236** Examples of terms under analysis:
drh3e355802007-02-23 23:13:33 +00001237**
drh1a58fe02008-12-20 02:06:13 +00001238** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
1239** (B) x=expr1 OR expr2=x OR x=expr3
1240** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
1241** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
1242** (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 +00001243**
drh1a58fe02008-12-20 02:06:13 +00001244** CASE 1:
1245**
drhc3e552f2013-02-08 16:04:19 +00001246** If all subterms are of the form T.C=expr for some single column of C and
drh1a58fe02008-12-20 02:06:13 +00001247** a single table T (as shown in example B above) then create a new virtual
1248** term that is an equivalent IN expression. In other words, if the term
1249** being analyzed is:
1250**
1251** x = expr1 OR expr2 = x OR x = expr3
1252**
1253** then create a new virtual term like this:
1254**
1255** x IN (expr1,expr2,expr3)
1256**
1257** CASE 2:
1258**
1259** If all subterms are indexable by a single table T, then set
1260**
1261** WhereTerm.eOperator = WO_OR
1262** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
1263**
1264** A subterm is "indexable" if it is of the form
1265** "T.C <op> <expr>" where C is any column of table T and
1266** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
1267** A subterm is also indexable if it is an AND of two or more
1268** subsubterms at least one of which is indexable. Indexable AND
1269** subterms have their eOperator set to WO_AND and they have
1270** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
1271**
1272** From another point of view, "indexable" means that the subterm could
1273** potentially be used with an index if an appropriate index exists.
1274** This analysis does not consider whether or not the index exists; that
drh4a6fc352013-08-07 01:18:38 +00001275** is decided elsewhere. This analysis only looks at whether subterms
1276** appropriate for indexing exist.
drh1a58fe02008-12-20 02:06:13 +00001277**
drh4a6fc352013-08-07 01:18:38 +00001278** All examples A through E above satisfy case 2. But if a term
drh1a58fe02008-12-20 02:06:13 +00001279** also statisfies case 1 (such as B) we know that the optimizer will
1280** always prefer case 1, so in that case we pretend that case 2 is not
1281** satisfied.
1282**
1283** It might be the case that multiple tables are indexable. For example,
1284** (E) above is indexable on tables P, Q, and R.
1285**
1286** Terms that satisfy case 2 are candidates for lookup by using
1287** separate indices to find rowids for each subterm and composing
1288** the union of all rowids using a RowSet object. This is similar
1289** to "bitmap indices" in other database engines.
1290**
1291** OTHERWISE:
1292**
1293** If neither case 1 nor case 2 apply, then leave the eOperator set to
1294** zero. This term is not useful for search.
drh3e355802007-02-23 23:13:33 +00001295*/
drh1a58fe02008-12-20 02:06:13 +00001296static void exprAnalyzeOrTerm(
1297 SrcList *pSrc, /* the FROM clause */
1298 WhereClause *pWC, /* the complete WHERE clause */
1299 int idxTerm /* Index of the OR-term to be analyzed */
1300){
drh70d18342013-06-06 19:16:33 +00001301 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1302 Parse *pParse = pWInfo->pParse; /* Parser context */
drh1a58fe02008-12-20 02:06:13 +00001303 sqlite3 *db = pParse->db; /* Database connection */
1304 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
1305 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
drh1a58fe02008-12-20 02:06:13 +00001306 int i; /* Loop counters */
1307 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
1308 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
1309 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
1310 Bitmask chngToIN; /* Tables that might satisfy case 1 */
1311 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
drh3e355802007-02-23 23:13:33 +00001312
drh1a58fe02008-12-20 02:06:13 +00001313 /*
1314 ** Break the OR clause into its separate subterms. The subterms are
1315 ** stored in a WhereClause structure containing within the WhereOrInfo
1316 ** object that is attached to the original OR clause term.
1317 */
1318 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
1319 assert( pExpr->op==TK_OR );
drh954701a2008-12-29 23:45:07 +00001320 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
drh1a58fe02008-12-20 02:06:13 +00001321 if( pOrInfo==0 ) return;
1322 pTerm->wtFlags |= TERM_ORINFO;
1323 pOrWc = &pOrInfo->wc;
drh70d18342013-06-06 19:16:33 +00001324 whereClauseInit(pOrWc, pWInfo);
drh1a58fe02008-12-20 02:06:13 +00001325 whereSplit(pOrWc, pExpr, TK_OR);
1326 exprAnalyzeAll(pSrc, pOrWc);
1327 if( db->mallocFailed ) return;
1328 assert( pOrWc->nTerm>=2 );
1329
1330 /*
1331 ** Compute the set of tables that might satisfy cases 1 or 2.
1332 */
danielk1977e672c8e2009-05-22 15:43:26 +00001333 indexable = ~(Bitmask)0;
drhc3e552f2013-02-08 16:04:19 +00001334 chngToIN = ~(Bitmask)0;
drh1a58fe02008-12-20 02:06:13 +00001335 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
1336 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
drh29435252008-12-28 18:35:08 +00001337 WhereAndInfo *pAndInfo;
drh29435252008-12-28 18:35:08 +00001338 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
drh1a58fe02008-12-20 02:06:13 +00001339 chngToIN = 0;
drh29435252008-12-28 18:35:08 +00001340 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
1341 if( pAndInfo ){
1342 WhereClause *pAndWC;
1343 WhereTerm *pAndTerm;
1344 int j;
1345 Bitmask b = 0;
1346 pOrTerm->u.pAndInfo = pAndInfo;
1347 pOrTerm->wtFlags |= TERM_ANDINFO;
1348 pOrTerm->eOperator = WO_AND;
1349 pAndWC = &pAndInfo->wc;
drh70d18342013-06-06 19:16:33 +00001350 whereClauseInit(pAndWC, pWC->pWInfo);
drh29435252008-12-28 18:35:08 +00001351 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
1352 exprAnalyzeAll(pSrc, pAndWC);
drh8871ef52011-10-07 13:33:10 +00001353 pAndWC->pOuter = pWC;
drh7c2fbde2009-01-07 20:58:57 +00001354 testcase( db->mallocFailed );
drh96c7a7d2009-01-10 15:34:12 +00001355 if( !db->mallocFailed ){
1356 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
1357 assert( pAndTerm->pExpr );
1358 if( allowedOp(pAndTerm->pExpr->op) ){
drh70d18342013-06-06 19:16:33 +00001359 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
drh96c7a7d2009-01-10 15:34:12 +00001360 }
drh29435252008-12-28 18:35:08 +00001361 }
1362 }
1363 indexable &= b;
1364 }
drh1a58fe02008-12-20 02:06:13 +00001365 }else if( pOrTerm->wtFlags & TERM_COPIED ){
1366 /* Skip this term for now. We revisit it when we process the
1367 ** corresponding TERM_VIRTUAL term */
1368 }else{
1369 Bitmask b;
drh70d18342013-06-06 19:16:33 +00001370 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001371 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
1372 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
drh70d18342013-06-06 19:16:33 +00001373 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
drh1a58fe02008-12-20 02:06:13 +00001374 }
1375 indexable &= b;
drh7a5bcc02013-01-16 17:08:58 +00001376 if( (pOrTerm->eOperator & WO_EQ)==0 ){
drh1a58fe02008-12-20 02:06:13 +00001377 chngToIN = 0;
1378 }else{
1379 chngToIN &= b;
1380 }
1381 }
drh3e355802007-02-23 23:13:33 +00001382 }
drh1a58fe02008-12-20 02:06:13 +00001383
1384 /*
1385 ** Record the set of tables that satisfy case 2. The set might be
drh111a6a72008-12-21 03:51:16 +00001386 ** empty.
drh1a58fe02008-12-20 02:06:13 +00001387 */
1388 pOrInfo->indexable = indexable;
drh111a6a72008-12-21 03:51:16 +00001389 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
drh1a58fe02008-12-20 02:06:13 +00001390
1391 /*
1392 ** chngToIN holds a set of tables that *might* satisfy case 1. But
1393 ** we have to do some additional checking to see if case 1 really
1394 ** is satisfied.
drh4e8be3b2009-06-08 17:11:08 +00001395 **
1396 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
1397 ** that there is no possibility of transforming the OR clause into an
1398 ** IN operator because one or more terms in the OR clause contain
1399 ** something other than == on a column in the single table. The 1-bit
1400 ** case means that every term of the OR clause is of the form
1401 ** "table.column=expr" for some single table. The one bit that is set
1402 ** will correspond to the common table. We still need to check to make
1403 ** sure the same column is used on all terms. The 2-bit case is when
1404 ** the all terms are of the form "table1.column=table2.column". It
1405 ** might be possible to form an IN operator with either table1.column
1406 ** or table2.column as the LHS if either is common to every term of
1407 ** the OR clause.
1408 **
1409 ** Note that terms of the form "table.column1=table.column2" (the
1410 ** same table on both sizes of the ==) cannot be optimized.
drh1a58fe02008-12-20 02:06:13 +00001411 */
1412 if( chngToIN ){
1413 int okToChngToIN = 0; /* True if the conversion to IN is valid */
1414 int iColumn = -1; /* Column index on lhs of IN operator */
shane63207ab2009-02-04 01:49:30 +00001415 int iCursor = -1; /* Table cursor common to all terms */
drh1a58fe02008-12-20 02:06:13 +00001416 int j = 0; /* Loop counter */
1417
1418 /* Search for a table and column that appears on one side or the
1419 ** other of the == operator in every subterm. That table and column
1420 ** will be recorded in iCursor and iColumn. There might not be any
1421 ** such table and column. Set okToChngToIN if an appropriate table
1422 ** and column is found but leave okToChngToIN false if not found.
1423 */
1424 for(j=0; j<2 && !okToChngToIN; j++){
1425 pOrTerm = pOrWc->a;
1426 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001427 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001428 pOrTerm->wtFlags &= ~TERM_OR_OK;
drh4e8be3b2009-06-08 17:11:08 +00001429 if( pOrTerm->leftCursor==iCursor ){
1430 /* This is the 2-bit case and we are on the second iteration and
1431 ** current term is from the first iteration. So skip this term. */
1432 assert( j==1 );
1433 continue;
1434 }
drh70d18342013-06-06 19:16:33 +00001435 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
drh4e8be3b2009-06-08 17:11:08 +00001436 /* This term must be of the form t1.a==t2.b where t2 is in the
1437 ** chngToIN set but t1 is not. This term will be either preceeded
1438 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
1439 ** and use its inversion. */
1440 testcase( pOrTerm->wtFlags & TERM_COPIED );
1441 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
1442 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
1443 continue;
1444 }
drh1a58fe02008-12-20 02:06:13 +00001445 iColumn = pOrTerm->u.leftColumn;
1446 iCursor = pOrTerm->leftCursor;
1447 break;
1448 }
1449 if( i<0 ){
drh4e8be3b2009-06-08 17:11:08 +00001450 /* No candidate table+column was found. This can only occur
1451 ** on the second iteration */
drh1a58fe02008-12-20 02:06:13 +00001452 assert( j==1 );
drh7a5bcc02013-01-16 17:08:58 +00001453 assert( IsPowerOfTwo(chngToIN) );
drh70d18342013-06-06 19:16:33 +00001454 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
drh1a58fe02008-12-20 02:06:13 +00001455 break;
1456 }
drh4e8be3b2009-06-08 17:11:08 +00001457 testcase( j==1 );
1458
1459 /* We have found a candidate table and column. Check to see if that
1460 ** table and column is common to every term in the OR clause */
drh1a58fe02008-12-20 02:06:13 +00001461 okToChngToIN = 1;
1462 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
drh7a5bcc02013-01-16 17:08:58 +00001463 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001464 if( pOrTerm->leftCursor!=iCursor ){
1465 pOrTerm->wtFlags &= ~TERM_OR_OK;
1466 }else if( pOrTerm->u.leftColumn!=iColumn ){
1467 okToChngToIN = 0;
1468 }else{
1469 int affLeft, affRight;
1470 /* If the right-hand side is also a column, then the affinities
1471 ** of both right and left sides must be such that no type
1472 ** conversions are required on the right. (Ticket #2249)
1473 */
1474 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
1475 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
1476 if( affRight!=0 && affRight!=affLeft ){
1477 okToChngToIN = 0;
1478 }else{
1479 pOrTerm->wtFlags |= TERM_OR_OK;
1480 }
1481 }
1482 }
1483 }
1484
1485 /* At this point, okToChngToIN is true if original pTerm satisfies
1486 ** case 1. In that case, construct a new virtual term that is
1487 ** pTerm converted into an IN operator.
1488 */
1489 if( okToChngToIN ){
1490 Expr *pDup; /* A transient duplicate expression */
1491 ExprList *pList = 0; /* The RHS of the IN operator */
1492 Expr *pLeft = 0; /* The LHS of the IN operator */
1493 Expr *pNew; /* The complete IN operator */
1494
1495 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
1496 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
drh7a5bcc02013-01-16 17:08:58 +00001497 assert( pOrTerm->eOperator & WO_EQ );
drh1a58fe02008-12-20 02:06:13 +00001498 assert( pOrTerm->leftCursor==iCursor );
1499 assert( pOrTerm->u.leftColumn==iColumn );
danielk19776ab3a2e2009-02-19 14:39:25 +00001500 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
drh70d18342013-06-06 19:16:33 +00001501 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
drh1a58fe02008-12-20 02:06:13 +00001502 pLeft = pOrTerm->pExpr->pLeft;
1503 }
1504 assert( pLeft!=0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001505 pDup = sqlite3ExprDup(db, pLeft, 0);
drhb7916a72009-05-27 10:31:29 +00001506 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
drh1a58fe02008-12-20 02:06:13 +00001507 if( pNew ){
1508 int idxNew;
1509 transferJoinMarkings(pNew, pExpr);
danielk19776ab3a2e2009-02-19 14:39:25 +00001510 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
1511 pNew->x.pList = pList;
drh1a58fe02008-12-20 02:06:13 +00001512 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
1513 testcase( idxNew==0 );
1514 exprAnalyze(pSrc, pWC, idxNew);
1515 pTerm = &pWC->a[idxTerm];
1516 pWC->a[idxNew].iParent = idxTerm;
1517 pTerm->nChild = 1;
1518 }else{
1519 sqlite3ExprListDelete(db, pList);
1520 }
drh534230c2011-01-22 00:10:45 +00001521 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
drh1a58fe02008-12-20 02:06:13 +00001522 }
drh3e355802007-02-23 23:13:33 +00001523 }
drh3e355802007-02-23 23:13:33 +00001524}
1525#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
drh54a167d2005-11-26 14:08:07 +00001526
drh7a5bcc02013-01-16 17:08:58 +00001527/*
drh0aa74ed2005-07-16 13:33:20 +00001528** The input to this routine is an WhereTerm structure with only the
drh51147ba2005-07-23 22:59:55 +00001529** "pExpr" field filled in. The job of this routine is to analyze the
drh0aa74ed2005-07-16 13:33:20 +00001530** subexpression and populate all the other fields of the WhereTerm
drh75897232000-05-29 14:26:00 +00001531** structure.
drh51147ba2005-07-23 22:59:55 +00001532**
1533** If the expression is of the form "<expr> <op> X" it gets commuted
drh1a58fe02008-12-20 02:06:13 +00001534** to the standard form of "X <op> <expr>".
1535**
1536** If the expression is of the form "X <op> Y" where both X and Y are
1537** columns, then the original expression is unchanged and a new virtual
1538** term of the form "Y <op> X" is added to the WHERE clause and
1539** analyzed separately. The original term is marked with TERM_COPIED
1540** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1541** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1542** is a commuted copy of a prior term.) The original term has nChild=1
1543** and the copy has idxParent set to the index of the original term.
drh75897232000-05-29 14:26:00 +00001544*/
drh0fcef5e2005-07-19 17:38:22 +00001545static void exprAnalyze(
1546 SrcList *pSrc, /* the FROM clause */
drh9eb20282005-08-24 03:52:18 +00001547 WhereClause *pWC, /* the WHERE clause */
1548 int idxTerm /* Index of the term to be analyzed */
drh0fcef5e2005-07-19 17:38:22 +00001549){
drh70d18342013-06-06 19:16:33 +00001550 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
drh1a58fe02008-12-20 02:06:13 +00001551 WhereTerm *pTerm; /* The term to be analyzed */
drh111a6a72008-12-21 03:51:16 +00001552 WhereMaskSet *pMaskSet; /* Set of table index masks */
drh1a58fe02008-12-20 02:06:13 +00001553 Expr *pExpr; /* The expression to be analyzed */
1554 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1555 Bitmask prereqAll; /* Prerequesites of pExpr */
drh5e767c52010-02-25 04:15:47 +00001556 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
drh1d452e12009-11-01 19:26:59 +00001557 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1558 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1559 int noCase = 0; /* LIKE/GLOB distinguishes case */
drh1a58fe02008-12-20 02:06:13 +00001560 int op; /* Top-level operator. pExpr->op */
drh70d18342013-06-06 19:16:33 +00001561 Parse *pParse = pWInfo->pParse; /* Parsing context */
drh1a58fe02008-12-20 02:06:13 +00001562 sqlite3 *db = pParse->db; /* Database connection */
drh0fcef5e2005-07-19 17:38:22 +00001563
drhf998b732007-11-26 13:36:00 +00001564 if( db->mallocFailed ){
1565 return;
1566 }
1567 pTerm = &pWC->a[idxTerm];
drh70d18342013-06-06 19:16:33 +00001568 pMaskSet = &pWInfo->sMaskSet;
drh7ee751d2012-12-19 15:53:51 +00001569 pExpr = pTerm->pExpr;
1570 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
drh0fcef5e2005-07-19 17:38:22 +00001571 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
drh50b39962006-10-28 00:28:09 +00001572 op = pExpr->op;
1573 if( op==TK_IN ){
drhf5b11382005-09-17 13:07:13 +00001574 assert( pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +00001575 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1576 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
1577 }else{
1578 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
1579 }
drh50b39962006-10-28 00:28:09 +00001580 }else if( op==TK_ISNULL ){
1581 pTerm->prereqRight = 0;
drhf5b11382005-09-17 13:07:13 +00001582 }else{
1583 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
1584 }
drh22d6a532005-09-19 21:05:48 +00001585 prereqAll = exprTableUsage(pMaskSet, pExpr);
1586 if( ExprHasProperty(pExpr, EP_FromJoin) ){
drh42165be2008-03-26 14:56:34 +00001587 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
1588 prereqAll |= x;
drhdafc0ce2008-04-17 19:14:02 +00001589 extraRight = x-1; /* ON clause terms may not be used with an index
1590 ** on left table of a LEFT JOIN. Ticket #3015 */
drh22d6a532005-09-19 21:05:48 +00001591 }
1592 pTerm->prereqAll = prereqAll;
drh0fcef5e2005-07-19 17:38:22 +00001593 pTerm->leftCursor = -1;
drh45b1ee42005-08-02 17:48:22 +00001594 pTerm->iParent = -1;
drhb52076c2006-01-23 13:22:09 +00001595 pTerm->eOperator = 0;
drh738fc792013-01-17 15:05:17 +00001596 if( allowedOp(op) ){
drh7a66da12012-12-07 20:31:11 +00001597 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1598 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
drh738fc792013-01-17 15:05:17 +00001599 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
drh0fcef5e2005-07-19 17:38:22 +00001600 if( pLeft->op==TK_COLUMN ){
1601 pTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001602 pTerm->u.leftColumn = pLeft->iColumn;
drh738fc792013-01-17 15:05:17 +00001603 pTerm->eOperator = operatorMask(op) & opMask;
drh75897232000-05-29 14:26:00 +00001604 }
drh0fcef5e2005-07-19 17:38:22 +00001605 if( pRight && pRight->op==TK_COLUMN ){
1606 WhereTerm *pNew;
1607 Expr *pDup;
drh7a5bcc02013-01-16 17:08:58 +00001608 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
drh0fcef5e2005-07-19 17:38:22 +00001609 if( pTerm->leftCursor>=0 ){
drh9eb20282005-08-24 03:52:18 +00001610 int idxNew;
danielk19776ab3a2e2009-02-19 14:39:25 +00001611 pDup = sqlite3ExprDup(db, pExpr, 0);
drh17435752007-08-16 04:30:38 +00001612 if( db->mallocFailed ){
drh633e6d52008-07-28 19:34:53 +00001613 sqlite3ExprDelete(db, pDup);
drh28f45912006-10-18 23:26:38 +00001614 return;
1615 }
drh9eb20282005-08-24 03:52:18 +00001616 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1617 if( idxNew==0 ) return;
1618 pNew = &pWC->a[idxNew];
1619 pNew->iParent = idxTerm;
1620 pTerm = &pWC->a[idxTerm];
drh45b1ee42005-08-02 17:48:22 +00001621 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001622 pTerm->wtFlags |= TERM_COPIED;
drheb5bc922013-01-17 16:43:33 +00001623 if( pExpr->op==TK_EQ
1624 && !ExprHasProperty(pExpr, EP_FromJoin)
1625 && OptimizationEnabled(db, SQLITE_Transitive)
1626 ){
drh7a5bcc02013-01-16 17:08:58 +00001627 pTerm->eOperator |= WO_EQUIV;
1628 eExtraOp = WO_EQUIV;
1629 }
drh0fcef5e2005-07-19 17:38:22 +00001630 }else{
1631 pDup = pExpr;
1632 pNew = pTerm;
1633 }
drh7d10d5a2008-08-20 16:35:10 +00001634 exprCommute(pParse, pDup);
drhfb76f5a2012-12-08 14:16:47 +00001635 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
drh0fcef5e2005-07-19 17:38:22 +00001636 pNew->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001637 pNew->u.leftColumn = pLeft->iColumn;
drh5e767c52010-02-25 04:15:47 +00001638 testcase( (prereqLeft | extraRight) != prereqLeft );
1639 pNew->prereqRight = prereqLeft | extraRight;
drh0fcef5e2005-07-19 17:38:22 +00001640 pNew->prereqAll = prereqAll;
drh738fc792013-01-17 15:05:17 +00001641 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
drh75897232000-05-29 14:26:00 +00001642 }
1643 }
drhed378002005-07-28 23:12:08 +00001644
drhd2687b72005-08-12 22:56:09 +00001645#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
drhed378002005-07-28 23:12:08 +00001646 /* If a term is the BETWEEN operator, create two new virtual terms
drh1a58fe02008-12-20 02:06:13 +00001647 ** that define the range that the BETWEEN implements. For example:
1648 **
1649 ** a BETWEEN b AND c
1650 **
1651 ** is converted into:
1652 **
1653 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1654 **
1655 ** The two new terms are added onto the end of the WhereClause object.
1656 ** The new terms are "dynamic" and are children of the original BETWEEN
1657 ** term. That means that if the BETWEEN term is coded, the children are
1658 ** skipped. Or, if the children are satisfied by an index, the original
1659 ** BETWEEN term is skipped.
drhed378002005-07-28 23:12:08 +00001660 */
drh29435252008-12-28 18:35:08 +00001661 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001662 ExprList *pList = pExpr->x.pList;
drhed378002005-07-28 23:12:08 +00001663 int i;
1664 static const u8 ops[] = {TK_GE, TK_LE};
1665 assert( pList!=0 );
1666 assert( pList->nExpr==2 );
1667 for(i=0; i<2; i++){
1668 Expr *pNewExpr;
drh9eb20282005-08-24 03:52:18 +00001669 int idxNew;
drhb7916a72009-05-27 10:31:29 +00001670 pNewExpr = sqlite3PExpr(pParse, ops[i],
1671 sqlite3ExprDup(db, pExpr->pLeft, 0),
danielk19776ab3a2e2009-02-19 14:39:25 +00001672 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
drhd41d39f2013-08-28 16:27:01 +00001673 transferJoinMarkings(pNewExpr, pExpr);
drh9eb20282005-08-24 03:52:18 +00001674 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001675 testcase( idxNew==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001676 exprAnalyze(pSrc, pWC, idxNew);
drh9eb20282005-08-24 03:52:18 +00001677 pTerm = &pWC->a[idxTerm];
1678 pWC->a[idxNew].iParent = idxTerm;
drhed378002005-07-28 23:12:08 +00001679 }
drh45b1ee42005-08-02 17:48:22 +00001680 pTerm->nChild = 2;
drhed378002005-07-28 23:12:08 +00001681 }
drhd2687b72005-08-12 22:56:09 +00001682#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
drhed378002005-07-28 23:12:08 +00001683
danielk19771576cd92006-01-14 08:02:28 +00001684#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
drh1a58fe02008-12-20 02:06:13 +00001685 /* Analyze a term that is composed of two or more subterms connected by
1686 ** an OR operator.
drh6c30be82005-07-29 15:10:17 +00001687 */
1688 else if( pExpr->op==TK_OR ){
drh29435252008-12-28 18:35:08 +00001689 assert( pWC->op==TK_AND );
drh1a58fe02008-12-20 02:06:13 +00001690 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
danielk1977f51d1bd2009-07-31 06:14:51 +00001691 pTerm = &pWC->a[idxTerm];
drh6c30be82005-07-29 15:10:17 +00001692 }
drhd2687b72005-08-12 22:56:09 +00001693#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1694
1695#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1696 /* Add constraints to reduce the search space on a LIKE or GLOB
1697 ** operator.
drh9f504ea2008-02-23 21:55:39 +00001698 **
1699 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
1700 **
1701 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
1702 **
1703 ** The last character of the prefix "abc" is incremented to form the
shane7bc71e52008-05-28 18:01:44 +00001704 ** termination condition "abd".
drhd2687b72005-08-12 22:56:09 +00001705 */
dan937d0de2009-10-15 18:35:38 +00001706 if( pWC->op==TK_AND
1707 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1708 ){
drh1d452e12009-11-01 19:26:59 +00001709 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1710 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1711 Expr *pNewExpr1;
1712 Expr *pNewExpr2;
1713 int idxNew1;
1714 int idxNew2;
drhae80dde2012-12-06 21:16:43 +00001715 Token sCollSeqName; /* Name of collating sequence */
drh9eb20282005-08-24 03:52:18 +00001716
danielk19776ab3a2e2009-02-19 14:39:25 +00001717 pLeft = pExpr->x.pList->a[1].pExpr;
danielk19776ab3a2e2009-02-19 14:39:25 +00001718 pStr2 = sqlite3ExprDup(db, pStr1, 0);
drhf998b732007-11-26 13:36:00 +00001719 if( !db->mallocFailed ){
drh254993e2009-06-08 19:44:36 +00001720 u8 c, *pC; /* Last character before the first wildcard */
dan937d0de2009-10-15 18:35:38 +00001721 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
drh9f504ea2008-02-23 21:55:39 +00001722 c = *pC;
drh02a50b72008-05-26 18:33:40 +00001723 if( noCase ){
drh254993e2009-06-08 19:44:36 +00001724 /* The point is to increment the last character before the first
1725 ** wildcard. But if we increment '@', that will push it into the
1726 ** alphabetic range where case conversions will mess up the
1727 ** inequality. To avoid this, make sure to also run the full
1728 ** LIKE on all candidate expressions by clearing the isComplete flag
1729 */
drh39759742013-08-02 23:40:45 +00001730 if( c=='A'-1 ) isComplete = 0;
drh02a50b72008-05-26 18:33:40 +00001731 c = sqlite3UpperToLower[c];
1732 }
drh9f504ea2008-02-23 21:55:39 +00001733 *pC = c + 1;
drhd2687b72005-08-12 22:56:09 +00001734 }
drhae80dde2012-12-06 21:16:43 +00001735 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
1736 sCollSeqName.n = 6;
1737 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001738 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
drh0a8a4062012-12-07 18:38:16 +00001739 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001740 pStr1, 0);
drhd41d39f2013-08-28 16:27:01 +00001741 transferJoinMarkings(pNewExpr1, pExpr);
drh9eb20282005-08-24 03:52:18 +00001742 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001743 testcase( idxNew1==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001744 exprAnalyze(pSrc, pWC, idxNew1);
drhae80dde2012-12-06 21:16:43 +00001745 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
drh8342e492010-07-22 17:49:52 +00001746 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
drh0a8a4062012-12-07 18:38:16 +00001747 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
drhae80dde2012-12-06 21:16:43 +00001748 pStr2, 0);
drhd41d39f2013-08-28 16:27:01 +00001749 transferJoinMarkings(pNewExpr2, pExpr);
drh9eb20282005-08-24 03:52:18 +00001750 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001751 testcase( idxNew2==0 );
drh7b4fc6a2007-02-06 13:26:32 +00001752 exprAnalyze(pSrc, pWC, idxNew2);
drh9eb20282005-08-24 03:52:18 +00001753 pTerm = &pWC->a[idxTerm];
drhd2687b72005-08-12 22:56:09 +00001754 if( isComplete ){
drh9eb20282005-08-24 03:52:18 +00001755 pWC->a[idxNew1].iParent = idxTerm;
1756 pWC->a[idxNew2].iParent = idxTerm;
drhd2687b72005-08-12 22:56:09 +00001757 pTerm->nChild = 2;
1758 }
1759 }
1760#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
drh7f375902006-06-13 17:38:59 +00001761
1762#ifndef SQLITE_OMIT_VIRTUALTABLE
1763 /* Add a WO_MATCH auxiliary term to the constraint set if the
1764 ** current expression is of the form: column MATCH expr.
1765 ** This information is used by the xBestIndex methods of
1766 ** virtual tables. The native query optimizer does not attempt
1767 ** to do anything with MATCH functions.
1768 */
1769 if( isMatchOfColumn(pExpr) ){
1770 int idxNew;
1771 Expr *pRight, *pLeft;
1772 WhereTerm *pNewTerm;
1773 Bitmask prereqColumn, prereqExpr;
1774
danielk19776ab3a2e2009-02-19 14:39:25 +00001775 pRight = pExpr->x.pList->a[0].pExpr;
1776 pLeft = pExpr->x.pList->a[1].pExpr;
drh7f375902006-06-13 17:38:59 +00001777 prereqExpr = exprTableUsage(pMaskSet, pRight);
1778 prereqColumn = exprTableUsage(pMaskSet, pLeft);
1779 if( (prereqExpr & prereqColumn)==0 ){
drh1a90e092006-06-14 22:07:10 +00001780 Expr *pNewExpr;
drhb7916a72009-05-27 10:31:29 +00001781 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1782 0, sqlite3ExprDup(db, pRight, 0), 0);
drh1a90e092006-06-14 22:07:10 +00001783 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
drh6a1e0712008-12-05 15:24:15 +00001784 testcase( idxNew==0 );
drh7f375902006-06-13 17:38:59 +00001785 pNewTerm = &pWC->a[idxNew];
1786 pNewTerm->prereqRight = prereqExpr;
1787 pNewTerm->leftCursor = pLeft->iTable;
drh700a2262008-12-17 19:22:15 +00001788 pNewTerm->u.leftColumn = pLeft->iColumn;
drh7f375902006-06-13 17:38:59 +00001789 pNewTerm->eOperator = WO_MATCH;
1790 pNewTerm->iParent = idxTerm;
drhd2ca60d2006-06-27 02:36:58 +00001791 pTerm = &pWC->a[idxTerm];
drh7f375902006-06-13 17:38:59 +00001792 pTerm->nChild = 1;
drh165be382008-12-05 02:36:33 +00001793 pTerm->wtFlags |= TERM_COPIED;
drh7f375902006-06-13 17:38:59 +00001794 pNewTerm->prereqAll = pTerm->prereqAll;
1795 }
1796 }
1797#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhdafc0ce2008-04-17 19:14:02 +00001798
drh1435a9a2013-08-27 23:15:44 +00001799#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhd3ed7342011-09-21 00:09:41 +00001800 /* When sqlite_stat3 histogram data is available an operator of the
drh534230c2011-01-22 00:10:45 +00001801 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1802 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1803 ** virtual term of that form.
1804 **
1805 ** Note that the virtual term must be tagged with TERM_VNULL. This
1806 ** TERM_VNULL tag will suppress the not-null check at the beginning
1807 ** of the loop. Without the TERM_VNULL flag, the not-null check at
1808 ** the start of the loop will prevent any results from being returned.
1809 */
drhea6dc442011-04-08 21:35:26 +00001810 if( pExpr->op==TK_NOTNULL
1811 && pExpr->pLeft->op==TK_COLUMN
1812 && pExpr->pLeft->iColumn>=0
drh40aa9362013-06-28 17:29:25 +00001813 && OptimizationEnabled(db, SQLITE_Stat3)
drhea6dc442011-04-08 21:35:26 +00001814 ){
drh534230c2011-01-22 00:10:45 +00001815 Expr *pNewExpr;
1816 Expr *pLeft = pExpr->pLeft;
1817 int idxNew;
1818 WhereTerm *pNewTerm;
1819
1820 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1821 sqlite3ExprDup(db, pLeft, 0),
1822 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1823
1824 idxNew = whereClauseInsert(pWC, pNewExpr,
1825 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
drhda91e712011-02-11 06:59:02 +00001826 if( idxNew ){
1827 pNewTerm = &pWC->a[idxNew];
1828 pNewTerm->prereqRight = 0;
1829 pNewTerm->leftCursor = pLeft->iTable;
1830 pNewTerm->u.leftColumn = pLeft->iColumn;
1831 pNewTerm->eOperator = WO_GT;
1832 pNewTerm->iParent = idxTerm;
1833 pTerm = &pWC->a[idxTerm];
1834 pTerm->nChild = 1;
1835 pTerm->wtFlags |= TERM_COPIED;
1836 pNewTerm->prereqAll = pTerm->prereqAll;
1837 }
drh534230c2011-01-22 00:10:45 +00001838 }
drh1435a9a2013-08-27 23:15:44 +00001839#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh534230c2011-01-22 00:10:45 +00001840
drhdafc0ce2008-04-17 19:14:02 +00001841 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1842 ** an index for tables to the left of the join.
1843 */
1844 pTerm->prereqRight |= extraRight;
drh75897232000-05-29 14:26:00 +00001845}
1846
drh7b4fc6a2007-02-06 13:26:32 +00001847/*
drh3b48e8c2013-06-12 20:18:16 +00001848** This function searches pList for a entry that matches the iCol-th column
1849** of index pIdx.
dan6f343962011-07-01 18:26:40 +00001850**
1851** If such an expression is found, its index in pList->a[] is returned. If
1852** no expression is found, -1 is returned.
1853*/
1854static int findIndexCol(
1855 Parse *pParse, /* Parse context */
1856 ExprList *pList, /* Expression list to search */
1857 int iBase, /* Cursor for table associated with pIdx */
1858 Index *pIdx, /* Index to match column of */
1859 int iCol /* Column of index to match */
1860){
1861 int i;
1862 const char *zColl = pIdx->azColl[iCol];
1863
1864 for(i=0; i<pList->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001865 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001866 if( p->op==TK_COLUMN
1867 && p->iColumn==pIdx->aiColumn[iCol]
1868 && p->iTable==iBase
1869 ){
drh580c8c12012-12-08 03:34:04 +00001870 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
drhf1d3e322011-07-09 13:00:41 +00001871 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
dan6f343962011-07-01 18:26:40 +00001872 return i;
1873 }
1874 }
1875 }
1876
1877 return -1;
1878}
1879
1880/*
dan6f343962011-07-01 18:26:40 +00001881** Return true if the DISTINCT expression-list passed as the third argument
drh4f402f22013-06-11 18:59:38 +00001882** is redundant.
1883**
drh3b48e8c2013-06-12 20:18:16 +00001884** A DISTINCT list is redundant if the database contains some subset of
drh4f402f22013-06-11 18:59:38 +00001885** columns that are unique and non-null.
dan6f343962011-07-01 18:26:40 +00001886*/
1887static int isDistinctRedundant(
drh4f402f22013-06-11 18:59:38 +00001888 Parse *pParse, /* Parsing context */
1889 SrcList *pTabList, /* The FROM clause */
1890 WhereClause *pWC, /* The WHERE clause */
1891 ExprList *pDistinct /* The result set that needs to be DISTINCT */
dan6f343962011-07-01 18:26:40 +00001892){
1893 Table *pTab;
1894 Index *pIdx;
1895 int i;
1896 int iBase;
1897
1898 /* If there is more than one table or sub-select in the FROM clause of
1899 ** this query, then it will not be possible to show that the DISTINCT
1900 ** clause is redundant. */
1901 if( pTabList->nSrc!=1 ) return 0;
1902 iBase = pTabList->a[0].iCursor;
1903 pTab = pTabList->a[0].pTab;
1904
dan94e08d92011-07-02 06:44:05 +00001905 /* If any of the expressions is an IPK column on table iBase, then return
1906 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
1907 ** current SELECT is a correlated sub-query.
1908 */
dan6f343962011-07-01 18:26:40 +00001909 for(i=0; i<pDistinct->nExpr; i++){
drh580c8c12012-12-08 03:34:04 +00001910 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
dan94e08d92011-07-02 06:44:05 +00001911 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
dan6f343962011-07-01 18:26:40 +00001912 }
1913
1914 /* Loop through all indices on the table, checking each to see if it makes
1915 ** the DISTINCT qualifier redundant. It does so if:
1916 **
1917 ** 1. The index is itself UNIQUE, and
1918 **
1919 ** 2. All of the columns in the index are either part of the pDistinct
1920 ** list, or else the WHERE clause contains a term of the form "col=X",
1921 ** where X is a constant value. The collation sequences of the
1922 ** comparison and select-list expressions must match those of the index.
dan6a36f432012-04-20 16:59:24 +00001923 **
1924 ** 3. All of those index columns for which the WHERE clause does not
1925 ** contain a "col=X" term are subject to a NOT NULL constraint.
dan6f343962011-07-01 18:26:40 +00001926 */
1927 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1928 if( pIdx->onError==OE_None ) continue;
1929 for(i=0; i<pIdx->nColumn; i++){
1930 int iCol = pIdx->aiColumn[i];
dan6a36f432012-04-20 16:59:24 +00001931 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
1932 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
1933 if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
1934 break;
1935 }
dan6f343962011-07-01 18:26:40 +00001936 }
1937 }
1938 if( i==pIdx->nColumn ){
1939 /* This index implies that the DISTINCT qualifier is redundant. */
1940 return 1;
1941 }
1942 }
1943
1944 return 0;
1945}
drh0fcef5e2005-07-19 17:38:22 +00001946
drhb8a8e8a2013-06-10 19:12:39 +00001947/*
drh4a6fc352013-08-07 01:18:38 +00001948** Find (an approximate) sum of two WhereCosts. This computation is
drh3b48e8c2013-06-12 20:18:16 +00001949** not a simple "+" operator because WhereCost is stored as a logarithmic
1950** value.
1951**
drhb8a8e8a2013-06-10 19:12:39 +00001952*/
1953static WhereCost whereCostAdd(WhereCost a, WhereCost b){
1954 static const unsigned char x[] = {
1955 10, 10, /* 0,1 */
1956 9, 9, /* 2,3 */
1957 8, 8, /* 4,5 */
1958 7, 7, 7, /* 6,7,8 */
1959 6, 6, 6, /* 9,10,11 */
1960 5, 5, 5, /* 12-14 */
1961 4, 4, 4, 4, /* 15-18 */
1962 3, 3, 3, 3, 3, 3, /* 19-24 */
1963 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
1964 };
1965 if( a>=b ){
1966 if( a>b+49 ) return a;
1967 if( a>b+31 ) return a+1;
1968 return a+x[a-b];
1969 }else{
1970 if( b>a+49 ) return b;
1971 if( b>a+31 ) return b+1;
1972 return b+x[b-a];
1973 }
1974}
1975
1976/*
drh3b48e8c2013-06-12 20:18:16 +00001977** Convert an integer into a WhereCost. In other words, compute a
1978** good approximatation for 10*log2(x).
drhb8a8e8a2013-06-10 19:12:39 +00001979*/
drhe1e2e9a2013-06-13 15:16:53 +00001980static WhereCost whereCost(tRowcnt x){
drhb8a8e8a2013-06-10 19:12:39 +00001981 static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
1982 WhereCost y = 40;
1983 if( x<8 ){
1984 if( x<2 ) return 0;
1985 while( x<8 ){ y -= 10; x <<= 1; }
1986 }else{
1987 while( x>255 ){ y += 40; x >>= 4; }
1988 while( x>15 ){ y += 10; x >>= 1; }
1989 }
1990 return a[x&7] + y - 10;
1991}
1992
drh8636e9c2013-06-11 01:50:08 +00001993#ifndef SQLITE_OMIT_VIRTUALTABLE
1994/*
1995** Convert a double (as received from xBestIndex of a virtual table)
drh3b48e8c2013-06-12 20:18:16 +00001996** into a WhereCost. In other words, compute an approximation for
1997** 10*log2(x).
drh8636e9c2013-06-11 01:50:08 +00001998*/
1999static WhereCost whereCostFromDouble(double x){
2000 u64 a;
2001 WhereCost e;
2002 assert( sizeof(x)==8 && sizeof(a)==8 );
2003 if( x<=1 ) return 0;
drhe1e2e9a2013-06-13 15:16:53 +00002004 if( x<=2000000000 ) return whereCost((tRowcnt)x);
drh8636e9c2013-06-11 01:50:08 +00002005 memcpy(&a, &x, 8);
2006 e = (a>>52) - 1022;
2007 return e*10;
2008}
2009#endif /* SQLITE_OMIT_VIRTUALTABLE */
2010
drh75897232000-05-29 14:26:00 +00002011/*
drh3b48e8c2013-06-12 20:18:16 +00002012** Estimate the logarithm of the input value to base 2.
drh28c4cf42005-07-27 20:41:43 +00002013*/
drh4efc9292013-06-06 23:02:03 +00002014static WhereCost estLog(WhereCost N){
drhe1e2e9a2013-06-13 15:16:53 +00002015 WhereCost x = whereCost(N);
drh4fe425a2013-06-12 17:08:06 +00002016 return x>33 ? x - 33 : 0;
drh28c4cf42005-07-27 20:41:43 +00002017}
2018
drh6d209d82006-06-27 01:54:26 +00002019/*
2020** Two routines for printing the content of an sqlite3_index_info
2021** structure. Used for testing and debugging only. If neither
2022** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
2023** are no-ops.
2024*/
drhd15cb172013-05-21 19:23:10 +00002025#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
drh6d209d82006-06-27 01:54:26 +00002026static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
2027 int i;
mlcreech3a00f902008-03-04 17:45:01 +00002028 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00002029 for(i=0; i<p->nConstraint; i++){
2030 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
2031 i,
2032 p->aConstraint[i].iColumn,
2033 p->aConstraint[i].iTermOffset,
2034 p->aConstraint[i].op,
2035 p->aConstraint[i].usable);
2036 }
2037 for(i=0; i<p->nOrderBy; i++){
2038 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
2039 i,
2040 p->aOrderBy[i].iColumn,
2041 p->aOrderBy[i].desc);
2042 }
2043}
2044static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
2045 int i;
mlcreech3a00f902008-03-04 17:45:01 +00002046 if( !sqlite3WhereTrace ) return;
drh6d209d82006-06-27 01:54:26 +00002047 for(i=0; i<p->nConstraint; i++){
2048 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
2049 i,
2050 p->aConstraintUsage[i].argvIndex,
2051 p->aConstraintUsage[i].omit);
2052 }
2053 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
2054 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
2055 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
2056 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
2057}
2058#else
2059#define TRACE_IDX_INPUTS(A)
2060#define TRACE_IDX_OUTPUTS(A)
2061#endif
2062
drhc6339082010-04-07 16:54:58 +00002063#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00002064/*
drh4139c992010-04-07 14:59:45 +00002065** Return TRUE if the WHERE clause term pTerm is of a form where it
2066** could be used with an index to access pSrc, assuming an appropriate
2067** index existed.
2068*/
2069static int termCanDriveIndex(
2070 WhereTerm *pTerm, /* WHERE clause term to check */
2071 struct SrcList_item *pSrc, /* Table we are trying to access */
2072 Bitmask notReady /* Tables in outer loops of the join */
2073){
2074 char aff;
2075 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
drh7a5bcc02013-01-16 17:08:58 +00002076 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
drh4139c992010-04-07 14:59:45 +00002077 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00002078 if( pTerm->u.leftColumn<0 ) return 0;
drh4139c992010-04-07 14:59:45 +00002079 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
2080 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
2081 return 1;
2082}
drhc6339082010-04-07 16:54:58 +00002083#endif
drh4139c992010-04-07 14:59:45 +00002084
drhc6339082010-04-07 16:54:58 +00002085
2086#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drh8b307fb2010-04-06 15:57:05 +00002087/*
drhc6339082010-04-07 16:54:58 +00002088** Generate code to construct the Index object for an automatic index
2089** and to set up the WhereLevel object pLevel so that the code generator
2090** makes use of the automatic index.
drh8b307fb2010-04-06 15:57:05 +00002091*/
drhc6339082010-04-07 16:54:58 +00002092static void constructAutomaticIndex(
drh8b307fb2010-04-06 15:57:05 +00002093 Parse *pParse, /* The parsing context */
2094 WhereClause *pWC, /* The WHERE clause */
2095 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
2096 Bitmask notReady, /* Mask of cursors that are not available */
2097 WhereLevel *pLevel /* Write new index here */
2098){
2099 int nColumn; /* Number of columns in the constructed index */
2100 WhereTerm *pTerm; /* A single term of the WHERE clause */
2101 WhereTerm *pWCEnd; /* End of pWC->a[] */
2102 int nByte; /* Byte of memory needed for pIdx */
2103 Index *pIdx; /* Object describing the transient index */
2104 Vdbe *v; /* Prepared statement under construction */
drh8b307fb2010-04-06 15:57:05 +00002105 int addrInit; /* Address of the initialization bypass jump */
2106 Table *pTable; /* The table being indexed */
2107 KeyInfo *pKeyinfo; /* Key information for the index */
2108 int addrTop; /* Top of the index fill loop */
2109 int regRecord; /* Register holding an index record */
2110 int n; /* Column counter */
drh4139c992010-04-07 14:59:45 +00002111 int i; /* Loop counter */
2112 int mxBitCol; /* Maximum column in pSrc->colUsed */
drh424aab82010-04-06 18:28:20 +00002113 CollSeq *pColl; /* Collating sequence to on a column */
drh7ba39a92013-05-30 17:43:19 +00002114 WhereLoop *pLoop; /* The Loop object */
drh4139c992010-04-07 14:59:45 +00002115 Bitmask idxCols; /* Bitmap of columns used for indexing */
2116 Bitmask extraCols; /* Bitmap of additional columns */
drh8d56e202013-06-28 23:55:45 +00002117 u8 sentWarning = 0; /* True if a warnning has been issued */
drh8b307fb2010-04-06 15:57:05 +00002118
2119 /* Generate code to skip over the creation and initialization of the
2120 ** transient index on 2nd and subsequent iterations of the loop. */
2121 v = pParse->pVdbe;
2122 assert( v!=0 );
dan1d8cb212011-12-09 13:24:16 +00002123 addrInit = sqlite3CodeOnce(pParse);
drh8b307fb2010-04-06 15:57:05 +00002124
drh4139c992010-04-07 14:59:45 +00002125 /* Count the number of columns that will be added to the index
2126 ** and used to match WHERE clause constraints */
drh8b307fb2010-04-06 15:57:05 +00002127 nColumn = 0;
drh424aab82010-04-06 18:28:20 +00002128 pTable = pSrc->pTab;
drh8b307fb2010-04-06 15:57:05 +00002129 pWCEnd = &pWC->a[pWC->nTerm];
drh7ba39a92013-05-30 17:43:19 +00002130 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00002131 idxCols = 0;
drh81186b42013-06-18 01:52:41 +00002132 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002133 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
2134 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002135 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh52ff8ea2010-04-08 14:15:56 +00002136 testcase( iCol==BMS );
2137 testcase( iCol==BMS-1 );
drh8d56e202013-06-28 23:55:45 +00002138 if( !sentWarning ){
2139 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
2140 "automatic index on %s(%s)", pTable->zName,
2141 pTable->aCol[iCol].zName);
2142 sentWarning = 1;
2143 }
drh0013e722010-04-08 00:40:15 +00002144 if( (idxCols & cMask)==0 ){
drh4efc9292013-06-06 23:02:03 +00002145 if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
2146 pLoop->aLTerm[nColumn++] = pTerm;
drh0013e722010-04-08 00:40:15 +00002147 idxCols |= cMask;
2148 }
drh8b307fb2010-04-06 15:57:05 +00002149 }
2150 }
2151 assert( nColumn>0 );
drh4efc9292013-06-06 23:02:03 +00002152 pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
drh53b52f72013-05-31 11:57:39 +00002153 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
drh986b3872013-06-28 21:12:20 +00002154 | WHERE_AUTO_INDEX;
drh4139c992010-04-07 14:59:45 +00002155
2156 /* Count the number of additional columns needed to create a
2157 ** covering index. A "covering index" is an index that contains all
2158 ** columns that are needed by the query. With a covering index, the
2159 ** original table never needs to be accessed. Automatic indices must
2160 ** be a covering index because the index will not be updated if the
2161 ** original table changes and the index and table cannot both be used
2162 ** if they go out of sync.
2163 */
drh7699d1c2013-06-04 12:42:29 +00002164 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
drh4139c992010-04-07 14:59:45 +00002165 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
drh52ff8ea2010-04-08 14:15:56 +00002166 testcase( pTable->nCol==BMS-1 );
2167 testcase( pTable->nCol==BMS-2 );
drh4139c992010-04-07 14:59:45 +00002168 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002169 if( extraCols & MASKBIT(i) ) nColumn++;
drh4139c992010-04-07 14:59:45 +00002170 }
drh7699d1c2013-06-04 12:42:29 +00002171 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002172 nColumn += pTable->nCol - BMS + 1;
2173 }
drh7ba39a92013-05-30 17:43:19 +00002174 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
drh8b307fb2010-04-06 15:57:05 +00002175
2176 /* Construct the Index object to describe this index */
2177 nByte = sizeof(Index);
2178 nByte += nColumn*sizeof(int); /* Index.aiColumn */
2179 nByte += nColumn*sizeof(char*); /* Index.azColl */
2180 nByte += nColumn; /* Index.aSortOrder */
2181 pIdx = sqlite3DbMallocZero(pParse->db, nByte);
2182 if( pIdx==0 ) return;
drh7ba39a92013-05-30 17:43:19 +00002183 pLoop->u.btree.pIndex = pIdx;
drh8b307fb2010-04-06 15:57:05 +00002184 pIdx->azColl = (char**)&pIdx[1];
2185 pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
2186 pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
2187 pIdx->zName = "auto-index";
2188 pIdx->nColumn = nColumn;
drh424aab82010-04-06 18:28:20 +00002189 pIdx->pTable = pTable;
drh8b307fb2010-04-06 15:57:05 +00002190 n = 0;
drh0013e722010-04-08 00:40:15 +00002191 idxCols = 0;
drh8b307fb2010-04-06 15:57:05 +00002192 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
drh4139c992010-04-07 14:59:45 +00002193 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
drh0013e722010-04-08 00:40:15 +00002194 int iCol = pTerm->u.leftColumn;
drh7699d1c2013-06-04 12:42:29 +00002195 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
drh7963b0e2013-06-17 21:37:40 +00002196 testcase( iCol==BMS-1 );
2197 testcase( iCol==BMS );
drh0013e722010-04-08 00:40:15 +00002198 if( (idxCols & cMask)==0 ){
2199 Expr *pX = pTerm->pExpr;
2200 idxCols |= cMask;
2201 pIdx->aiColumn[n] = pTerm->u.leftColumn;
2202 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
drh6f2e6c02011-02-17 13:33:15 +00002203 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
drh0013e722010-04-08 00:40:15 +00002204 n++;
2205 }
drh8b307fb2010-04-06 15:57:05 +00002206 }
2207 }
drh7ba39a92013-05-30 17:43:19 +00002208 assert( (u32)n==pLoop->u.btree.nEq );
drh4139c992010-04-07 14:59:45 +00002209
drhc6339082010-04-07 16:54:58 +00002210 /* Add additional columns needed to make the automatic index into
2211 ** a covering index */
drh4139c992010-04-07 14:59:45 +00002212 for(i=0; i<mxBitCol; i++){
drh7699d1c2013-06-04 12:42:29 +00002213 if( extraCols & MASKBIT(i) ){
drh4139c992010-04-07 14:59:45 +00002214 pIdx->aiColumn[n] = i;
2215 pIdx->azColl[n] = "BINARY";
2216 n++;
2217 }
2218 }
drh7699d1c2013-06-04 12:42:29 +00002219 if( pSrc->colUsed & MASKBIT(BMS-1) ){
drh4139c992010-04-07 14:59:45 +00002220 for(i=BMS-1; i<pTable->nCol; i++){
2221 pIdx->aiColumn[n] = i;
2222 pIdx->azColl[n] = "BINARY";
2223 n++;
2224 }
2225 }
2226 assert( n==nColumn );
drh8b307fb2010-04-06 15:57:05 +00002227
drhc6339082010-04-07 16:54:58 +00002228 /* Create the automatic index */
drh8b307fb2010-04-06 15:57:05 +00002229 pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
2230 assert( pLevel->iIdxCur>=0 );
drha1f41242013-05-31 20:00:58 +00002231 pLevel->iIdxCur = pParse->nTab++;
drha21a64d2010-04-06 22:33:55 +00002232 sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
drh8b307fb2010-04-06 15:57:05 +00002233 (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
drha21a64d2010-04-06 22:33:55 +00002234 VdbeComment((v, "for %s", pTable->zName));
drh8b307fb2010-04-06 15:57:05 +00002235
drhc6339082010-04-07 16:54:58 +00002236 /* Fill the automatic index with content */
drh8b307fb2010-04-06 15:57:05 +00002237 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
2238 regRecord = sqlite3GetTempReg(pParse);
drhb2b9d3d2013-08-01 01:14:43 +00002239 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
drh8b307fb2010-04-06 15:57:05 +00002240 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
2241 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
2242 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
drha21a64d2010-04-06 22:33:55 +00002243 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
drh8b307fb2010-04-06 15:57:05 +00002244 sqlite3VdbeJumpHere(v, addrTop);
2245 sqlite3ReleaseTempReg(pParse, regRecord);
2246
2247 /* Jump here when skipping the initialization */
2248 sqlite3VdbeJumpHere(v, addrInit);
2249}
drhc6339082010-04-07 16:54:58 +00002250#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh8b307fb2010-04-06 15:57:05 +00002251
drh9eff6162006-06-12 21:59:13 +00002252#ifndef SQLITE_OMIT_VIRTUALTABLE
2253/*
danielk19771d461462009-04-21 09:02:45 +00002254** Allocate and populate an sqlite3_index_info structure. It is the
2255** responsibility of the caller to eventually release the structure
2256** by passing the pointer returned by this function to sqlite3_free().
2257*/
drh5346e952013-05-08 14:14:26 +00002258static sqlite3_index_info *allocateIndexInfo(
2259 Parse *pParse,
2260 WhereClause *pWC,
2261 struct SrcList_item *pSrc,
2262 ExprList *pOrderBy
2263){
danielk19771d461462009-04-21 09:02:45 +00002264 int i, j;
2265 int nTerm;
2266 struct sqlite3_index_constraint *pIdxCons;
2267 struct sqlite3_index_orderby *pIdxOrderBy;
2268 struct sqlite3_index_constraint_usage *pUsage;
2269 WhereTerm *pTerm;
2270 int nOrderBy;
2271 sqlite3_index_info *pIdxInfo;
2272
danielk19771d461462009-04-21 09:02:45 +00002273 /* Count the number of possible WHERE clause constraints referring
2274 ** to this virtual table */
2275 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
2276 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002277 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2278 testcase( pTerm->eOperator & WO_IN );
2279 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002280 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002281 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002282 nTerm++;
2283 }
2284
2285 /* If the ORDER BY clause contains only columns in the current
2286 ** virtual table then allocate space for the aOrderBy part of
2287 ** the sqlite3_index_info structure.
2288 */
2289 nOrderBy = 0;
2290 if( pOrderBy ){
drh56f1b992012-09-25 14:29:39 +00002291 int n = pOrderBy->nExpr;
2292 for(i=0; i<n; i++){
danielk19771d461462009-04-21 09:02:45 +00002293 Expr *pExpr = pOrderBy->a[i].pExpr;
2294 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
2295 }
drh56f1b992012-09-25 14:29:39 +00002296 if( i==n){
2297 nOrderBy = n;
danielk19771d461462009-04-21 09:02:45 +00002298 }
2299 }
2300
2301 /* Allocate the sqlite3_index_info structure
2302 */
2303 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
2304 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
2305 + sizeof(*pIdxOrderBy)*nOrderBy );
2306 if( pIdxInfo==0 ){
2307 sqlite3ErrorMsg(pParse, "out of memory");
danielk19771d461462009-04-21 09:02:45 +00002308 return 0;
2309 }
2310
2311 /* Initialize the structure. The sqlite3_index_info structure contains
2312 ** many fields that are declared "const" to prevent xBestIndex from
2313 ** changing them. We have to do some funky casting in order to
2314 ** initialize those fields.
2315 */
2316 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
2317 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
2318 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
2319 *(int*)&pIdxInfo->nConstraint = nTerm;
2320 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
2321 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
2322 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
2323 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
2324 pUsage;
2325
2326 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
drh281bbe22012-10-16 23:17:14 +00002327 u8 op;
danielk19771d461462009-04-21 09:02:45 +00002328 if( pTerm->leftCursor != pSrc->iCursor ) continue;
drh7a5bcc02013-01-16 17:08:58 +00002329 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
2330 testcase( pTerm->eOperator & WO_IN );
2331 testcase( pTerm->eOperator & WO_ISNULL );
drh281bbe22012-10-16 23:17:14 +00002332 if( pTerm->eOperator & (WO_ISNULL) ) continue;
drhb4256992011-08-02 01:57:39 +00002333 if( pTerm->wtFlags & TERM_VNULL ) continue;
danielk19771d461462009-04-21 09:02:45 +00002334 pIdxCons[j].iColumn = pTerm->u.leftColumn;
2335 pIdxCons[j].iTermOffset = i;
drh7a5bcc02013-01-16 17:08:58 +00002336 op = (u8)pTerm->eOperator & WO_ALL;
drh281bbe22012-10-16 23:17:14 +00002337 if( op==WO_IN ) op = WO_EQ;
2338 pIdxCons[j].op = op;
danielk19771d461462009-04-21 09:02:45 +00002339 /* The direct assignment in the previous line is possible only because
2340 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
2341 ** following asserts verify this fact. */
2342 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
2343 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
2344 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
2345 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
2346 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
2347 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
drh281bbe22012-10-16 23:17:14 +00002348 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
danielk19771d461462009-04-21 09:02:45 +00002349 j++;
2350 }
2351 for(i=0; i<nOrderBy; i++){
2352 Expr *pExpr = pOrderBy->a[i].pExpr;
2353 pIdxOrderBy[i].iColumn = pExpr->iColumn;
2354 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
2355 }
2356
2357 return pIdxInfo;
2358}
2359
2360/*
2361** The table object reference passed as the second argument to this function
2362** must represent a virtual table. This function invokes the xBestIndex()
drh3b48e8c2013-06-12 20:18:16 +00002363** method of the virtual table with the sqlite3_index_info object that
2364** comes in as the 3rd argument to this function.
danielk19771d461462009-04-21 09:02:45 +00002365**
2366** If an error occurs, pParse is populated with an error message and a
2367** non-zero value is returned. Otherwise, 0 is returned and the output
2368** part of the sqlite3_index_info structure is left populated.
2369**
2370** Whether or not an error is returned, it is the responsibility of the
2371** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
2372** that this is required.
2373*/
2374static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
danielk1977595a5232009-07-24 17:58:53 +00002375 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
danielk19771d461462009-04-21 09:02:45 +00002376 int i;
2377 int rc;
2378
danielk19771d461462009-04-21 09:02:45 +00002379 TRACE_IDX_INPUTS(p);
2380 rc = pVtab->pModule->xBestIndex(pVtab, p);
2381 TRACE_IDX_OUTPUTS(p);
danielk19771d461462009-04-21 09:02:45 +00002382
2383 if( rc!=SQLITE_OK ){
2384 if( rc==SQLITE_NOMEM ){
2385 pParse->db->mallocFailed = 1;
2386 }else if( !pVtab->zErrMsg ){
2387 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
2388 }else{
2389 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
2390 }
2391 }
drhb9755982010-07-24 16:34:37 +00002392 sqlite3_free(pVtab->zErrMsg);
danielk19771d461462009-04-21 09:02:45 +00002393 pVtab->zErrMsg = 0;
2394
2395 for(i=0; i<p->nConstraint; i++){
2396 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
2397 sqlite3ErrorMsg(pParse,
2398 "table %s: xBestIndex returned an invalid plan", pTab->zName);
2399 }
2400 }
2401
2402 return pParse->nErr;
2403}
drh7ba39a92013-05-30 17:43:19 +00002404#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
danielk19771d461462009-04-21 09:02:45 +00002405
2406
drh1435a9a2013-08-27 23:15:44 +00002407#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh28c4cf42005-07-27 20:41:43 +00002408/*
drhfaacf172011-08-12 01:51:45 +00002409** Estimate the location of a particular key among all keys in an
2410** index. Store the results in aStat as follows:
drhe847d322011-01-20 02:56:37 +00002411**
drhfaacf172011-08-12 01:51:45 +00002412** aStat[0] Est. number of rows less than pVal
2413** aStat[1] Est. number of rows equal to pVal
dan02fa4692009-08-17 17:06:58 +00002414**
drhfaacf172011-08-12 01:51:45 +00002415** Return SQLITE_OK on success.
dan02fa4692009-08-17 17:06:58 +00002416*/
danb3c02e22013-08-08 19:38:40 +00002417static void whereKeyStats(
dan02fa4692009-08-17 17:06:58 +00002418 Parse *pParse, /* Database connection */
2419 Index *pIdx, /* Index to consider domain of */
dan7a419232013-08-06 20:01:43 +00002420 UnpackedRecord *pRec, /* Vector of values to consider */
drhfaacf172011-08-12 01:51:45 +00002421 int roundUp, /* Round up if true. Round down if false */
2422 tRowcnt *aStat /* OUT: stats written here */
dan02fa4692009-08-17 17:06:58 +00002423){
danf52bb8d2013-08-03 20:24:58 +00002424 IndexSample *aSample = pIdx->aSample;
drhfbc38de2013-09-03 19:26:22 +00002425 int iCol; /* Index of required stats in anEq[] etc. */
dan84c309b2013-08-08 16:17:12 +00002426 int iMin = 0; /* Smallest sample not yet tested */
2427 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
2428 int iTest; /* Next sample to test */
2429 int res; /* Result of comparison operation */
dan02fa4692009-08-17 17:06:58 +00002430
drhfbc38de2013-09-03 19:26:22 +00002431 assert( pRec!=0 || pParse->db->mallocFailed );
2432 if( pRec==0 ) return;
2433 iCol = pRec->nField - 1;
drh5c624862011-09-22 18:46:34 +00002434 assert( pIdx->nSample>0 );
dan8ad169a2013-08-12 20:14:04 +00002435 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
dan84c309b2013-08-08 16:17:12 +00002436 do{
2437 iTest = (iMin+i)/2;
2438 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
2439 if( res<0 ){
2440 iMin = iTest+1;
2441 }else{
2442 i = iTest;
dan02fa4692009-08-17 17:06:58 +00002443 }
dan84c309b2013-08-08 16:17:12 +00002444 }while( res && iMin<i );
drh51147ba2005-07-23 22:59:55 +00002445
dan84c309b2013-08-08 16:17:12 +00002446#ifdef SQLITE_DEBUG
2447 /* The following assert statements check that the binary search code
2448 ** above found the right answer. This block serves no purpose other
2449 ** than to invoke the asserts. */
2450 if( res==0 ){
2451 /* If (res==0) is true, then sample $i must be equal to pRec */
2452 assert( i<pIdx->nSample );
drh0e1f0022013-08-16 14:49:00 +00002453 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
2454 || pParse->db->mallocFailed );
dan02fa4692009-08-17 17:06:58 +00002455 }else{
dan84c309b2013-08-08 16:17:12 +00002456 /* Otherwise, pRec must be smaller than sample $i and larger than
2457 ** sample ($i-1). */
2458 assert( i==pIdx->nSample
drh0e1f0022013-08-16 14:49:00 +00002459 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
2460 || pParse->db->mallocFailed );
dan84c309b2013-08-08 16:17:12 +00002461 assert( i==0
drh0e1f0022013-08-16 14:49:00 +00002462 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
2463 || pParse->db->mallocFailed );
drhfaacf172011-08-12 01:51:45 +00002464 }
dan84c309b2013-08-08 16:17:12 +00002465#endif /* ifdef SQLITE_DEBUG */
dan02fa4692009-08-17 17:06:58 +00002466
drhfaacf172011-08-12 01:51:45 +00002467 /* At this point, aSample[i] is the first sample that is greater than
2468 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
dan84c309b2013-08-08 16:17:12 +00002469 ** than pVal. If aSample[i]==pVal, then res==0.
drhfaacf172011-08-12 01:51:45 +00002470 */
dan84c309b2013-08-08 16:17:12 +00002471 if( res==0 ){
daneea568d2013-08-07 19:46:15 +00002472 aStat[0] = aSample[i].anLt[iCol];
2473 aStat[1] = aSample[i].anEq[iCol];
drhfaacf172011-08-12 01:51:45 +00002474 }else{
2475 tRowcnt iLower, iUpper, iGap;
2476 if( i==0 ){
2477 iLower = 0;
daneea568d2013-08-07 19:46:15 +00002478 iUpper = aSample[0].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002479 }else{
daneea568d2013-08-07 19:46:15 +00002480 iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
2481 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
drhfaacf172011-08-12 01:51:45 +00002482 }
dan568cd512013-08-12 09:29:04 +00002483 aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1);
drhfaacf172011-08-12 01:51:45 +00002484 if( iLower>=iUpper ){
2485 iGap = 0;
2486 }else{
2487 iGap = iUpper - iLower;
drhfaacf172011-08-12 01:51:45 +00002488 }
2489 if( roundUp ){
2490 iGap = (iGap*2)/3;
2491 }else{
2492 iGap = iGap/3;
2493 }
2494 aStat[0] = iLower + iGap;
dan02fa4692009-08-17 17:06:58 +00002495 }
dan02fa4692009-08-17 17:06:58 +00002496}
drh1435a9a2013-08-27 23:15:44 +00002497#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan937d0de2009-10-15 18:35:38 +00002498
2499/*
dan02fa4692009-08-17 17:06:58 +00002500** This function is used to estimate the number of rows that will be visited
2501** by scanning an index for a range of values. The range may have an upper
2502** bound, a lower bound, or both. The WHERE clause terms that set the upper
2503** and lower bounds are represented by pLower and pUpper respectively. For
2504** example, assuming that index p is on t1(a):
2505**
2506** ... FROM t1 WHERE a > ? AND a < ? ...
2507** |_____| |_____|
2508** | |
2509** pLower pUpper
2510**
drh98cdf622009-08-20 18:14:42 +00002511** If either of the upper or lower bound is not present, then NULL is passed in
drhcdaca552009-08-20 13:45:07 +00002512** place of the corresponding WhereTerm.
dan02fa4692009-08-17 17:06:58 +00002513**
dan6cb8d762013-08-08 11:48:57 +00002514** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
2515** column subject to the range constraint. Or, equivalently, the number of
2516** equality constraints optimized by the proposed index scan. For example,
2517** assuming index p is on t1(a, b), and the SQL query is:
dan02fa4692009-08-17 17:06:58 +00002518**
2519** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
2520**
dan6cb8d762013-08-08 11:48:57 +00002521** then nEq is set to 1 (as the range restricted column, b, is the second
2522** left-most column of the index). Or, if the query is:
dan02fa4692009-08-17 17:06:58 +00002523**
2524** ... FROM t1 WHERE a > ? AND a < ? ...
2525**
dan6cb8d762013-08-08 11:48:57 +00002526** then nEq is set to 0.
dan02fa4692009-08-17 17:06:58 +00002527**
dan6cb8d762013-08-08 11:48:57 +00002528** When this function is called, *pnOut is set to the whereCost() of the
2529** number of rows that the index scan is expected to visit without
2530** considering the range constraints. If nEq is 0, this is the number of
2531** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
2532** to account for the range contraints pLower and pUpper.
2533**
2534** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
2535** used, each range inequality reduces the search space by a factor of 4.
2536** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
2537** rows visited by a factor of 16.
dan02fa4692009-08-17 17:06:58 +00002538*/
2539static int whereRangeScanEst(
drhcdaca552009-08-20 13:45:07 +00002540 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002541 WhereLoopBuilder *pBuilder,
drhcdaca552009-08-20 13:45:07 +00002542 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
2543 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
dan6cb8d762013-08-08 11:48:57 +00002544 WhereCost *pnOut /* IN/OUT: Number of rows visited */
dan02fa4692009-08-17 17:06:58 +00002545){
dan69188d92009-08-19 08:18:32 +00002546 int rc = SQLITE_OK;
dan6cb8d762013-08-08 11:48:57 +00002547 int nOut = (int)*pnOut;
dan69188d92009-08-19 08:18:32 +00002548
drh1435a9a2013-08-27 23:15:44 +00002549#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00002550 Index *p = pBuilder->pNew->u.btree.pIndex;
2551 int nEq = pBuilder->pNew->u.btree.nEq;
dan02fa4692009-08-17 17:06:58 +00002552
drh74dade22013-09-04 18:14:53 +00002553 if( p->nSample>0
2554 && nEq==pBuilder->nRecValid
dan8ad169a2013-08-12 20:14:04 +00002555 && nEq<p->nSampleCol
dan7a419232013-08-06 20:01:43 +00002556 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
2557 ){
2558 UnpackedRecord *pRec = pBuilder->pRec;
drhfaacf172011-08-12 01:51:45 +00002559 tRowcnt a[2];
dan575ab2f2013-09-02 07:16:40 +00002560 u8 aff;
drh98cdf622009-08-20 18:14:42 +00002561
danb3c02e22013-08-08 19:38:40 +00002562 /* Variable iLower will be set to the estimate of the number of rows in
2563 ** the index that are less than the lower bound of the range query. The
2564 ** lower bound being the concatenation of $P and $L, where $P is the
2565 ** key-prefix formed by the nEq values matched against the nEq left-most
2566 ** columns of the index, and $L is the value in pLower.
2567 **
2568 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
2569 ** is not a simple variable or literal value), the lower bound of the
2570 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
2571 ** if $L is available, whereKeyStats() is called for both ($P) and
2572 ** ($P:$L) and the larger of the two returned values used.
2573 **
2574 ** Similarly, iUpper is to be set to the estimate of the number of rows
2575 ** less than the upper bound of the range query. Where the upper bound
2576 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
2577 ** of iUpper are requested of whereKeyStats() and the smaller used.
2578 */
2579 tRowcnt iLower;
2580 tRowcnt iUpper;
2581
mistachkinc2cfb512013-09-04 04:04:08 +00002582 if( nEq==p->nColumn ){
2583 aff = SQLITE_AFF_INTEGER;
2584 }else{
2585 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
2586 }
danb3c02e22013-08-08 19:38:40 +00002587 /* Determine iLower and iUpper using ($P) only. */
2588 if( nEq==0 ){
2589 iLower = 0;
2590 iUpper = p->aiRowEst[0];
2591 }else{
2592 /* Note: this call could be optimized away - since the same values must
2593 ** have been requested when testing key $P in whereEqualScanEst(). */
2594 whereKeyStats(pParse, p, pRec, 0, a);
2595 iLower = a[0];
2596 iUpper = a[0] + a[1];
2597 }
2598
2599 /* If possible, improve on the iLower estimate using ($P:$L). */
dan02fa4692009-08-17 17:06:58 +00002600 if( pLower ){
dan7a419232013-08-06 20:01:43 +00002601 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002602 Expr *pExpr = pLower->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002603 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002604 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002605 if( rc==SQLITE_OK && bOk ){
2606 tRowcnt iNew;
2607 whereKeyStats(pParse, p, pRec, 0, a);
2608 iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
2609 if( iNew>iLower ) iLower = iNew;
drhfaacf172011-08-12 01:51:45 +00002610 }
dan02fa4692009-08-17 17:06:58 +00002611 }
danb3c02e22013-08-08 19:38:40 +00002612
2613 /* If possible, improve on the iUpper estimate using ($P:$U). */
2614 if( pUpper ){
dan7a419232013-08-06 20:01:43 +00002615 int bOk; /* True if value is extracted from pExpr */
dan02fa4692009-08-17 17:06:58 +00002616 Expr *pExpr = pUpper->pExpr->pRight;
drh7a5bcc02013-01-16 17:08:58 +00002617 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
dan87cd9322013-08-07 15:52:41 +00002618 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
danb3c02e22013-08-08 19:38:40 +00002619 if( rc==SQLITE_OK && bOk ){
2620 tRowcnt iNew;
2621 whereKeyStats(pParse, p, pRec, 1, a);
2622 iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
2623 if( iNew<iUpper ) iUpper = iNew;
dan02fa4692009-08-17 17:06:58 +00002624 }
2625 }
danb3c02e22013-08-08 19:38:40 +00002626
dan87cd9322013-08-07 15:52:41 +00002627 pBuilder->pRec = pRec;
drhfaacf172011-08-12 01:51:45 +00002628 if( rc==SQLITE_OK ){
dan6cb8d762013-08-08 11:48:57 +00002629 WhereCost nNew;
drhb8a8e8a2013-06-10 19:12:39 +00002630 if( iUpper>iLower ){
dan6cb8d762013-08-08 11:48:57 +00002631 nNew = whereCost(iUpper - iLower);
dan7a419232013-08-06 20:01:43 +00002632 }else{
danb3c02e22013-08-08 19:38:40 +00002633 nNew = 10; assert( 10==whereCost(2) );
drhfaacf172011-08-12 01:51:45 +00002634 }
dan6cb8d762013-08-08 11:48:57 +00002635 if( nNew<nOut ){
2636 nOut = nNew;
2637 }
2638 *pnOut = (WhereCost)nOut;
2639 WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
2640 (u32)iLower, (u32)iUpper, nOut));
drhfaacf172011-08-12 01:51:45 +00002641 return SQLITE_OK;
drh98cdf622009-08-20 18:14:42 +00002642 }
dan02fa4692009-08-17 17:06:58 +00002643 }
drh3f022182009-09-09 16:10:50 +00002644#else
2645 UNUSED_PARAMETER(pParse);
dan7a419232013-08-06 20:01:43 +00002646 UNUSED_PARAMETER(pBuilder);
dan69188d92009-08-19 08:18:32 +00002647#endif
dan02fa4692009-08-17 17:06:58 +00002648 assert( pLower || pUpper );
drhe1e2e9a2013-06-13 15:16:53 +00002649 /* TUNING: Each inequality constraint reduces the search space 4-fold.
2650 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
drhb8a8e8a2013-06-10 19:12:39 +00002651 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
dan6cb8d762013-08-08 11:48:57 +00002652 nOut -= 20; assert( 20==whereCost(4) );
drhb8a8e8a2013-06-10 19:12:39 +00002653 }
2654 if( pUpper ){
dan6cb8d762013-08-08 11:48:57 +00002655 nOut -= 20; assert( 20==whereCost(4) );
drhb8a8e8a2013-06-10 19:12:39 +00002656 }
dan6cb8d762013-08-08 11:48:57 +00002657 if( nOut<10 ) nOut = 10;
2658 *pnOut = (WhereCost)nOut;
dan02fa4692009-08-17 17:06:58 +00002659 return rc;
2660}
2661
drh1435a9a2013-08-27 23:15:44 +00002662#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh82759752011-01-20 16:52:09 +00002663/*
2664** Estimate the number of rows that will be returned based on
2665** an equality constraint x=VALUE and where that VALUE occurs in
2666** the histogram data. This only works when x is the left-most
drhfaacf172011-08-12 01:51:45 +00002667** column of an index and sqlite_stat3 histogram data is available
drhac8eb112011-03-17 01:58:21 +00002668** for that index. When pExpr==NULL that means the constraint is
2669** "x IS NULL" instead of "x=VALUE".
drh82759752011-01-20 16:52:09 +00002670**
drh0c50fa02011-01-21 16:27:18 +00002671** Write the estimated row count into *pnRow and return SQLITE_OK.
2672** If unable to make an estimate, leave *pnRow unchanged and return
2673** non-zero.
drh9b3eb0a2011-01-21 14:37:04 +00002674**
2675** This routine can fail if it is unable to load a collating sequence
2676** required for string comparison, or if unable to allocate memory
2677** for a UTF conversion required for comparison. The error is stored
2678** in the pParse structure.
drh82759752011-01-20 16:52:09 +00002679*/
drh041e09f2011-04-07 19:56:21 +00002680static int whereEqualScanEst(
drh82759752011-01-20 16:52:09 +00002681 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002682 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002683 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
drhb8a8e8a2013-06-10 19:12:39 +00002684 tRowcnt *pnRow /* Write the revised row estimate here */
drh82759752011-01-20 16:52:09 +00002685){
dan7a419232013-08-06 20:01:43 +00002686 Index *p = pBuilder->pNew->u.btree.pIndex;
2687 int nEq = pBuilder->pNew->u.btree.nEq;
2688 UnpackedRecord *pRec = pBuilder->pRec;
drh82759752011-01-20 16:52:09 +00002689 u8 aff; /* Column affinity */
2690 int rc; /* Subfunction return code */
drhfaacf172011-08-12 01:51:45 +00002691 tRowcnt a[2]; /* Statistics */
dan7a419232013-08-06 20:01:43 +00002692 int bOk;
drh82759752011-01-20 16:52:09 +00002693
dan7a419232013-08-06 20:01:43 +00002694 assert( nEq>=1 );
2695 assert( nEq<=(p->nColumn+1) );
drh82759752011-01-20 16:52:09 +00002696 assert( p->aSample!=0 );
drh5c624862011-09-22 18:46:34 +00002697 assert( p->nSample>0 );
dan7a419232013-08-06 20:01:43 +00002698 assert( pBuilder->nRecValid<nEq );
2699
2700 /* If values are not available for all fields of the index to the left
2701 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
2702 if( pBuilder->nRecValid<(nEq-1) ){
2703 return SQLITE_NOTFOUND;
drh1f9c7662011-03-17 01:34:26 +00002704 }
dan7a419232013-08-06 20:01:43 +00002705
dandd6e1f12013-08-10 19:08:30 +00002706 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2707 ** below would return the same value. */
dan7a419232013-08-06 20:01:43 +00002708 if( nEq>p->nColumn ){
2709 *pnRow = 1;
2710 return SQLITE_OK;
drh82759752011-01-20 16:52:09 +00002711 }
dan7a419232013-08-06 20:01:43 +00002712
daneea568d2013-08-07 19:46:15 +00002713 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
dan87cd9322013-08-07 15:52:41 +00002714 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
2715 pBuilder->pRec = pRec;
dan7a419232013-08-06 20:01:43 +00002716 if( rc!=SQLITE_OK ) return rc;
2717 if( bOk==0 ) return SQLITE_NOTFOUND;
dan7a419232013-08-06 20:01:43 +00002718 pBuilder->nRecValid = nEq;
dan7a419232013-08-06 20:01:43 +00002719
danb3c02e22013-08-08 19:38:40 +00002720 whereKeyStats(pParse, p, pRec, 0, a);
2721 WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
2722 *pnRow = a[1];
daneea568d2013-08-07 19:46:15 +00002723
drh0c50fa02011-01-21 16:27:18 +00002724 return rc;
2725}
drh1435a9a2013-08-27 23:15:44 +00002726#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh0c50fa02011-01-21 16:27:18 +00002727
drh1435a9a2013-08-27 23:15:44 +00002728#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh0c50fa02011-01-21 16:27:18 +00002729/*
2730** Estimate the number of rows that will be returned based on
drh5ac06072011-01-21 18:18:13 +00002731** an IN constraint where the right-hand side of the IN operator
2732** is a list of values. Example:
2733**
2734** WHERE x IN (1,2,3,4)
drh0c50fa02011-01-21 16:27:18 +00002735**
2736** Write the estimated row count into *pnRow and return SQLITE_OK.
2737** If unable to make an estimate, leave *pnRow unchanged and return
2738** non-zero.
2739**
2740** This routine can fail if it is unable to load a collating sequence
2741** required for string comparison, or if unable to allocate memory
2742** for a UTF conversion required for comparison. The error is stored
2743** in the pParse structure.
2744*/
drh041e09f2011-04-07 19:56:21 +00002745static int whereInScanEst(
drh0c50fa02011-01-21 16:27:18 +00002746 Parse *pParse, /* Parsing & code generating context */
dan7a419232013-08-06 20:01:43 +00002747 WhereLoopBuilder *pBuilder,
drh0c50fa02011-01-21 16:27:18 +00002748 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
drhb8a8e8a2013-06-10 19:12:39 +00002749 tRowcnt *pnRow /* Write the revised row estimate here */
drh0c50fa02011-01-21 16:27:18 +00002750){
dan7a419232013-08-06 20:01:43 +00002751 Index *p = pBuilder->pNew->u.btree.pIndex;
2752 int nRecValid = pBuilder->nRecValid;
drhb8a8e8a2013-06-10 19:12:39 +00002753 int rc = SQLITE_OK; /* Subfunction return code */
2754 tRowcnt nEst; /* Number of rows for a single term */
2755 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
2756 int i; /* Loop counter */
drh0c50fa02011-01-21 16:27:18 +00002757
2758 assert( p->aSample!=0 );
drhfaacf172011-08-12 01:51:45 +00002759 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2760 nEst = p->aiRowEst[0];
dan7a419232013-08-06 20:01:43 +00002761 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
drhfaacf172011-08-12 01:51:45 +00002762 nRowEst += nEst;
dan7a419232013-08-06 20:01:43 +00002763 pBuilder->nRecValid = nRecValid;
drh0c50fa02011-01-21 16:27:18 +00002764 }
dan7a419232013-08-06 20:01:43 +00002765
drh0c50fa02011-01-21 16:27:18 +00002766 if( rc==SQLITE_OK ){
drh0c50fa02011-01-21 16:27:18 +00002767 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
2768 *pnRow = nRowEst;
drh3b48e8c2013-06-12 20:18:16 +00002769 WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
drh0c50fa02011-01-21 16:27:18 +00002770 }
dan7a419232013-08-06 20:01:43 +00002771 assert( pBuilder->nRecValid==nRecValid );
drh0c50fa02011-01-21 16:27:18 +00002772 return rc;
drh82759752011-01-20 16:52:09 +00002773}
drh1435a9a2013-08-27 23:15:44 +00002774#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh82759752011-01-20 16:52:09 +00002775
drh46c35f92012-09-26 23:17:01 +00002776/*
drh2ffb1182004-07-19 19:14:01 +00002777** Disable a term in the WHERE clause. Except, do not disable the term
2778** if it controls a LEFT OUTER JOIN and it did not originate in the ON
2779** or USING clause of that join.
2780**
2781** Consider the term t2.z='ok' in the following queries:
2782**
2783** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
2784** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
2785** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
2786**
drh23bf66d2004-12-14 03:34:34 +00002787** The t2.z='ok' is disabled in the in (2) because it originates
drh2ffb1182004-07-19 19:14:01 +00002788** in the ON clause. The term is disabled in (3) because it is not part
2789** of a LEFT OUTER JOIN. In (1), the term is not disabled.
2790**
2791** Disabling a term causes that term to not be tested in the inner loop
drhb6fb62d2005-09-20 08:47:20 +00002792** of the join. Disabling is an optimization. When terms are satisfied
2793** by indices, we disable them to prevent redundant tests in the inner
2794** loop. We would get the correct results if nothing were ever disabled,
2795** but joins might run a little slower. The trick is to disable as much
2796** as we can without disabling too much. If we disabled in (1), we'd get
2797** the wrong answer. See ticket #813.
drh2ffb1182004-07-19 19:14:01 +00002798*/
drh0fcef5e2005-07-19 17:38:22 +00002799static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
2800 if( pTerm
drhbe837bd2010-04-30 21:03:24 +00002801 && (pTerm->wtFlags & TERM_CODED)==0
drh0fcef5e2005-07-19 17:38:22 +00002802 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
drh0259bc32013-09-09 19:37:46 +00002803 && (pLevel->notReady & pTerm->prereqAll)==0
drh0fcef5e2005-07-19 17:38:22 +00002804 ){
drh165be382008-12-05 02:36:33 +00002805 pTerm->wtFlags |= TERM_CODED;
drh45b1ee42005-08-02 17:48:22 +00002806 if( pTerm->iParent>=0 ){
2807 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
2808 if( (--pOther->nChild)==0 ){
drhed378002005-07-28 23:12:08 +00002809 disableTerm(pLevel, pOther);
2810 }
drh0fcef5e2005-07-19 17:38:22 +00002811 }
drh2ffb1182004-07-19 19:14:01 +00002812 }
2813}
2814
2815/*
dan69f8bb92009-08-13 19:21:16 +00002816** Code an OP_Affinity opcode to apply the column affinity string zAff
2817** to the n registers starting at base.
2818**
drh039fc322009-11-17 18:31:47 +00002819** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
2820** beginning and end of zAff are ignored. If all entries in zAff are
2821** SQLITE_AFF_NONE, then no code gets generated.
2822**
2823** This routine makes its own copy of zAff so that the caller is free
2824** to modify zAff after this routine returns.
drh94a11212004-09-25 13:12:14 +00002825*/
dan69f8bb92009-08-13 19:21:16 +00002826static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
2827 Vdbe *v = pParse->pVdbe;
drh039fc322009-11-17 18:31:47 +00002828 if( zAff==0 ){
2829 assert( pParse->db->mallocFailed );
2830 return;
2831 }
dan69f8bb92009-08-13 19:21:16 +00002832 assert( v!=0 );
drh039fc322009-11-17 18:31:47 +00002833
2834 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
2835 ** and end of the affinity string.
2836 */
2837 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
2838 n--;
2839 base++;
2840 zAff++;
2841 }
2842 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
2843 n--;
2844 }
2845
2846 /* Code the OP_Affinity opcode if there is anything left to do. */
2847 if( n>0 ){
2848 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
2849 sqlite3VdbeChangeP4(v, -1, zAff, n);
2850 sqlite3ExprCacheAffinityChange(pParse, base, n);
2851 }
drh94a11212004-09-25 13:12:14 +00002852}
2853
drhe8b97272005-07-19 22:22:12 +00002854
2855/*
drh51147ba2005-07-23 22:59:55 +00002856** Generate code for a single equality term of the WHERE clause. An equality
2857** term can be either X=expr or X IN (...). pTerm is the term to be
2858** coded.
2859**
drh1db639c2008-01-17 02:36:28 +00002860** The current value for the constraint is left in register iReg.
drh51147ba2005-07-23 22:59:55 +00002861**
2862** For a constraint of the form X=expr, the expression is evaluated and its
2863** result is left on the stack. For constraints of the form X IN (...)
2864** this routine sets up a loop that will iterate over all values of X.
drh94a11212004-09-25 13:12:14 +00002865*/
drh678ccce2008-03-31 18:19:54 +00002866static int codeEqualityTerm(
drh94a11212004-09-25 13:12:14 +00002867 Parse *pParse, /* The parsing context */
drhe23399f2005-07-22 00:31:39 +00002868 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
drh0fe456b2013-03-12 18:34:50 +00002869 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
2870 int iEq, /* Index of the equality term within this level */
drh7ba39a92013-05-30 17:43:19 +00002871 int bRev, /* True for reverse-order IN operations */
drh678ccce2008-03-31 18:19:54 +00002872 int iTarget /* Attempt to leave results in this register */
drh94a11212004-09-25 13:12:14 +00002873){
drh0fcef5e2005-07-19 17:38:22 +00002874 Expr *pX = pTerm->pExpr;
drh50b39962006-10-28 00:28:09 +00002875 Vdbe *v = pParse->pVdbe;
drh678ccce2008-03-31 18:19:54 +00002876 int iReg; /* Register holding results */
drh1db639c2008-01-17 02:36:28 +00002877
danielk19772d605492008-10-01 08:43:03 +00002878 assert( iTarget>0 );
drh50b39962006-10-28 00:28:09 +00002879 if( pX->op==TK_EQ ){
drh678ccce2008-03-31 18:19:54 +00002880 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
drh50b39962006-10-28 00:28:09 +00002881 }else if( pX->op==TK_ISNULL ){
drh678ccce2008-03-31 18:19:54 +00002882 iReg = iTarget;
drh1db639c2008-01-17 02:36:28 +00002883 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
danielk1977b3bce662005-01-29 08:32:43 +00002884#ifndef SQLITE_OMIT_SUBQUERY
drh94a11212004-09-25 13:12:14 +00002885 }else{
danielk19779a96b662007-11-29 17:05:18 +00002886 int eType;
danielk1977b3bce662005-01-29 08:32:43 +00002887 int iTab;
drh72e8fa42007-03-28 14:30:06 +00002888 struct InLoop *pIn;
drh7ba39a92013-05-30 17:43:19 +00002889 WhereLoop *pLoop = pLevel->pWLoop;
danielk1977b3bce662005-01-29 08:32:43 +00002890
drh7ba39a92013-05-30 17:43:19 +00002891 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
2892 && pLoop->u.btree.pIndex!=0
2893 && pLoop->u.btree.pIndex->aSortOrder[iEq]
drhd3832162013-03-12 18:49:25 +00002894 ){
drh725e1ae2013-03-12 23:58:42 +00002895 testcase( iEq==0 );
drh725e1ae2013-03-12 23:58:42 +00002896 testcase( bRev );
drh1ccce442013-03-12 20:38:51 +00002897 bRev = !bRev;
drh0fe456b2013-03-12 18:34:50 +00002898 }
drh50b39962006-10-28 00:28:09 +00002899 assert( pX->op==TK_IN );
drh678ccce2008-03-31 18:19:54 +00002900 iReg = iTarget;
danielk19770cdc0222008-06-26 18:04:03 +00002901 eType = sqlite3FindInIndex(pParse, pX, 0);
drh725e1ae2013-03-12 23:58:42 +00002902 if( eType==IN_INDEX_INDEX_DESC ){
2903 testcase( bRev );
2904 bRev = !bRev;
2905 }
danielk1977b3bce662005-01-29 08:32:43 +00002906 iTab = pX->iTable;
drh2d96b932013-02-08 18:48:23 +00002907 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
drh6fa978d2013-05-30 19:29:19 +00002908 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
2909 pLoop->wsFlags |= WHERE_IN_ABLE;
drh111a6a72008-12-21 03:51:16 +00002910 if( pLevel->u.in.nIn==0 ){
drhb3190c12008-12-08 21:37:14 +00002911 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
drh72e8fa42007-03-28 14:30:06 +00002912 }
drh111a6a72008-12-21 03:51:16 +00002913 pLevel->u.in.nIn++;
2914 pLevel->u.in.aInLoop =
2915 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
2916 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
2917 pIn = pLevel->u.in.aInLoop;
drh72e8fa42007-03-28 14:30:06 +00002918 if( pIn ){
drh111a6a72008-12-21 03:51:16 +00002919 pIn += pLevel->u.in.nIn - 1;
drh72e8fa42007-03-28 14:30:06 +00002920 pIn->iCur = iTab;
drh1db639c2008-01-17 02:36:28 +00002921 if( eType==IN_INDEX_ROWID ){
drhb3190c12008-12-08 21:37:14 +00002922 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
drh1db639c2008-01-17 02:36:28 +00002923 }else{
drhb3190c12008-12-08 21:37:14 +00002924 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
drh1db639c2008-01-17 02:36:28 +00002925 }
drh2d96b932013-02-08 18:48:23 +00002926 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
drh1db639c2008-01-17 02:36:28 +00002927 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
drha6110402005-07-28 20:51:19 +00002928 }else{
drh111a6a72008-12-21 03:51:16 +00002929 pLevel->u.in.nIn = 0;
drhe23399f2005-07-22 00:31:39 +00002930 }
danielk1977b3bce662005-01-29 08:32:43 +00002931#endif
drh94a11212004-09-25 13:12:14 +00002932 }
drh0fcef5e2005-07-19 17:38:22 +00002933 disableTerm(pLevel, pTerm);
drh678ccce2008-03-31 18:19:54 +00002934 return iReg;
drh94a11212004-09-25 13:12:14 +00002935}
2936
drh51147ba2005-07-23 22:59:55 +00002937/*
2938** Generate code that will evaluate all == and IN constraints for an
drh039fc322009-11-17 18:31:47 +00002939** index.
drh51147ba2005-07-23 22:59:55 +00002940**
2941** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
2942** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
2943** The index has as many as three equality constraints, but in this
2944** example, the third "c" value is an inequality. So only two
2945** constraints are coded. This routine will generate code to evaluate
drh6df2acd2008-12-28 16:55:25 +00002946** a==5 and b IN (1,2,3). The current values for a and b will be stored
2947** in consecutive registers and the index of the first register is returned.
drh51147ba2005-07-23 22:59:55 +00002948**
2949** In the example above nEq==2. But this subroutine works for any value
2950** of nEq including 0. If nEq==0, this routine is nearly a no-op.
drh039fc322009-11-17 18:31:47 +00002951** The only thing it does is allocate the pLevel->iMem memory cell and
2952** compute the affinity string.
drh51147ba2005-07-23 22:59:55 +00002953**
drh700a2262008-12-17 19:22:15 +00002954** This routine always allocates at least one memory cell and returns
2955** the index of that memory cell. The code that
2956** calls this routine will use that memory cell to store the termination
drh51147ba2005-07-23 22:59:55 +00002957** key value of the loop. If one or more IN operators appear, then
2958** this routine allocates an additional nEq memory cells for internal
2959** use.
dan69f8bb92009-08-13 19:21:16 +00002960**
2961** Before returning, *pzAff is set to point to a buffer containing a
2962** copy of the column affinity string of the index allocated using
2963** sqlite3DbMalloc(). Except, entries in the copy of the string associated
2964** with equality constraints that use NONE affinity are set to
2965** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
2966**
2967** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
2968** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
2969**
2970** In the example above, the index on t1(a) has TEXT affinity. But since
2971** the right hand side of the equality constraint (t2.b) has NONE affinity,
2972** no conversion should be attempted before using a t2.b value as part of
2973** a key to search the index. Hence the first byte in the returned affinity
2974** string in this example would be set to SQLITE_AFF_NONE.
drh51147ba2005-07-23 22:59:55 +00002975*/
drh1db639c2008-01-17 02:36:28 +00002976static int codeAllEqualityTerms(
drh51147ba2005-07-23 22:59:55 +00002977 Parse *pParse, /* Parsing context */
2978 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
drh7ba39a92013-05-30 17:43:19 +00002979 int bRev, /* Reverse the order of IN operators */
dan69f8bb92009-08-13 19:21:16 +00002980 int nExtraReg, /* Number of extra registers to allocate */
2981 char **pzAff /* OUT: Set to point to affinity string */
drh51147ba2005-07-23 22:59:55 +00002982){
drh7ba39a92013-05-30 17:43:19 +00002983 int nEq; /* The number of == or IN constraints to code */
drh111a6a72008-12-21 03:51:16 +00002984 Vdbe *v = pParse->pVdbe; /* The vm under construction */
2985 Index *pIdx; /* The index being used for this loop */
drh51147ba2005-07-23 22:59:55 +00002986 WhereTerm *pTerm; /* A single constraint term */
drh7ba39a92013-05-30 17:43:19 +00002987 WhereLoop *pLoop; /* The WhereLoop object */
drh51147ba2005-07-23 22:59:55 +00002988 int j; /* Loop counter */
drh1db639c2008-01-17 02:36:28 +00002989 int regBase; /* Base register */
drh6df2acd2008-12-28 16:55:25 +00002990 int nReg; /* Number of registers to allocate */
dan69f8bb92009-08-13 19:21:16 +00002991 char *zAff; /* Affinity string to return */
drh51147ba2005-07-23 22:59:55 +00002992
drh111a6a72008-12-21 03:51:16 +00002993 /* This module is only called on query plans that use an index. */
drh7ba39a92013-05-30 17:43:19 +00002994 pLoop = pLevel->pWLoop;
2995 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
2996 nEq = pLoop->u.btree.nEq;
2997 pIdx = pLoop->u.btree.pIndex;
2998 assert( pIdx!=0 );
drh111a6a72008-12-21 03:51:16 +00002999
drh51147ba2005-07-23 22:59:55 +00003000 /* Figure out how many memory cells we will need then allocate them.
drh51147ba2005-07-23 22:59:55 +00003001 */
drh700a2262008-12-17 19:22:15 +00003002 regBase = pParse->nMem + 1;
drh7ba39a92013-05-30 17:43:19 +00003003 nReg = pLoop->u.btree.nEq + nExtraReg;
drh6df2acd2008-12-28 16:55:25 +00003004 pParse->nMem += nReg;
drh51147ba2005-07-23 22:59:55 +00003005
dan69f8bb92009-08-13 19:21:16 +00003006 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
3007 if( !zAff ){
3008 pParse->db->mallocFailed = 1;
3009 }
3010
drh51147ba2005-07-23 22:59:55 +00003011 /* Evaluate the equality constraints
3012 */
mistachkinf6418892013-08-28 01:54:12 +00003013 assert( zAff==0 || (int)strlen(zAff)>=nEq );
drhc49de5d2007-01-19 01:06:01 +00003014 for(j=0; j<nEq; j++){
drh678ccce2008-03-31 18:19:54 +00003015 int r1;
drh4efc9292013-06-06 23:02:03 +00003016 pTerm = pLoop->aLTerm[j];
drh7ba39a92013-05-30 17:43:19 +00003017 assert( pTerm!=0 );
drhbe837bd2010-04-30 21:03:24 +00003018 /* The following true for indices with redundant columns.
3019 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
3020 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
drh39759742013-08-02 23:40:45 +00003021 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00003022 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
drh678ccce2008-03-31 18:19:54 +00003023 if( r1!=regBase+j ){
drh6df2acd2008-12-28 16:55:25 +00003024 if( nReg==1 ){
3025 sqlite3ReleaseTempReg(pParse, regBase);
3026 regBase = r1;
3027 }else{
3028 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
3029 }
drh678ccce2008-03-31 18:19:54 +00003030 }
drh981642f2008-04-19 14:40:43 +00003031 testcase( pTerm->eOperator & WO_ISNULL );
3032 testcase( pTerm->eOperator & WO_IN );
drh72e8fa42007-03-28 14:30:06 +00003033 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
drh039fc322009-11-17 18:31:47 +00003034 Expr *pRight = pTerm->pExpr->pRight;
drh2f2855b2009-11-18 01:25:26 +00003035 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
drh039fc322009-11-17 18:31:47 +00003036 if( zAff ){
3037 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
3038 zAff[j] = SQLITE_AFF_NONE;
3039 }
3040 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
3041 zAff[j] = SQLITE_AFF_NONE;
3042 }
dan69f8bb92009-08-13 19:21:16 +00003043 }
drh51147ba2005-07-23 22:59:55 +00003044 }
3045 }
dan69f8bb92009-08-13 19:21:16 +00003046 *pzAff = zAff;
drh1db639c2008-01-17 02:36:28 +00003047 return regBase;
drh51147ba2005-07-23 22:59:55 +00003048}
3049
dan2ce22452010-11-08 19:01:16 +00003050#ifndef SQLITE_OMIT_EXPLAIN
dan17c0bc02010-11-09 17:35:19 +00003051/*
drh69174c42010-11-12 15:35:59 +00003052** This routine is a helper for explainIndexRange() below
3053**
3054** pStr holds the text of an expression that we are building up one term
3055** at a time. This routine adds a new term to the end of the expression.
3056** Terms are separated by AND so add the "AND" text for second and subsequent
3057** terms only.
3058*/
3059static void explainAppendTerm(
3060 StrAccum *pStr, /* The text expression being built */
3061 int iTerm, /* Index of this term. First is zero */
3062 const char *zColumn, /* Name of the column */
3063 const char *zOp /* Name of the operator */
3064){
3065 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
3066 sqlite3StrAccumAppend(pStr, zColumn, -1);
3067 sqlite3StrAccumAppend(pStr, zOp, 1);
3068 sqlite3StrAccumAppend(pStr, "?", 1);
3069}
3070
3071/*
dan17c0bc02010-11-09 17:35:19 +00003072** Argument pLevel describes a strategy for scanning table pTab. This
3073** function returns a pointer to a string buffer containing a description
3074** of the subset of table rows scanned by the strategy in the form of an
3075** SQL expression. Or, if all rows are scanned, NULL is returned.
3076**
3077** For example, if the query:
3078**
3079** SELECT * FROM t1 WHERE a=1 AND b>2;
3080**
3081** is run and there is an index on (a, b), then this function returns a
3082** string similar to:
3083**
3084** "a=? AND b>?"
3085**
3086** The returned pointer points to memory obtained from sqlite3DbMalloc().
3087** It is the responsibility of the caller to free the buffer when it is
3088** no longer required.
3089*/
drhef866372013-05-22 20:49:02 +00003090static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
3091 Index *pIndex = pLoop->u.btree.pIndex;
3092 int nEq = pLoop->u.btree.nEq;
drh69174c42010-11-12 15:35:59 +00003093 int i, j;
3094 Column *aCol = pTab->aCol;
3095 int *aiColumn = pIndex->aiColumn;
3096 StrAccum txt;
dan2ce22452010-11-08 19:01:16 +00003097
drhef866372013-05-22 20:49:02 +00003098 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
drh69174c42010-11-12 15:35:59 +00003099 return 0;
3100 }
3101 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
drh03b6df12010-11-15 16:29:30 +00003102 txt.db = db;
drh69174c42010-11-12 15:35:59 +00003103 sqlite3StrAccumAppend(&txt, " (", 2);
dan2ce22452010-11-08 19:01:16 +00003104 for(i=0; i<nEq; i++){
dane934e632013-08-20 17:14:57 +00003105 char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
3106 explainAppendTerm(&txt, i, z, "=");
dan2ce22452010-11-08 19:01:16 +00003107 }
3108
drh69174c42010-11-12 15:35:59 +00003109 j = i;
drhef866372013-05-22 20:49:02 +00003110 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00003111 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
3112 explainAppendTerm(&txt, i++, z, ">");
dan2ce22452010-11-08 19:01:16 +00003113 }
drhef866372013-05-22 20:49:02 +00003114 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
dan0c733f62011-11-16 15:27:09 +00003115 char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
3116 explainAppendTerm(&txt, i, z, "<");
dan2ce22452010-11-08 19:01:16 +00003117 }
drh69174c42010-11-12 15:35:59 +00003118 sqlite3StrAccumAppend(&txt, ")", 1);
3119 return sqlite3StrAccumFinish(&txt);
dan2ce22452010-11-08 19:01:16 +00003120}
3121
dan17c0bc02010-11-09 17:35:19 +00003122/*
3123** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
3124** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
3125** record is added to the output to describe the table scan strategy in
3126** pLevel.
3127*/
3128static void explainOneScan(
dan2ce22452010-11-08 19:01:16 +00003129 Parse *pParse, /* Parse context */
3130 SrcList *pTabList, /* Table list this loop refers to */
3131 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
3132 int iLevel, /* Value for "level" column of output */
dan4a07e3d2010-11-09 14:48:59 +00003133 int iFrom, /* Value for "from" column of output */
3134 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
dan2ce22452010-11-08 19:01:16 +00003135){
3136 if( pParse->explain==2 ){
dan2ce22452010-11-08 19:01:16 +00003137 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
dan17c0bc02010-11-09 17:35:19 +00003138 Vdbe *v = pParse->pVdbe; /* VM being constructed */
3139 sqlite3 *db = pParse->db; /* Database handle */
3140 char *zMsg; /* Text to add to EQP output */
dan4a07e3d2010-11-09 14:48:59 +00003141 int iId = pParse->iSelectId; /* Select id (left-most output column) */
dan4bc39fa2010-11-13 16:42:27 +00003142 int isSearch; /* True for a SEARCH. False for SCAN. */
drhef866372013-05-22 20:49:02 +00003143 WhereLoop *pLoop; /* The controlling WhereLoop object */
3144 u32 flags; /* Flags that describe this loop */
dan2ce22452010-11-08 19:01:16 +00003145
drhef866372013-05-22 20:49:02 +00003146 pLoop = pLevel->pWLoop;
3147 flags = pLoop->wsFlags;
dan4a07e3d2010-11-09 14:48:59 +00003148 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
dan2ce22452010-11-08 19:01:16 +00003149
drhef866372013-05-22 20:49:02 +00003150 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
3151 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
3152 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
dan4bc39fa2010-11-13 16:42:27 +00003153
3154 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
dan4a07e3d2010-11-09 14:48:59 +00003155 if( pItem->pSelect ){
dan4bc39fa2010-11-13 16:42:27 +00003156 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
dan4a07e3d2010-11-09 14:48:59 +00003157 }else{
dan4bc39fa2010-11-13 16:42:27 +00003158 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
dan4a07e3d2010-11-09 14:48:59 +00003159 }
3160
dan2ce22452010-11-08 19:01:16 +00003161 if( pItem->zAlias ){
3162 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
3163 }
drhef866372013-05-22 20:49:02 +00003164 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
drh7963b0e2013-06-17 21:37:40 +00003165 && ALWAYS(pLoop->u.btree.pIndex!=0)
drhef866372013-05-22 20:49:02 +00003166 ){
3167 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
drh986b3872013-06-28 21:12:20 +00003168 zMsg = sqlite3MAppendf(db, zMsg,
3169 ((flags & WHERE_AUTO_INDEX) ?
3170 "%s USING AUTOMATIC %sINDEX%.0s%s" :
3171 "%s USING %sINDEX %s%s"),
3172 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
3173 pLoop->u.btree.pIndex->zName, zWhere);
dan2ce22452010-11-08 19:01:16 +00003174 sqlite3DbFree(db, zWhere);
drhef71c1f2013-06-04 12:58:02 +00003175 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
dan4bc39fa2010-11-13 16:42:27 +00003176 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
dan2ce22452010-11-08 19:01:16 +00003177
drh8e23daf2013-06-11 13:30:04 +00003178 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
dan2ce22452010-11-08 19:01:16 +00003179 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
drh04098e62010-11-15 21:50:19 +00003180 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
dan2ce22452010-11-08 19:01:16 +00003181 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
3182 }else if( flags&WHERE_BTM_LIMIT ){
3183 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
drh7963b0e2013-06-17 21:37:40 +00003184 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
dan2ce22452010-11-08 19:01:16 +00003185 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
3186 }
3187 }
3188#ifndef SQLITE_OMIT_VIRTUALTABLE
3189 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
dan2ce22452010-11-08 19:01:16 +00003190 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
drhef866372013-05-22 20:49:02 +00003191 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
dan2ce22452010-11-08 19:01:16 +00003192 }
3193#endif
drhb8a8e8a2013-06-10 19:12:39 +00003194 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
dan4a07e3d2010-11-09 14:48:59 +00003195 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
dan2ce22452010-11-08 19:01:16 +00003196 }
3197}
3198#else
dan17c0bc02010-11-09 17:35:19 +00003199# define explainOneScan(u,v,w,x,y,z)
dan2ce22452010-11-08 19:01:16 +00003200#endif /* SQLITE_OMIT_EXPLAIN */
3201
3202
drh111a6a72008-12-21 03:51:16 +00003203/*
3204** Generate code for the start of the iLevel-th loop in the WHERE clause
3205** implementation described by pWInfo.
3206*/
3207static Bitmask codeOneLoopStart(
3208 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
3209 int iLevel, /* Which level of pWInfo->a[] should be coded */
drh7a484802012-03-16 00:28:11 +00003210 Bitmask notReady /* Which tables are currently available */
drh111a6a72008-12-21 03:51:16 +00003211){
3212 int j, k; /* Loop counters */
3213 int iCur; /* The VDBE cursor for the table */
3214 int addrNxt; /* Where to jump to continue with the next IN case */
3215 int omitTable; /* True if we use the index only */
3216 int bRev; /* True if we need to scan in reverse order */
3217 WhereLevel *pLevel; /* The where level to be coded */
drh7ba39a92013-05-30 17:43:19 +00003218 WhereLoop *pLoop; /* The WhereLoop object being coded */
drh111a6a72008-12-21 03:51:16 +00003219 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
3220 WhereTerm *pTerm; /* A WHERE clause term */
3221 Parse *pParse; /* Parsing context */
drh6b36e822013-07-30 15:10:32 +00003222 sqlite3 *db; /* Database connection */
drh111a6a72008-12-21 03:51:16 +00003223 Vdbe *v; /* The prepared stmt under constructions */
3224 struct SrcList_item *pTabItem; /* FROM clause term being coded */
drh23d04d52008-12-23 23:56:22 +00003225 int addrBrk; /* Jump here to break out of the loop */
3226 int addrCont; /* Jump here to continue with next cycle */
drh61495262009-04-22 15:32:59 +00003227 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
3228 int iReleaseReg = 0; /* Temp register to free before returning */
drh111a6a72008-12-21 03:51:16 +00003229
3230 pParse = pWInfo->pParse;
3231 v = pParse->pVdbe;
drh70d18342013-06-06 19:16:33 +00003232 pWC = &pWInfo->sWC;
drh6b36e822013-07-30 15:10:32 +00003233 db = pParse->db;
drh111a6a72008-12-21 03:51:16 +00003234 pLevel = &pWInfo->a[iLevel];
drh7ba39a92013-05-30 17:43:19 +00003235 pLoop = pLevel->pWLoop;
drh111a6a72008-12-21 03:51:16 +00003236 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
3237 iCur = pTabItem->iCursor;
drh0259bc32013-09-09 19:37:46 +00003238 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
drh7ba39a92013-05-30 17:43:19 +00003239 bRev = (pWInfo->revMask>>iLevel)&1;
3240 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
drh70d18342013-06-06 19:16:33 +00003241 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
drh0c41d222013-04-22 02:39:10 +00003242 VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
drh111a6a72008-12-21 03:51:16 +00003243
3244 /* Create labels for the "break" and "continue" instructions
3245 ** for the current loop. Jump to addrBrk to break out of a loop.
3246 ** Jump to cont to go immediately to the next iteration of the
3247 ** loop.
3248 **
3249 ** When there is an IN operator, we also have a "addrNxt" label that
3250 ** means to continue with the next IN value combination. When
3251 ** there are no IN operators in the constraints, the "addrNxt" label
3252 ** is the same as "addrBrk".
3253 */
3254 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
3255 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
3256
3257 /* If this is the right table of a LEFT OUTER JOIN, allocate and
3258 ** initialize a memory cell that records if this table matches any
3259 ** row of the left table of the join.
3260 */
3261 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
3262 pLevel->iLeftJoin = ++pParse->nMem;
3263 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
3264 VdbeComment((v, "init LEFT JOIN no-match flag"));
3265 }
3266
drh21172c42012-10-30 00:29:07 +00003267 /* Special case of a FROM clause subquery implemented as a co-routine */
3268 if( pTabItem->viaCoroutine ){
3269 int regYield = pTabItem->regReturn;
3270 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
3271 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
3272 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
3273 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
3274 pLevel->op = OP_Goto;
3275 }else
3276
drh111a6a72008-12-21 03:51:16 +00003277#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00003278 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
3279 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
drh111a6a72008-12-21 03:51:16 +00003280 ** to access the data.
3281 */
3282 int iReg; /* P3 Value for OP_VFilter */
drh281bbe22012-10-16 23:17:14 +00003283 int addrNotFound;
drh4efc9292013-06-06 23:02:03 +00003284 int nConstraint = pLoop->nLTerm;
drh111a6a72008-12-21 03:51:16 +00003285
drha62bb8d2009-11-23 21:23:45 +00003286 sqlite3ExprCachePush(pParse);
drh111a6a72008-12-21 03:51:16 +00003287 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
drh281bbe22012-10-16 23:17:14 +00003288 addrNotFound = pLevel->addrBrk;
drh111a6a72008-12-21 03:51:16 +00003289 for(j=0; j<nConstraint; j++){
drhe2250172013-05-31 18:13:50 +00003290 int iTarget = iReg+j+2;
drh4efc9292013-06-06 23:02:03 +00003291 pTerm = pLoop->aLTerm[j];
drh95ed68d2013-06-12 17:55:50 +00003292 if( pTerm==0 ) continue;
drh7ba39a92013-05-30 17:43:19 +00003293 if( pTerm->eOperator & WO_IN ){
3294 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
3295 addrNotFound = pLevel->addrNxt;
3296 }else{
3297 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
3298 }
3299 }
3300 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
drh7e47cb82013-05-31 17:55:27 +00003301 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
drh7ba39a92013-05-30 17:43:19 +00003302 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
3303 pLoop->u.vtab.idxStr,
3304 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
3305 pLoop->u.vtab.needFree = 0;
3306 for(j=0; j<nConstraint && j<16; j++){
3307 if( (pLoop->u.vtab.omitMask>>j)&1 ){
drh4efc9292013-06-06 23:02:03 +00003308 disableTerm(pLevel, pLoop->aLTerm[j]);
drh111a6a72008-12-21 03:51:16 +00003309 }
3310 }
3311 pLevel->op = OP_VNext;
3312 pLevel->p1 = iCur;
3313 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
drh23d04d52008-12-23 23:56:22 +00003314 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
drha62bb8d2009-11-23 21:23:45 +00003315 sqlite3ExprCachePop(pParse, 1);
drh111a6a72008-12-21 03:51:16 +00003316 }else
3317#endif /* SQLITE_OMIT_VIRTUALTABLE */
3318
drh7ba39a92013-05-30 17:43:19 +00003319 if( (pLoop->wsFlags & WHERE_IPK)!=0
3320 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
3321 ){
3322 /* Case 2: We can directly reference a single row using an
drh111a6a72008-12-21 03:51:16 +00003323 ** equality comparison against the ROWID field. Or
3324 ** we reference multiple rows using a "rowid IN (...)"
3325 ** construct.
3326 */
drh7ba39a92013-05-30 17:43:19 +00003327 assert( pLoop->u.btree.nEq==1 );
danielk19771d461462009-04-21 09:02:45 +00003328 iReleaseReg = sqlite3GetTempReg(pParse);
drh4efc9292013-06-06 23:02:03 +00003329 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003330 assert( pTerm!=0 );
3331 assert( pTerm->pExpr!=0 );
drh111a6a72008-12-21 03:51:16 +00003332 assert( omitTable==0 );
drh39759742013-08-02 23:40:45 +00003333 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh7ba39a92013-05-30 17:43:19 +00003334 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
drh111a6a72008-12-21 03:51:16 +00003335 addrNxt = pLevel->addrNxt;
danielk19771d461462009-04-21 09:02:45 +00003336 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
3337 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
drh459f63e2013-03-06 01:55:27 +00003338 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
drhceea3322009-04-23 13:22:42 +00003339 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
drh111a6a72008-12-21 03:51:16 +00003340 VdbeComment((v, "pk"));
3341 pLevel->op = OP_Noop;
drh7ba39a92013-05-30 17:43:19 +00003342 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
3343 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
3344 ){
3345 /* Case 3: We have an inequality comparison against the ROWID field.
drh111a6a72008-12-21 03:51:16 +00003346 */
3347 int testOp = OP_Noop;
3348 int start;
3349 int memEndValue = 0;
3350 WhereTerm *pStart, *pEnd;
3351
3352 assert( omitTable==0 );
drh7ba39a92013-05-30 17:43:19 +00003353 j = 0;
3354 pStart = pEnd = 0;
drh4efc9292013-06-06 23:02:03 +00003355 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
3356 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
drh81186b42013-06-18 01:52:41 +00003357 assert( pStart!=0 || pEnd!=0 );
drh111a6a72008-12-21 03:51:16 +00003358 if( bRev ){
3359 pTerm = pStart;
3360 pStart = pEnd;
3361 pEnd = pTerm;
3362 }
3363 if( pStart ){
3364 Expr *pX; /* The expression that defines the start bound */
3365 int r1, rTemp; /* Registers for holding the start boundary */
3366
3367 /* The following constant maps TK_xx codes into corresponding
3368 ** seek opcodes. It depends on a particular ordering of TK_xx
3369 */
3370 const u8 aMoveOp[] = {
3371 /* TK_GT */ OP_SeekGt,
3372 /* TK_LE */ OP_SeekLe,
3373 /* TK_LT */ OP_SeekLt,
3374 /* TK_GE */ OP_SeekGe
3375 };
3376 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
3377 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
3378 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
3379
drhb5246e52013-07-08 21:12:57 +00003380 assert( (pStart->wtFlags & TERM_VNULL)==0 );
drh39759742013-08-02 23:40:45 +00003381 testcase( pStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003382 pX = pStart->pExpr;
3383 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003384 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
drh111a6a72008-12-21 03:51:16 +00003385 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
3386 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
3387 VdbeComment((v, "pk"));
3388 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
3389 sqlite3ReleaseTempReg(pParse, rTemp);
3390 disableTerm(pLevel, pStart);
3391 }else{
3392 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
3393 }
3394 if( pEnd ){
3395 Expr *pX;
3396 pX = pEnd->pExpr;
3397 assert( pX!=0 );
drhb5246e52013-07-08 21:12:57 +00003398 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
3399 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
drh39759742013-08-02 23:40:45 +00003400 testcase( pEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003401 memEndValue = ++pParse->nMem;
3402 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
3403 if( pX->op==TK_LT || pX->op==TK_GT ){
3404 testOp = bRev ? OP_Le : OP_Ge;
3405 }else{
3406 testOp = bRev ? OP_Lt : OP_Gt;
3407 }
3408 disableTerm(pLevel, pEnd);
3409 }
3410 start = sqlite3VdbeCurrentAddr(v);
3411 pLevel->op = bRev ? OP_Prev : OP_Next;
3412 pLevel->p1 = iCur;
3413 pLevel->p2 = start;
drh81186b42013-06-18 01:52:41 +00003414 assert( pLevel->p5==0 );
danielk19771d461462009-04-21 09:02:45 +00003415 if( testOp!=OP_Noop ){
3416 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3417 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003418 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003419 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
3420 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003421 }
drh1b0f0262013-05-30 22:27:09 +00003422 }else if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00003423 /* Case 4: A scan using an index.
drh111a6a72008-12-21 03:51:16 +00003424 **
3425 ** The WHERE clause may contain zero or more equality
3426 ** terms ("==" or "IN" operators) that refer to the N
3427 ** left-most columns of the index. It may also contain
3428 ** inequality constraints (>, <, >= or <=) on the indexed
3429 ** column that immediately follows the N equalities. Only
3430 ** the right-most column can be an inequality - the rest must
3431 ** use the "==" and "IN" operators. For example, if the
3432 ** index is on (x,y,z), then the following clauses are all
3433 ** optimized:
3434 **
3435 ** x=5
3436 ** x=5 AND y=10
3437 ** x=5 AND y<10
3438 ** x=5 AND y>5 AND y<10
3439 ** x=5 AND y=5 AND z<=10
3440 **
3441 ** The z<10 term of the following cannot be used, only
3442 ** the x=5 term:
3443 **
3444 ** x=5 AND z<10
3445 **
3446 ** N may be zero if there are inequality constraints.
3447 ** If there are no inequality constraints, then N is at
3448 ** least one.
3449 **
3450 ** This case is also used when there are no WHERE clause
3451 ** constraints but an index is selected anyway, in order
3452 ** to force the output order to conform to an ORDER BY.
3453 */
drh3bb9b932010-08-06 02:10:00 +00003454 static const u8 aStartOp[] = {
drh111a6a72008-12-21 03:51:16 +00003455 0,
3456 0,
3457 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
3458 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
3459 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
3460 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
3461 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
3462 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
3463 };
drh3bb9b932010-08-06 02:10:00 +00003464 static const u8 aEndOp[] = {
drh111a6a72008-12-21 03:51:16 +00003465 OP_Noop, /* 0: (!end_constraints) */
3466 OP_IdxGE, /* 1: (end_constraints && !bRev) */
3467 OP_IdxLT /* 2: (end_constraints && bRev) */
3468 };
drh7ba39a92013-05-30 17:43:19 +00003469 int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
3470 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
drh111a6a72008-12-21 03:51:16 +00003471 int regBase; /* Base register holding constraint values */
3472 int r1; /* Temp register */
3473 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
3474 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
3475 int startEq; /* True if range start uses ==, >= or <= */
3476 int endEq; /* True if range end uses ==, >= or <= */
3477 int start_constraints; /* Start of range is constrained */
3478 int nConstraint; /* Number of constraint terms */
drh3bb9b932010-08-06 02:10:00 +00003479 Index *pIdx; /* The index we will be using */
3480 int iIdxCur; /* The VDBE cursor for the index */
3481 int nExtraReg = 0; /* Number of extra registers needed */
3482 int op; /* Instruction opcode */
dan6ac43392010-06-09 15:47:11 +00003483 char *zStartAff; /* Affinity for start of range constraint */
3484 char *zEndAff; /* Affinity for end of range constraint */
drh111a6a72008-12-21 03:51:16 +00003485
drh7ba39a92013-05-30 17:43:19 +00003486 pIdx = pLoop->u.btree.pIndex;
drh111a6a72008-12-21 03:51:16 +00003487 iIdxCur = pLevel->iIdxCur;
drh111a6a72008-12-21 03:51:16 +00003488
drh111a6a72008-12-21 03:51:16 +00003489 /* If this loop satisfies a sort order (pOrderBy) request that
3490 ** was passed to this function to implement a "SELECT min(x) ..."
3491 ** query, then the caller will only allow the loop to run for
3492 ** a single iteration. This means that the first row returned
3493 ** should not have a NULL value stored in 'x'. If column 'x' is
3494 ** the first one after the nEq equality constraints in the index,
3495 ** this requires some special handling.
3496 */
drh70d18342013-06-06 19:16:33 +00003497 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
drh4f402f22013-06-11 18:59:38 +00003498 && (pWInfo->bOBSat!=0)
drh111a6a72008-12-21 03:51:16 +00003499 && (pIdx->nColumn>nEq)
3500 ){
3501 /* assert( pOrderBy->nExpr==1 ); */
3502 /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
3503 isMinQuery = 1;
drh6df2acd2008-12-28 16:55:25 +00003504 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003505 }
3506
3507 /* Find any inequality constraint terms for the start and end
3508 ** of the range.
3509 */
drh7ba39a92013-05-30 17:43:19 +00003510 j = nEq;
3511 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003512 pRangeStart = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003513 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003514 }
drh7ba39a92013-05-30 17:43:19 +00003515 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
drh4efc9292013-06-06 23:02:03 +00003516 pRangeEnd = pLoop->aLTerm[j++];
drh6df2acd2008-12-28 16:55:25 +00003517 nExtraReg = 1;
drh111a6a72008-12-21 03:51:16 +00003518 }
3519
drh6df2acd2008-12-28 16:55:25 +00003520 /* Generate code to evaluate all constraint terms using == or IN
3521 ** and store the values of those terms in an array of registers
3522 ** starting at regBase.
3523 */
drh613ba1e2013-06-15 15:11:45 +00003524 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
drh6b36e822013-07-30 15:10:32 +00003525 zEndAff = sqlite3DbStrDup(db, zStartAff);
drh6df2acd2008-12-28 16:55:25 +00003526 addrNxt = pLevel->addrNxt;
3527
drh111a6a72008-12-21 03:51:16 +00003528 /* If we are doing a reverse order scan on an ascending index, or
3529 ** a forward order scan on a descending index, interchange the
3530 ** start and end terms (pRangeStart and pRangeEnd).
3531 */
dan0c733f62011-11-16 15:27:09 +00003532 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
3533 || (bRev && pIdx->nColumn==nEq)
3534 ){
drh111a6a72008-12-21 03:51:16 +00003535 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
3536 }
3537
drh7963b0e2013-06-17 21:37:40 +00003538 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
3539 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
3540 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
3541 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
drh111a6a72008-12-21 03:51:16 +00003542 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
3543 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
3544 start_constraints = pRangeStart || nEq>0;
3545
3546 /* Seek the index cursor to the start of the range. */
3547 nConstraint = nEq;
3548 if( pRangeStart ){
dan69f8bb92009-08-13 19:21:16 +00003549 Expr *pRight = pRangeStart->pExpr->pRight;
3550 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003551 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
3552 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3553 }
dan6ac43392010-06-09 15:47:11 +00003554 if( zStartAff ){
3555 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003556 /* Since the comparison is to be performed with no conversions
3557 ** applied to the operands, set the affinity to apply to pRight to
3558 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003559 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003560 }
dan6ac43392010-06-09 15:47:11 +00003561 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
3562 zStartAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003563 }
3564 }
drh111a6a72008-12-21 03:51:16 +00003565 nConstraint++;
drh39759742013-08-02 23:40:45 +00003566 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003567 }else if( isMinQuery ){
3568 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
3569 nConstraint++;
3570 startEq = 0;
3571 start_constraints = 1;
3572 }
dan6ac43392010-06-09 15:47:11 +00003573 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
drh111a6a72008-12-21 03:51:16 +00003574 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
3575 assert( op!=0 );
3576 testcase( op==OP_Rewind );
3577 testcase( op==OP_Last );
3578 testcase( op==OP_SeekGt );
3579 testcase( op==OP_SeekGe );
3580 testcase( op==OP_SeekLe );
3581 testcase( op==OP_SeekLt );
drh8cff69d2009-11-12 19:59:44 +00003582 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh111a6a72008-12-21 03:51:16 +00003583
3584 /* Load the value for the inequality constraint at the end of the
3585 ** range (if any).
3586 */
3587 nConstraint = nEq;
3588 if( pRangeEnd ){
dan69f8bb92009-08-13 19:21:16 +00003589 Expr *pRight = pRangeEnd->pExpr->pRight;
drhf49f3522009-12-30 14:12:38 +00003590 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
dan69f8bb92009-08-13 19:21:16 +00003591 sqlite3ExprCode(pParse, pRight, regBase+nEq);
drh534230c2011-01-22 00:10:45 +00003592 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
3593 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
3594 }
dan6ac43392010-06-09 15:47:11 +00003595 if( zEndAff ){
3596 if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
drh039fc322009-11-17 18:31:47 +00003597 /* Since the comparison is to be performed with no conversions
3598 ** applied to the operands, set the affinity to apply to pRight to
3599 ** SQLITE_AFF_NONE. */
dan6ac43392010-06-09 15:47:11 +00003600 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003601 }
dan6ac43392010-06-09 15:47:11 +00003602 if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
3603 zEndAff[nEq] = SQLITE_AFF_NONE;
drh039fc322009-11-17 18:31:47 +00003604 }
3605 }
dan6ac43392010-06-09 15:47:11 +00003606 codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003607 nConstraint++;
drh39759742013-08-02 23:40:45 +00003608 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003609 }
drh6b36e822013-07-30 15:10:32 +00003610 sqlite3DbFree(db, zStartAff);
3611 sqlite3DbFree(db, zEndAff);
drh111a6a72008-12-21 03:51:16 +00003612
3613 /* Top of the loop body */
3614 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
3615
3616 /* Check if the index cursor is past the end of the range. */
3617 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
3618 testcase( op==OP_Noop );
3619 testcase( op==OP_IdxGE );
3620 testcase( op==OP_IdxLT );
drh6df2acd2008-12-28 16:55:25 +00003621 if( op!=OP_Noop ){
drh8cff69d2009-11-12 19:59:44 +00003622 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
drh6df2acd2008-12-28 16:55:25 +00003623 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
3624 }
drh111a6a72008-12-21 03:51:16 +00003625
3626 /* If there are inequality constraints, check that the value
3627 ** of the table column that the inequality contrains is not NULL.
3628 ** If it is, jump to the next iteration of the loop.
3629 */
3630 r1 = sqlite3GetTempReg(pParse);
drh37ca0482013-06-12 17:17:45 +00003631 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
3632 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
drh7ba39a92013-05-30 17:43:19 +00003633 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
drh111a6a72008-12-21 03:51:16 +00003634 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
3635 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
3636 }
danielk19771d461462009-04-21 09:02:45 +00003637 sqlite3ReleaseTempReg(pParse, r1);
drh111a6a72008-12-21 03:51:16 +00003638
3639 /* Seek the table cursor, if required */
drh23d04d52008-12-23 23:56:22 +00003640 disableTerm(pLevel, pRangeStart);
3641 disableTerm(pLevel, pRangeEnd);
danielk19771d461462009-04-21 09:02:45 +00003642 if( !omitTable ){
3643 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
3644 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
drhceea3322009-04-23 13:22:42 +00003645 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
danielk19771d461462009-04-21 09:02:45 +00003646 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
drh111a6a72008-12-21 03:51:16 +00003647 }
drh111a6a72008-12-21 03:51:16 +00003648
3649 /* Record the instruction used to terminate the loop. Disable
3650 ** WHERE clause terms made redundant by the index range scan.
3651 */
drh7699d1c2013-06-04 12:42:29 +00003652 if( pLoop->wsFlags & WHERE_ONEROW ){
drh95e037b2011-03-09 21:02:31 +00003653 pLevel->op = OP_Noop;
3654 }else if( bRev ){
3655 pLevel->op = OP_Prev;
3656 }else{
3657 pLevel->op = OP_Next;
3658 }
drh111a6a72008-12-21 03:51:16 +00003659 pLevel->p1 = iIdxCur;
drh53cfbe92013-06-13 17:28:22 +00003660 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
drh3f4d1d12012-09-15 18:45:54 +00003661 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3662 }else{
3663 assert( pLevel->p5==0 );
3664 }
drhdd5f5a62008-12-23 13:35:23 +00003665 }else
3666
drh23d04d52008-12-23 23:56:22 +00003667#ifndef SQLITE_OMIT_OR_OPTIMIZATION
drh7ba39a92013-05-30 17:43:19 +00003668 if( pLoop->wsFlags & WHERE_MULTI_OR ){
3669 /* Case 5: Two or more separately indexed terms connected by OR
drh111a6a72008-12-21 03:51:16 +00003670 **
3671 ** Example:
3672 **
3673 ** CREATE TABLE t1(a,b,c,d);
3674 ** CREATE INDEX i1 ON t1(a);
3675 ** CREATE INDEX i2 ON t1(b);
3676 ** CREATE INDEX i3 ON t1(c);
3677 **
3678 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
3679 **
3680 ** In the example, there are three indexed terms connected by OR.
danielk19771d461462009-04-21 09:02:45 +00003681 ** The top of the loop looks like this:
drh111a6a72008-12-21 03:51:16 +00003682 **
drh1b26c7c2009-04-22 02:15:47 +00003683 ** Null 1 # Zero the rowset in reg 1
drh111a6a72008-12-21 03:51:16 +00003684 **
danielk19771d461462009-04-21 09:02:45 +00003685 ** Then, for each indexed term, the following. The arguments to
drh1b26c7c2009-04-22 02:15:47 +00003686 ** RowSetTest are such that the rowid of the current row is inserted
3687 ** into the RowSet. If it is already present, control skips the
danielk19771d461462009-04-21 09:02:45 +00003688 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
drh111a6a72008-12-21 03:51:16 +00003689 **
danielk19771d461462009-04-21 09:02:45 +00003690 ** sqlite3WhereBegin(<term>)
drh1b26c7c2009-04-22 02:15:47 +00003691 ** RowSetTest # Insert rowid into rowset
danielk19771d461462009-04-21 09:02:45 +00003692 ** Gosub 2 A
3693 ** sqlite3WhereEnd()
3694 **
3695 ** Following the above, code to terminate the loop. Label A, the target
3696 ** of the Gosub above, jumps to the instruction right after the Goto.
3697 **
drh1b26c7c2009-04-22 02:15:47 +00003698 ** Null 1 # Zero the rowset in reg 1
danielk19771d461462009-04-21 09:02:45 +00003699 ** Goto B # The loop is finished.
3700 **
3701 ** A: <loop body> # Return data, whatever.
3702 **
3703 ** Return 2 # Jump back to the Gosub
3704 **
3705 ** B: <after the loop>
3706 **
drh111a6a72008-12-21 03:51:16 +00003707 */
drh111a6a72008-12-21 03:51:16 +00003708 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
drhc01a3c12009-12-16 22:10:49 +00003709 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
dan0efb72c2012-08-24 18:44:56 +00003710 Index *pCov = 0; /* Potential covering index (or NULL) */
3711 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
danielk19771d461462009-04-21 09:02:45 +00003712
3713 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
shane85095702009-06-15 16:27:08 +00003714 int regRowset = 0; /* Register for RowSet object */
3715 int regRowid = 0; /* Register holding rowid */
danielk19771d461462009-04-21 09:02:45 +00003716 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
3717 int iRetInit; /* Address of regReturn init */
drhc01a3c12009-12-16 22:10:49 +00003718 int untestedTerms = 0; /* Some terms not completely tested */
drh8871ef52011-10-07 13:33:10 +00003719 int ii; /* Loop counter */
3720 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
drh111a6a72008-12-21 03:51:16 +00003721
drh4efc9292013-06-06 23:02:03 +00003722 pTerm = pLoop->aLTerm[0];
drh111a6a72008-12-21 03:51:16 +00003723 assert( pTerm!=0 );
drh7a5bcc02013-01-16 17:08:58 +00003724 assert( pTerm->eOperator & WO_OR );
drh111a6a72008-12-21 03:51:16 +00003725 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
3726 pOrWc = &pTerm->u.pOrInfo->wc;
drhc01a3c12009-12-16 22:10:49 +00003727 pLevel->op = OP_Return;
3728 pLevel->p1 = regReturn;
drh23d04d52008-12-23 23:56:22 +00003729
danbfca6a42012-08-24 10:52:35 +00003730 /* Set up a new SrcList in pOrTab containing the table being scanned
drhc01a3c12009-12-16 22:10:49 +00003731 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
3732 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
3733 */
3734 if( pWInfo->nLevel>1 ){
3735 int nNotReady; /* The number of notReady tables */
3736 struct SrcList_item *origSrc; /* Original list of tables */
3737 nNotReady = pWInfo->nLevel - iLevel - 1;
drh6b36e822013-07-30 15:10:32 +00003738 pOrTab = sqlite3StackAllocRaw(db,
drhc01a3c12009-12-16 22:10:49 +00003739 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
3740 if( pOrTab==0 ) return notReady;
drhad01d892013-06-19 13:59:49 +00003741 pOrTab->nAlloc = (u8)(nNotReady + 1);
shaneh46aae3c2009-12-31 19:06:23 +00003742 pOrTab->nSrc = pOrTab->nAlloc;
drhc01a3c12009-12-16 22:10:49 +00003743 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
3744 origSrc = pWInfo->pTabList->a;
3745 for(k=1; k<=nNotReady; k++){
3746 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
3747 }
3748 }else{
3749 pOrTab = pWInfo->pTabList;
3750 }
danielk19771d461462009-04-21 09:02:45 +00003751
drh1b26c7c2009-04-22 02:15:47 +00003752 /* Initialize the rowset register to contain NULL. An SQL NULL is
3753 ** equivalent to an empty rowset.
danielk19771d461462009-04-21 09:02:45 +00003754 **
3755 ** Also initialize regReturn to contain the address of the instruction
3756 ** immediately following the OP_Return at the bottom of the loop. This
3757 ** is required in a few obscure LEFT JOIN cases where control jumps
3758 ** over the top of the loop into the body of it. In this case the
3759 ** correct response for the end-of-loop code (the OP_Return) is to
3760 ** fall through to the next instruction, just as an OP_Next does if
3761 ** called on an uninitialized cursor.
3762 */
drh70d18342013-06-06 19:16:33 +00003763 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003764 regRowset = ++pParse->nMem;
3765 regRowid = ++pParse->nMem;
3766 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
3767 }
danielk19771d461462009-04-21 09:02:45 +00003768 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
3769
drh8871ef52011-10-07 13:33:10 +00003770 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
3771 ** Then for every term xN, evaluate as the subexpression: xN AND z
3772 ** That way, terms in y that are factored into the disjunction will
3773 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
drh331b67c2012-03-09 22:02:08 +00003774 **
3775 ** Actually, each subexpression is converted to "xN AND w" where w is
3776 ** the "interesting" terms of z - terms that did not originate in the
3777 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
3778 ** indices.
drhb3129fa2013-05-09 14:20:11 +00003779 **
3780 ** This optimization also only applies if the (x1 OR x2 OR ...) term
3781 ** is not contained in the ON clause of a LEFT JOIN.
3782 ** See ticket http://www.sqlite.org/src/info/f2369304e4
drh8871ef52011-10-07 13:33:10 +00003783 */
3784 if( pWC->nTerm>1 ){
drh7a484802012-03-16 00:28:11 +00003785 int iTerm;
3786 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
3787 Expr *pExpr = pWC->a[iTerm].pExpr;
drhaa32e3c2013-07-16 21:31:23 +00003788 if( &pWC->a[iTerm] == pTerm ) continue;
drh331b67c2012-03-09 22:02:08 +00003789 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
drhaa32e3c2013-07-16 21:31:23 +00003790 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
drh7a484802012-03-16 00:28:11 +00003791 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
drh6b36e822013-07-30 15:10:32 +00003792 pExpr = sqlite3ExprDup(db, pExpr, 0);
3793 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
drh331b67c2012-03-09 22:02:08 +00003794 }
3795 if( pAndExpr ){
3796 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
3797 }
drh8871ef52011-10-07 13:33:10 +00003798 }
3799
danielk19771d461462009-04-21 09:02:45 +00003800 for(ii=0; ii<pOrWc->nTerm; ii++){
3801 WhereTerm *pOrTerm = &pOrWc->a[ii];
drh7a5bcc02013-01-16 17:08:58 +00003802 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
danielk19771d461462009-04-21 09:02:45 +00003803 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
drh8871ef52011-10-07 13:33:10 +00003804 Expr *pOrExpr = pOrTerm->pExpr;
drhb3129fa2013-05-09 14:20:11 +00003805 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
drh8871ef52011-10-07 13:33:10 +00003806 pAndExpr->pLeft = pOrExpr;
3807 pOrExpr = pAndExpr;
3808 }
danielk19771d461462009-04-21 09:02:45 +00003809 /* Loop through table entries that match term pOrTerm. */
drh8871ef52011-10-07 13:33:10 +00003810 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
drh9ef61f42011-10-07 14:40:59 +00003811 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
dan0efb72c2012-08-24 18:44:56 +00003812 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
drh6b36e822013-07-30 15:10:32 +00003813 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
danielk19771d461462009-04-21 09:02:45 +00003814 if( pSubWInfo ){
drh7ba39a92013-05-30 17:43:19 +00003815 WhereLoop *pSubLoop;
dan17c0bc02010-11-09 17:35:19 +00003816 explainOneScan(
dan4a07e3d2010-11-09 14:48:59 +00003817 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
dan2ce22452010-11-08 19:01:16 +00003818 );
drh70d18342013-06-06 19:16:33 +00003819 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
drh336a5302009-04-24 15:46:21 +00003820 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
3821 int r;
3822 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
drha748fdc2012-03-28 01:34:47 +00003823 regRowid, 0);
drh8cff69d2009-11-12 19:59:44 +00003824 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
3825 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
drh336a5302009-04-24 15:46:21 +00003826 }
danielk19771d461462009-04-21 09:02:45 +00003827 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
3828
drhc01a3c12009-12-16 22:10:49 +00003829 /* The pSubWInfo->untestedTerms flag means that this OR term
3830 ** contained one or more AND term from a notReady table. The
3831 ** terms from the notReady table could not be tested and will
3832 ** need to be tested later.
3833 */
3834 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
3835
danbfca6a42012-08-24 10:52:35 +00003836 /* If all of the OR-connected terms are optimized using the same
3837 ** index, and the index is opened using the same cursor number
3838 ** by each call to sqlite3WhereBegin() made by this loop, it may
3839 ** be possible to use that index as a covering index.
3840 **
3841 ** If the call to sqlite3WhereBegin() above resulted in a scan that
3842 ** uses an index, and this is either the first OR-connected term
3843 ** processed or the index is the same as that used by all previous
dan0efb72c2012-08-24 18:44:56 +00003844 ** terms, set pCov to the candidate covering index. Otherwise, set
3845 ** pCov to NULL to indicate that no candidate covering index will
3846 ** be available.
danbfca6a42012-08-24 10:52:35 +00003847 */
drh7ba39a92013-05-30 17:43:19 +00003848 pSubLoop = pSubWInfo->a[0].pWLoop;
drh986b3872013-06-28 21:12:20 +00003849 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
drh7ba39a92013-05-30 17:43:19 +00003850 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
drh7ba39a92013-05-30 17:43:19 +00003851 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
danbfca6a42012-08-24 10:52:35 +00003852 ){
drh7ba39a92013-05-30 17:43:19 +00003853 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
drh907717f2013-06-04 18:03:22 +00003854 pCov = pSubLoop->u.btree.pIndex;
danbfca6a42012-08-24 10:52:35 +00003855 }else{
3856 pCov = 0;
3857 }
3858
danielk19771d461462009-04-21 09:02:45 +00003859 /* Finish the loop through table entries that match term pOrTerm. */
3860 sqlite3WhereEnd(pSubWInfo);
3861 }
drhdd5f5a62008-12-23 13:35:23 +00003862 }
3863 }
drhd40e2082012-08-24 23:24:15 +00003864 pLevel->u.pCovidx = pCov;
drh90abfd02012-10-09 21:07:23 +00003865 if( pCov ) pLevel->iIdxCur = iCovCur;
drh331b67c2012-03-09 22:02:08 +00003866 if( pAndExpr ){
3867 pAndExpr->pLeft = 0;
drh6b36e822013-07-30 15:10:32 +00003868 sqlite3ExprDelete(db, pAndExpr);
drh331b67c2012-03-09 22:02:08 +00003869 }
danielk19771d461462009-04-21 09:02:45 +00003870 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
danielk19771d461462009-04-21 09:02:45 +00003871 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
3872 sqlite3VdbeResolveLabel(v, iLoopBody);
3873
drh6b36e822013-07-30 15:10:32 +00003874 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
drhc01a3c12009-12-16 22:10:49 +00003875 if( !untestedTerms ) disableTerm(pLevel, pTerm);
drhdd5f5a62008-12-23 13:35:23 +00003876 }else
drh23d04d52008-12-23 23:56:22 +00003877#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
drhdd5f5a62008-12-23 13:35:23 +00003878
3879 {
drh7ba39a92013-05-30 17:43:19 +00003880 /* Case 6: There is no usable index. We must do a complete
drh111a6a72008-12-21 03:51:16 +00003881 ** scan of the entire table.
3882 */
drh699b3d42009-02-23 16:52:07 +00003883 static const u8 aStep[] = { OP_Next, OP_Prev };
3884 static const u8 aStart[] = { OP_Rewind, OP_Last };
3885 assert( bRev==0 || bRev==1 );
drh699b3d42009-02-23 16:52:07 +00003886 pLevel->op = aStep[bRev];
drh111a6a72008-12-21 03:51:16 +00003887 pLevel->p1 = iCur;
drh699b3d42009-02-23 16:52:07 +00003888 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
drh111a6a72008-12-21 03:51:16 +00003889 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
3890 }
drh111a6a72008-12-21 03:51:16 +00003891
3892 /* Insert code to test every subexpression that can be completely
3893 ** computed using the current set of tables.
3894 */
drh111a6a72008-12-21 03:51:16 +00003895 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
3896 Expr *pE;
drh39759742013-08-02 23:40:45 +00003897 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003898 testcase( pTerm->wtFlags & TERM_CODED );
3899 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003900 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhc01a3c12009-12-16 22:10:49 +00003901 testcase( pWInfo->untestedTerms==0
3902 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
3903 pWInfo->untestedTerms = 1;
3904 continue;
3905 }
drh111a6a72008-12-21 03:51:16 +00003906 pE = pTerm->pExpr;
3907 assert( pE!=0 );
3908 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
3909 continue;
3910 }
drh111a6a72008-12-21 03:51:16 +00003911 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
drh111a6a72008-12-21 03:51:16 +00003912 pTerm->wtFlags |= TERM_CODED;
3913 }
3914
drh0c41d222013-04-22 02:39:10 +00003915 /* Insert code to test for implied constraints based on transitivity
3916 ** of the "==" operator.
3917 **
3918 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
3919 ** and we are coding the t1 loop and the t2 loop has not yet coded,
3920 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
3921 ** the implied "t1.a=123" constraint.
3922 */
3923 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
drh6b36e822013-07-30 15:10:32 +00003924 Expr *pE, *pEAlt;
drh0c41d222013-04-22 02:39:10 +00003925 WhereTerm *pAlt;
drh0c41d222013-04-22 02:39:10 +00003926 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
3927 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
3928 if( pTerm->leftCursor!=iCur ) continue;
drhcdc2e432013-07-01 17:27:19 +00003929 if( pLevel->iLeftJoin ) continue;
drh0c41d222013-04-22 02:39:10 +00003930 pE = pTerm->pExpr;
3931 assert( !ExprHasProperty(pE, EP_FromJoin) );
drh0259bc32013-09-09 19:37:46 +00003932 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
drh0c41d222013-04-22 02:39:10 +00003933 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
3934 if( pAlt==0 ) continue;
drh5c10f3b2013-05-01 17:22:38 +00003935 if( pAlt->wtFlags & (TERM_CODED) ) continue;
drh7963b0e2013-06-17 21:37:40 +00003936 testcase( pAlt->eOperator & WO_EQ );
3937 testcase( pAlt->eOperator & WO_IN );
drh0c41d222013-04-22 02:39:10 +00003938 VdbeNoopComment((v, "begin transitive constraint"));
drh6b36e822013-07-30 15:10:32 +00003939 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
3940 if( pEAlt ){
3941 *pEAlt = *pAlt->pExpr;
3942 pEAlt->pLeft = pE->pLeft;
3943 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
3944 sqlite3StackFree(db, pEAlt);
3945 }
drh0c41d222013-04-22 02:39:10 +00003946 }
3947
drh111a6a72008-12-21 03:51:16 +00003948 /* For a LEFT OUTER JOIN, generate code that will record the fact that
3949 ** at least one row of the right table has matched the left table.
3950 */
3951 if( pLevel->iLeftJoin ){
3952 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
3953 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
3954 VdbeComment((v, "record LEFT JOIN hit"));
drhceea3322009-04-23 13:22:42 +00003955 sqlite3ExprCacheClear(pParse);
drh111a6a72008-12-21 03:51:16 +00003956 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
drh39759742013-08-02 23:40:45 +00003957 testcase( pTerm->wtFlags & TERM_VIRTUAL );
drh111a6a72008-12-21 03:51:16 +00003958 testcase( pTerm->wtFlags & TERM_CODED );
3959 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
drh0259bc32013-09-09 19:37:46 +00003960 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
drhb057e562009-12-16 23:43:55 +00003961 assert( pWInfo->untestedTerms );
drhc01a3c12009-12-16 22:10:49 +00003962 continue;
3963 }
drh111a6a72008-12-21 03:51:16 +00003964 assert( pTerm->pExpr );
3965 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
3966 pTerm->wtFlags |= TERM_CODED;
3967 }
3968 }
danielk19771d461462009-04-21 09:02:45 +00003969 sqlite3ReleaseTempReg(pParse, iReleaseReg);
drh23d04d52008-12-23 23:56:22 +00003970
drh0259bc32013-09-09 19:37:46 +00003971 return pLevel->notReady;
drh111a6a72008-12-21 03:51:16 +00003972}
3973
drhd15cb172013-05-21 19:23:10 +00003974#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00003975/*
3976** Print a WhereLoop object for debugging purposes
3977*/
3978static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
drhb8a8e8a2013-06-10 19:12:39 +00003979 int nb = 1+(pTabList->nSrc+7)/8;
drha18f3d22013-05-08 03:05:41 +00003980 struct SrcList_item *pItem = pTabList->a + p->iTab;
3981 Table *pTab = pItem->pTab;
drh6457a352013-06-21 00:35:37 +00003982 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
drha184fb82013-05-08 04:22:59 +00003983 p->iTab, nb, p->maskSelf, nb, p->prereq);
drh6457a352013-06-21 00:35:37 +00003984 sqlite3DebugPrintf(" %12s",
drha18f3d22013-05-08 03:05:41 +00003985 pItem->zAlias ? pItem->zAlias : pTab->zName);
drh5346e952013-05-08 14:14:26 +00003986 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
3987 if( p->u.btree.pIndex ){
drh319f6772013-05-14 15:31:07 +00003988 const char *zName = p->u.btree.pIndex->zName;
drhae70cf12013-05-31 15:18:46 +00003989 if( zName==0 ) zName = "ipk";
drh319f6772013-05-14 15:31:07 +00003990 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
3991 int i = sqlite3Strlen30(zName) - 1;
3992 while( zName[i]!='_' ) i--;
3993 zName += i;
3994 }
drh6457a352013-06-21 00:35:37 +00003995 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
drh5346e952013-05-08 14:14:26 +00003996 }else{
drh6457a352013-06-21 00:35:37 +00003997 sqlite3DebugPrintf("%20s","");
drh5346e952013-05-08 14:14:26 +00003998 }
drha18f3d22013-05-08 03:05:41 +00003999 }else{
drh5346e952013-05-08 14:14:26 +00004000 char *z;
4001 if( p->u.vtab.idxStr ){
drh3bd26f02013-05-24 14:52:03 +00004002 z = sqlite3_mprintf("(%d,\"%s\",%x)",
4003 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004004 }else{
drh3bd26f02013-05-24 14:52:03 +00004005 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
drh5346e952013-05-08 14:14:26 +00004006 }
drh6457a352013-06-21 00:35:37 +00004007 sqlite3DebugPrintf(" %-19s", z);
drh5346e952013-05-08 14:14:26 +00004008 sqlite3_free(z);
drha18f3d22013-05-08 03:05:41 +00004009 }
drh6457a352013-06-21 00:35:37 +00004010 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
drhb8a8e8a2013-06-10 19:12:39 +00004011 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
drha18f3d22013-05-08 03:05:41 +00004012}
4013#endif
4014
drhf1b5f5b2013-05-02 00:15:01 +00004015/*
drh4efc9292013-06-06 23:02:03 +00004016** Convert bulk memory into a valid WhereLoop that can be passed
4017** to whereLoopClear harmlessly.
drh5346e952013-05-08 14:14:26 +00004018*/
drh4efc9292013-06-06 23:02:03 +00004019static void whereLoopInit(WhereLoop *p){
4020 p->aLTerm = p->aLTermSpace;
4021 p->nLTerm = 0;
4022 p->nLSlot = ArraySize(p->aLTermSpace);
4023 p->wsFlags = 0;
4024}
4025
4026/*
4027** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
4028*/
4029static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
drh986b3872013-06-28 21:12:20 +00004030 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
drh13e11b42013-06-06 23:44:25 +00004031 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
4032 sqlite3_free(p->u.vtab.idxStr);
4033 p->u.vtab.needFree = 0;
4034 p->u.vtab.idxStr = 0;
drh986b3872013-06-28 21:12:20 +00004035 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
drh13e11b42013-06-06 23:44:25 +00004036 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
4037 sqlite3DbFree(db, p->u.btree.pIndex);
4038 p->u.btree.pIndex = 0;
4039 }
drh5346e952013-05-08 14:14:26 +00004040 }
4041}
4042
drh4efc9292013-06-06 23:02:03 +00004043/*
4044** Deallocate internal memory used by a WhereLoop object
4045*/
4046static void whereLoopClear(sqlite3 *db, WhereLoop *p){
4047 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4048 whereLoopClearUnion(db, p);
4049 whereLoopInit(p);
4050}
4051
4052/*
4053** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
4054*/
4055static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
4056 WhereTerm **paNew;
4057 if( p->nLSlot>=n ) return SQLITE_OK;
4058 n = (n+7)&~7;
4059 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
4060 if( paNew==0 ) return SQLITE_NOMEM;
4061 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
4062 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
4063 p->aLTerm = paNew;
4064 p->nLSlot = n;
4065 return SQLITE_OK;
4066}
4067
4068/*
4069** Transfer content from the second pLoop into the first.
4070*/
4071static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
drh4efc9292013-06-06 23:02:03 +00004072 whereLoopClearUnion(db, pTo);
drh0d31dc32013-09-06 00:40:59 +00004073 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
4074 memset(&pTo->u, 0, sizeof(pTo->u));
4075 return SQLITE_NOMEM;
4076 }
drha2014152013-06-07 00:29:23 +00004077 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
4078 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
drh4efc9292013-06-06 23:02:03 +00004079 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
4080 pFrom->u.vtab.needFree = 0;
drh986b3872013-06-28 21:12:20 +00004081 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
drh4efc9292013-06-06 23:02:03 +00004082 pFrom->u.btree.pIndex = 0;
4083 }
4084 return SQLITE_OK;
4085}
4086
drh5346e952013-05-08 14:14:26 +00004087/*
drhf1b5f5b2013-05-02 00:15:01 +00004088** Delete a WhereLoop object
4089*/
4090static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
drh5346e952013-05-08 14:14:26 +00004091 whereLoopClear(db, p);
drhf1b5f5b2013-05-02 00:15:01 +00004092 sqlite3DbFree(db, p);
4093}
drh84bfda42005-07-15 13:05:21 +00004094
drh9eff6162006-06-12 21:59:13 +00004095/*
4096** Free a WhereInfo structure
4097*/
drh10fe8402008-10-11 16:47:35 +00004098static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
drh52ff8ea2010-04-08 14:15:56 +00004099 if( ALWAYS(pWInfo) ){
drh70d18342013-06-06 19:16:33 +00004100 whereClauseClear(&pWInfo->sWC);
drhf1b5f5b2013-05-02 00:15:01 +00004101 while( pWInfo->pLoops ){
4102 WhereLoop *p = pWInfo->pLoops;
4103 pWInfo->pLoops = p->pNextLoop;
4104 whereLoopDelete(db, p);
4105 }
drh633e6d52008-07-28 19:34:53 +00004106 sqlite3DbFree(db, pWInfo);
drh9eff6162006-06-12 21:59:13 +00004107 }
4108}
4109
drhf1b5f5b2013-05-02 00:15:01 +00004110/*
4111** Insert or replace a WhereLoop entry using the template supplied.
4112**
4113** An existing WhereLoop entry might be overwritten if the new template
4114** is better and has fewer dependencies. Or the template will be ignored
4115** and no insert will occur if an existing WhereLoop is faster and has
4116** fewer dependencies than the template. Otherwise a new WhereLoop is
drhd044d202013-05-31 12:43:55 +00004117** added based on the template.
drh23f98da2013-05-21 15:52:07 +00004118**
drhaa32e3c2013-07-16 21:31:23 +00004119** If pBuilder->pOrSet is not NULL then we only care about only the
4120** prerequisites and rRun and nOut costs of the N best loops. That
4121** information is gathered in the pBuilder->pOrSet object. This special
4122** processing mode is used only for OR clause processing.
drh23f98da2013-05-21 15:52:07 +00004123**
drhaa32e3c2013-07-16 21:31:23 +00004124** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
drh23f98da2013-05-21 15:52:07 +00004125** still might overwrite similar loops with the new template if the
4126** template is better. Loops may be overwritten if the following
4127** conditions are met:
4128**
4129** (1) They have the same iTab.
4130** (2) They have the same iSortIdx.
4131** (3) The template has same or fewer dependencies than the current loop
4132** (4) The template has the same or lower cost than the current loop
drhd044d202013-05-31 12:43:55 +00004133** (5) The template uses more terms of the same index but has no additional
4134** dependencies
drhf1b5f5b2013-05-02 00:15:01 +00004135*/
drhcf8fa7a2013-05-10 20:26:22 +00004136static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
drh4efc9292013-06-06 23:02:03 +00004137 WhereLoop **ppPrev, *p, *pNext = 0;
drhcf8fa7a2013-05-10 20:26:22 +00004138 WhereInfo *pWInfo = pBuilder->pWInfo;
drh70d18342013-06-06 19:16:33 +00004139 sqlite3 *db = pWInfo->pParse->db;
drhcf8fa7a2013-05-10 20:26:22 +00004140
drhaa32e3c2013-07-16 21:31:23 +00004141 /* If pBuilder->pOrSet is defined, then only keep track of the costs
4142 ** and prereqs.
drh23f98da2013-05-21 15:52:07 +00004143 */
drhaa32e3c2013-07-16 21:31:23 +00004144 if( pBuilder->pOrSet!=0 ){
4145#if WHERETRACE_ENABLED
4146 u16 n = pBuilder->pOrSet->n;
4147 int x =
4148#endif
4149 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
4150 pTemplate->nOut);
drhae70cf12013-05-31 15:18:46 +00004151#if WHERETRACE_ENABLED
4152 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00004153 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
drh70d18342013-06-06 19:16:33 +00004154 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004155 }
4156#endif
drhcf8fa7a2013-05-10 20:26:22 +00004157 return SQLITE_OK;
4158 }
drhf1b5f5b2013-05-02 00:15:01 +00004159
4160 /* Search for an existing WhereLoop to overwrite, or which takes
4161 ** priority over pTemplate.
4162 */
4163 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
drhdbb80232013-06-19 12:34:13 +00004164 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
4165 /* If either the iTab or iSortIdx values for two WhereLoop are different
4166 ** then those WhereLoops need to be considered separately. Neither is
4167 ** a candidate to replace the other. */
4168 continue;
4169 }
4170 /* In the current implementation, the rSetup value is either zero
4171 ** or the cost of building an automatic index (NlogN) and the NlogN
4172 ** is the same for compatible WhereLoops. */
4173 assert( p->rSetup==0 || pTemplate->rSetup==0
4174 || p->rSetup==pTemplate->rSetup );
4175
4176 /* whereLoopAddBtree() always generates and inserts the automatic index
4177 ** case first. Hence compatible candidate WhereLoops never have a larger
4178 ** rSetup. Call this SETUP-INVARIANT */
4179 assert( p->rSetup>=pTemplate->rSetup );
4180
drhf1b5f5b2013-05-02 00:15:01 +00004181 if( (p->prereq & pTemplate->prereq)==p->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004182 && p->rSetup<=pTemplate->rSetup
4183 && p->rRun<=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00004184 && p->nOut<=pTemplate->nOut
drhf1b5f5b2013-05-02 00:15:01 +00004185 ){
drh4a5acf82013-06-18 20:06:23 +00004186 /* This branch taken when p is equal or better than pTemplate in
drhe56dd3a2013-08-30 17:50:35 +00004187 ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
drhf46af732013-08-30 17:35:44 +00004188 ** (4) number of output rows. */
drhdbb80232013-06-19 12:34:13 +00004189 assert( p->rSetup==pTemplate->rSetup );
drh05db3c72013-09-02 20:22:18 +00004190 if( p->prereq==pTemplate->prereq
4191 && p->nLTerm<pTemplate->nLTerm
drhcd0f4072013-06-05 12:47:59 +00004192 && (p->wsFlags & WHERE_INDEXED)!=0
4193 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
4194 && p->u.btree.pIndex==pTemplate->u.btree.pIndex
drhcd0f4072013-06-05 12:47:59 +00004195 ){
4196 /* Overwrite an existing WhereLoop with an similar one that uses
4197 ** more terms of the index */
4198 pNext = p->pNextLoop;
drhcd0f4072013-06-05 12:47:59 +00004199 break;
4200 }else{
4201 /* pTemplate is not helpful.
4202 ** Return without changing or adding anything */
4203 goto whereLoopInsert_noop;
4204 }
drhf1b5f5b2013-05-02 00:15:01 +00004205 }
4206 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
drhf1b5f5b2013-05-02 00:15:01 +00004207 && p->rRun>=pTemplate->rRun
drhf46af732013-08-30 17:35:44 +00004208 && p->nOut>=pTemplate->nOut
drhdbb80232013-06-19 12:34:13 +00004209 && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
drhf1b5f5b2013-05-02 00:15:01 +00004210 ){
drh4a5acf82013-06-18 20:06:23 +00004211 /* Overwrite an existing WhereLoop with a better one: one that is
drhe56dd3a2013-08-30 17:50:35 +00004212 ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
drhf46af732013-08-30 17:35:44 +00004213 ** or (4) number of output rows, and is no worse in any of those
4214 ** categories. */
drh43fe25f2013-05-07 23:06:23 +00004215 pNext = p->pNextLoop;
drhf1b5f5b2013-05-02 00:15:01 +00004216 break;
4217 }
4218 }
4219
4220 /* If we reach this point it means that either p[] should be overwritten
4221 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
4222 ** WhereLoop and insert it.
4223 */
drhae70cf12013-05-31 15:18:46 +00004224#if WHERETRACE_ENABLED
4225 if( sqlite3WhereTrace & 0x8 ){
4226 if( p!=0 ){
4227 sqlite3DebugPrintf("ins-del: ");
drh70d18342013-06-06 19:16:33 +00004228 whereLoopPrint(p, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004229 }
4230 sqlite3DebugPrintf("ins-new: ");
drh70d18342013-06-06 19:16:33 +00004231 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004232 }
4233#endif
drhf1b5f5b2013-05-02 00:15:01 +00004234 if( p==0 ){
drh4efc9292013-06-06 23:02:03 +00004235 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
drhf1b5f5b2013-05-02 00:15:01 +00004236 if( p==0 ) return SQLITE_NOMEM;
drh4efc9292013-06-06 23:02:03 +00004237 whereLoopInit(p);
drhf1b5f5b2013-05-02 00:15:01 +00004238 }
drh4efc9292013-06-06 23:02:03 +00004239 whereLoopXfer(db, p, pTemplate);
drh43fe25f2013-05-07 23:06:23 +00004240 p->pNextLoop = pNext;
4241 *ppPrev = p;
drh5346e952013-05-08 14:14:26 +00004242 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
drhef866372013-05-22 20:49:02 +00004243 Index *pIndex = p->u.btree.pIndex;
4244 if( pIndex && pIndex->tnum==0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004245 p->u.btree.pIndex = 0;
4246 }
drh5346e952013-05-08 14:14:26 +00004247 }
drhf1b5f5b2013-05-02 00:15:01 +00004248 return SQLITE_OK;
drhae70cf12013-05-31 15:18:46 +00004249
4250 /* Jump here if the insert is a no-op */
4251whereLoopInsert_noop:
4252#if WHERETRACE_ENABLED
4253 if( sqlite3WhereTrace & 0x8 ){
drhaa32e3c2013-07-16 21:31:23 +00004254 sqlite3DebugPrintf("ins-noop: ");
drh70d18342013-06-06 19:16:33 +00004255 whereLoopPrint(pTemplate, pWInfo->pTabList);
drhae70cf12013-05-31 15:18:46 +00004256 }
4257#endif
4258 return SQLITE_OK;
drhf1b5f5b2013-05-02 00:15:01 +00004259}
4260
4261/*
drh5346e952013-05-08 14:14:26 +00004262** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
drh1c8148f2013-05-04 20:25:23 +00004263** Try to match one more.
4264**
4265** If pProbe->tnum==0, that means pIndex is a fake index used for the
4266** INTEGER PRIMARY KEY.
4267*/
drh5346e952013-05-08 14:14:26 +00004268static int whereLoopAddBtreeIndex(
drh1c8148f2013-05-04 20:25:23 +00004269 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
4270 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
4271 Index *pProbe, /* An index on pSrc */
drhb8a8e8a2013-06-10 19:12:39 +00004272 WhereCost nInMul /* log(Number of iterations due to IN) */
drh1c8148f2013-05-04 20:25:23 +00004273){
drh70d18342013-06-06 19:16:33 +00004274 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
4275 Parse *pParse = pWInfo->pParse; /* Parsing context */
4276 sqlite3 *db = pParse->db; /* Database connection malloc context */
drh1c8148f2013-05-04 20:25:23 +00004277 WhereLoop *pNew; /* Template WhereLoop under construction */
4278 WhereTerm *pTerm; /* A WhereTerm under consideration */
drh43fe25f2013-05-07 23:06:23 +00004279 int opMask; /* Valid operators for constraints */
drh1c8148f2013-05-04 20:25:23 +00004280 WhereScan scan; /* Iterator for WHERE terms */
drh4efc9292013-06-06 23:02:03 +00004281 Bitmask saved_prereq; /* Original value of pNew->prereq */
4282 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
4283 int saved_nEq; /* Original value of pNew->u.btree.nEq */
4284 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
4285 WhereCost saved_nOut; /* Original value of pNew->nOut */
drha18f3d22013-05-08 03:05:41 +00004286 int iCol; /* Index of the column in the table */
drh5346e952013-05-08 14:14:26 +00004287 int rc = SQLITE_OK; /* Return code */
drhb8a8e8a2013-06-10 19:12:39 +00004288 WhereCost nRowEst; /* Estimated index selectivity */
drh4efc9292013-06-06 23:02:03 +00004289 WhereCost rLogSize; /* Logarithm of table size */
drhc7f0d222013-06-19 03:27:12 +00004290 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
drh1c8148f2013-05-04 20:25:23 +00004291
drh1c8148f2013-05-04 20:25:23 +00004292 pNew = pBuilder->pNew;
drh5346e952013-05-08 14:14:26 +00004293 if( db->mallocFailed ) return SQLITE_NOMEM;
drh1c8148f2013-05-04 20:25:23 +00004294
drh5346e952013-05-08 14:14:26 +00004295 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh43fe25f2013-05-07 23:06:23 +00004296 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
4297 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
4298 opMask = WO_LT|WO_LE;
4299 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
4300 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004301 }else{
drh43fe25f2013-05-07 23:06:23 +00004302 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
drh1c8148f2013-05-04 20:25:23 +00004303 }
drhef866372013-05-22 20:49:02 +00004304 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
drh1c8148f2013-05-04 20:25:23 +00004305
drh7963b0e2013-06-17 21:37:40 +00004306 assert( pNew->u.btree.nEq<=pProbe->nColumn );
drh0f133a42013-05-22 17:01:17 +00004307 if( pNew->u.btree.nEq < pProbe->nColumn ){
4308 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
drhe1e2e9a2013-06-13 15:16:53 +00004309 nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
drhc7f0d222013-06-19 03:27:12 +00004310 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
drh0f133a42013-05-22 17:01:17 +00004311 }else{
4312 iCol = -1;
drhb8a8e8a2013-06-10 19:12:39 +00004313 nRowEst = 0;
drh0f133a42013-05-22 17:01:17 +00004314 }
drha18f3d22013-05-08 03:05:41 +00004315 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
drh0f133a42013-05-22 17:01:17 +00004316 opMask, pProbe);
drh4efc9292013-06-06 23:02:03 +00004317 saved_nEq = pNew->u.btree.nEq;
4318 saved_nLTerm = pNew->nLTerm;
4319 saved_wsFlags = pNew->wsFlags;
4320 saved_prereq = pNew->prereq;
4321 saved_nOut = pNew->nOut;
drhb8a8e8a2013-06-10 19:12:39 +00004322 pNew->rSetup = 0;
drhe1e2e9a2013-06-13 15:16:53 +00004323 rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
drh5346e952013-05-08 14:14:26 +00004324 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
drhb8a8e8a2013-06-10 19:12:39 +00004325 int nIn = 0;
drh1435a9a2013-08-27 23:15:44 +00004326#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004327 int nRecValid = pBuilder->nRecValid;
drhb5246e52013-07-08 21:12:57 +00004328#endif
dan8bff07a2013-08-29 14:56:14 +00004329 if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
4330 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
4331 ){
4332 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
4333 }
dan7a419232013-08-06 20:01:43 +00004334 if( pTerm->prereqRight & pNew->maskSelf ) continue;
4335
danad45ed72013-08-08 12:21:32 +00004336 assert( pNew->nOut==saved_nOut );
4337
drh4efc9292013-06-06 23:02:03 +00004338 pNew->wsFlags = saved_wsFlags;
4339 pNew->u.btree.nEq = saved_nEq;
4340 pNew->nLTerm = saved_nLTerm;
4341 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
4342 pNew->aLTerm[pNew->nLTerm++] = pTerm;
4343 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
drhe1e2e9a2013-06-13 15:16:53 +00004344 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
drha18f3d22013-05-08 03:05:41 +00004345 if( pTerm->eOperator & WO_IN ){
4346 Expr *pExpr = pTerm->pExpr;
4347 pNew->wsFlags |= WHERE_COLUMN_IN;
4348 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhe1e2e9a2013-06-13 15:16:53 +00004349 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
4350 nIn = 46; assert( 46==whereCost(25) );
drha18f3d22013-05-08 03:05:41 +00004351 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
4352 /* "x IN (value, value, ...)" */
drhe1e2e9a2013-06-13 15:16:53 +00004353 nIn = whereCost(pExpr->x.pList->nExpr);
drhf1645f02013-05-07 19:44:38 +00004354 }
drhb8a8e8a2013-06-10 19:12:39 +00004355 pNew->rRun += nIn;
drh5346e952013-05-08 14:14:26 +00004356 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004357 pNew->nOut = nRowEst + nInMul + nIn;
drh6fa978d2013-05-30 19:29:19 +00004358 }else if( pTerm->eOperator & (WO_EQ) ){
drh7699d1c2013-06-04 12:42:29 +00004359 assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
drhb8a8e8a2013-06-10 19:12:39 +00004360 || nInMul==0 );
drha18f3d22013-05-08 03:05:41 +00004361 pNew->wsFlags |= WHERE_COLUMN_EQ;
drh7699d1c2013-06-04 12:42:29 +00004362 if( iCol<0
drhb8a8e8a2013-06-10 19:12:39 +00004363 || (pProbe->onError!=OE_None && nInMul==0
drh21f7ff72013-06-03 15:07:23 +00004364 && pNew->u.btree.nEq==pProbe->nColumn-1)
4365 ){
drh4a5acf82013-06-18 20:06:23 +00004366 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
drh7699d1c2013-06-04 12:42:29 +00004367 pNew->wsFlags |= WHERE_ONEROW;
drh21f7ff72013-06-03 15:07:23 +00004368 }
drh5346e952013-05-08 14:14:26 +00004369 pNew->u.btree.nEq++;
drhb8a8e8a2013-06-10 19:12:39 +00004370 pNew->nOut = nRowEst + nInMul;
drh6fa978d2013-05-30 19:29:19 +00004371 }else if( pTerm->eOperator & (WO_ISNULL) ){
4372 pNew->wsFlags |= WHERE_COLUMN_NULL;
4373 pNew->u.btree.nEq++;
drhe1e2e9a2013-06-13 15:16:53 +00004374 /* TUNING: IS NULL selects 2 rows */
4375 nIn = 10; assert( 10==whereCost(2) );
drhb8a8e8a2013-06-10 19:12:39 +00004376 pNew->nOut = nRowEst + nInMul + nIn;
drha18f3d22013-05-08 03:05:41 +00004377 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
drh7963b0e2013-06-17 21:37:40 +00004378 testcase( pTerm->eOperator & WO_GT );
4379 testcase( pTerm->eOperator & WO_GE );
drha18f3d22013-05-08 03:05:41 +00004380 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004381 pBtm = pTerm;
4382 pTop = 0;
drh7963b0e2013-06-17 21:37:40 +00004383 }else{
4384 assert( pTerm->eOperator & (WO_LT|WO_LE) );
4385 testcase( pTerm->eOperator & WO_LT );
4386 testcase( pTerm->eOperator & WO_LE );
drha18f3d22013-05-08 03:05:41 +00004387 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
drh6f2bfad2013-06-03 17:35:22 +00004388 pTop = pTerm;
4389 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
drh4efc9292013-06-06 23:02:03 +00004390 pNew->aLTerm[pNew->nLTerm-2] : 0;
drh1c8148f2013-05-04 20:25:23 +00004391 }
drh6f2bfad2013-06-03 17:35:22 +00004392 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
4393 /* Adjust nOut and rRun for STAT3 range values */
dan6cb8d762013-08-08 11:48:57 +00004394 assert( pNew->nOut==saved_nOut );
4395 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, &pNew->nOut);
drh6f2bfad2013-06-03 17:35:22 +00004396 }
drh1435a9a2013-08-27 23:15:44 +00004397#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan8ad169a2013-08-12 20:14:04 +00004398 if( nInMul==0
4399 && pProbe->nSample
4400 && pNew->u.btree.nEq<=pProbe->nSampleCol
4401 && OptimizationEnabled(db, SQLITE_Stat3)
4402 ){
dan7a419232013-08-06 20:01:43 +00004403 Expr *pExpr = pTerm->pExpr;
drhb8a8e8a2013-06-10 19:12:39 +00004404 tRowcnt nOut = 0;
drh6f2bfad2013-06-03 17:35:22 +00004405 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
drh93ec45d2013-06-17 18:20:48 +00004406 testcase( pTerm->eOperator & WO_EQ );
4407 testcase( pTerm->eOperator & WO_ISNULL );
dan7a419232013-08-06 20:01:43 +00004408 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004409 }else if( (pTerm->eOperator & WO_IN)
dan7a419232013-08-06 20:01:43 +00004410 && !ExprHasProperty(pExpr, EP_xIsSelect) ){
4411 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
drh6f2bfad2013-06-03 17:35:22 +00004412 }
drh82846332013-08-01 17:21:26 +00004413 assert( nOut==0 || rc==SQLITE_OK );
dan6cb8d762013-08-08 11:48:57 +00004414 if( nOut ){
4415 nOut = whereCost(nOut);
4416 pNew->nOut = MIN(nOut, saved_nOut);
4417 }
drh6f2bfad2013-06-03 17:35:22 +00004418 }
4419#endif
drhe217efc2013-06-12 03:48:41 +00004420 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
drheb04de32013-05-10 15:16:30 +00004421 /* Each row involves a step of the index, then a binary search of
4422 ** the main table */
drhe217efc2013-06-12 03:48:41 +00004423 pNew->rRun = whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
drheb04de32013-05-10 15:16:30 +00004424 }
drhe217efc2013-06-12 03:48:41 +00004425 /* Step cost for each output row */
4426 pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
drheb04de32013-05-10 15:16:30 +00004427 /* TBD: Adjust nOut for additional constraints */
drhcf8fa7a2013-05-10 20:26:22 +00004428 rc = whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004429 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
drhbbe8b242013-06-13 15:50:59 +00004430 && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
drh5346e952013-05-08 14:14:26 +00004431 ){
drhb8a8e8a2013-06-10 19:12:39 +00004432 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
drha18f3d22013-05-08 03:05:41 +00004433 }
danad45ed72013-08-08 12:21:32 +00004434 pNew->nOut = saved_nOut;
drh1435a9a2013-08-27 23:15:44 +00004435#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan7a419232013-08-06 20:01:43 +00004436 pBuilder->nRecValid = nRecValid;
dan7a419232013-08-06 20:01:43 +00004437#endif
drh1c8148f2013-05-04 20:25:23 +00004438 }
drh4efc9292013-06-06 23:02:03 +00004439 pNew->prereq = saved_prereq;
4440 pNew->u.btree.nEq = saved_nEq;
4441 pNew->wsFlags = saved_wsFlags;
4442 pNew->nOut = saved_nOut;
4443 pNew->nLTerm = saved_nLTerm;
drh5346e952013-05-08 14:14:26 +00004444 return rc;
drh1c8148f2013-05-04 20:25:23 +00004445}
4446
4447/*
drh23f98da2013-05-21 15:52:07 +00004448** Return True if it is possible that pIndex might be useful in
4449** implementing the ORDER BY clause in pBuilder.
4450**
4451** Return False if pBuilder does not contain an ORDER BY clause or
4452** if there is no way for pIndex to be useful in implementing that
4453** ORDER BY clause.
4454*/
4455static int indexMightHelpWithOrderBy(
4456 WhereLoopBuilder *pBuilder,
4457 Index *pIndex,
4458 int iCursor
4459){
4460 ExprList *pOB;
drh6d381472013-06-13 17:58:08 +00004461 int ii, jj;
drh23f98da2013-05-21 15:52:07 +00004462
drh53cfbe92013-06-13 17:28:22 +00004463 if( pIndex->bUnordered ) return 0;
drh70d18342013-06-06 19:16:33 +00004464 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
drh23f98da2013-05-21 15:52:07 +00004465 for(ii=0; ii<pOB->nExpr; ii++){
drh45c154a2013-06-03 20:46:35 +00004466 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
drh23f98da2013-05-21 15:52:07 +00004467 if( pExpr->op!=TK_COLUMN ) return 0;
4468 if( pExpr->iTable==iCursor ){
drh6d381472013-06-13 17:58:08 +00004469 for(jj=0; jj<pIndex->nColumn; jj++){
4470 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
4471 }
drh23f98da2013-05-21 15:52:07 +00004472 }
4473 }
4474 return 0;
4475}
4476
4477/*
drh92a121f2013-06-10 12:15:47 +00004478** Return a bitmask where 1s indicate that the corresponding column of
4479** the table is used by an index. Only the first 63 columns are considered.
4480*/
drhfd5874d2013-06-12 14:52:39 +00004481static Bitmask columnsInIndex(Index *pIdx){
drh92a121f2013-06-10 12:15:47 +00004482 Bitmask m = 0;
4483 int j;
4484 for(j=pIdx->nColumn-1; j>=0; j--){
4485 int x = pIdx->aiColumn[j];
dan2c187882013-08-19 19:29:50 +00004486 assert( x>=0 );
drh7963b0e2013-06-17 21:37:40 +00004487 testcase( x==BMS-1 );
4488 testcase( x==BMS-2 );
drh92a121f2013-06-10 12:15:47 +00004489 if( x<BMS-1 ) m |= MASKBIT(x);
4490 }
4491 return m;
4492}
4493
drh4bd5f732013-07-31 23:22:39 +00004494/* Check to see if a partial index with pPartIndexWhere can be used
4495** in the current query. Return true if it can be and false if not.
4496*/
4497static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
4498 int i;
4499 WhereTerm *pTerm;
4500 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
4501 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
4502 }
4503 return 0;
4504}
drh92a121f2013-06-10 12:15:47 +00004505
4506/*
dan51576f42013-07-02 10:06:15 +00004507** Add all WhereLoop objects for a single table of the join where the table
drh0823c892013-05-11 00:06:23 +00004508** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
4509** a b-tree table, not a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004510*/
drh5346e952013-05-08 14:14:26 +00004511static int whereLoopAddBtree(
drh1c8148f2013-05-04 20:25:23 +00004512 WhereLoopBuilder *pBuilder, /* WHERE clause information */
drh1c8148f2013-05-04 20:25:23 +00004513 Bitmask mExtra /* Extra prerequesites for using this table */
drhf1b5f5b2013-05-02 00:15:01 +00004514){
drh70d18342013-06-06 19:16:33 +00004515 WhereInfo *pWInfo; /* WHERE analysis context */
drh1c8148f2013-05-04 20:25:23 +00004516 Index *pProbe; /* An index we are evaluating */
drh1c8148f2013-05-04 20:25:23 +00004517 Index sPk; /* A fake index object for the primary key */
4518 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
4519 int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
drh70d18342013-06-06 19:16:33 +00004520 SrcList *pTabList; /* The FROM clause */
drh1c8148f2013-05-04 20:25:23 +00004521 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
drh1c8148f2013-05-04 20:25:23 +00004522 WhereLoop *pNew; /* Template WhereLoop object */
drh5346e952013-05-08 14:14:26 +00004523 int rc = SQLITE_OK; /* Return code */
drhd044d202013-05-31 12:43:55 +00004524 int iSortIdx = 1; /* Index number */
drh23f98da2013-05-21 15:52:07 +00004525 int b; /* A boolean value */
drhb8a8e8a2013-06-10 19:12:39 +00004526 WhereCost rSize; /* number of rows in the table */
4527 WhereCost rLogSize; /* Logarithm of the number of rows in the table */
drh4bd5f732013-07-31 23:22:39 +00004528 WhereClause *pWC; /* The parsed WHERE clause */
drh23f98da2013-05-21 15:52:07 +00004529
drh1c8148f2013-05-04 20:25:23 +00004530 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004531 pWInfo = pBuilder->pWInfo;
4532 pTabList = pWInfo->pTabList;
4533 pSrc = pTabList->a + pNew->iTab;
drh4bd5f732013-07-31 23:22:39 +00004534 pWC = pBuilder->pWC;
drh0823c892013-05-11 00:06:23 +00004535 assert( !IsVirtual(pSrc->pTab) );
drh1c8148f2013-05-04 20:25:23 +00004536
4537 if( pSrc->pIndex ){
4538 /* An INDEXED BY clause specifies a particular index to use */
4539 pProbe = pSrc->pIndex;
4540 }else{
4541 /* There is no INDEXED BY clause. Create a fake Index object in local
4542 ** variable sPk to represent the rowid primary key index. Make this
4543 ** fake index the first in a chain of Index objects with all of the real
4544 ** indices to follow */
4545 Index *pFirst; /* First of real indices on the table */
4546 memset(&sPk, 0, sizeof(Index));
4547 sPk.nColumn = 1;
4548 sPk.aiColumn = &aiColumnPk;
4549 sPk.aiRowEst = aiRowEstPk;
4550 sPk.onError = OE_Replace;
4551 sPk.pTable = pSrc->pTab;
4552 aiRowEstPk[0] = pSrc->pTab->nRowEst;
4553 aiRowEstPk[1] = 1;
4554 pFirst = pSrc->pTab->pIndex;
4555 if( pSrc->notIndexed==0 ){
4556 /* The real indices of the table are only considered if the
4557 ** NOT INDEXED qualifier is omitted from the FROM clause */
4558 sPk.pNext = pFirst;
4559 }
4560 pProbe = &sPk;
4561 }
drhe1e2e9a2013-06-13 15:16:53 +00004562 rSize = whereCost(pSrc->pTab->nRowEst);
drheb04de32013-05-10 15:16:30 +00004563 rLogSize = estLog(rSize);
4564
drhfeb56e02013-08-23 17:33:46 +00004565#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
drheb04de32013-05-10 15:16:30 +00004566 /* Automatic indexes */
drhaa32e3c2013-07-16 21:31:23 +00004567 if( !pBuilder->pOrSet
drh4fe425a2013-06-12 17:08:06 +00004568 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
4569 && pSrc->pIndex==0
drheb04de32013-05-10 15:16:30 +00004570 && !pSrc->viaCoroutine
4571 && !pSrc->notIndexed
4572 && !pSrc->isCorrelated
4573 ){
4574 /* Generate auto-index WhereLoops */
drheb04de32013-05-10 15:16:30 +00004575 WhereTerm *pTerm;
4576 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
4577 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
drh79a13bf2013-05-31 20:28:28 +00004578 if( pTerm->prereqRight & pNew->maskSelf ) continue;
drheb04de32013-05-10 15:16:30 +00004579 if( termCanDriveIndex(pTerm, pSrc, 0) ){
4580 pNew->u.btree.nEq = 1;
drhef866372013-05-22 20:49:02 +00004581 pNew->u.btree.pIndex = 0;
drh4efc9292013-06-06 23:02:03 +00004582 pNew->nLTerm = 1;
4583 pNew->aLTerm[0] = pTerm;
drhe1e2e9a2013-06-13 15:16:53 +00004584 /* TUNING: One-time cost for computing the automatic index is
drh986b3872013-06-28 21:12:20 +00004585 ** approximately 7*N*log2(N) where N is the number of rows in
drhe1e2e9a2013-06-13 15:16:53 +00004586 ** the table being indexed. */
drh986b3872013-06-28 21:12:20 +00004587 pNew->rSetup = rLogSize + rSize + 28; assert( 28==whereCost(7) );
4588 /* TUNING: Each index lookup yields 20 rows in the table. This
4589 ** is more than the usual guess of 10 rows, since we have no way
4590 ** of knowning how selective the index will ultimately be. It would
4591 ** not be unreasonable to make this value much larger. */
4592 pNew->nOut = 43; assert( 43==whereCost(20) );
drhb8a8e8a2013-06-10 19:12:39 +00004593 pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
drh986b3872013-06-28 21:12:20 +00004594 pNew->wsFlags = WHERE_AUTO_INDEX;
drheb04de32013-05-10 15:16:30 +00004595 pNew->prereq = mExtra | pTerm->prereqRight;
drhcf8fa7a2013-05-10 20:26:22 +00004596 rc = whereLoopInsert(pBuilder, pNew);
drheb04de32013-05-10 15:16:30 +00004597 }
4598 }
4599 }
drhfeb56e02013-08-23 17:33:46 +00004600#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
drh1c8148f2013-05-04 20:25:23 +00004601
4602 /* Loop over all indices
4603 */
drh23f98da2013-05-21 15:52:07 +00004604 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
drh4bd5f732013-07-31 23:22:39 +00004605 if( pProbe->pPartIdxWhere!=0
4606 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
4607 continue; /* Partial index inappropriate for this query */
4608 }
drh5346e952013-05-08 14:14:26 +00004609 pNew->u.btree.nEq = 0;
drh4efc9292013-06-06 23:02:03 +00004610 pNew->nLTerm = 0;
drh23f98da2013-05-21 15:52:07 +00004611 pNew->iSortIdx = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004612 pNew->rSetup = 0;
drh23f98da2013-05-21 15:52:07 +00004613 pNew->prereq = mExtra;
drh74f91d42013-06-19 18:01:44 +00004614 pNew->nOut = rSize;
drh23f98da2013-05-21 15:52:07 +00004615 pNew->u.btree.pIndex = pProbe;
4616 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
drh53cfbe92013-06-13 17:28:22 +00004617 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
4618 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
drh43fe25f2013-05-07 23:06:23 +00004619 if( pProbe->tnum<=0 ){
4620 /* Integer primary key index */
4621 pNew->wsFlags = WHERE_IPK;
drh23f98da2013-05-21 15:52:07 +00004622
4623 /* Full table scan */
drhd044d202013-05-31 12:43:55 +00004624 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004625 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
4626 ** + The extra 3 factor is to encourage the use of indexed lookups
4627 ** over full scans. A smaller constant 2 is used for covering
4628 ** index scans so that a covering index scan will be favored over
4629 ** a table scan. */
4630 pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
drh23f98da2013-05-21 15:52:07 +00004631 rc = whereLoopInsert(pBuilder, pNew);
4632 if( rc ) break;
drh43fe25f2013-05-07 23:06:23 +00004633 }else{
drhfd5874d2013-06-12 14:52:39 +00004634 Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
drh6fa978d2013-05-30 19:29:19 +00004635 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
drh1c8148f2013-05-04 20:25:23 +00004636
drh23f98da2013-05-21 15:52:07 +00004637 /* Full scan via index */
drh53cfbe92013-06-13 17:28:22 +00004638 if( b
4639 || ( m==0
4640 && pProbe->bUnordered==0
4641 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
4642 && sqlite3GlobalConfig.bUseCis
4643 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
4644 )
drhe3b7c922013-06-03 19:17:40 +00004645 ){
drh23f98da2013-05-21 15:52:07 +00004646 pNew->iSortIdx = b ? iSortIdx : 0;
drhe1e2e9a2013-06-13 15:16:53 +00004647 if( m==0 ){
4648 /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
4649 ** + The extra 2 factor is to encourage the use of indexed lookups
4650 ** over index scans. A table scan uses a factor of 3 so that
4651 ** index scans are favored over table scans.
4652 ** + If this covering index might also help satisfy the ORDER BY
4653 ** clause, then the cost is fudged down slightly so that this
4654 ** index is favored above other indices that have no hope of
4655 ** helping with the ORDER BY. */
4656 pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
4657 }else{
4658 assert( b!=0 );
4659 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
4660 ** which we will simplify to just N*log2(N) */
4661 pNew->rRun = rSize + rLogSize;
4662 }
drh23f98da2013-05-21 15:52:07 +00004663 rc = whereLoopInsert(pBuilder, pNew);
4664 if( rc ) break;
4665 }
4666 }
dan7a419232013-08-06 20:01:43 +00004667
drhb8a8e8a2013-06-10 19:12:39 +00004668 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
drh1435a9a2013-08-27 23:15:44 +00004669#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan87cd9322013-08-07 15:52:41 +00004670 sqlite3Stat4ProbeFree(pBuilder->pRec);
4671 pBuilder->nRecValid = 0;
4672 pBuilder->pRec = 0;
danddc2d6e2013-08-06 20:15:06 +00004673#endif
drh1c8148f2013-05-04 20:25:23 +00004674
4675 /* If there was an INDEXED BY clause, then only that one index is
4676 ** considered. */
4677 if( pSrc->pIndex ) break;
4678 }
drh5346e952013-05-08 14:14:26 +00004679 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004680}
4681
drh8636e9c2013-06-11 01:50:08 +00004682#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf1b5f5b2013-05-02 00:15:01 +00004683/*
drh0823c892013-05-11 00:06:23 +00004684** Add all WhereLoop objects for a table of the join identified by
4685** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
drhf1b5f5b2013-05-02 00:15:01 +00004686*/
drh5346e952013-05-08 14:14:26 +00004687static int whereLoopAddVirtual(
drh613ba1e2013-06-15 15:11:45 +00004688 WhereLoopBuilder *pBuilder /* WHERE clause information */
drhf1b5f5b2013-05-02 00:15:01 +00004689){
drh70d18342013-06-06 19:16:33 +00004690 WhereInfo *pWInfo; /* WHERE analysis context */
drh5346e952013-05-08 14:14:26 +00004691 Parse *pParse; /* The parsing context */
4692 WhereClause *pWC; /* The WHERE clause */
4693 struct SrcList_item *pSrc; /* The FROM clause term to search */
4694 Table *pTab;
4695 sqlite3 *db;
4696 sqlite3_index_info *pIdxInfo;
4697 struct sqlite3_index_constraint *pIdxCons;
4698 struct sqlite3_index_constraint_usage *pUsage;
4699 WhereTerm *pTerm;
4700 int i, j;
4701 int iTerm, mxTerm;
drh4efc9292013-06-06 23:02:03 +00004702 int nConstraint;
drh5346e952013-05-08 14:14:26 +00004703 int seenIn = 0; /* True if an IN operator is seen */
4704 int seenVar = 0; /* True if a non-constant constraint is seen */
4705 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
4706 WhereLoop *pNew;
drh5346e952013-05-08 14:14:26 +00004707 int rc = SQLITE_OK;
4708
drh70d18342013-06-06 19:16:33 +00004709 pWInfo = pBuilder->pWInfo;
4710 pParse = pWInfo->pParse;
drh5346e952013-05-08 14:14:26 +00004711 db = pParse->db;
4712 pWC = pBuilder->pWC;
drh5346e952013-05-08 14:14:26 +00004713 pNew = pBuilder->pNew;
drh70d18342013-06-06 19:16:33 +00004714 pSrc = &pWInfo->pTabList->a[pNew->iTab];
drhb2a90f02013-05-10 03:30:49 +00004715 pTab = pSrc->pTab;
drh0823c892013-05-11 00:06:23 +00004716 assert( IsVirtual(pTab) );
drhb2a90f02013-05-10 03:30:49 +00004717 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
drh5346e952013-05-08 14:14:26 +00004718 if( pIdxInfo==0 ) return SQLITE_NOMEM;
drh5346e952013-05-08 14:14:26 +00004719 pNew->prereq = 0;
drh5346e952013-05-08 14:14:26 +00004720 pNew->rSetup = 0;
4721 pNew->wsFlags = WHERE_VIRTUALTABLE;
drh4efc9292013-06-06 23:02:03 +00004722 pNew->nLTerm = 0;
drh5346e952013-05-08 14:14:26 +00004723 pNew->u.vtab.needFree = 0;
4724 pUsage = pIdxInfo->aConstraintUsage;
drh4efc9292013-06-06 23:02:03 +00004725 nConstraint = pIdxInfo->nConstraint;
drh7963b0e2013-06-17 21:37:40 +00004726 if( whereLoopResize(db, pNew, nConstraint) ){
4727 sqlite3DbFree(db, pIdxInfo);
4728 return SQLITE_NOMEM;
4729 }
drh5346e952013-05-08 14:14:26 +00004730
drh0823c892013-05-11 00:06:23 +00004731 for(iPhase=0; iPhase<=3; iPhase++){
drh5346e952013-05-08 14:14:26 +00004732 if( !seenIn && (iPhase&1)!=0 ){
4733 iPhase++;
4734 if( iPhase>3 ) break;
4735 }
4736 if( !seenVar && iPhase>1 ) break;
4737 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4738 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
4739 j = pIdxCons->iTermOffset;
4740 pTerm = &pWC->a[j];
4741 switch( iPhase ){
4742 case 0: /* Constants without IN operator */
4743 pIdxCons->usable = 0;
4744 if( (pTerm->eOperator & WO_IN)!=0 ){
4745 seenIn = 1;
drh7963b0e2013-06-17 21:37:40 +00004746 }
4747 if( pTerm->prereqRight!=0 ){
drh5346e952013-05-08 14:14:26 +00004748 seenVar = 1;
drh7963b0e2013-06-17 21:37:40 +00004749 }else if( (pTerm->eOperator & WO_IN)==0 ){
drh5346e952013-05-08 14:14:26 +00004750 pIdxCons->usable = 1;
4751 }
4752 break;
4753 case 1: /* Constants with IN operators */
4754 assert( seenIn );
4755 pIdxCons->usable = (pTerm->prereqRight==0);
4756 break;
4757 case 2: /* Variables without IN */
4758 assert( seenVar );
4759 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
4760 break;
4761 default: /* Variables with IN */
4762 assert( seenVar && seenIn );
4763 pIdxCons->usable = 1;
4764 break;
4765 }
4766 }
4767 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
4768 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4769 pIdxInfo->idxStr = 0;
4770 pIdxInfo->idxNum = 0;
4771 pIdxInfo->needToFreeIdxStr = 0;
4772 pIdxInfo->orderByConsumed = 0;
drh8636e9c2013-06-11 01:50:08 +00004773 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
drh5346e952013-05-08 14:14:26 +00004774 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
4775 if( rc ) goto whereLoopAddVtab_exit;
4776 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
4777 pNew->prereq = 0;
drhc718f1c2013-05-08 20:05:58 +00004778 mxTerm = -1;
drh4efc9292013-06-06 23:02:03 +00004779 assert( pNew->nLSlot>=nConstraint );
4780 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
drh3bd26f02013-05-24 14:52:03 +00004781 pNew->u.vtab.omitMask = 0;
drh4efc9292013-06-06 23:02:03 +00004782 for(i=0; i<nConstraint; i++, pIdxCons++){
drh5346e952013-05-08 14:14:26 +00004783 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
4784 j = pIdxCons->iTermOffset;
drh4efc9292013-06-06 23:02:03 +00004785 if( iTerm>=nConstraint
drh5346e952013-05-08 14:14:26 +00004786 || j<0
4787 || j>=pWC->nTerm
drh4efc9292013-06-06 23:02:03 +00004788 || pNew->aLTerm[iTerm]!=0
drh5346e952013-05-08 14:14:26 +00004789 ){
4790 rc = SQLITE_ERROR;
4791 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
4792 goto whereLoopAddVtab_exit;
4793 }
drh7963b0e2013-06-17 21:37:40 +00004794 testcase( iTerm==nConstraint-1 );
4795 testcase( j==0 );
4796 testcase( j==pWC->nTerm-1 );
drh5346e952013-05-08 14:14:26 +00004797 pTerm = &pWC->a[j];
4798 pNew->prereq |= pTerm->prereqRight;
drh4efc9292013-06-06 23:02:03 +00004799 assert( iTerm<pNew->nLSlot );
4800 pNew->aLTerm[iTerm] = pTerm;
drh5346e952013-05-08 14:14:26 +00004801 if( iTerm>mxTerm ) mxTerm = iTerm;
drh7963b0e2013-06-17 21:37:40 +00004802 testcase( iTerm==15 );
4803 testcase( iTerm==16 );
drh52986302013-06-03 16:03:16 +00004804 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
drh5346e952013-05-08 14:14:26 +00004805 if( (pTerm->eOperator & WO_IN)!=0 ){
4806 if( pUsage[i].omit==0 ){
4807 /* Do not attempt to use an IN constraint if the virtual table
4808 ** says that the equivalent EQ constraint cannot be safely omitted.
4809 ** If we do attempt to use such a constraint, some rows might be
4810 ** repeated in the output. */
4811 break;
4812 }
4813 /* A virtual table that is constrained by an IN clause may not
4814 ** consume the ORDER BY clause because (1) the order of IN terms
4815 ** is not necessarily related to the order of output terms and
4816 ** (2) Multiple outputs from a single IN value will not merge
4817 ** together. */
4818 pIdxInfo->orderByConsumed = 0;
4819 }
4820 }
4821 }
drh4efc9292013-06-06 23:02:03 +00004822 if( i>=nConstraint ){
4823 pNew->nLTerm = mxTerm+1;
4824 assert( pNew->nLTerm<=pNew->nLSlot );
drh5346e952013-05-08 14:14:26 +00004825 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
4826 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
4827 pIdxInfo->needToFreeIdxStr = 0;
4828 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
drh3b1d8082013-06-03 16:56:37 +00004829 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
4830 && pIdxInfo->orderByConsumed);
drhb8a8e8a2013-06-10 19:12:39 +00004831 pNew->rSetup = 0;
drh8636e9c2013-06-11 01:50:08 +00004832 pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
drhe1e2e9a2013-06-13 15:16:53 +00004833 /* TUNING: Every virtual table query returns 25 rows */
4834 pNew->nOut = 46; assert( 46==whereCost(25) );
drhcf8fa7a2013-05-10 20:26:22 +00004835 whereLoopInsert(pBuilder, pNew);
drh5346e952013-05-08 14:14:26 +00004836 if( pNew->u.vtab.needFree ){
4837 sqlite3_free(pNew->u.vtab.idxStr);
4838 pNew->u.vtab.needFree = 0;
4839 }
4840 }
4841 }
4842
4843whereLoopAddVtab_exit:
4844 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
4845 sqlite3DbFree(db, pIdxInfo);
4846 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004847}
drh8636e9c2013-06-11 01:50:08 +00004848#endif /* SQLITE_OMIT_VIRTUALTABLE */
drhf1b5f5b2013-05-02 00:15:01 +00004849
4850/*
drhcf8fa7a2013-05-10 20:26:22 +00004851** Add WhereLoop entries to handle OR terms. This works for either
4852** btrees or virtual tables.
4853*/
4854static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
drh70d18342013-06-06 19:16:33 +00004855 WhereInfo *pWInfo = pBuilder->pWInfo;
drhcf8fa7a2013-05-10 20:26:22 +00004856 WhereClause *pWC;
4857 WhereLoop *pNew;
4858 WhereTerm *pTerm, *pWCEnd;
4859 int rc = SQLITE_OK;
4860 int iCur;
4861 WhereClause tempWC;
4862 WhereLoopBuilder sSubBuild;
drhaa32e3c2013-07-16 21:31:23 +00004863 WhereOrSet sSum, sCur, sPrev;
drhcf8fa7a2013-05-10 20:26:22 +00004864 struct SrcList_item *pItem;
4865
drhcf8fa7a2013-05-10 20:26:22 +00004866 pWC = pBuilder->pWC;
drh70d18342013-06-06 19:16:33 +00004867 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
drhcf8fa7a2013-05-10 20:26:22 +00004868 pWCEnd = pWC->a + pWC->nTerm;
4869 pNew = pBuilder->pNew;
drh77dfd5b2013-08-19 11:15:48 +00004870 memset(&sSum, 0, sizeof(sSum));
drhcf8fa7a2013-05-10 20:26:22 +00004871
4872 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4873 if( (pTerm->eOperator & WO_OR)!=0
4874 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4875 ){
4876 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4877 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4878 WhereTerm *pOrTerm;
drhaa32e3c2013-07-16 21:31:23 +00004879 int once = 1;
4880 int i, j;
drh783dece2013-06-05 17:53:43 +00004881
drh70d18342013-06-06 19:16:33 +00004882 pItem = pWInfo->pTabList->a + pNew->iTab;
drh783dece2013-06-05 17:53:43 +00004883 iCur = pItem->iCursor;
4884 sSubBuild = *pBuilder;
4885 sSubBuild.pOrderBy = 0;
drhaa32e3c2013-07-16 21:31:23 +00004886 sSubBuild.pOrSet = &sCur;
drhcf8fa7a2013-05-10 20:26:22 +00004887
drhc7f0d222013-06-19 03:27:12 +00004888 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
drh783dece2013-06-05 17:53:43 +00004889 if( (pOrTerm->eOperator & WO_AND)!=0 ){
drhcf8fa7a2013-05-10 20:26:22 +00004890 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4891 }else if( pOrTerm->leftCursor==iCur ){
drh70d18342013-06-06 19:16:33 +00004892 tempWC.pWInfo = pWC->pWInfo;
drh783dece2013-06-05 17:53:43 +00004893 tempWC.pOuter = pWC;
4894 tempWC.op = TK_AND;
drh783dece2013-06-05 17:53:43 +00004895 tempWC.nTerm = 1;
drhcf8fa7a2013-05-10 20:26:22 +00004896 tempWC.a = pOrTerm;
4897 sSubBuild.pWC = &tempWC;
4898 }else{
4899 continue;
4900 }
drhaa32e3c2013-07-16 21:31:23 +00004901 sCur.n = 0;
drh8636e9c2013-06-11 01:50:08 +00004902#ifndef SQLITE_OMIT_VIRTUALTABLE
drhcf8fa7a2013-05-10 20:26:22 +00004903 if( IsVirtual(pItem->pTab) ){
drh613ba1e2013-06-15 15:11:45 +00004904 rc = whereLoopAddVirtual(&sSubBuild);
drhaa32e3c2013-07-16 21:31:23 +00004905 for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
drh8636e9c2013-06-11 01:50:08 +00004906 }else
4907#endif
4908 {
drhcf8fa7a2013-05-10 20:26:22 +00004909 rc = whereLoopAddBtree(&sSubBuild, mExtra);
4910 }
drhaa32e3c2013-07-16 21:31:23 +00004911 assert( rc==SQLITE_OK || sCur.n==0 );
4912 if( sCur.n==0 ){
4913 sSum.n = 0;
4914 break;
4915 }else if( once ){
4916 whereOrMove(&sSum, &sCur);
4917 once = 0;
4918 }else{
4919 whereOrMove(&sPrev, &sSum);
4920 sSum.n = 0;
4921 for(i=0; i<sPrev.n; i++){
4922 for(j=0; j<sCur.n; j++){
4923 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4924 whereCostAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4925 whereCostAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4926 }
4927 }
4928 }
drhcf8fa7a2013-05-10 20:26:22 +00004929 }
drhaa32e3c2013-07-16 21:31:23 +00004930 pNew->nLTerm = 1;
4931 pNew->aLTerm[0] = pTerm;
4932 pNew->wsFlags = WHERE_MULTI_OR;
4933 pNew->rSetup = 0;
4934 pNew->iSortIdx = 0;
4935 memset(&pNew->u, 0, sizeof(pNew->u));
4936 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
drh74f91d42013-06-19 18:01:44 +00004937 /* TUNING: Multiple by 3.5 for the secondary table lookup */
drhaa32e3c2013-07-16 21:31:23 +00004938 pNew->rRun = sSum.a[i].rRun + 18;
4939 pNew->nOut = sSum.a[i].nOut;
4940 pNew->prereq = sSum.a[i].prereq;
drhfd5874d2013-06-12 14:52:39 +00004941 rc = whereLoopInsert(pBuilder, pNew);
4942 }
drhcf8fa7a2013-05-10 20:26:22 +00004943 }
4944 }
4945 return rc;
4946}
4947
4948/*
drhf1b5f5b2013-05-02 00:15:01 +00004949** Add all WhereLoop objects for all tables
4950*/
drh5346e952013-05-08 14:14:26 +00004951static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
drh70d18342013-06-06 19:16:33 +00004952 WhereInfo *pWInfo = pBuilder->pWInfo;
drhf1b5f5b2013-05-02 00:15:01 +00004953 Bitmask mExtra = 0;
4954 Bitmask mPrior = 0;
4955 int iTab;
drh70d18342013-06-06 19:16:33 +00004956 SrcList *pTabList = pWInfo->pTabList;
drhf1b5f5b2013-05-02 00:15:01 +00004957 struct SrcList_item *pItem;
drh70d18342013-06-06 19:16:33 +00004958 sqlite3 *db = pWInfo->pParse->db;
4959 int nTabList = pWInfo->nLevel;
drh5346e952013-05-08 14:14:26 +00004960 int rc = SQLITE_OK;
drhc63367e2013-06-10 20:46:50 +00004961 u8 priorJoinType = 0;
drhb8a8e8a2013-06-10 19:12:39 +00004962 WhereLoop *pNew;
drhf1b5f5b2013-05-02 00:15:01 +00004963
4964 /* Loop over the tables in the join, from left to right */
drhb8a8e8a2013-06-10 19:12:39 +00004965 pNew = pBuilder->pNew;
drha2014152013-06-07 00:29:23 +00004966 whereLoopInit(pNew);
drha18f3d22013-05-08 03:05:41 +00004967 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
drhb2a90f02013-05-10 03:30:49 +00004968 pNew->iTab = iTab;
drh70d18342013-06-06 19:16:33 +00004969 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
drhc63367e2013-06-10 20:46:50 +00004970 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
drhf1b5f5b2013-05-02 00:15:01 +00004971 mExtra = mPrior;
4972 }
drhc63367e2013-06-10 20:46:50 +00004973 priorJoinType = pItem->jointype;
drhb2a90f02013-05-10 03:30:49 +00004974 if( IsVirtual(pItem->pTab) ){
drh613ba1e2013-06-15 15:11:45 +00004975 rc = whereLoopAddVirtual(pBuilder);
drhb2a90f02013-05-10 03:30:49 +00004976 }else{
4977 rc = whereLoopAddBtree(pBuilder, mExtra);
4978 }
drhb2a90f02013-05-10 03:30:49 +00004979 if( rc==SQLITE_OK ){
4980 rc = whereLoopAddOr(pBuilder, mExtra);
4981 }
drhb2a90f02013-05-10 03:30:49 +00004982 mPrior |= pNew->maskSelf;
drh5346e952013-05-08 14:14:26 +00004983 if( rc || db->mallocFailed ) break;
drhf1b5f5b2013-05-02 00:15:01 +00004984 }
drha2014152013-06-07 00:29:23 +00004985 whereLoopClear(db, pNew);
drh5346e952013-05-08 14:14:26 +00004986 return rc;
drhf1b5f5b2013-05-02 00:15:01 +00004987}
4988
drha18f3d22013-05-08 03:05:41 +00004989/*
drh7699d1c2013-06-04 12:42:29 +00004990** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
drh319f6772013-05-14 15:31:07 +00004991** parameters) to see if it outputs rows in the requested ORDER BY
drh94433422013-07-01 11:05:50 +00004992** (or GROUP BY) without requiring a separate sort operation. Return:
drh319f6772013-05-14 15:31:07 +00004993**
4994** 0: ORDER BY is not satisfied. Sorting required
4995** 1: ORDER BY is satisfied. Omit sorting
4996** -1: Unknown at this time
4997**
drh94433422013-07-01 11:05:50 +00004998** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
4999** strict. With GROUP BY and DISTINCT the only requirement is that
5000** equivalent rows appear immediately adjacent to one another. GROUP BY
5001** and DISTINT do not require rows to appear in any particular order as long
5002** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
5003** the pOrderBy terms can be matched in any order. With ORDER BY, the
5004** pOrderBy terms must be matched in strict left-to-right order.
drh6b7157b2013-05-10 02:00:35 +00005005*/
5006static int wherePathSatisfiesOrderBy(
5007 WhereInfo *pWInfo, /* The WHERE clause */
drh4f402f22013-06-11 18:59:38 +00005008 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
drh6b7157b2013-05-10 02:00:35 +00005009 WherePath *pPath, /* The WherePath to check */
drh4f402f22013-06-11 18:59:38 +00005010 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
5011 u16 nLoop, /* Number of entries in pPath->aLoop[] */
drh319f6772013-05-14 15:31:07 +00005012 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
drh4f402f22013-06-11 18:59:38 +00005013 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
drh6b7157b2013-05-10 02:00:35 +00005014){
drh88da6442013-05-27 17:59:37 +00005015 u8 revSet; /* True if rev is known */
5016 u8 rev; /* Composite sort order */
5017 u8 revIdx; /* Index sort order */
drhe353ee32013-06-04 23:40:53 +00005018 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
5019 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
5020 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
drh7699d1c2013-06-04 12:42:29 +00005021 u16 nColumn; /* Number of columns in pIndex */
5022 u16 nOrderBy; /* Number terms in the ORDER BY clause */
5023 int iLoop; /* Index of WhereLoop in pPath being processed */
5024 int i, j; /* Loop counters */
5025 int iCur; /* Cursor number for current WhereLoop */
5026 int iColumn; /* A column number within table iCur */
drhe8ae5832013-06-19 13:32:46 +00005027 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
drh7699d1c2013-06-04 12:42:29 +00005028 WhereTerm *pTerm; /* A single term of the WHERE clause */
5029 Expr *pOBExpr; /* An expression from the ORDER BY clause */
5030 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
5031 Index *pIndex; /* The index associated with pLoop */
5032 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
5033 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
5034 Bitmask obDone; /* Mask of all ORDER BY terms */
drhe353ee32013-06-04 23:40:53 +00005035 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
drhb8916be2013-06-14 02:51:48 +00005036 Bitmask ready; /* Mask of inner loops */
drh319f6772013-05-14 15:31:07 +00005037
5038 /*
drh7699d1c2013-06-04 12:42:29 +00005039 ** We say the WhereLoop is "one-row" if it generates no more than one
5040 ** row of output. A WhereLoop is one-row if all of the following are true:
drh319f6772013-05-14 15:31:07 +00005041 ** (a) All index columns match with WHERE_COLUMN_EQ.
5042 ** (b) The index is unique
drh7699d1c2013-06-04 12:42:29 +00005043 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
5044 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
drh319f6772013-05-14 15:31:07 +00005045 **
drhe353ee32013-06-04 23:40:53 +00005046 ** We say the WhereLoop is "order-distinct" if the set of columns from
5047 ** that WhereLoop that are in the ORDER BY clause are different for every
5048 ** row of the WhereLoop. Every one-row WhereLoop is automatically
5049 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
5050 ** is not order-distinct. To be order-distinct is not quite the same as being
5051 ** UNIQUE since a UNIQUE column or index can have multiple rows that
5052 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
5053 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
5054 **
5055 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
5056 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
5057 ** automatically order-distinct.
drh319f6772013-05-14 15:31:07 +00005058 */
5059
5060 assert( pOrderBy!=0 );
5061
5062 /* Sortability of virtual tables is determined by the xBestIndex method
5063 ** of the virtual table itself */
5064 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
drh7699d1c2013-06-04 12:42:29 +00005065 testcase( nLoop>0 ); /* True when outer loops are one-row and match
5066 ** no ORDER BY terms */
drh319f6772013-05-14 15:31:07 +00005067 return pLast->u.vtab.isOrdered;
drh6b7157b2013-05-10 02:00:35 +00005068 }
drh7699d1c2013-06-04 12:42:29 +00005069 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
drh319f6772013-05-14 15:31:07 +00005070
drh319f6772013-05-14 15:31:07 +00005071 nOrderBy = pOrderBy->nExpr;
drh7963b0e2013-06-17 21:37:40 +00005072 testcase( nOrderBy==BMS-1 );
drhe353ee32013-06-04 23:40:53 +00005073 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
5074 isOrderDistinct = 1;
drh7699d1c2013-06-04 12:42:29 +00005075 obDone = MASKBIT(nOrderBy)-1;
drhe353ee32013-06-04 23:40:53 +00005076 orderDistinctMask = 0;
drhb8916be2013-06-14 02:51:48 +00005077 ready = 0;
drhe353ee32013-06-04 23:40:53 +00005078 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
drhb8916be2013-06-14 02:51:48 +00005079 if( iLoop>0 ) ready |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005080 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
drh319f6772013-05-14 15:31:07 +00005081 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
drh319f6772013-05-14 15:31:07 +00005082 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
drhb8916be2013-06-14 02:51:48 +00005083
5084 /* Mark off any ORDER BY term X that is a column in the table of
5085 ** the current loop for which there is term in the WHERE
5086 ** clause of the form X IS NULL or X=? that reference only outer
5087 ** loops.
5088 */
5089 for(i=0; i<nOrderBy; i++){
5090 if( MASKBIT(i) & obSat ) continue;
5091 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
5092 if( pOBExpr->op!=TK_COLUMN ) continue;
5093 if( pOBExpr->iTable!=iCur ) continue;
5094 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
5095 ~ready, WO_EQ|WO_ISNULL, 0);
5096 if( pTerm==0 ) continue;
drh7963b0e2013-06-17 21:37:40 +00005097 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
drhb8916be2013-06-14 02:51:48 +00005098 const char *z1, *z2;
5099 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5100 if( !pColl ) pColl = db->pDfltColl;
5101 z1 = pColl->zName;
5102 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
5103 if( !pColl ) pColl = db->pDfltColl;
5104 z2 = pColl->zName;
5105 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
5106 }
5107 obSat |= MASKBIT(i);
5108 }
5109
drh7699d1c2013-06-04 12:42:29 +00005110 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
5111 if( pLoop->wsFlags & WHERE_IPK ){
5112 pIndex = 0;
5113 nColumn = 0;
5114 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
drh1b0f0262013-05-30 22:27:09 +00005115 return 0;
drh7699d1c2013-06-04 12:42:29 +00005116 }else{
5117 nColumn = pIndex->nColumn;
drhe353ee32013-06-04 23:40:53 +00005118 isOrderDistinct = pIndex->onError!=OE_None;
drh1b0f0262013-05-30 22:27:09 +00005119 }
drh7699d1c2013-06-04 12:42:29 +00005120
drh7699d1c2013-06-04 12:42:29 +00005121 /* Loop through all columns of the index and deal with the ones
5122 ** that are not constrained by == or IN.
5123 */
5124 rev = revSet = 0;
drhe353ee32013-06-04 23:40:53 +00005125 distinctColumns = 0;
drh7699d1c2013-06-04 12:42:29 +00005126 for(j=0; j<=nColumn; j++){
5127 u8 bOnce; /* True to run the ORDER BY search loop */
5128
drhe353ee32013-06-04 23:40:53 +00005129 /* Skip over == and IS NULL terms */
drh7699d1c2013-06-04 12:42:29 +00005130 if( j<pLoop->u.btree.nEq
drh4efc9292013-06-06 23:02:03 +00005131 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
drh7699d1c2013-06-04 12:42:29 +00005132 ){
drh7963b0e2013-06-17 21:37:40 +00005133 if( i & WO_ISNULL ){
5134 testcase( isOrderDistinct );
5135 isOrderDistinct = 0;
5136 }
drhe353ee32013-06-04 23:40:53 +00005137 continue;
drh7699d1c2013-06-04 12:42:29 +00005138 }
5139
drhe353ee32013-06-04 23:40:53 +00005140 /* Get the column number in the table (iColumn) and sort order
5141 ** (revIdx) for the j-th column of the index.
drh7699d1c2013-06-04 12:42:29 +00005142 */
5143 if( j<nColumn ){
5144 /* Normal index columns */
5145 iColumn = pIndex->aiColumn[j];
5146 revIdx = pIndex->aSortOrder[j];
5147 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
drhdc3cd4b2013-05-30 23:21:20 +00005148 }else{
drh7699d1c2013-06-04 12:42:29 +00005149 /* The ROWID column at the end */
drh7963b0e2013-06-17 21:37:40 +00005150 assert( j==nColumn );
drh7699d1c2013-06-04 12:42:29 +00005151 iColumn = -1;
5152 revIdx = 0;
drhdc3cd4b2013-05-30 23:21:20 +00005153 }
drh7699d1c2013-06-04 12:42:29 +00005154
5155 /* An unconstrained column that might be NULL means that this
5156 ** WhereLoop is not well-ordered
5157 */
drhe353ee32013-06-04 23:40:53 +00005158 if( isOrderDistinct
5159 && iColumn>=0
drh7699d1c2013-06-04 12:42:29 +00005160 && j>=pLoop->u.btree.nEq
5161 && pIndex->pTable->aCol[iColumn].notNull==0
5162 ){
drhe353ee32013-06-04 23:40:53 +00005163 isOrderDistinct = 0;
drh7699d1c2013-06-04 12:42:29 +00005164 }
5165
5166 /* Find the ORDER BY term that corresponds to the j-th column
5167 ** of the index and and mark that ORDER BY term off
5168 */
5169 bOnce = 1;
drhe353ee32013-06-04 23:40:53 +00005170 isMatch = 0;
drh7699d1c2013-06-04 12:42:29 +00005171 for(i=0; bOnce && i<nOrderBy; i++){
5172 if( MASKBIT(i) & obSat ) continue;
5173 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
drh93ec45d2013-06-17 18:20:48 +00005174 testcase( wctrlFlags & WHERE_GROUPBY );
5175 testcase( wctrlFlags & WHERE_DISTINCTBY );
drh4f402f22013-06-11 18:59:38 +00005176 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
drhe353ee32013-06-04 23:40:53 +00005177 if( pOBExpr->op!=TK_COLUMN ) continue;
drh7699d1c2013-06-04 12:42:29 +00005178 if( pOBExpr->iTable!=iCur ) continue;
5179 if( pOBExpr->iColumn!=iColumn ) continue;
5180 if( iColumn>=0 ){
5181 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
5182 if( !pColl ) pColl = db->pDfltColl;
5183 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
5184 }
drhe353ee32013-06-04 23:40:53 +00005185 isMatch = 1;
drh7699d1c2013-06-04 12:42:29 +00005186 break;
5187 }
drhe353ee32013-06-04 23:40:53 +00005188 if( isMatch ){
drh7963b0e2013-06-17 21:37:40 +00005189 if( iColumn<0 ){
5190 testcase( distinctColumns==0 );
5191 distinctColumns = 1;
5192 }
drh7699d1c2013-06-04 12:42:29 +00005193 obSat |= MASKBIT(i);
5194 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
drhe353ee32013-06-04 23:40:53 +00005195 /* Make sure the sort order is compatible in an ORDER BY clause.
5196 ** Sort order is irrelevant for a GROUP BY clause. */
drh7699d1c2013-06-04 12:42:29 +00005197 if( revSet ){
5198 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
5199 }else{
5200 rev = revIdx ^ pOrderBy->a[i].sortOrder;
5201 if( rev ) *pRevMask |= MASKBIT(iLoop);
5202 revSet = 1;
5203 }
5204 }
5205 }else{
5206 /* No match found */
drh7963b0e2013-06-17 21:37:40 +00005207 if( j==0 || j<nColumn ){
5208 testcase( isOrderDistinct!=0 );
5209 isOrderDistinct = 0;
5210 }
drh7699d1c2013-06-04 12:42:29 +00005211 break;
5212 }
5213 } /* end Loop over all index columns */
drh81186b42013-06-18 01:52:41 +00005214 if( distinctColumns ){
5215 testcase( isOrderDistinct==0 );
5216 isOrderDistinct = 1;
5217 }
drh7699d1c2013-06-04 12:42:29 +00005218 } /* end-if not one-row */
5219
5220 /* Mark off any other ORDER BY terms that reference pLoop */
drhe353ee32013-06-04 23:40:53 +00005221 if( isOrderDistinct ){
5222 orderDistinctMask |= pLoop->maskSelf;
drh7699d1c2013-06-04 12:42:29 +00005223 for(i=0; i<nOrderBy; i++){
5224 Expr *p;
5225 if( MASKBIT(i) & obSat ) continue;
5226 p = pOrderBy->a[i].pExpr;
drh70d18342013-06-06 19:16:33 +00005227 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
drh7699d1c2013-06-04 12:42:29 +00005228 obSat |= MASKBIT(i);
5229 }
drh0afb4232013-05-31 13:36:32 +00005230 }
drh319f6772013-05-14 15:31:07 +00005231 }
drhb8916be2013-06-14 02:51:48 +00005232 } /* End the loop over all WhereLoops from outer-most down to inner-most */
drh7699d1c2013-06-04 12:42:29 +00005233 if( obSat==obDone ) return 1;
drhe353ee32013-06-04 23:40:53 +00005234 if( !isOrderDistinct ) return 0;
drh319f6772013-05-14 15:31:07 +00005235 return -1;
drh6b7157b2013-05-10 02:00:35 +00005236}
5237
drhd15cb172013-05-21 19:23:10 +00005238#ifdef WHERETRACE_ENABLED
5239/* For debugging use only: */
5240static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
5241 static char zName[65];
5242 int i;
5243 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
5244 if( pLast ) zName[i++] = pLast->cId;
5245 zName[i] = 0;
5246 return zName;
5247}
5248#endif
5249
drh6b7157b2013-05-10 02:00:35 +00005250
5251/*
dan51576f42013-07-02 10:06:15 +00005252** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
drha18f3d22013-05-08 03:05:41 +00005253** attempts to find the lowest cost path that visits each WhereLoop
5254** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
5255**
drhc7f0d222013-06-19 03:27:12 +00005256** Assume that the total number of output rows that will need to be sorted
5257** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
5258** costs if nRowEst==0.
5259**
drha18f3d22013-05-08 03:05:41 +00005260** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
5261** error occurs.
5262*/
drh4efc9292013-06-06 23:02:03 +00005263static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
drh783dece2013-06-05 17:53:43 +00005264 int mxChoice; /* Maximum number of simultaneous paths tracked */
drha18f3d22013-05-08 03:05:41 +00005265 int nLoop; /* Number of terms in the join */
drhe1e2e9a2013-06-13 15:16:53 +00005266 Parse *pParse; /* Parsing context */
drha18f3d22013-05-08 03:05:41 +00005267 sqlite3 *db; /* The database connection */
5268 int iLoop; /* Loop counter over the terms of the join */
5269 int ii, jj; /* Loop counters */
drh4efc9292013-06-06 23:02:03 +00005270 WhereCost rCost; /* Cost of a path */
drhc7f0d222013-06-19 03:27:12 +00005271 WhereCost mxCost = 0; /* Maximum cost of a set of paths */
drh4efc9292013-06-06 23:02:03 +00005272 WhereCost rSortCost; /* Cost to do a sort */
drha18f3d22013-05-08 03:05:41 +00005273 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
5274 WherePath *aFrom; /* All nFrom paths at the previous level */
5275 WherePath *aTo; /* The nTo best paths at the current level */
5276 WherePath *pFrom; /* An element of aFrom[] that we are working on */
5277 WherePath *pTo; /* An element of aTo[] that we are working on */
5278 WhereLoop *pWLoop; /* One of the WhereLoop objects */
5279 WhereLoop **pX; /* Used to divy up the pSpace memory */
5280 char *pSpace; /* Temporary memory used by this routine */
5281
drhe1e2e9a2013-06-13 15:16:53 +00005282 pParse = pWInfo->pParse;
5283 db = pParse->db;
drha18f3d22013-05-08 03:05:41 +00005284 nLoop = pWInfo->nLevel;
drhe1e2e9a2013-06-13 15:16:53 +00005285 /* TUNING: For simple queries, only the best path is tracked.
5286 ** For 2-way joins, the 5 best paths are followed.
5287 ** For joins of 3 or more tables, track the 10 best paths */
drhe9d935a2013-06-05 16:19:59 +00005288 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
drha18f3d22013-05-08 03:05:41 +00005289 assert( nLoop<=pWInfo->pTabList->nSrc );
drh3b48e8c2013-06-12 20:18:16 +00005290 WHERETRACE(0x002, ("---- begin solver\n"));
drha18f3d22013-05-08 03:05:41 +00005291
5292 /* Allocate and initialize space for aTo and aFrom */
5293 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
5294 pSpace = sqlite3DbMallocRaw(db, ii);
5295 if( pSpace==0 ) return SQLITE_NOMEM;
5296 aTo = (WherePath*)pSpace;
5297 aFrom = aTo+mxChoice;
5298 memset(aFrom, 0, sizeof(aFrom[0]));
5299 pX = (WhereLoop**)(aFrom+mxChoice);
drhe9d935a2013-06-05 16:19:59 +00005300 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
drha18f3d22013-05-08 03:05:41 +00005301 pFrom->aLoop = pX;
5302 }
5303
drhe1e2e9a2013-06-13 15:16:53 +00005304 /* Seed the search with a single WherePath containing zero WhereLoops.
5305 **
5306 ** TUNING: Do not let the number of iterations go above 25. If the cost
5307 ** of computing an automatic index is not paid back within the first 25
5308 ** rows, then do not use the automatic index. */
5309 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==whereCost(25) );
drha18f3d22013-05-08 03:05:41 +00005310 nFrom = 1;
drh6b7157b2013-05-10 02:00:35 +00005311
5312 /* Precompute the cost of sorting the final result set, if the caller
5313 ** to sqlite3WhereBegin() was concerned about sorting */
drhb8a8e8a2013-06-10 19:12:39 +00005314 rSortCost = 0;
5315 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
drh6b7157b2013-05-10 02:00:35 +00005316 aFrom[0].isOrderedValid = 1;
5317 }else{
drhe1e2e9a2013-06-13 15:16:53 +00005318 /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
5319 ** number of output rows. */
drhb8a8e8a2013-06-10 19:12:39 +00005320 rSortCost = nRowEst + estLog(nRowEst);
drh3b48e8c2013-06-12 20:18:16 +00005321 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
drh6b7157b2013-05-10 02:00:35 +00005322 }
5323
5324 /* Compute successively longer WherePaths using the previous generation
5325 ** of WherePaths as the basis for the next. Keep track of the mxChoice
5326 ** best paths at each generation */
drha18f3d22013-05-08 03:05:41 +00005327 for(iLoop=0; iLoop<nLoop; iLoop++){
5328 nTo = 0;
5329 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
5330 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
5331 Bitmask maskNew;
drh319f6772013-05-14 15:31:07 +00005332 Bitmask revMask = 0;
drh6b7157b2013-05-10 02:00:35 +00005333 u8 isOrderedValid = pFrom->isOrderedValid;
5334 u8 isOrdered = pFrom->isOrdered;
drha18f3d22013-05-08 03:05:41 +00005335 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
5336 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
drh6b7157b2013-05-10 02:00:35 +00005337 /* At this point, pWLoop is a candidate to be the next loop.
5338 ** Compute its cost */
drhb8a8e8a2013-06-10 19:12:39 +00005339 rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
5340 rCost = whereCostAdd(rCost, pFrom->rCost);
drha18f3d22013-05-08 03:05:41 +00005341 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
drh6b7157b2013-05-10 02:00:35 +00005342 if( !isOrderedValid ){
drh4f402f22013-06-11 18:59:38 +00005343 switch( wherePathSatisfiesOrderBy(pWInfo,
5344 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
drh93ec45d2013-06-17 18:20:48 +00005345 iLoop, pWLoop, &revMask) ){
drh6b7157b2013-05-10 02:00:35 +00005346 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
5347 isOrdered = 1;
5348 isOrderedValid = 1;
5349 break;
5350 case 0: /* No. pFrom+pWLoop will require a separate sort */
5351 isOrdered = 0;
5352 isOrderedValid = 1;
drhb8a8e8a2013-06-10 19:12:39 +00005353 rCost = whereCostAdd(rCost, rSortCost);
drh6b7157b2013-05-10 02:00:35 +00005354 break;
5355 default: /* Cannot tell yet. Try again on the next iteration */
5356 break;
5357 }
drh3a5ba8b2013-06-03 15:34:48 +00005358 }else{
5359 revMask = pFrom->revLoop;
drh6b7157b2013-05-10 02:00:35 +00005360 }
5361 /* Check to see if pWLoop should be added to the mxChoice best so far */
5362 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
5363 if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
drh7963b0e2013-06-17 21:37:40 +00005364 testcase( jj==nTo-1 );
drh6b7157b2013-05-10 02:00:35 +00005365 break;
5366 }
5367 }
drha18f3d22013-05-08 03:05:41 +00005368 if( jj>=nTo ){
drhd15cb172013-05-21 19:23:10 +00005369 if( nTo>=mxChoice && rCost>=mxCost ){
drhae70cf12013-05-31 15:18:46 +00005370#ifdef WHERETRACE_ENABLED
5371 if( sqlite3WhereTrace&0x4 ){
drhb8a8e8a2013-06-10 19:12:39 +00005372 sqlite3DebugPrintf("Skip %s cost=%3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005373 wherePathName(pFrom, iLoop, pWLoop), rCost,
5374 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5375 }
5376#endif
5377 continue;
5378 }
5379 /* Add a new Path to the aTo[] set */
drha18f3d22013-05-08 03:05:41 +00005380 if( nTo<mxChoice ){
drhd15cb172013-05-21 19:23:10 +00005381 /* Increase the size of the aTo set by one */
drha18f3d22013-05-08 03:05:41 +00005382 jj = nTo++;
5383 }else{
drhd15cb172013-05-21 19:23:10 +00005384 /* New path replaces the prior worst to keep count below mxChoice */
drhc718f1c2013-05-08 20:05:58 +00005385 for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
drha18f3d22013-05-08 03:05:41 +00005386 }
5387 pTo = &aTo[jj];
drhd15cb172013-05-21 19:23:10 +00005388#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005389 if( sqlite3WhereTrace&0x4 ){
drhb8a8e8a2013-06-10 19:12:39 +00005390 sqlite3DebugPrintf("New %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005391 wherePathName(pFrom, iLoop, pWLoop), rCost,
5392 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
5393 }
5394#endif
drhf204dac2013-05-08 03:22:07 +00005395 }else{
drhd15cb172013-05-21 19:23:10 +00005396 if( pTo->rCost<=rCost ){
5397#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005398 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005399 sqlite3DebugPrintf(
drhb8a8e8a2013-06-10 19:12:39 +00005400 "Skip %s cost=%-3d order=%c",
drhd15cb172013-05-21 19:23:10 +00005401 wherePathName(pFrom, iLoop, pWLoop), rCost,
5402 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhb8a8e8a2013-06-10 19:12:39 +00005403 sqlite3DebugPrintf(" vs %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005404 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5405 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5406 }
5407#endif
drh7963b0e2013-06-17 21:37:40 +00005408 testcase( pTo->rCost==rCost );
drhd15cb172013-05-21 19:23:10 +00005409 continue;
5410 }
drh7963b0e2013-06-17 21:37:40 +00005411 testcase( pTo->rCost==rCost+1 );
drhd15cb172013-05-21 19:23:10 +00005412 /* A new and better score for a previously created equivalent path */
5413#ifdef WHERETRACE_ENABLED
drhae70cf12013-05-31 15:18:46 +00005414 if( sqlite3WhereTrace&0x4 ){
drhd15cb172013-05-21 19:23:10 +00005415 sqlite3DebugPrintf(
drhb8a8e8a2013-06-10 19:12:39 +00005416 "Update %s cost=%-3d order=%c",
drhd15cb172013-05-21 19:23:10 +00005417 wherePathName(pFrom, iLoop, pWLoop), rCost,
5418 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
drhb8a8e8a2013-06-10 19:12:39 +00005419 sqlite3DebugPrintf(" was %s cost=%-3d order=%c\n",
drhd15cb172013-05-21 19:23:10 +00005420 wherePathName(pTo, iLoop+1, 0), pTo->rCost,
5421 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
5422 }
5423#endif
drha18f3d22013-05-08 03:05:41 +00005424 }
drh6b7157b2013-05-10 02:00:35 +00005425 /* pWLoop is a winner. Add it to the set of best so far */
drha18f3d22013-05-08 03:05:41 +00005426 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
drh319f6772013-05-14 15:31:07 +00005427 pTo->revLoop = revMask;
drhb8a8e8a2013-06-10 19:12:39 +00005428 pTo->nRow = pFrom->nRow + pWLoop->nOut;
drha18f3d22013-05-08 03:05:41 +00005429 pTo->rCost = rCost;
drh6b7157b2013-05-10 02:00:35 +00005430 pTo->isOrderedValid = isOrderedValid;
5431 pTo->isOrdered = isOrdered;
drha18f3d22013-05-08 03:05:41 +00005432 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5433 pTo->aLoop[iLoop] = pWLoop;
5434 if( nTo>=mxChoice ){
5435 mxCost = aTo[0].rCost;
5436 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
5437 if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
5438 }
5439 }
5440 }
5441 }
5442
drhd15cb172013-05-21 19:23:10 +00005443#ifdef WHERETRACE_ENABLED
5444 if( sqlite3WhereTrace>=2 ){
drha50ef112013-05-22 02:06:59 +00005445 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
drhd15cb172013-05-21 19:23:10 +00005446 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
drhb8a8e8a2013-06-10 19:12:39 +00005447 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
drha50ef112013-05-22 02:06:59 +00005448 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
drhd15cb172013-05-21 19:23:10 +00005449 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
drh88da6442013-05-27 17:59:37 +00005450 if( pTo->isOrderedValid && pTo->isOrdered ){
5451 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
5452 }else{
5453 sqlite3DebugPrintf("\n");
5454 }
drhf204dac2013-05-08 03:22:07 +00005455 }
5456 }
5457#endif
5458
drh6b7157b2013-05-10 02:00:35 +00005459 /* Swap the roles of aFrom and aTo for the next generation */
drha18f3d22013-05-08 03:05:41 +00005460 pFrom = aTo;
5461 aTo = aFrom;
5462 aFrom = pFrom;
5463 nFrom = nTo;
5464 }
5465
drh75b93402013-05-31 20:43:57 +00005466 if( nFrom==0 ){
drhe1e2e9a2013-06-13 15:16:53 +00005467 sqlite3ErrorMsg(pParse, "no query solution");
drh75b93402013-05-31 20:43:57 +00005468 sqlite3DbFree(db, pSpace);
5469 return SQLITE_ERROR;
5470 }
drha18f3d22013-05-08 03:05:41 +00005471
drh6b7157b2013-05-10 02:00:35 +00005472 /* Find the lowest cost path. pFrom will be left pointing to that path */
drha18f3d22013-05-08 03:05:41 +00005473 pFrom = aFrom;
drh93ec45d2013-06-17 18:20:48 +00005474 assert( nFrom==1 );
5475#if 0 /* The following is needed if nFrom is ever more than 1 */
drha18f3d22013-05-08 03:05:41 +00005476 for(ii=1; ii<nFrom; ii++){
5477 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5478 }
drh93ec45d2013-06-17 18:20:48 +00005479#endif
drha18f3d22013-05-08 03:05:41 +00005480 assert( pWInfo->nLevel==nLoop );
drh6b7157b2013-05-10 02:00:35 +00005481 /* Load the lowest cost path into pWInfo */
drha18f3d22013-05-08 03:05:41 +00005482 for(iLoop=0; iLoop<nLoop; iLoop++){
drh7ba39a92013-05-30 17:43:19 +00005483 WhereLevel *pLevel = pWInfo->a + iLoop;
5484 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
drhe217efc2013-06-12 03:48:41 +00005485 pLevel->iFrom = pWLoop->iTab;
drh7ba39a92013-05-30 17:43:19 +00005486 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
drha18f3d22013-05-08 03:05:41 +00005487 }
drhfd636c72013-06-21 02:05:06 +00005488 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5489 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5490 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
drh4f402f22013-06-11 18:59:38 +00005491 && nRowEst
5492 ){
5493 Bitmask notUsed;
drh6457a352013-06-21 00:35:37 +00005494 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
drh93ec45d2013-06-17 18:20:48 +00005495 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
drh4f402f22013-06-11 18:59:38 +00005496 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5497 }
drh6b7157b2013-05-10 02:00:35 +00005498 if( pFrom->isOrdered ){
drh4f402f22013-06-11 18:59:38 +00005499 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5500 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5501 }else{
5502 pWInfo->bOBSat = 1;
5503 pWInfo->revMask = pFrom->revLoop;
5504 }
drh6b7157b2013-05-10 02:00:35 +00005505 }
drha50ef112013-05-22 02:06:59 +00005506 pWInfo->nRowOut = pFrom->nRow;
drha18f3d22013-05-08 03:05:41 +00005507
5508 /* Free temporary memory and return success */
5509 sqlite3DbFree(db, pSpace);
5510 return SQLITE_OK;
5511}
drh94a11212004-09-25 13:12:14 +00005512
5513/*
drh60c96cd2013-06-09 17:21:25 +00005514** Most queries use only a single table (they are not joins) and have
5515** simple == constraints against indexed fields. This routine attempts
5516** to plan those simple cases using much less ceremony than the
5517** general-purpose query planner, and thereby yield faster sqlite3_prepare()
5518** times for the common case.
5519**
5520** Return non-zero on success, if this query can be handled by this
5521** no-frills query planner. Return zero if this query needs the
5522** general-purpose query planner.
5523*/
drhb8a8e8a2013-06-10 19:12:39 +00005524static int whereShortCut(WhereLoopBuilder *pBuilder){
drh60c96cd2013-06-09 17:21:25 +00005525 WhereInfo *pWInfo;
5526 struct SrcList_item *pItem;
5527 WhereClause *pWC;
5528 WhereTerm *pTerm;
5529 WhereLoop *pLoop;
5530 int iCur;
drh92a121f2013-06-10 12:15:47 +00005531 int j;
drh60c96cd2013-06-09 17:21:25 +00005532 Table *pTab;
5533 Index *pIdx;
5534
5535 pWInfo = pBuilder->pWInfo;
drh5822d6f2013-06-10 23:30:09 +00005536 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
drh60c96cd2013-06-09 17:21:25 +00005537 assert( pWInfo->pTabList->nSrc>=1 );
5538 pItem = pWInfo->pTabList->a;
5539 pTab = pItem->pTab;
5540 if( IsVirtual(pTab) ) return 0;
5541 if( pItem->zIndex ) return 0;
5542 iCur = pItem->iCursor;
5543 pWC = &pWInfo->sWC;
5544 pLoop = pBuilder->pNew;
drh60c96cd2013-06-09 17:21:25 +00005545 pLoop->wsFlags = 0;
drh3b75ffa2013-06-10 14:56:25 +00005546 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
drh60c96cd2013-06-09 17:21:25 +00005547 if( pTerm ){
5548 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
5549 pLoop->aLTerm[0] = pTerm;
5550 pLoop->nLTerm = 1;
5551 pLoop->u.btree.nEq = 1;
drhe1e2e9a2013-06-13 15:16:53 +00005552 /* TUNING: Cost of a rowid lookup is 10 */
5553 pLoop->rRun = 33; /* 33==whereCost(10) */
drh60c96cd2013-06-09 17:21:25 +00005554 }else{
5555 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
dancd40abb2013-08-29 10:46:05 +00005556 assert( pLoop->aLTermSpace==pLoop->aLTerm );
5557 assert( ArraySize(pLoop->aLTermSpace)==4 );
5558 if( pIdx->onError==OE_None
5559 || pIdx->pPartIdxWhere!=0
5560 || pIdx->nColumn>ArraySize(pLoop->aLTermSpace)
5561 ) continue;
drh60c96cd2013-06-09 17:21:25 +00005562 for(j=0; j<pIdx->nColumn; j++){
drh3b75ffa2013-06-10 14:56:25 +00005563 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
drh60c96cd2013-06-09 17:21:25 +00005564 if( pTerm==0 ) break;
drh60c96cd2013-06-09 17:21:25 +00005565 pLoop->aLTerm[j] = pTerm;
5566 }
5567 if( j!=pIdx->nColumn ) continue;
drh92a121f2013-06-10 12:15:47 +00005568 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
drhfd5874d2013-06-12 14:52:39 +00005569 if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
drh92a121f2013-06-10 12:15:47 +00005570 pLoop->wsFlags |= WHERE_IDX_ONLY;
5571 }
drh60c96cd2013-06-09 17:21:25 +00005572 pLoop->nLTerm = j;
5573 pLoop->u.btree.nEq = j;
5574 pLoop->u.btree.pIndex = pIdx;
drhe1e2e9a2013-06-13 15:16:53 +00005575 /* TUNING: Cost of a unique index lookup is 15 */
5576 pLoop->rRun = 39; /* 39==whereCost(15) */
drh60c96cd2013-06-09 17:21:25 +00005577 break;
5578 }
5579 }
drh3b75ffa2013-06-10 14:56:25 +00005580 if( pLoop->wsFlags ){
5581 pLoop->nOut = (WhereCost)1;
5582 pWInfo->a[0].pWLoop = pLoop;
5583 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
5584 pWInfo->a[0].iTabCur = iCur;
5585 pWInfo->nRowOut = 1;
drh4f402f22013-06-11 18:59:38 +00005586 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005587 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
5588 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5589 }
drh3b75ffa2013-06-10 14:56:25 +00005590#ifdef SQLITE_DEBUG
5591 pLoop->cId = '0';
5592#endif
5593 return 1;
5594 }
5595 return 0;
drh60c96cd2013-06-09 17:21:25 +00005596}
5597
5598/*
drhe3184742002-06-19 14:27:05 +00005599** Generate the beginning of the loop used for WHERE clause processing.
drhacf3b982005-01-03 01:27:18 +00005600** The return value is a pointer to an opaque structure that contains
drh75897232000-05-29 14:26:00 +00005601** information needed to terminate the loop. Later, the calling routine
danielk19774adee202004-05-08 08:23:19 +00005602** should invoke sqlite3WhereEnd() with the return value of this function
drh75897232000-05-29 14:26:00 +00005603** in order to complete the WHERE clause processing.
5604**
5605** If an error occurs, this routine returns NULL.
drhc27a1ce2002-06-14 20:58:45 +00005606**
5607** The basic idea is to do a nested loop, one loop for each table in
5608** the FROM clause of a select. (INSERT and UPDATE statements are the
5609** same as a SELECT with only a single table in the FROM clause.) For
5610** example, if the SQL is this:
5611**
5612** SELECT * FROM t1, t2, t3 WHERE ...;
5613**
5614** Then the code generated is conceptually like the following:
5615**
5616** foreach row1 in t1 do \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005617** foreach row2 in t2 do |-- by sqlite3WhereBegin()
drhc27a1ce2002-06-14 20:58:45 +00005618** foreach row3 in t3 do /
5619** ...
5620** end \ Code generated
danielk19774adee202004-05-08 08:23:19 +00005621** end |-- by sqlite3WhereEnd()
drhc27a1ce2002-06-14 20:58:45 +00005622** end /
5623**
drh29dda4a2005-07-21 18:23:20 +00005624** Note that the loops might not be nested in the order in which they
5625** appear in the FROM clause if a different order is better able to make
drh51147ba2005-07-23 22:59:55 +00005626** use of indices. Note also that when the IN operator appears in
5627** the WHERE clause, it might result in additional nested loops for
5628** scanning through all values on the right-hand side of the IN.
drh29dda4a2005-07-21 18:23:20 +00005629**
drhc27a1ce2002-06-14 20:58:45 +00005630** There are Btree cursors associated with each table. t1 uses cursor
drh6a3ea0e2003-05-02 14:32:12 +00005631** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
5632** And so forth. This routine generates code to open those VDBE cursors
danielk19774adee202004-05-08 08:23:19 +00005633** and sqlite3WhereEnd() generates the code to close them.
drhc27a1ce2002-06-14 20:58:45 +00005634**
drhe6f85e72004-12-25 01:03:13 +00005635** The code that sqlite3WhereBegin() generates leaves the cursors named
5636** in pTabList pointing at their appropriate entries. The [...] code
drhf0863fe2005-06-12 21:35:51 +00005637** can use OP_Column and OP_Rowid opcodes on these cursors to extract
drhe6f85e72004-12-25 01:03:13 +00005638** data from the various tables of the loop.
5639**
drhc27a1ce2002-06-14 20:58:45 +00005640** If the WHERE clause is empty, the foreach loops must each scan their
5641** entire tables. Thus a three-way join is an O(N^3) operation. But if
5642** the tables have indices and there are terms in the WHERE clause that
5643** refer to those indices, a complete table scan can be avoided and the
5644** code will run much faster. Most of the work of this routine is checking
5645** to see if there are indices that can be used to speed up the loop.
5646**
5647** Terms of the WHERE clause are also used to limit which rows actually
5648** make it to the "..." in the middle of the loop. After each "foreach",
5649** terms of the WHERE clause that use only terms in that loop and outer
5650** loops are evaluated and if false a jump is made around all subsequent
5651** inner loops (or around the "..." if the test occurs within the inner-
5652** most loop)
5653**
5654** OUTER JOINS
5655**
5656** An outer join of tables t1 and t2 is conceptally coded as follows:
5657**
5658** foreach row1 in t1 do
5659** flag = 0
5660** foreach row2 in t2 do
5661** start:
5662** ...
5663** flag = 1
5664** end
drhe3184742002-06-19 14:27:05 +00005665** if flag==0 then
5666** move the row2 cursor to a null row
5667** goto start
5668** fi
drhc27a1ce2002-06-14 20:58:45 +00005669** end
5670**
drhe3184742002-06-19 14:27:05 +00005671** ORDER BY CLAUSE PROCESSING
5672**
drh94433422013-07-01 11:05:50 +00005673** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
5674** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
drhe3184742002-06-19 14:27:05 +00005675** if there is one. If there is no ORDER BY clause or if this routine
drh46ec5b62012-09-24 15:30:54 +00005676** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
drh75897232000-05-29 14:26:00 +00005677*/
danielk19774adee202004-05-08 08:23:19 +00005678WhereInfo *sqlite3WhereBegin(
danielk1977ed326d72004-11-16 15:50:19 +00005679 Parse *pParse, /* The parser context */
drh6457a352013-06-21 00:35:37 +00005680 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
danielk1977ed326d72004-11-16 15:50:19 +00005681 Expr *pWhere, /* The WHERE clause */
drh46ec5b62012-09-24 15:30:54 +00005682 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
drh6457a352013-06-21 00:35:37 +00005683 ExprList *pResultSet, /* Result set of the query */
dan0efb72c2012-08-24 18:44:56 +00005684 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
5685 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
drh75897232000-05-29 14:26:00 +00005686){
danielk1977be229652009-03-20 14:18:51 +00005687 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
drhc01a3c12009-12-16 22:10:49 +00005688 int nTabList; /* Number of elements in pTabList */
drh75897232000-05-29 14:26:00 +00005689 WhereInfo *pWInfo; /* Will become the return value of this function */
5690 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
drhfe05af82005-07-21 03:14:59 +00005691 Bitmask notReady; /* Cursors that are not yet positioned */
drh1c8148f2013-05-04 20:25:23 +00005692 WhereLoopBuilder sWLB; /* The WhereLoop builder */
drh111a6a72008-12-21 03:51:16 +00005693 WhereMaskSet *pMaskSet; /* The expression mask set */
drh56f1b992012-09-25 14:29:39 +00005694 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
drhfd636c72013-06-21 02:05:06 +00005695 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
drh9cd1c992012-09-25 20:43:35 +00005696 int ii; /* Loop counter */
drh17435752007-08-16 04:30:38 +00005697 sqlite3 *db; /* Database connection */
drh5346e952013-05-08 14:14:26 +00005698 int rc; /* Return code */
drh75897232000-05-29 14:26:00 +00005699
drh56f1b992012-09-25 14:29:39 +00005700
5701 /* Variable initialization */
drhfd636c72013-06-21 02:05:06 +00005702 db = pParse->db;
drh1c8148f2013-05-04 20:25:23 +00005703 memset(&sWLB, 0, sizeof(sWLB));
drh1c8148f2013-05-04 20:25:23 +00005704 sWLB.pOrderBy = pOrderBy;
drh56f1b992012-09-25 14:29:39 +00005705
drhfd636c72013-06-21 02:05:06 +00005706 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
5707 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
5708 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
5709 wctrlFlags &= ~WHERE_WANT_DISTINCT;
5710 }
5711
drh29dda4a2005-07-21 18:23:20 +00005712 /* The number of tables in the FROM clause is limited by the number of
drh1398ad32005-01-19 23:24:50 +00005713 ** bits in a Bitmask
5714 */
drh67ae0cb2010-04-08 14:38:51 +00005715 testcase( pTabList->nSrc==BMS );
drh29dda4a2005-07-21 18:23:20 +00005716 if( pTabList->nSrc>BMS ){
5717 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
drh1398ad32005-01-19 23:24:50 +00005718 return 0;
5719 }
5720
drhc01a3c12009-12-16 22:10:49 +00005721 /* This function normally generates a nested loop for all tables in
5722 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
5723 ** only generate code for the first table in pTabList and assume that
5724 ** any cursors associated with subsequent tables are uninitialized.
5725 */
5726 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
5727
drh75897232000-05-29 14:26:00 +00005728 /* Allocate and initialize the WhereInfo structure that will become the
danielk1977be229652009-03-20 14:18:51 +00005729 ** return value. A single allocation is used to store the WhereInfo
5730 ** struct, the contents of WhereInfo.a[], the WhereClause structure
5731 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5732 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5733 ** some architectures. Hence the ROUND8() below.
drh75897232000-05-29 14:26:00 +00005734 */
drhc01a3c12009-12-16 22:10:49 +00005735 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
drh60c96cd2013-06-09 17:21:25 +00005736 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
drh17435752007-08-16 04:30:38 +00005737 if( db->mallocFailed ){
drh8b307fb2010-04-06 15:57:05 +00005738 sqlite3DbFree(db, pWInfo);
5739 pWInfo = 0;
danielk197785574e32008-10-06 05:32:18 +00005740 goto whereBeginError;
drh75897232000-05-29 14:26:00 +00005741 }
drhc01a3c12009-12-16 22:10:49 +00005742 pWInfo->nLevel = nTabList;
drh75897232000-05-29 14:26:00 +00005743 pWInfo->pParse = pParse;
5744 pWInfo->pTabList = pTabList;
drh6b7157b2013-05-10 02:00:35 +00005745 pWInfo->pOrderBy = pOrderBy;
drh6457a352013-06-21 00:35:37 +00005746 pWInfo->pResultSet = pResultSet;
danielk19774adee202004-05-08 08:23:19 +00005747 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
drh6df2acd2008-12-28 16:55:25 +00005748 pWInfo->wctrlFlags = wctrlFlags;
drh8b307fb2010-04-06 15:57:05 +00005749 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
drh70d18342013-06-06 19:16:33 +00005750 pMaskSet = &pWInfo->sMaskSet;
drh1c8148f2013-05-04 20:25:23 +00005751 sWLB.pWInfo = pWInfo;
drh70d18342013-06-06 19:16:33 +00005752 sWLB.pWC = &pWInfo->sWC;
drh1ac87e12013-07-18 14:50:56 +00005753 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
5754 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
drh60c96cd2013-06-09 17:21:25 +00005755 whereLoopInit(sWLB.pNew);
drhb8a8e8a2013-06-10 19:12:39 +00005756#ifdef SQLITE_DEBUG
5757 sWLB.pNew->cId = '*';
5758#endif
drh08192d52002-04-30 19:20:28 +00005759
drh111a6a72008-12-21 03:51:16 +00005760 /* Split the WHERE clause into separate subexpressions where each
5761 ** subexpression is separated by an AND operator.
5762 */
5763 initMaskSet(pMaskSet);
drh70d18342013-06-06 19:16:33 +00005764 whereClauseInit(&pWInfo->sWC, pWInfo);
drh111a6a72008-12-21 03:51:16 +00005765 sqlite3ExprCodeConstants(pParse, pWhere);
drh39759742013-08-02 23:40:45 +00005766 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
drh5e128b22013-07-09 03:04:32 +00005767 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
drh111a6a72008-12-21 03:51:16 +00005768
drh08192d52002-04-30 19:20:28 +00005769 /* Special case: a WHERE clause that is constant. Evaluate the
5770 ** expression and either jump over all of the code or fall thru.
5771 */
drhc01a3c12009-12-16 22:10:49 +00005772 if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
drh35573352008-01-08 23:54:25 +00005773 sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
drhdf199a22002-06-14 22:38:41 +00005774 pWhere = 0;
drh08192d52002-04-30 19:20:28 +00005775 }
drh75897232000-05-29 14:26:00 +00005776
drh4fe425a2013-06-12 17:08:06 +00005777 /* Special case: No FROM clause
5778 */
5779 if( nTabList==0 ){
5780 if( pOrderBy ) pWInfo->bOBSat = 1;
drh6457a352013-06-21 00:35:37 +00005781 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5782 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5783 }
drh4fe425a2013-06-12 17:08:06 +00005784 }
5785
drh42165be2008-03-26 14:56:34 +00005786 /* Assign a bit from the bitmask to every term in the FROM clause.
5787 **
5788 ** When assigning bitmask values to FROM clause cursors, it must be
5789 ** the case that if X is the bitmask for the N-th FROM clause term then
5790 ** the bitmask for all FROM clause terms to the left of the N-th term
5791 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
5792 ** its Expr.iRightJoinTable value to find the bitmask of the right table
5793 ** of the join. Subtracting one from the right table bitmask gives a
5794 ** bitmask for all tables to the left of the join. Knowing the bitmask
5795 ** for all tables to the left of a left join is important. Ticket #3015.
danielk1977e672c8e2009-05-22 15:43:26 +00005796 **
drhc01a3c12009-12-16 22:10:49 +00005797 ** Note that bitmasks are created for all pTabList->nSrc tables in
5798 ** pTabList, not just the first nTabList tables. nTabList is normally
5799 ** equal to pTabList->nSrc but might be shortened to 1 if the
5800 ** WHERE_ONETABLE_ONLY flag is set.
drh42165be2008-03-26 14:56:34 +00005801 */
drh9cd1c992012-09-25 20:43:35 +00005802 for(ii=0; ii<pTabList->nSrc; ii++){
5803 createMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005804 }
5805#ifndef NDEBUG
5806 {
5807 Bitmask toTheLeft = 0;
drh9cd1c992012-09-25 20:43:35 +00005808 for(ii=0; ii<pTabList->nSrc; ii++){
5809 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
drh42165be2008-03-26 14:56:34 +00005810 assert( (m-1)==toTheLeft );
5811 toTheLeft |= m;
5812 }
5813 }
5814#endif
5815
drh29dda4a2005-07-21 18:23:20 +00005816 /* Analyze all of the subexpressions. Note that exprAnalyze() might
5817 ** add new virtual terms onto the end of the WHERE clause. We do not
5818 ** want to analyze these virtual terms, so start analyzing at the end
drhb6fb62d2005-09-20 08:47:20 +00005819 ** and work forward so that the added virtual terms are never processed.
drh75897232000-05-29 14:26:00 +00005820 */
drh70d18342013-06-06 19:16:33 +00005821 exprAnalyzeAll(pTabList, &pWInfo->sWC);
drh17435752007-08-16 04:30:38 +00005822 if( db->mallocFailed ){
danielk197785574e32008-10-06 05:32:18 +00005823 goto whereBeginError;
drh0bbaa1b2005-08-19 19:14:12 +00005824 }
drh75897232000-05-29 14:26:00 +00005825
drh4f402f22013-06-11 18:59:38 +00005826 /* If the ORDER BY (or GROUP BY) clause contains references to general
5827 ** expressions, then we won't be able to satisfy it using indices, so
5828 ** go ahead and disable it now.
5829 */
drh6457a352013-06-21 00:35:37 +00005830 if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
drh4f402f22013-06-11 18:59:38 +00005831 for(ii=0; ii<pOrderBy->nExpr; ii++){
5832 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
5833 if( pExpr->op!=TK_COLUMN ){
5834 pWInfo->pOrderBy = pOrderBy = 0;
5835 break;
drhe217efc2013-06-12 03:48:41 +00005836 }else if( pExpr->iColumn<0 ){
5837 break;
drh4f402f22013-06-11 18:59:38 +00005838 }
5839 }
5840 }
5841
drh6457a352013-06-21 00:35:37 +00005842 if( wctrlFlags & WHERE_WANT_DISTINCT ){
5843 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
5844 /* The DISTINCT marking is pointless. Ignore it. */
drh4f402f22013-06-11 18:59:38 +00005845 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
5846 }else if( pOrderBy==0 ){
drh6457a352013-06-21 00:35:37 +00005847 /* Try to ORDER BY the result set to make distinct processing easier */
drh4f402f22013-06-11 18:59:38 +00005848 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
drh6457a352013-06-21 00:35:37 +00005849 pWInfo->pOrderBy = pResultSet;
drh4f402f22013-06-11 18:59:38 +00005850 }
dan38cc40c2011-06-30 20:17:15 +00005851 }
5852
drhf1b5f5b2013-05-02 00:15:01 +00005853 /* Construct the WhereLoop objects */
drh3b48e8c2013-06-12 20:18:16 +00005854 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
drhb8a8e8a2013-06-10 19:12:39 +00005855 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
drh60c96cd2013-06-09 17:21:25 +00005856 rc = whereLoopAddAll(&sWLB);
5857 if( rc ) goto whereBeginError;
5858
5859 /* Display all of the WhereLoop objects if wheretrace is enabled */
drhd15cb172013-05-21 19:23:10 +00005860#ifdef WHERETRACE_ENABLED
drh60c96cd2013-06-09 17:21:25 +00005861 if( sqlite3WhereTrace ){
5862 WhereLoop *p;
drhfd636c72013-06-21 02:05:06 +00005863 int i;
drh60c96cd2013-06-09 17:21:25 +00005864 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5865 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
drhfd636c72013-06-21 02:05:06 +00005866 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5867 p->cId = zLabel[i%sizeof(zLabel)];
drh60c96cd2013-06-09 17:21:25 +00005868 whereLoopPrint(p, pTabList);
5869 }
5870 }
5871#endif
5872
drh4f402f22013-06-11 18:59:38 +00005873 wherePathSolver(pWInfo, 0);
drh60c96cd2013-06-09 17:21:25 +00005874 if( db->mallocFailed ) goto whereBeginError;
5875 if( pWInfo->pOrderBy ){
drhc7f0d222013-06-19 03:27:12 +00005876 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
drh60c96cd2013-06-09 17:21:25 +00005877 if( db->mallocFailed ) goto whereBeginError;
drha18f3d22013-05-08 03:05:41 +00005878 }
5879 }
drh60c96cd2013-06-09 17:21:25 +00005880 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
drhd84ce352013-06-04 18:27:41 +00005881 pWInfo->revMask = (Bitmask)(-1);
drha50ef112013-05-22 02:06:59 +00005882 }
drh81186b42013-06-18 01:52:41 +00005883 if( pParse->nErr || NEVER(db->mallocFailed) ){
drh75b93402013-05-31 20:43:57 +00005884 goto whereBeginError;
5885 }
drhd15cb172013-05-21 19:23:10 +00005886#ifdef WHERETRACE_ENABLED
drha18f3d22013-05-08 03:05:41 +00005887 if( sqlite3WhereTrace ){
5888 int ii;
drh4f402f22013-06-11 18:59:38 +00005889 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5890 if( pWInfo->bOBSat ){
5891 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
drh319f6772013-05-14 15:31:07 +00005892 }
drh4f402f22013-06-11 18:59:38 +00005893 switch( pWInfo->eDistinct ){
5894 case WHERE_DISTINCT_UNIQUE: {
5895 sqlite3DebugPrintf(" DISTINCT=unique");
5896 break;
5897 }
5898 case WHERE_DISTINCT_ORDERED: {
5899 sqlite3DebugPrintf(" DISTINCT=ordered");
5900 break;
5901 }
5902 case WHERE_DISTINCT_UNORDERED: {
5903 sqlite3DebugPrintf(" DISTINCT=unordered");
5904 break;
5905 }
5906 }
5907 sqlite3DebugPrintf("\n");
drhfd636c72013-06-21 02:05:06 +00005908 for(ii=0; ii<pWInfo->nLevel; ii++){
drha18f3d22013-05-08 03:05:41 +00005909 whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
drhf1b5f5b2013-05-02 00:15:01 +00005910 }
5911 }
5912#endif
drhfd636c72013-06-21 02:05:06 +00005913 /* Attempt to omit tables from the join that do not effect the result */
drh1031bd92013-06-22 15:44:26 +00005914 if( pWInfo->nLevel>=2
5915 && pResultSet!=0
5916 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
5917 ){
drhfd636c72013-06-21 02:05:06 +00005918 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
drh67a5ec72013-09-03 14:03:47 +00005919 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
drhfd636c72013-06-21 02:05:06 +00005920 while( pWInfo->nLevel>=2 ){
drh9d5a5792013-06-28 13:43:33 +00005921 WhereTerm *pTerm, *pEnd;
drhfd636c72013-06-21 02:05:06 +00005922 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
drhbc71b1d2013-06-21 02:15:48 +00005923 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
5924 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
5925 && (pLoop->wsFlags & WHERE_ONEROW)==0
drhfd636c72013-06-21 02:05:06 +00005926 ){
drhfd636c72013-06-21 02:05:06 +00005927 break;
5928 }
drhbc71b1d2013-06-21 02:15:48 +00005929 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
drh9d5a5792013-06-28 13:43:33 +00005930 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
5931 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
5932 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
5933 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
5934 ){
5935 break;
5936 }
5937 }
5938 if( pTerm<pEnd ) break;
drhbc71b1d2013-06-21 02:15:48 +00005939 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
5940 pWInfo->nLevel--;
5941 nTabList--;
drhfd636c72013-06-21 02:05:06 +00005942 }
5943 }
drh3b48e8c2013-06-12 20:18:16 +00005944 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
drh8e23daf2013-06-11 13:30:04 +00005945 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
drhf1b5f5b2013-05-02 00:15:01 +00005946
drh08c88eb2008-04-10 13:33:18 +00005947 /* If the caller is an UPDATE or DELETE statement that is requesting
5948 ** to use a one-pass algorithm, determine if this is appropriate.
5949 ** The one-pass algorithm only works if the WHERE clause constraints
5950 ** the statement to update a single row.
5951 */
drh165be382008-12-05 02:36:33 +00005952 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
drh3b48e8c2013-06-12 20:18:16 +00005953 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5954 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
drh08c88eb2008-04-10 13:33:18 +00005955 pWInfo->okOnePass = 1;
drh3b48e8c2013-06-12 20:18:16 +00005956 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
drh08c88eb2008-04-10 13:33:18 +00005957 }
drheb04de32013-05-10 15:16:30 +00005958
drh9012bcb2004-12-19 00:11:35 +00005959 /* Open all tables in the pTabList and any indices selected for
5960 ** searching those tables.
5961 */
drh8b307fb2010-04-06 15:57:05 +00005962 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00005963 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
danielk1977da184232006-01-05 11:34:32 +00005964 Table *pTab; /* Table to open */
danielk1977da184232006-01-05 11:34:32 +00005965 int iDb; /* Index of database containing table/index */
drh56f1b992012-09-25 14:29:39 +00005966 struct SrcList_item *pTabItem;
drh9012bcb2004-12-19 00:11:35 +00005967
drh29dda4a2005-07-21 18:23:20 +00005968 pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00005969 pTab = pTabItem->pTab;
danielk1977595a5232009-07-24 17:58:53 +00005970 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh7ba39a92013-05-30 17:43:19 +00005971 pLoop = pLevel->pWLoop;
drh424aab82010-04-06 18:28:20 +00005972 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
drh75bb9f52010-04-06 18:51:42 +00005973 /* Do nothing */
5974 }else
drh9eff6162006-06-12 21:59:13 +00005975#ifndef SQLITE_OMIT_VIRTUALTABLE
drh7ba39a92013-05-30 17:43:19 +00005976 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
danielk1977595a5232009-07-24 17:58:53 +00005977 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
danielk197793626f42006-06-20 13:07:27 +00005978 int iCur = pTabItem->iCursor;
danielk1977595a5232009-07-24 17:58:53 +00005979 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
drhfc5e5462012-12-03 17:04:40 +00005980 }else if( IsVirtual(pTab) ){
5981 /* noop */
drh9eff6162006-06-12 21:59:13 +00005982 }else
5983#endif
drh7ba39a92013-05-30 17:43:19 +00005984 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
drh9ef61f42011-10-07 14:40:59 +00005985 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
drh08c88eb2008-04-10 13:33:18 +00005986 int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
5987 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
drh7963b0e2013-06-17 21:37:40 +00005988 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
5989 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
danielk197723432972008-11-17 16:42:00 +00005990 if( !pWInfo->okOnePass && pTab->nCol<BMS ){
danielk19779792eef2006-01-13 15:58:43 +00005991 Bitmask b = pTabItem->colUsed;
5992 int n = 0;
drh74161702006-02-24 02:53:49 +00005993 for(; b; b=b>>1, n++){}
drh8cff69d2009-11-12 19:59:44 +00005994 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
5995 SQLITE_INT_TO_PTR(n), P4_INT32);
danielk19779792eef2006-01-13 15:58:43 +00005996 assert( n<=pTab->nCol );
5997 }
danielk1977c00da102006-01-07 13:21:04 +00005998 }else{
5999 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
drh9012bcb2004-12-19 00:11:35 +00006000 }
drh7e47cb82013-05-31 17:55:27 +00006001 if( pLoop->wsFlags & WHERE_INDEXED ){
drh7ba39a92013-05-30 17:43:19 +00006002 Index *pIx = pLoop->u.btree.pIndex;
danielk1977b3bf5562006-01-10 17:58:23 +00006003 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
drhae70cf12013-05-31 15:18:46 +00006004 /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
6005 int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
danielk1977da184232006-01-05 11:34:32 +00006006 assert( pIx->pSchema==pTab->pSchema );
drhb0367fb2012-08-25 02:11:13 +00006007 assert( iIndexCur>=0 );
6008 sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00006009 (char*)pKey, P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00006010 VdbeComment((v, "%s", pIx->zName));
drh9012bcb2004-12-19 00:11:35 +00006011 }
danielk1977da184232006-01-05 11:34:32 +00006012 sqlite3CodeVerifySchema(pParse, iDb);
drh70d18342013-06-06 19:16:33 +00006013 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
drh9012bcb2004-12-19 00:11:35 +00006014 }
6015 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
drha21a64d2010-04-06 22:33:55 +00006016 if( db->mallocFailed ) goto whereBeginError;
drh9012bcb2004-12-19 00:11:35 +00006017
drh29dda4a2005-07-21 18:23:20 +00006018 /* Generate the code to do the search. Each iteration of the for
6019 ** loop below generates code for a single nested loop of the VM
6020 ** program.
drh75897232000-05-29 14:26:00 +00006021 */
drhfe05af82005-07-21 03:14:59 +00006022 notReady = ~(Bitmask)0;
drh9cd1c992012-09-25 20:43:35 +00006023 for(ii=0; ii<nTabList; ii++){
6024 pLevel = &pWInfo->a[ii];
drhcc04afd2013-08-22 02:56:28 +00006025#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6026 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
6027 constructAutomaticIndex(pParse, &pWInfo->sWC,
6028 &pTabList->a[pLevel->iFrom], notReady, pLevel);
6029 if( db->mallocFailed ) goto whereBeginError;
6030 }
6031#endif
drh9cd1c992012-09-25 20:43:35 +00006032 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
drhcc04afd2013-08-22 02:56:28 +00006033 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
drh70d18342013-06-06 19:16:33 +00006034 notReady = codeOneLoopStart(pWInfo, ii, notReady);
dan4a07e3d2010-11-09 14:48:59 +00006035 pWInfo->iContinue = pLevel->addrCont;
drh75897232000-05-29 14:26:00 +00006036 }
drh7ec764a2005-07-21 03:48:20 +00006037
drh6fa978d2013-05-30 19:29:19 +00006038 /* Done. */
drh75897232000-05-29 14:26:00 +00006039 return pWInfo;
drhe23399f2005-07-22 00:31:39 +00006040
6041 /* Jump here if malloc fails */
danielk197785574e32008-10-06 05:32:18 +00006042whereBeginError:
drh8b307fb2010-04-06 15:57:05 +00006043 if( pWInfo ){
6044 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6045 whereInfoFree(db, pWInfo);
6046 }
drhe23399f2005-07-22 00:31:39 +00006047 return 0;
drh75897232000-05-29 14:26:00 +00006048}
6049
6050/*
drhc27a1ce2002-06-14 20:58:45 +00006051** Generate the end of the WHERE loop. See comments on
danielk19774adee202004-05-08 08:23:19 +00006052** sqlite3WhereBegin() for additional information.
drh75897232000-05-29 14:26:00 +00006053*/
danielk19774adee202004-05-08 08:23:19 +00006054void sqlite3WhereEnd(WhereInfo *pWInfo){
drh633e6d52008-07-28 19:34:53 +00006055 Parse *pParse = pWInfo->pParse;
6056 Vdbe *v = pParse->pVdbe;
drh19a775c2000-06-05 18:54:46 +00006057 int i;
drh6b563442001-11-07 16:48:26 +00006058 WhereLevel *pLevel;
drh7ba39a92013-05-30 17:43:19 +00006059 WhereLoop *pLoop;
drhad3cab52002-05-24 02:04:32 +00006060 SrcList *pTabList = pWInfo->pTabList;
drh633e6d52008-07-28 19:34:53 +00006061 sqlite3 *db = pParse->db;
drh19a775c2000-06-05 18:54:46 +00006062
drh9012bcb2004-12-19 00:11:35 +00006063 /* Generate loop termination code.
6064 */
drhceea3322009-04-23 13:22:42 +00006065 sqlite3ExprCacheClear(pParse);
drhc01a3c12009-12-16 22:10:49 +00006066 for(i=pWInfo->nLevel-1; i>=0; i--){
drh6b563442001-11-07 16:48:26 +00006067 pLevel = &pWInfo->a[i];
drh7ba39a92013-05-30 17:43:19 +00006068 pLoop = pLevel->pWLoop;
drhb3190c12008-12-08 21:37:14 +00006069 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
drh6b563442001-11-07 16:48:26 +00006070 if( pLevel->op!=OP_Noop ){
drh66a51672008-01-03 00:01:23 +00006071 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
drhd1d38482008-10-07 23:46:38 +00006072 sqlite3VdbeChangeP5(v, pLevel->p5);
drh19a775c2000-06-05 18:54:46 +00006073 }
drh7ba39a92013-05-30 17:43:19 +00006074 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
drh72e8fa42007-03-28 14:30:06 +00006075 struct InLoop *pIn;
drhe23399f2005-07-22 00:31:39 +00006076 int j;
drhb3190c12008-12-08 21:37:14 +00006077 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
drh111a6a72008-12-21 03:51:16 +00006078 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
drhb3190c12008-12-08 21:37:14 +00006079 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
drh2d96b932013-02-08 18:48:23 +00006080 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
drhb3190c12008-12-08 21:37:14 +00006081 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
drhe23399f2005-07-22 00:31:39 +00006082 }
drh111a6a72008-12-21 03:51:16 +00006083 sqlite3DbFree(db, pLevel->u.in.aInLoop);
drhd99f7062002-06-08 23:25:08 +00006084 }
drhb3190c12008-12-08 21:37:14 +00006085 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
drhad2d8302002-05-24 20:31:36 +00006086 if( pLevel->iLeftJoin ){
6087 int addr;
drh3c84ddf2008-01-09 02:15:38 +00006088 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
drh7ba39a92013-05-30 17:43:19 +00006089 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6090 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
6091 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
drh35451c62009-11-12 04:26:39 +00006092 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
6093 }
drh76f4cfb2013-05-31 18:20:52 +00006094 if( pLoop->wsFlags & WHERE_INDEXED ){
drh3c84ddf2008-01-09 02:15:38 +00006095 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
drh7f09b3e2002-08-13 13:15:49 +00006096 }
drh336a5302009-04-24 15:46:21 +00006097 if( pLevel->op==OP_Return ){
6098 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6099 }else{
6100 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
6101 }
drhd654be82005-09-20 17:42:23 +00006102 sqlite3VdbeJumpHere(v, addr);
drhad2d8302002-05-24 20:31:36 +00006103 }
drh19a775c2000-06-05 18:54:46 +00006104 }
drh9012bcb2004-12-19 00:11:35 +00006105
6106 /* The "break" point is here, just past the end of the outer loop.
6107 ** Set it.
6108 */
danielk19774adee202004-05-08 08:23:19 +00006109 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
drh9012bcb2004-12-19 00:11:35 +00006110
drh29dda4a2005-07-21 18:23:20 +00006111 /* Close all of the cursors that were opened by sqlite3WhereBegin.
drh9012bcb2004-12-19 00:11:35 +00006112 */
drhfd636c72013-06-21 02:05:06 +00006113 assert( pWInfo->nLevel<=pTabList->nSrc );
drhc01a3c12009-12-16 22:10:49 +00006114 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
danbfca6a42012-08-24 10:52:35 +00006115 Index *pIdx = 0;
drh29dda4a2005-07-21 18:23:20 +00006116 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
drh9012bcb2004-12-19 00:11:35 +00006117 Table *pTab = pTabItem->pTab;
drh5cf590c2003-04-24 01:45:04 +00006118 assert( pTab!=0 );
drh7ba39a92013-05-30 17:43:19 +00006119 pLoop = pLevel->pWLoop;
drh4139c992010-04-07 14:59:45 +00006120 if( (pTab->tabFlags & TF_Ephemeral)==0
6121 && pTab->pSelect==0
drh9ef61f42011-10-07 14:40:59 +00006122 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
drh4139c992010-04-07 14:59:45 +00006123 ){
drh7ba39a92013-05-30 17:43:19 +00006124 int ws = pLoop->wsFlags;
drh8b307fb2010-04-06 15:57:05 +00006125 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
drh6df2acd2008-12-28 16:55:25 +00006126 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
6127 }
drh986b3872013-06-28 21:12:20 +00006128 if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
drh6df2acd2008-12-28 16:55:25 +00006129 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
6130 }
drh9012bcb2004-12-19 00:11:35 +00006131 }
6132
drhf0030762013-06-14 13:27:01 +00006133 /* If this scan uses an index, make VDBE code substitutions to read data
6134 ** from the index instead of from the table where possible. In some cases
6135 ** this optimization prevents the table from ever being read, which can
6136 ** yield a significant performance boost.
drh9012bcb2004-12-19 00:11:35 +00006137 **
6138 ** Calls to the code generator in between sqlite3WhereBegin and
6139 ** sqlite3WhereEnd will have created code that references the table
6140 ** directly. This loop scans all that code looking for opcodes
6141 ** that reference the table and converts them into opcodes that
6142 ** reference the index.
6143 */
drh7ba39a92013-05-30 17:43:19 +00006144 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
6145 pIdx = pLoop->u.btree.pIndex;
6146 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
drhd40e2082012-08-24 23:24:15 +00006147 pIdx = pLevel->u.pCovidx;
danbfca6a42012-08-24 10:52:35 +00006148 }
drh7ba39a92013-05-30 17:43:19 +00006149 if( pIdx && !db->mallocFailed ){
danielk1977f0113002006-01-24 12:09:17 +00006150 int k, j, last;
drh9012bcb2004-12-19 00:11:35 +00006151 VdbeOp *pOp;
drh9012bcb2004-12-19 00:11:35 +00006152
drh9012bcb2004-12-19 00:11:35 +00006153 last = sqlite3VdbeCurrentAddr(v);
drhcc04afd2013-08-22 02:56:28 +00006154 k = pLevel->addrBody;
6155 pOp = sqlite3VdbeGetOp(v, k);
6156 for(; k<last; k++, pOp++){
drh9012bcb2004-12-19 00:11:35 +00006157 if( pOp->p1!=pLevel->iTabCur ) continue;
6158 if( pOp->opcode==OP_Column ){
drh9012bcb2004-12-19 00:11:35 +00006159 for(j=0; j<pIdx->nColumn; j++){
6160 if( pOp->p2==pIdx->aiColumn[j] ){
6161 pOp->p2 = j;
danielk197721de2e72007-11-29 17:43:27 +00006162 pOp->p1 = pLevel->iIdxCur;
drh9012bcb2004-12-19 00:11:35 +00006163 break;
6164 }
6165 }
drh7ba39a92013-05-30 17:43:19 +00006166 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
drhf0863fe2005-06-12 21:35:51 +00006167 }else if( pOp->opcode==OP_Rowid ){
drh9012bcb2004-12-19 00:11:35 +00006168 pOp->p1 = pLevel->iIdxCur;
drhf0863fe2005-06-12 21:35:51 +00006169 pOp->opcode = OP_IdxRowid;
drh9012bcb2004-12-19 00:11:35 +00006170 }
6171 }
drh6b563442001-11-07 16:48:26 +00006172 }
drh19a775c2000-06-05 18:54:46 +00006173 }
drh9012bcb2004-12-19 00:11:35 +00006174
6175 /* Final cleanup
6176 */
drhf12cde52010-04-08 17:28:00 +00006177 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
6178 whereInfoFree(db, pWInfo);
drh75897232000-05-29 14:26:00 +00006179 return;
6180}